Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice
  2. Ever participated in one our Game Jams? Want pointers on your project? Our Evangelists will be available on Friday to give feedback. Come share your games with us!
    Dismiss Notice

turret rotate issue

Discussion in 'Scripting' started by onur-oz, Jul 19, 2019.

  1. onur-oz

    onur-oz

    Joined:
    Jul 19, 2019
    Posts:
    3
    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.

    Code (CSharp):
    1. public class Target : MonoBehaviour {
    2.  
    3.     public float targetSpeed;
    4.    
    5.     void Update () {
    6.         transform.RotateAround(Vector3.zero, transform.right, targetSpeed * Time.deltaTime);
    7.     }
    8. }
    Code (CSharp):
    1. public class Turret : MonoBehaviour {
    2.  
    3.     public Transform target;
    4.     public float rotateSpeed;
    5.  
    6.     private Rigidbody rb;
    7.     private Vector3 direction;
    8.     private float rotateAmount;
    9.  
    10.     void Start () {
    11.         rb = GetComponent<Rigidbody>();
    12.     }
    13.    
    14.     void Update () {
    15.         TurretDirection();
    16.     }
    17.  
    18.     void TurretDirection()
    19.     {
    20.         direction = target.position - transform.position;
    21.         direction.Normalize();
    22.         rotateAmount = Vector3.Cross(direction, transform.forward).y;
    23.         rb.angularVelocity = -rotateSpeed * rotateAmount * transform.up;
    24.     }
    25. }
     

    Attached Files:

  2. Starmind01

    Starmind01

    Joined:
    May 23, 2019
    Posts:
    57
    This may not be right, but it doesn't look like you are updating the target. Have you tried putting
    transform.LookAt(target); 
    in the Update?
     
  3. onur-oz

    onur-oz

    Joined:
    Jul 19, 2019
    Posts:
    3
    so the code is completely wrong.
     
  4. Starmind01

    Starmind01

    Joined:
    May 23, 2019
    Posts:
    57
    Didn't say it was wrong. Maybe this would help you more forum.unity.com/threads/unity-turret-tutorial.341866/
     
  5. onur-oz

    onur-oz

    Joined:
    Jul 19, 2019
    Posts:
    3
    Thanks
     
unityunity