- Home /
Need help with my movement script.. :(
Currently, my movement script uses only these few lines of code for the horizontal movement in the Update method:
movement = Input.GetAxis("Horizontal");
if (sprinting)
{
rb.velocity = new Vector2(movement * sprintSpeed, rb.velocity.y);
}
else
{
rb.velocity = new Vector2(movement * speed, rb.velocity.y);
}
It works just how I wanted it thus far. However, now I have implemented horizontal boost pads. They worked fine vertically since I don't set the rb.velocity.y each frame.
However, this script does not allow my player to be boosted on the x-axis, since I set the rb.velocity.x each frame. Recursion makes this a real pain to deal with.. I've been trying to find a solution for the past 2-3 hours, and have come to nothing really working. Can someone help me with this? :(
Answer by Octoberwolf · Oct 03, 2020 at 01:06 AM
Depending on the effect that you are looking for I can think of a couple solutions.
You could multiply the movement * speed by another term.. for purposes of example I will call it boost_Mult. Set this equal to 1 when you declare it so you get.
movement = Input.GetAxis("Horizontal"); float boost_Mult = 1; if (sprinting) { rb.velocity = new Vector2(movement * sprintSpeed * boost_Mult, rb.velocity.y); } else { rb.velocity = new Vector2(movement * speed * boost_Mult, rb.velocity.y); }
You could use Vector2.lerp (or smoothdamp) for your velocities. This will give you a smoother transition from one speed to the next so you could write the following. Where "t" is reset to zero when you hit a booster and boostSpd is whatever speed you want the player to be at upon being boosted, also set when the player hits a booster.
movement = Input.GetAxis("Horizontal"); Vector2 noBoostSpd; Vector2 boostSpd; float spdDampRate = 2.0f; float t = 0; if (t >= 1) { t = 1; } else { t += Time.deltaTime * spdDampRate ; } if (sprinting) { noBoostSpd = new Vector2(movement * sprintSpeed, rb.velocity.y); } else { noBoostSpd = new Vector2(movement * speed, rb.velocity.y); } rb.velocity = Vector2.Lerp(boostSpd, noBoostSpd, t);
Something like this.
That was really helpful. I guess I'll have to rule all player movement over that script then.. but it's a viable solution. Thanks!
Your answer
Follow this Question
Related Questions
.normalized sometimes returns 0 values, in a condition that only functions if value is not 0... 1 Answer
Smooth Player Ball Rolling 1 Answer
Why is my vertical movement faster than my horizontal? 1 Answer
How can I slow the velocity of my player without it affecting fall speed? 0 Answers
move 2d character affected by physics with velocity and/or add force 2 Answers