Search Unity

Question Help with rotating turret

Discussion in 'Editor & General Support' started by FrogMan78, Feb 26, 2024.

  1. FrogMan78

    FrogMan78

    Joined:
    Mar 31, 2023
    Posts:
    1
    Hello! I'm still very new to Unity, and am currently attempting to make a turret object in my 3D Unity game, whose head will look in the direction of the player once the player gets close enough to the turret. However, whenever the player gets close enough to the turret, the turret's head will in fact rotate, however it will end up facing the wrong direction. The turret does rotate every time the player gets close enough, just not in the right direction. Below is the code attached to the turret object:

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using Unity.VisualScripting;
    5. using UnityEngine;
    6.  
    7. public class Turret_script : MonoBehaviour
    8. {
    9.     public Transform Head;
    10.     public Transform yes;
    11.     private  Quaternion originalRot;
    12.     // Start is called before the first frame update
    13.     void Start()
    14.     {
    15.  
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.      
    22.     }
    23.  
    24.     public void StartTurret (GameObject objToLock) {
    25.         print("yes");
    26.         Vector3 direction = (objToLock.transform.position - Head.transform.position).normalized;
    27.         Quaternion rotation = Quaternion.LookRotation(direction);
    28.         Head.rotation = rotation;
    29.     }
    30.  
    31.  
    32.  
    33.  
    34. }
    35.  
    StartTurret is called from another game object (Turret_Radius), which shares the same parent as the turret head. I feel like this is something that's really easy to fix, but I'm absolutely stumped.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686