#Player Movement with RigidBody.AddForce()

1 messages · Page 1 of 1 (latest)

iron aurora
#

Hi, I am implementing a player movement with rb.AddForce so that if I want to apply forces later i can
I created a basic script that handles that but i dont know how to apply a force for jumping correctly

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    [Header("Movement Data")] [SerializeField]
    private float maxSpeed = 5f;

    [SerializeField] private float acceleration = 5f;
    [SerializeField] private float deceleration = 5f;
    [SerializeField] private float jumpForce = 5f;


    private PlayerInputHandler playerInput;
    private Rigidbody2D rb;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Start()
    {
        playerInput = PlayerInputHandler.Instance;
    }

    void FixedUpdate()
    { 
        HandleMove();
        HandleJump();

    }

    private void HandleMove()
    {
        if (playerInput.IsMoving)
        {
            rb.AddForce(new Vector2(playerInput.MoveInput * acceleration, 0f), ForceMode2D.Force);
            if (rb.linearVelocity.magnitude > maxSpeed)
            {
                rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
            }
        }
        else
        {
            rb.linearVelocity = new Vector2(Mathf.MoveTowards(rb.linearVelocity.x, 0, deceleration * Time.fixedDeltaTime), rb.linearVelocity.y);
        }
    }

    private void HandleJump()
    {
        if (playerInput.JumpInput)
        {
            rb.AddForce(new Vector2(rb.linearVelocity.x, jumpForce), ForceMode2D.Impulse);
        }
    }
}

When jumping, the jump force is just weird and is being applied only for a certain period of time so that you see the player going fast up, then slow up, then go down
Also if jumpForce is too strong it just ignore the direction and just go almost up.

vale maple
#

I think what you're seeing is that it's clamped by

 if (rb.linearVelocity.magnitude > maxSpeed)
{
    rb.linearVelocity = rb.linearVelocity.normalized * maxSpeed;
}
#

Maybe try clamping horizontal velocity instead:

float3 velocity = (float3)rb.linearVelocity; // Convert Vector3 to float3 to get swizzling
float2 horizontalVelocity = velocity.xz; // use swizzling to get only X and Z properties
if(math.lengthsq(horizontalVelocity) > maxSpeed * maxSpeed) // Compare square length to square of max speed
{
  horizontalVelocity = math.clamp(horizontalVelocity, maxSpeed); // Clamp
  velocity.xz = horizontalVelocity; // Reassign
  rb.linearVelocity = velocity; // Assign result to Rigidbody
}