Skip to content

Instantly share code, notes, and snippets.

@troy-lamerton
Created April 18, 2017 20:53
Show Gist options
  • Save troy-lamerton/692e9843fb98e591e4034b7634ff8614 to your computer and use it in GitHub Desktop.
Save troy-lamerton/692e9843fb98e591e4034b7634ff8614 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class TopDownMovement : MonoBehaviour {
public float walkSpeed = 5f;
public Boundary boundary; // optional rectangle boundary
float maxSpeed = 10f;
float curSpeed;
float sprintSpeed;
Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
// sprintSpeed = walkSpeed + (walkSpeed / 2);
}
void FixedUpdate() {
curSpeed = walkSpeed;
maxSpeed = curSpeed;
// the movement magic
rb.velocity = new Vector3(
Mathf.Lerp(0, Input.GetAxis("Horizontal")* curSpeed, 0.8f),
rb.velocity.y,
Mathf.Lerp(0, Input.GetAxis("Vertical")* curSpeed, 0.8f)
);
// optional: clamp position inside a rectangle
rb.position = new Vector3(
Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax),
rb.position.y,
Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax)
);
}
}
// optional rectangle boundary
[System.Serializable]
public struct Boundary {
public float xMin;
public float xMax;
public float zMin;
public float zMax;
}
@troy-lamerton
Copy link
Author

Adapted from best 2D, top down, movement script:
http://answers.unity3d.com/answers/635453/view.html

@DodiMax
Copy link

DodiMax commented Aug 17, 2021

that is great

@Hiytu
Copy link

Hiytu commented Jan 3, 2022

Is this 3d?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment