transform.Rotate not rotating with conditional statement

I have an object flying around on my screen and I want it to vary its flight path randomly. I have it programmed to continuously fly straight and then test an IF statement to see if it rotates up or down. The “else” of my if statement is never happening.

    function Update () {
    
    	transform.Translate(Vector3.forward * (Time.deltaTime*50));

Random.seed = Random.Range(0, 10000);
    
    	if ((Random.Range(0, 10))>5)
    	{
    		transform.Rotate(Vector3.up * (Time.deltaTime*50));
    	}
    	else
    	{
    		transform.Rotate(Vector3.up *(-1 * (Time.deltaTime*50)));
    	
    	}
    }

I assume this is a really dumb logic error, but Im apparently not seeing it.

3 Answers

3

It’s just going to jitter randomly right or left every frame, with a 6/10 chance of the first Rotate, and a 4/10 chance of the second, so on average it will rotate right more often than left. Perhaps you meant “Random.value > .5”, although I’m not really sure what you’re trying to do exactly. Also, setting Random.seed every frame is pointless.

Yeah, I’m thinking it probably has something to do with your seed. I wouldn’t bother with that line of code.

As @Eric5h5 said, the object will rotate almost every frame, what doesn’t produce a noticeable rotating effect - the object just shakes wildly. A better approach would be to turn it left during a random time, then right during another random time, and so on:

private var timeToChange:float = 0.0;
private var speed = 50.0; // 50 degrees per second

function Update () {
    transform.Translate(Vector3.forward * (Time.deltaTime*50.0));
    if (Time.time > timeToChange){ // when random time elapsed...
        // draw a new random time between 0.3s and 1.3s
        timeToChange = Time.time+0.3+Random.value;
        speed = -speed; // and revert direction
    }
    transform.Rotate(Vector3.up*speed*Time.deltaTime);
}