1
votes

I want my object to choose random direction, rotate to it and then follow it for a while. After this repeat it all again. Here is my code for choosing direction

private void ChooseDirection() {
    // create a random angle from 0.0 to 360.0, Remap is a simple function for it
    float angle = Utils.Remap (Random.value, 0.0f, 1.0f, 0.0f, 360.0f);
    transform.Rotate (Vector3.up, angle);
    print (angle + " : " + transform.rotation.eulerAngles.y);

}

The code above produces the following output to the console

38.12973 : 38.12972

283.771 : 321.9007

295.227 : 257.1267

142.9637 : 40.09043

178.7077 : 218.7981

126.3595 : 345.1576

347.749 : 332.9065

250.1977 : 223.1042

243.5038 : 106.608

252.1878 : 358.7958

20.00817 : 18.804

As you can see the actual rotation angle is not the randomly chosen angle. As the result my object doesn't face the direction in which it's moving.

1
You aren't setting the rotation. You are rotating. (i.e. Adding the chosen rotation to the transform's existing rotation.)Abion47
I changed my code, now the angles match. I am still having the problem that the object is facing wrong direction. I will try to set angle to known values such as 0, 10, 45, 90 ... and see how it movessasha199568
I found my problem. In Translate function I used transform.forward. I should have used Vector3.forward. My bad, you could not have solved my problem, because I didn't post my moving codesasha199568

1 Answers

3
votes

You are currently just rotating the object, not setting its rotation. Instead of transform.Rotate(...) you should be using:

transform.rotation = Quaternion.Euler(0, 0, angle);