I am trying to make a turret gun rotate towards the mouse. The game is in 2D and the the turret gun is under turret gameobject rotated 90 degrees on x axis and 180 degrees on y axis and the gun has local rotation of 180 degrees on y axis and 180 degrees on z axis. So I want the lookrotation to only rotate on local y axis of the gun. Tried looking for solutions around but couldn't find any. Hope someone can help me with this. Also, if you need more information, go ahead and ask. Code (CSharp): using UnityEngine; using System.Collections; public class testi : MonoBehaviour { public Vector3 newDir; public bool mouseObj; public Transform target; void Start () { } void Update () { if(!mouseObj){ Vector3 targetDir = target.position - transform.position; newDir = Vector3.RotateTowards(transform.up, targetDir, 1 * Time.deltaTime, 0.0F); transform.rotation = Quaternion.LookRotation(newDir); }else{ Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); pos[2] = 0; transform.position = pos; } } }
Nevermind, I got the issue fixed by adding a "testObj" GameObject into the scene at the same position as the turret gameobject and then changing the code to Code (CSharp): using UnityEngine; using System.Collections; public class turret : MonoBehaviour { public Transform rotObj; void Start () { } void Update () { if(transform.localEulerAngles[1] < 150){ transform.localEulerAngles = new Vector3(0, 150, 180); } if(transform.localEulerAngles[1] > 210){ transform.localEulerAngles = new Vector3(0, 210, 180); } Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition); pos[2] = 0; Vector3 targetDir = pos - transform.position; Vector3 newDir = Vector3.RotateTowards(-transform.right, targetDir, 0.5f * Time.deltaTime, 0.0F); rotObj.rotation = Quaternion.LookRotation(newDir); if(rotObj.localEulerAngles[1]-90 > 150 && rotObj.localEulerAngles[1]-90 < 210){ transform.localEulerAngles = new Vector3(0, rotObj.localEulerAngles[1]-90, 180); } } }
I am trying to follow your example but I got some questions. Your explanation says 2D. Is it simple 2D top-down? x = east/west, Y= north/south, Z=not used (or maybe used for layering) Is it 2D top-down view in 3D? x = east/west, Z= north/south, Y=not used (or maybe used for layering) or simple 2D side view: x = east/west, Y=up/down, Z= depth (for things in background like parallax scrolling)?
Well, it's x = west/east, y = up/down and z = layering, but I'm not sure if the code is adaptable like that. If it isn't, tell me and I'll see if I can help. (Also, sorry replying took so long... I just recently started checking this email's inbox.)