Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save troy-lamerton/0aa85310efdfc3f70d809045a457a21b to your computer and use it in GitHub Desktop.
Save troy-lamerton/0aa85310efdfc3f70d809045a457a21b to your computer and use it in GitHub Desktop.
Improvement by jannysice
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;
//Normalize movement vector so diagonal movement is not twice as fast.
float xDir = Input.GetAxis("Horizontal"), zDir = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(xDir,zDir).normalized;
// the movement magic
rb.velocity = new Vector3(
Mathf.Lerp(0, movement.x* curSpeed, 0.8f),
rb.velocity.y,
Mathf.Lerp(0, movement.y* 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment