- Home /
Rigidbody2D AddForce not working
(Edit: I commented out the MovePosition function and the jumping works fine now. I'm assuming the MovePosition function is overriding the AddForce function?)
I am currently in the process of writing a player script for a game I am making. However when I use the AddForce function to make my player jump, nothing happens. I am not sure if it is a problem with the code or with my RigidBody2D settings. Here is the code:
public class Player : MonoBehaviour
{
private Rigidbody2D rb;
private Vector2 movement;
[SerializeField] private float movementSpeed = 5;
[SerializeField] private float jumpForce;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
movement.x = Input.GetAxis("Horizontal");
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
}
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * movementSpeed * Time.deltaTime);
}
}
And here is a screenshot of my components: [1]: /storage/temp/167733-capture.png
Thank you.
I think your issue is thatyou shouldn't mix two different movement techniques in one object. $$anonymous$$ovePosition will move your object to the destination regardless of any physics being applied. So, most likely the first physics frame after you apply the jump force, moveposition is moving your player in the direction of moveposition and ignoring the add force you applied. I would recommend probably switching your jump to using moveposition by updating your movement variable to the jump destination, or probably less effort to change your character movement to using addforce instead.
Your answer
Follow this Question
Related Questions
making a mushroom trampoline , bouncing the gameobject relative to mushroom's rotation 1 Answer
I'm following a tut - converting to 3d - and confuzzled by RigidBody2d - vector 3 0 Answers
Rigidbody2D adding force vs modifying velocity for character jump 1 Answer
Why doesn't Rigidbody.velocity.x = 0 in a collision? 1 Answer
How do I stop a RigidBody2D from moving after applying addForce? 1 Answer