Hey! So I’m an absolute newbie when it comes to Unity and looking for some help. Apologies too if this info is clearly available elsewhere and I’ve missed it.
Using a very basic movement script, like this:
public class PlayerController : MonoBehaviour {
public float speed;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rigidbody.velocity = movement * speed;
}
How would I then add a function to rapidly increase movement for a short period of time? With the input of another button, say space bar? With the overall goal being for this to act like a dodge/dash type movement for the player sprite.
You should be able to create a new float variable say, speedModifier that defaults to a value of 1 (so no change in velocity normally) but can be set to say 1.5 when the Space bar is pressed. Create a second integer variable say, dashTime that defaults to 0 as well.
rigidbody.velocity = movement * speed * speedModifier;
If you press the Space button and dashTime == 0, alter this value to 1.5 ( or whatever) then set the dashTime to however many frames you want the dash speed to last. Then simply decrement dashTime to 0. When dashTime == 0 have the speedModifier reset to 1.
As a rough example…
rigidbody.velocity = movement * speed * speedModifier;
if (Input.GetKey (KeyCode.Space) && dashTime == 0) {
dashTime = 5;
}
if (dashTime > 0) {
speedModifier = 1.5;
dashTime--;
}
if (dashTime == 0) {
speedModifier = 1;
}
Sorry the code is in JS, that’s what I’m using in my own project.
Hey, thanks for helping out! I actually came to a similar though less elegant solution myself but your suggestion’s still very helpful! Much appreciated.