Ok,
I’ll make this simple:
I am making a simple 2d driving based runner clone. I want to change the speed of my player vehicle when it hits a hazard. The hazard is a plane that is on the same Y position as the vehicle. Im using OnTriggerEnter to make it work, but so far no luck. I’m not sure if it is a problem in the editor or in the code. Ill post the code below but basically when the player hits the hazard it will slow down by a float rate. If anyone could figure this out, I would be most appreciative.
Here is the player script, the part that doesn’t work is near the bottom.
using UnityEngine;
using System.Collections;
public class sPlayer : MonoBehaviour {
public float speed = 30;
public float maxspeed = 40;
public float minspeed = 20;
public float accelrate = .099f;
public float crashslowrate = -5f;
public AudioClip EngineLoop;
public AudioClip VanAccelSound;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
bool applyDefault = true;
//if (Input.GetKey (KeyCode.D) == true)
//{
//AudioSource.PlayClipAtPoint(VanAccelSound, Camera.mainCamera.transform.position);
//transform.Translate(transform.right * maxspeed * Time.deltaTime);
//applyDefault = false;
//}
if (Input.GetKey (KeyCode.W) == true)
{
transform.Translate (Vector3.forward * -3f);
}
if(Input.GetKey (KeyCode.S)==true)
{
transform.Translate (Vector3.forward * 3f);
}
//if(Input.GetKey (KeyCode.A)==true)
//{
//transform.Translate(transform.right * minspeed * Time.deltaTime);
//applyDefault = false;
//}
if(applyDefault)
{
AudioSource.PlayClipAtPoint(EngineLoop, Camera.mainCamera.transform.position);
transform.Translate(transform.right * speed * Time.deltaTime);
speed = speed += accelrate;
}
}
void OnTriggerEnter(Collision crashslow)
{
if(crashslow.gameObject.tag == "Hazards")
{
speed = speed += crashslowrate;
}
}
}
You seem to be using this idiom quite a lot: variable = variable += increment; Are you sure that's what you want to do? The += operator gets expanded into this: variable = variable + increment; which means that your line actually looks like this: variable = variable = variable + increment While the result of that line is no different from the simpler version, it would be clearer if you simply used either variable += increment; or variable = variable + increment; not both.
– syclamothYou say you are using a "Plane" why would you do that? I would have thought a box collider was much more likely to work - a plane will be one directional and easily passed through by a fast moving object.
– whydoidoit