- Home /
2D mouse/touch controlled turret problems
I am quite new to unity, just started messing about with it about a week ago, and have looked at many tutorials. So I'm trying to make a 2d game for andriod, which involves using a touch controlled turret to shoot down enemies falling from the skies. I of course got stuck right away, I figured out a way for the turret barrel to point where the player the player taps, and moves, but once it goes from right to left the barrel rotates 180 on the y axis, and no matter where I look, I can't figure out why it does this, or how to fix it.
Here is my code:
private var ray : Ray;
private var rayCastHit : RaycastHit;
var aPosition = Vector3(1, 1, 1);
function Update()
{
if(Input.GetMouseButton(0))
{
ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, rayCastHit))
{
aPosition = Vector3(rayCastHit.point.x, rayCastHit.point.y, this.transform.position.z);
transform.LookAt(aPosition);
}
}
}
If you search around a bit in UA, you'll find answers to the 2D flipping issue with Transform.LookAt(). One answer here using Atan2():
http://answers.unity3d.com/questions/411419/rotationy-flips-when-turning-around-x-axis.html