- Home /
Object moving and facing center
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?
Answer by robertbu · Sep 29, 2014 at 04:37 PM
Before anyone can give you accurate advice, you need to define clearly the behavior you want for your rockets. Do you want them to start facing the origin, or turn to the origin over time? What are you attempting to do with random1 and random2? Does the object need to collide with other objects, etc. One error jumps out. Your 'vec' is being calcuated as a world direction, but transform.Translate() is local. Try changing to:
transform.Translate(tr, Space.World);
Well, sorry for that. I wanted them to face the origin (they spawn out of the screen) when they spawn, and only then update their position. About random1 & random2, I made a mistake, I wanted to do some random speed, but I needed only one random. And thanks your answer solved the problem, I didn't know that Translate was local. thanks a lot mate.