- Home /
CharacterController sprint functionality.
So I'm trying to implement a sprint function, but I'm having trouble because i don't know how to set it so if the LSHIFT is pressed the 'sprint' will take over, when its raised, it will return back to the 'speed'. However, i've tried using the ELSE function but it just produces errors. The code for the else function is;
else {
if(Input.GetKeyDown(KeyCode.LeftShift)){
moveDirection *= sprint;
}
}
However, that code keeps bringing errors.
This is the code I'm currently using.
using UnityEngine; using System.Collections;
public class characterMovement : MonoBehaviour {
public float speed = 6.0F;
public float sprint = 10.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
if (Input.GetKeyDown(KeyCode.LeftShift)){
moveDirection *= sprint;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
Get$$anonymous$$eyDown only calls once, you would need to use Get$$anonymous$$ey in order for it to continuously sprint.
Figured it out. Heres the script.
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.LeftShift)){
moveDirection *= speed * 5.0F;
}
}
moveDirection.y -= gravity * Time.deltaTime;
controller.$$anonymous$$ove(moveDirection * Time.deltaTime);
}
Answer by T27M · Aug 03, 2014 at 01:27 AM
GetKey is correct, but I think it's because you have
moveDirection *= speed;
and
moveDirection *= sprint;
both working against each other. Try modifying it to this:
if (Input.GetKey(KeyCode.LeftShift)){
speed = sprint;
} else {
speed = 6.0f;
}
Wow, I missed that. Still, what I said about Get$$anonymous$$eyDown still improved the code.
I've tried to use the else function before, but for some reason errors kept popping up. I've changed my script now from the previous one and now all i did was created a public float;
public float sprint = 5.0F;
and just set the move direction to add, the sprint speed, for example;
moveDirection *= speed + sprint;
//you could use * ins$$anonymous$$d of +.