Reputation: 45
I have declared a variable named RandomX and RandomY. I use a random generator function to return a random number between -1 to 1. I then use an if statement to check the number that is generated. If the number generated (RandomX or RandomY) is less than -0.4 then I want to set the variable movementX to -1. If the number is greater than 0.4 I was to set the variable movementX to 1. If neither of these are true I want to set the value to 0.
Here is what I have, but for some reason if the number is less than -0.4 instead of it setting the number to -1 it sets the number to 0. What am I missing?
float randomX = Random.Range (-1f,1f);
if (randomX < -0.4)
{
movementX = (-1);
}
if (randomX > 0.4)
{
movementX = movementX * -1;
}
else
{
movementX = 0;
}
randomY = Random.Range (-1f,1f);
Debug.Log (randomY);
if (randomY < -0.4)
{
movementY = -1;
}
if (randomY > 0.4)
{
movementY = 1;
}
else
{
movementY = 0;
}
Upvotes: 0
Views: 3790
Reputation: 37020
The problem is here.
if (randomX < -0.4)
{
movementX = -1;
}
Here you assign -1
if the condition fits. However afterwards you do this:
if (randomX > 0.4)
{
movementX = movementX * -1;
}
else
{
movementX = 0;
}
Which will check if the new value is less 0.4
which it apparently is now. Furthermore when your input is greater than 0.4 it should return 1 if I understand you correctly.
Write this instead:
if (randomX < -0.4)
{
movementX = -1;
}
else if (randomX > 0.4)
{
movementX = 1;
}
else
{
movementX = 0;
}
Upvotes: 3