Hello all, I’m stuck on a problem regarding collecting items and applying speed from that item, right now I have this working, but every time I run the game, sometimes the speed will not reset back to it’s original speed and keep going forwards. This is a 2D game for the record, forwards to me means to the right on the x axis.
I have multiple’s of the same speed pick-up that the player needs to collect to stay going forwards, they are quite close together, they have to be for the game to work, each of them have the following script on them:
using UnityEngine;
using System.Collections;
public class SpeedItem : MonoBehaviour {
public float bonusTime = 0.3f;
public float bonusGain = 0.4f;
private bool collected = false;
private float timer = 0;
public float powerUpPosition = 2f;
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Player")
{
collected =true;
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMove>().forwardsSpeed+=bonusGain;
gameObject.renderer.enabled = false;
}
}
void Update()
{
if (collected == true)
{
timer += Time.deltaTime;
if(timer >= bonusTime)
{
GameObject.FindGameObjectWithTag("Player").GetComponent<PlayerMove>().forwardsSpeed-=bonusGain;
Destroy(gameObject);
}
}
transform.position -= Vector3.right * powerUpPosition * Time.deltaTime;
}
}
And this is the player script it’s referencing:
public float forwardsSpeed = 0.3f;
public float backwardsSpeed = 0.37f;
void Update() {
transform.position += Vector3.right * forwardsSpeed * Time.deltaTime;
transform.position -= Vector3.right * backwardsSpeed * Time.deltaTime;
}
}
I need to work out how to reset the forwardsSpeed back to it’s original before it accepts another item, otherwise I get results like I am now which allows the player to gain more speed and only take away what it just recieved, and not all the amounts it received in that collection of items.
Is there anyone who knows how I can fix this and would be willing to help? I’d very much appreciate that, thanks!