AddForce seems to save the velocity and continue it.

Hello! I have a problem with rigidbody.AddForce. I have a character movescript and the player looks at the cursor, so on pressing the “Jump” key it should add force in the direction where the player looks. And it only kinda works. link to gif : Imgur: The magic of the Internet
code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public float movementSpeed = 5f;
    public float rollforce = 15f;
    public Rigidbody2D rb;
    public Camera cam;
    Vector2 movement;
    Vector2 mousePos;
    private bool isrolling;
    void Update()
    {


        if (Input.GetButtonDown("Jump"))
        {
            isrolling = true;
        }
        if (Input.GetButtonUp("Jump"))
        {
            isrolling = false;
        }

        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");

        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    private void FixedUpdate()
    {
        if (isrolling == true)
        {
            Debug.Log("pressed");
            //rb.AddForce(transform.forward * rollforce, ForceMode2D.Impulse);
            rb.AddRelativeForce(transform.up * rollforce, ForceMode2D.Force);
        }
        if (isrolling == false)
        {
            rb.MovePosition(rb.position + movement * movementSpeed * Time.fixedDeltaTime);

            Vector2 lookDir = mousePos - rb.position;
            float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
            rb.rotation = angle;
        }


    }
}

You’re using two completely different methods for movement here. You’re adding a force which then, during the simulation step, updates the velocity which cause it to move. At this point the body has velocity.

You then (when rolling) start issuing kinematic movements, ignoring the velocity the body has, telling it to move to specific positions but you leave any velocity it has intact so I’m not sure why you are surprised it still has velocity. Maybe you expect the MovePosition to modify the velocity. It has no reason to do that; it’s totally under your control.

If when you start rolling, you want to zero the velocity the object has then do so by setting the following property to zero: Rigidbody2D.velocity either before the MovePosition or more appropriately when you set Isrolling to true.

1 Like

Thanks for the help! I’m quite new to unity thats why i asked.