Search code examples
c#unity-game-enginecontrollergame-physicsrigid-bodies

Need Help in Rigidbody based FPS Controller in Unity


I am Learning unity and trying to create a fps game, but while making its controller i am facing a bit problem, like i want to move player ,, but using rigidbody not the character controller as i want it to completely interact the environment, but when i try to make player move using addforce it works fine but when i stop pressing the moving keys even the player moves for some amount of time, i want a little more snappy movement, should i use addForce or should i move player by using velocity, and can you help me find the counter movement when i stop pressing the movement buttons, using the script not by increasing the friction


Solution

  • When you add force to a Rigidbody to move it you have a couple options on how to slow down that rigidbody.

    1. Consider setting the velocity to zero to stop movement instantly
    2. Consider Clamping the velocity of the GameObject
    3. Consider adding additional velocity in the opposite direction the rigid body is traveling.

    Set The Velocity

    if(stopPlayer)
    {
        rigidbody.Velocity = new Vector3();
    }
    

    Clamp the Velocity

    Vector3 velocity =  rigidbody.Velocity;
    velocity.x = Mathf.Clamp(velocity.x, -MaxVelocity,MaxVelocity);
    velocity.y = Mathf.Clamp(velocity.y, -MaxVelocity,MaxVelocity);
    velocity.z = Mathf.Clamp(velocity.z, -MaxVelocity,MaxVelocity);
    rigidbody.Velocity = velocity;
    

    Add Velocity in opposite direction

    Vector3 velocity =  rigidbody.Velocity;
    rigidbody.AddForce(-velocity * SlowDownModifier * Time.fixedDeltaTime);