2d bullet rotation - nearly there...

Hi,

Here’s my code of shooting via a joystick, the bullet shoots in the right direction, faces the camera fine, BUT doesn’t rotate around the Z (right axis?) so the points in the direction it should ;(

					Vector3 shootDirection = new Vector3(Input.GetAxis("FireHorizontal"),Input.GetAxis("FireVertical") * -1f, 0).normalized;

					Vector3 _fireFromHere = fireFromHere.transform.position;

					// create bullet
 					GameObject bulletInstance = Instantiate(bullet,_fireFromHere,Quaternion.identity) as GameObject;	// wrong angle

					// face direction ready to shoot....
					float angle = Vector3.Angle(Vector3.zero, shootDirection);
					Quaternion rot =  Quaternion.AngleAxis(angle, Vector3.forward);
					bulletInstance.transform.rotation = rot;
					Debug.Log("shootDirection: " + shootDirection + "  |  angle:" + angle + "  | rot: " + rot);

					// ....shoot!
					bulletInstance.rigidbody2D.AddForce(shootDirection*bulletSpeed);

I’ve tried Vector3.forward/up/right but honestly don’t really understand the maths behind so would appreciate a hand.

Extra points for explaining how it the maths DOES work :wink:

Cheers,
Andy

Some time ago I had a similar task - to make my main object rotate to the destination point. Here is my code, maybe it will help you:

// Calculate the distance between the destination and the farmer.
Vector3 distance = destination - transform.position;

// Calculate the angel between them.
float angle = Mathf.Atan2(distance.y, distance.x);

// Make the angle a bit larger.
angle *= 20;

// And round it to zero if it's too small.
if (Mathf.Abs(angle) < 1)
        angle = 0;

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

Nope, gives the same result. thanks anyway.

Sorry to necro, but THANK YOU Maklaud. After a day or two of hxc googling your solution helped me solve the same problem as OP.

In case it can help anyone else:

the orientation of the original gameobject/sprite will change the value multiplied in line 8 of Maklaud’s example. Just play around!