- Home /
changing the speed of an enemy on key press?
so i have a mover script, this allows me to move all enemies and objects down a 2D plane from top to bottom. now that script is on all my enemy prefabs. and looks like this.
public class Mover : MonoBehaviour
{
public float speed;
private Rigidbody rb;
void Start()
{
Func();
}
public void Func()
{
rb = GetComponent<Rigidbody>();
rb.velocity = transform.forward * speed;
}
}
now this is a seperate script I wrote to change speed on my object when "H" is pressed. this breaks the physics of the object and instead of moving down the screen they fly in random directions. also it seems to only work while the key is held down.
public class faster : MonoBehaviour
{
private float speed;
private Rigidbody rb;
private void Update()
{
if (Input.GetKey(KeyCode.H))
{
rb = GetComponent<Rigidbody>();
speed = -10;
rb.velocity = transform.forward * speed;
}
}
}
Answer by Jeezker · Apr 24, 2019 at 12:40 AM
Use Input.GetKeyDown to only trigger it once. Also reference the Mover in your script and change the speed of that.
i think i have found the issue... just not how to fix it. since the speed is called in start i cannot change that value in update?
Answer by galactichyperstar · Apr 24, 2019 at 03:20 AM
Moving down a 2D plane? Is this only on the X and Y axis? If so, why not create a 2D project instead? If you need it in 3D, then you should know that transform.forward points in the positive Z direction. Also, make sure the Rigidbody drag is set to 0 so the object never slows down, since you are only applying the first velocity when the object is created. Then, if you press H the object should instantly start moving towards the other direction.
Your answer
Follow this Question
Related Questions
Sometimes the ball isn't moving 0 Answers
Click to move a character in a terrain 1 Answer
How to handle walls with my FirstPersonCharacter? 1 Answer
Weird Movement 1 Answer
Simple Movement Game: Physics vs Manual Collision Detection? 2 Answers