#Best way of having instant acceleration on a player movement script for 3D.

1 messages · Page 1 of 1 (latest)

proven mountain
#

Hi there,

I am trying to make my own player movement script for a 2.5D metroidvania game (using a 3D physics engine, but the movement is 2D).

I've been using AddForce() to move the player, however, when I use it, I don't get the desired behaviour.

I want the character's movement to be snappy, with instant acceleration and deceleration on the x-axis.

I have sort of achieved that with the code below, but with a strange caveat. The character moves faster or slower based on what I have the runningAcceleration set to, not maxSpeed.

I don't think I understand AddForce correctly... What I want is for the character to immediately start moving at the velocity set in maxSpeed. I set runningAcceleration to a really high number because I want it to be instant, but why does the character move faster or slower based on the runningAcceleration, shouldn't it be clamped to maxSpeed regardless?

public class Test3d : MonoBehaviour
{
    public Rigidbody rb;
    public Vector3 velocity;
    public float runningAcceleration;
    public float maxSpeed;

    void Awake(){
        rb = GetComponent<Rigidbody>();
    }
    void FixedUpdate(){
        Vector3 direction = new(Input.GetAxisRaw("Horizontal"), 0, 0);
        Vector3 targetVelocity = direction + velocity;

        // if the player is changing direction (signs are different), ignore the current velocity
        if (Math.Sign(direction.x) != Math.Sign(velocity.x)){
            targetVelocity.x = direction.x;
        }

        rb.AddForce(targetVelocity * runningAcceleration, ForceMode.VelocityChange);

        // stop the player, AddForce doesnt stop when the input is 0
        if (targetVelocity.x == 0){
            rb.velocity = new Vector3(0, rb.velocity.y, 0);
        }

        // clamp rb.velocity to max speed
        rb.velocity = new Vector3(Mathf.Clamp(rb.velocity.x, -maxSpeed, maxSpeed), rb.velocity.y, 0);

        velocity = rb.velocity;
    }
}
#

I know I can just set rb.velocity directly, and it sort of works, but it seems to be a bit laggy, and I've heard that it isn't the best practice.

runic portal
#

Honestly, just use rb.velocity.

proven mountain
proven mountain
#

I know "buggy" isnt the best way to describe it

runic portal
#

Perhaps it doesn't actually increase the maximum speed. It increases the acceleration, so you get to a higher/max speed faster.

runic portal
proven mountain
#

Hard to describe, essentially, the capsule would flicker a bunch, and it would sometimes look like it's teleporting (dropping frames maybe?).

#

I'm new to game dev, so it's hard for me to understand what exactly could be going wrong

runic portal
#

Is it just the fixed update jitter? Do you have interpolation enabled on the rb?

proven mountain
proven mountain
#

ty for your help though

#

I checked the rb, its set to None