Hi, my current movement when rapidly pressing left, right, forward, backward feels too snappy. How do I make it so that the speed builds up to its full potential speed, when you hold the button long enough? I’m a beginner, so could you explain why and how it would work?
Here’s my code:
public class CharacterMovement : MonoBehaviour
{
public CharacterController controller;
public Transform cam;
public float speed = 6f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
if (direction.magnitude >= 0.1f)
{
float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
Vector3 moveDirection = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
controller.Move(moveDirection.normalized * speed * Time.deltaTime);
}
}
Create a speed or velocity member variable and increase / decrease that when you press the button. For example
float speed; // make this a member of the class
float forwardInput = keyPressed? 1 : 0;
speed = Mathf.MoveTowards(speed, forwardInput * walkSpeed, Time.deltaTime * acceleration);
Make sure it’s the class member variable, not a local variable, so its value is preserved.
Then, simply move the character by the speed / velocity in every Update
position += Transform.forward * speed * Time.deltaTime;
Extend this code to add negative speed when backwards button is pressed (or add strafing as well)
The difference between the speed and velocity could be that speed is a scalar while velocity is a vector. In the example above, you accumulate speed that you move forward with, even after your character changes facing (rotates / turns). You could hold a velocity variable instead of a speed, expressing the movement over time in world space. In such case it could look like this
Vector3 velocity; //again, a member of the class
float forwardInput = keyPressed? 1 : 0;
velocity = Vector3.MoveTowards(velocity, Transform.forward * forwardInput * walkSpeed, Time.deltaTime * acceleration);
position += velocity * Time.deltaTime;
The difference here is that once you accumulate velocity, you will continue moving in that same direction even after your character turns / rotates