Getting a pivoted look at in 2D
I'm trying to get a gameobject to pivot around an origin and look at other gameobject as they are coming at it. Currently, I am using this:
Vector3 direction = transform.Find ("turretGun").transform.position - gameTarget.transform.position;
transform.Find ("turretGun").transform.RotateAround (new Vector3 (transform.Find ("turretGun").transform.position.x, transform.Find ("turretGun").transform.position.y, transform.Find ("turretGun").transform.position.z), new Vector3(0, 0, 1), Mathf.Lerp(transform.rotation.z, Quaternion.AngleAxis(Mathf.Atan2(direction.y, direction.x) * 180 / Mathf.PI, new Vector3(0, 0, 1)).z, Mathf.SmoothStep(0.0f, 1.0f, rotateSpeed)));
I'm having a lot of trouble getting it to both look at and pivot around the point. I was able to get a look at replication using:
Quaternion.Lerp(transform.rotation, Quaternion.AngleAxis(Mathf.Atan2(direction.y, direction.x) * 180 / Mathf.PI, new Vector3(0, 0, 1)), Mathf.SmoothStep(0.0f, 1.0f, rotateSpeed));
The issue was also making sure it stayed around its pivot. Any ideas?
Edit: I should also mention that the starting Z rotation for parent is -180 while the child is set to -90. I am trying to rotate the child while keeping the parent locked in place.
Answer by Gordrik · Apr 04, 2018 at 11:11 AM
So just attach rotation to the child object, child doesn't affect parent, also I would use
transform.LookAt(target);
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
Hope this will help
Answer by TEEBQNE · Apr 04, 2018 at 04:11 PM
@Gordrik Using lookAt in 2D makes it rotate in other axes than just the Z. I was able to isolate rotating in the Z with lookAt but it did not give me accurate results. This is what I ended up using that worked:
Vector3 difference = gameTarget.transform.position - transform.Find("turretGun").position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.Find("turretGun").transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ-90f);
I had to subtract the 90f in the Z as the rotation started out at 90 initially.