I’ve written code blocks for turrets and a target on a sphere.
See the attached files for a sample picture.
My goal is that Turret_1 and Turret_2 aim at the target continuously. Turret_1 and Turret_2 rotate only on the y-axis. The target spins around the sphere. I couldn’t solve the problem in my script. Turret_2 does not move at all. Turret_1 is aiming at the target but if the target is moving towards turret_1, it is not aiming at the target.
public class Target : MonoBehaviour {
public float targetSpeed;
void Update () {
transform.RotateAround(Vector3.zero, transform.right, targetSpeed * Time.deltaTime);
}
}
public class Turret : MonoBehaviour {
public Transform target;
public float rotateSpeed;
private Rigidbody rb;
private Vector3 direction;
private float rotateAmount;
void Start () {
rb = GetComponent<Rigidbody>();
}
void Update () {
TurretDirection();
}
void TurretDirection()
{
direction = target.position - transform.position;
direction.Normalize();
rotateAmount = Vector3.Cross(direction, transform.forward).y;
rb.angularVelocity = -rotateSpeed * rotateAmount * transform.up;
}
}
