- 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 Chrissyeah_ · Sep 03, 2020 at 08:51 PM
Potentially there are ways this can be simplified, but you can use Mathf.Lerp to transition the value overtime. If you add this code and then adjust your velocity code to rb.velocity = new Vector2(hAxis * (spd + Impulse), rb.velocity.y);
Then you can achieve the effect you are looking for.
public bool ImpulseTrigger;
float ImpulseTimer;
public float Impulse;
float initialImpulse = 5;
float LerpInterpolator;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
TriggerImpulse();
}
}
private void FixedUpdate()
{
if (ImpulseTrigger)
{
ImpulseTimer -= Time.fixedDeltaTime;
if (ImpulseTimer < 0)
{
ImpulseTrigger = false;
}
LerpInterpolator += Time.deltaTime;
Impulse = Mathf.Lerp(initialImpulse, 0, LerpInterpolator);
}
}
void TriggerImpulse()
{
LerpInterpolator = 0;
ImpulseTrigger = true;
ImpulseTimer = 2;
}
This works great, and is an interesting mechanic by itself, but I want the gun to shoot the player in the opposite direction of the mouse, whether that be up, down, left, right, or anywhere in between. This code boosts the player forward. I tried implementing the lerp idea into my own code but I still couldn't figure it out. Thanks for your help though.
I've figured it out, I just stopped using the rigidbody gravity and made my own. I made the impulse lerp down like you suggested at it works like a charm. Thanks I couldn't have figured it out without you
@$$anonymous$$ikul_ I'm glad you came right :D You are more then welcome to mark my answer as correct ;P