Reputation: 13
I'm editing a Space Shooter game for class and I am trying to create a "Hard Mode" that speeds up the asteroids when the player presses the key "e". Currently with my code, pressing the key will speed up every asteroid that is currently on the screen but new asteroids spawned in are at regular speed. I have no idea how to fix and would like some suggestions in what to do. Here's my code:
public float speed;
private Rigidbody rb;
Vector3 initialForwardVector;
void Start()
{
rb = GetComponent<Rigidbody>();
initialForwardVector = transform.forward;
rb.velocity = initialForwardVector * speed;
}
void Update()
{
if (Input.GetKey (KeyCode.E))
{
rb.velocity = initialForwardVector * (2*speed);
}
}
Upvotes: 1
Views: 78
Reputation: 787
Quickest simplest solution:
public float speed;
public static float speedModifier = 1f;
private Rigidbody rb;
Vector3 initialForwardVector;
void Start()
{
rb = GetComponent<Rigidbody>();
initialForwardVector = transform.forward;
rb.velocity = initialForwardVector * speed * speedModifier;
}
void Update()
{
if (Input.GetKey(KeyCode.E))
{
speedModifier = 2f;
rb.velocity = initialForwardVector * (speedModifier * speed);
}
}
The speed modifer will apply to all new projectiles since the value is shared(static) between all instances of the class. For a more robust implementation i suggest adding an Initialize function that would set a local speed modifier for new asteroids.
Upvotes: 1