Hi guys, I am currently doing a 2D game for Android.
Let’s say I would like Rockets to spawn a bit everywhere, and when they spawn, they face towards the center of the screen (0,0) and they move slowly towards it.
My Rocket is a sprite which faces left.
I have a script which is in charge of spawning them in a random location.
I thought: First I have to rotate the sprite in order to make the left (direction of the rocket) facing the center. So I wrote it in its Start function:
void Start() {
Vector3 vec = new Vector3 (-transform.position.x, -transform.position.y, 0f).normalized;
angle = Vector3.Angle (Vector3.left, vec);
if (transform.position.y > 0)
transform.Rotate (Vector3.forward, angle, Space.Self);
else
transform.Rotate (Vector3.forward, -angle, Space.Self);
}
When I launch the game, I can see that Rockets are well oriented.
In the update function, to go towards the center I wrote this:
void Update () {
float random1 = Random.Range (0.02f, 0.06f);
float random2 = Random.Range (0.02f, 0.06f);
Vector3 vec = new Vector3 (-transform.position.x, -transform.position.y, 0f).normalized;
Vector3 tr = new Vector3 (vec.x * random1, vec.y *random2, 0f);
this.transform.Translate (tr);
}
If I don’t use the rotation, it works. I mean rockets are going to the center even if not well oriented. My problem is that when I activate both Rotation & Translation, they are doing weird things like circles and I can’t figure out why. I mean, I am supposed to have done the rotation on start (so only once), and then only for every update, translating my sprite along the vector to the origin.
What am I doing wrong?