C#
I have a little game where the player dodges traffic kind of like an endless frogger level. Currently one script spawns the traffic with the 1st function below. The cars have the 2nd function in a script attached to them. “speed” is a public float set to 3 in this case. aTraffic is a list of pooled cars.
The car’s script has “transform.Translate (speed * Time.deltaTime, 0, 0);” in Update.
The idea is for the script to spawn cars at randomly selected sides of the road(so x= either 5 or -5) and a random y value. If they spawn on the right side, the sprite gets flipped by taking the negative x scale and is told to move in the correct direction by flipping the ‘speed’ variable whenever it enables(3 becomes -3).
This is working MOST of the time, but maybe 10% of the time the speed doesn’t get appropriately set even though checking with Debug.Log shows that OnEnable fired just fine. As a result, I get that ~10% of cars spawning and driving in reverse away from road instead of going across it. It happens to cars spawning on both the left and right.
Any thoughts?
void OncomingTraffic () {
VehicleDeploying = Random.Range (0, aTraffic.Count);
if (!aTraffic[VehicleDeploying].activeInHierarchy)
{
sidecheck = Random.Range (0, 2);
if (sidecheck == 0) {
side = -5;
aTraffic [VehicleDeploying].transform.localScale = new Vector2(1.5f, 1.5f);
} else {
side = 5;
aTraffic [VehicleDeploying].transform.localScale = new Vector2(-1.5f, 1.5f);
}
levelCenter = transform.position.y;
aTraffic[VehicleDeploying].transform.position = new Vector2 (side, Random.Range (levelCenter - 6.5f, levelCenter + 6.5f));
aTraffic[VehicleDeploying].transform.rotation = transform.rotation;
aTraffic[VehicleDeploying].SetActive(true);
}
void OnEnable () {
if (transform.position.x > 0)
speed = -speed;
}
Good info, thanks!
– wkhigleyI have no baking activated in my game. It's all realtime since there are no non-moving objects.
– christopf