- Home /
How can I add an impulse force on top of my walking force?
I want to have 3 forces in my 2D platformer game - basic left and right walking, a jump, and a gun which boosts the player away from the mouse.
The only way I have found to make my player move linearly with a constant velocity has been to do something like this:
float hAxis = Input.GetAxisRaw("Horizontal");
rb.velocity = new Vector2(hAxis * spd, rb.velocity.y);
and my gun force code is
if (Input.GetMouseButtonDown(0))
{
var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
rb.velocity = -dir.normalized * gunForce;
}
However, by directly setting the x velocity of the rigidbody it overrides whatever force the gun was putting on the character, which I don't want. I would want for moving left when the gun is sending you right to slowly stop the character, and if the character was moving right and the gun is also sending you right I would want the character to either continue at the speed the gun was moving the character or to slowly move to the normal walking speed (whichever is easier to code).
Any way that I have tried to change the walking script has just made the movement exponential.
Answer by AdrianTEC · Sep 04, 2020 at 04:13 PM
if I understand what you want to do, you can do it with [AddForce][1] [1]: https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html you can have inertia after force impulse
int forceConstant= 3
if(Input.GetKey("d"))
{
rb.AddForce(transform.right* forceConstant, ForceMode.Impulse);
}
//Force mode can also be
//ForceMode.Force
//ForceMode.Acceleration
//ForceMode.Impulse
//ForceMode.VelocityChange
Your answer
Follow this Question
Related Questions
Rigidbody2D character movement problem 0 Answers
How can I add an impulse force on top of my walking force? 1 Answer
Collision problem 1 Answer
Need help with Raycast2D 0 Answers
Smoothly Jump to mouse position 1 Answer