Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Gun turret with rotation problems

Discussion in 'Scripting' started by Powersurge, Aug 6, 2015.

  1. Powersurge

    Powersurge

    Joined:
    Jun 9, 2014
    Posts:
    9
    Hi all,
    I have a model of a gun turret, the turret will rotate horizontally to track the target, the gun (a child of the turret) will rotate up and down to track the vertical movement of the target, all sitting on a base, so only 3 primary components. In a sense , it is exactly the same as a tank turret rotating towards a target then aiming the gun up and down.
    The body is a child object of a pivot (turret_pivot) .
    The gun is a child object of another pivot (gun_pivot), this pivot is a child of turret_pivot.
    This is so that everything turns horizontally when I rotate the turret_pivot horizontally, and then I rotate the gun_pivot vertically, leaving the body of the turret horizontal.
    I thought this would be straight forward, but have encountered some strange issues; once the target moves to z=0 distance, the guns point directly upwards, and once z goes negative (target moves behind the turret), the turret continues to rotate forwards, exactly 180 degrees ie mirroring where it should be pointing.

    var dir1 :Vector3 =(CurrentTarget.position-transform.position).normalized; //points at the target

    var dir2 :Vector3 =(CurrentTarget.position-transform.position).normalized ;

    dir1.y = 0; // keep only the horizontal direction
    dir2.x=0;; //keep only the vertical direction





    var rot1 = Quaternion.LookRotation(dir1); //for rotating the body and gun pivot
    var rot2= Quaternion.LookRotation(dir2); //for rotating the gun, it will look up and down

    turet_pivot.localRotation = Quaternion.Slerp(turet_pivot.localRotation, rot1, 25*Time.deltaTime);
    gun_pivot.localRotation = Quaternion.Slerp(gun_pivot.localRotation, rot2, 25*Time.deltaTime);
     
  2. sterynkng14

    sterynkng14

    Joined:
    Sep 19, 2013
    Posts:
    36
    Why not try Transform.LookAt? Or are you trying to do it over time, like control the speed of the turrets rotation?