Created
April 20, 2017 12:30
-
-
Save troy-lamerton/0aa85310efdfc3f70d809045a457a21b to your computer and use it in GitHub Desktop.
Improvement by jannysice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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