I just added 3 objects to my scene to a new project. To be sure where the problem is I created a new project.
Then added to the scene: 2 Cubes and 1 Sphere 1 empty GameObject.
Cube is the target.
Sphere and Cube (1) are the Turret and both are childs of the empty GameObject. The script is attached to the empty GameObject.
The logic say if I will rotate the empty GameObject both Sphere and Cube (1) will rotate at the same time. But I found that if I'm not setting both Sphere and Cube (1) same direction before running the game they will never face to the target only the Sphere.
I had to figure out where is the Sphere facing direction before running the game and change the Cube (1) to face the same direction of the Sphere on the Z Blue axis.
I can't figure out yet and understand why is it so hard to rotate two objects at the same time to be facing the same direction (target).
Now it's working once the sphere and the cube (1) are facing same direction before running the game. It didn't work if I made them childs or parents or changed the Cube (1) position to 0,0,0 nothing.
They were both rotating but never faced the target only the Sphere faced the target.
So now each time I want to rotate two objects at the same time to face another gameobject like a turret, or cannon or anything that is built of two parts I need first to make them facing same direction ?
I guess I did something wrong but not sure what.
The script:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rotateturret : MonoBehaviour { public float speed = 3.0f; public GameObject m_target = null; Vector3 m_lastKnownPosition = Vector3.zero; Quaternion m_lookAtRotation; private void Start() { } // Update is called once per frame void Update() { if (m_target) { if (m_lastKnownPosition != m_target.transform.position) { m_lastKnownPosition = m_target.transform.position; m_lookAtRotation = Quaternion.LookRotation(m_lastKnownPosition - transform.position); } if (transform.rotation != m_lookAtRotation) { transform.rotation = Quaternion.RotateTowards(transform.rotation, m_lookAtRotation, speed * Time.deltaTime); } } } bool SetTarget(GameObject target) { if (!target) { return false; } m_target = target; return true; } } Here is a link for a short video clip I recorded showing what I mean:


LookAt, Unity will rotate the transform so that the forward vector is pointing at the given position. So align the cannon with the forward vector of your sphere. \$\endgroup\$