This question was
closed Dec 28, 2016 at 08:14 PM by
Tegomlee for the following reason:
The question is answered, right answer was accepted
How to add sprinting and crouching?
Hello everyone, I am creating a sandbox game and I need my character to be able to sprint and crouch. This is my c# script:
private Rigidbody player;
private bool canJump = true;
private RaycastHit ray;
public float walkSpeed;
public float gravity;
void Start() {
Cursor.lockState = CursorLockMode.Locked;
player = GetComponent<Rigidbody> ();
}
void FixedUpdate() {
Physics.Raycast (transform.position, Vector3.down, out ray);
if(Vector3.Distance(transform.position,ray.point) < 1.1) {
canJump = true;
}
if (Input.GetKey(KeyCode.Space)) {
if (canJump == true) {
player.velocity = Vector3.up * gravity;
canJump = false;
}
}
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.forward * walkSpeed);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate (Vector3.left * walkSpeed);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.back * walkSpeed);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate (Vector3.right * walkSpeed);
}
}
Thanks in advance.
Comment
Best Answer
Answer by Tegomlee · Dec 28, 2016 at 08:13 PM
Never mind, I answered it. Here's the code just in case there were others in the same boat:
private Rigidbody player;
private bool canJump = true;
private RaycastHit ray;
private float speed;
public float walkSpeed;
public float gravity;
public float sprintSpeed;
void Start() {
Cursor.lockState = CursorLockMode.Locked;
player = GetComponent<Rigidbody> ();
}
void FixedUpdate() {
Physics.Raycast (transform.position, Vector3.down, out ray);
speed = walkSpeed;
if(Vector3.Distance(transform.position,ray.point) < 1.1) {
canJump = true;
}
if (Input.GetKey(KeyCode.Space)) {
if (canJump == true) {
player.velocity = Vector3.up * gravity;
canJump = false;
}
}
if (Input.GetKey(KeyCode.LeftShift)) {
speed = sprintSpeed;
}
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector3.forward * speed);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate (Vector3.left * speed);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector3.back * speed);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate (Vector3.right * speed);
}
}