Force vector calculation

Let’s say there’s a Rigidbody2D falling due to gravity. I need to calculate an impulse force vector that, after being applied to the Rigidbody, will cause it to travel along the x-axis.
Does anyone have an idea how to come up with that force vector?

I’m not great at unity physics, but in theory all you have to do is rb.addforce(new Vector2(xSpeed, -1 * rb.velocity.y), Forcemode2D.Impulse)

I found this while searching the forum but it doesn’t work either

rigidBody.AddForce(-Physics2D.gravity + new Vector2(isfacingRight ? 100 : -100, 0), ForceMode2D.Impulse);

The question isn’t entirely clear. If you want to have the velocity to be (xSpeed, 0) then just set that. It’s not clear why you’re trying to use impulses to do this.

rb.velocity = new Vector2(xSpeed, 0f);
1 Like

Okay my previous formula will work, but only if the mass of the RB2D is 1. To make it work all the time you need to do rb.AddForce(new Vector2(xSpeed, -1 * rb.velocity.y) * rb.mass, Forcemode2D.Impulse)

But again, that’s pointless if all you want to do is have the Y component of velocity zero and the X component of velocity to xSpeed. Your “formula” isn’t required.

I thought it was bad practice to directly edit the rigidbody’s velocity. Is this the case?

There’s no such blanket “bad practice” rules. For anything you do, you need to know the consequences of doing it and if it’d affect what you’re doing.

You seem to be referring to the fact that if you explicitly set the velocity then you will be removing what things like forces and gravity are doing to it but you actually want to do this i.e. set the X velocity and Y velocity explicitly for a moment in time. There’s no “bad practice” to achieve what you want to achieve directly.

1 Like

Okay I got you good clarification.