Rotation of game objects?

I would like my spaceship game object to be facing forward as if its flying the right direction like this: Screen capture - a8f66c6de237a5014be406a8ac393f35 - Gyazo
The issue is that my spaceship is spawned randomly on the circumference of a circle so the way it is facing can be wrong, like this: Screen capture - d22dbb6a6cad71fbbe5efc508b3254ac - Gyazo
This happens when it is spawned in certain locations around the circle’s circumference.
I’m not sure how to transform.Rotate so that my game object faces the way I want no matter where it spawns on the cirumference.

my code currently:

public class SpaceShip : MonoBehaviour
{
    public GameObject ship;
    // Start is called before the first frame update
    void Start()
    {
        float theta = Random.Range(0f, 10f) * Mathf.PI * 2;
        float randomPosx = Mathf.Cos(theta) * 10;
        float randomPosZ = Mathf.Sin(theta) * 10;
        Vector3 position = new Vector3(randomPosx, 1.0f, randomPosZ);
        ship = Instantiate(ship, position, Quaternion.identity);
        ship.transform.Rotate(100f, 0f, 0f, Space.World);
    }

    // Update is called once per frame
    void Update()
    {
        ship.transform.RotateAround(Camera.main.transform.position, Vector3.up, Random.Range(20f, 40f) * -Time.deltaTime);
    }
}

One note: I don’t think you need the Random.Range(0f, 10f) * Mathf.PI * 2 for theta, just Random.Range(0f, Mathf.PI * 2), which would be one complete circle of possible angles.

Not sure about the rotation issue though.

If your ship prefab is +Z forward, then you can just use transform.LookAt(yourCenterObject.transform.position); and it will look there.

If not, probably easiest to remake the ship prefab so this is true.

1 Like