Angle between two objects

Hello

I’m really new to Unity but since this is a 2D issue, didn’t want to go in the beginner’s forum and get 3D answers.

Anyway, the situation is this. I have a ship (Player), and a thing that orbits around it (Orbiter) in a circle. When the player presses Fire1, I want a bullet to emit from the orbiter. My Prefab looks like this:

Player

Ship
Orbiter

I’m having real trouble with this and I really shouldn’t be and feel like a total idiot for having to ask. I know how to instantiate a prefab with the position of the orbiter - the problem comes when finding the angle the bullet needs to travel at (which is basically along a line between the orbiter and the ship). I have no idea how to use the Quaternion parameter of Instantiate(), so instead I tried horrible work-arounds just for the purposes of making it work, such as pointing the bullet at the ship with LookAt, then rotating it another 180 degrees, also tried to find the angle between the ship and orbiter using Mathf.Atan2() (this is how I would have done it in Blitzmax) but that didn’t work either, which leads me to believe I’m having a bit of confusion between degrees/radians and/or world/local coords. But I just gave up in the end!

Anybody point me in the right direction (pun intended)?

Try one of these :slight_smile:

There a lot of people with the same problem, do a little more search and you will find more answers.

1 Like

Mathf.Atan2 should be able to accomplish this, but keep in mind that it returns radians and Quaternion.Euler wants degrees, so you’d have to convert it.

Thanks - I sorted it. I knew I was on the right track with Mathf.Atan2(). Where I was going wrong, was in using the position of Player and Orbiter, when I should have been using the position of Ship and Orbiter.

It still ended up 90 degrees off (hence the -90), but hey-ho!

clone = Instantiate(bullet, orbiter.transform.position,Quaternion.identity) as GameObject;
clone.transform.Rotate(0, 0, (Mathf.Atan2 (orbiter.transform.position.y - ship.transform.position.y, orbiter.transform.position.x-ship.transform.position.x) * Mathf.Rad2Deg)-90);