Search Unity

Making an object turn to target

Discussion in 'Scripting' started by Markuinhos, Oct 13, 2015.

  1. Markuinhos

    Markuinhos

    Joined:
    Sep 2, 2015
    Posts:
    6
    Hi, I am trying to make my turret turn towards the target as soon as it enters the collider range.
    I tried using the following code but it only makes the turret turn sideways, is there anyway I can specify which direction of the turret is forwards, so it can face the target?

    public Transform target;

    void Update () {
    target = GetComponent<Tower> ().myTarget;
    if (target)
    transform.LookAt(target);
    }
     
  2. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    That code is correct. The most likely case is that the turret's model isn't aligned with the "forwards" direciton in Unity, which is positive Z.

    If you made the model then rotate it and re-export it in your 3D package. If you didn't then you can stick it in a child game object and rotate that accordingly, running the script on an unrotated parent.
     
  3. Markuinhos

    Markuinhos

    Joined:
    Sep 2, 2015
    Posts:
    6
    Sorry I am still new to this.
    I made the model with blender and I am not sure I understood correctly, but I tried rotating the turret to face the positive Z axis and it doesnt work.
     
  4. angrypenguin

    angrypenguin

    Joined:
    Dec 29, 2011
    Posts:
    15,620
    Saying "it doesn't work" doesn't give us any useful information to help you with. What does it do or not do that is relevant to what you're trying to achieve?

    Something worth noting is that the axes in different programs don't line up with each other. In Unity "up" is positive Y, "right" is positive X and "forwards" is positive Z. In Blender that might not be the case, so to have something facing "forwards" you might need it to point along a differently labelled axis.

    An easy way to find out what the different directions are labelled is to look at a camera, since it has clearly defined forwards (the direction of the rendered picture), up (the top of the rendered picture) and right directions.
     
  5. Markuinhos

    Markuinhos

    Joined:
    Sep 2, 2015
    Posts:
    6
    All good, I figured it out, thanks!