Search Unity

Rotate towards object script not working as intended

Discussion in 'Scripting' started by GIitch, Jan 29, 2019.

  1. GIitch

    GIitch

    Joined:
    Aug 1, 2013
    Posts:
    24
    I'll do my best to explain this. The usage is a bit unconventional and I've had a hard time getting the purpose across to others. I'm trying to get an object to aim at the player character using a spotlight with a slight offset. This object is a visual representation of the Main Camera and should not affect its behavior or movement.

    Imagine the Lakitu camera guy from Mario Kart if that helps, but with a spot light attached.

    With that explanation in mind, this is a script I thought fit pretty well in principle, but it doesn't aim at the player like it's supposed to. Independently maybe it would work just fine, but I'd like to figure out what's wrong here.

    Code (CSharp):
    1. public class LightTarget : MonoBehaviour
    2. {
    3.     public Transform target;
    4.     public float speed = 5;
    5.  
    6.     private void update()
    7.     {
    8.         Vector3 direction = target.position - transform.position;
    9.         Quaternion rotation = Quaternion.LookRotation(direction);
    10.         transform.rotation = Quaternion.Lerp(transform.rotation, rotation, speed * Time.deltaTime);
    11.     }
    12. }
    Here's a screenshot of how I've got things setup.
    https://i.imgur.com/jcNdlh6.png

    I've got an Empty Object (named Main Camera), Systems (the camera and other various components), and then the Drone (a simple sphere) with the Light Target script attached to it. Child to the Drone is the standard Spot Light component and a basic Cylinder to determine if the Sphere and Spot Light are rotating or not.

    Any help or suggestions would be greatly appreciated.
     
  2. eses

    eses

    Joined:
    Feb 26, 2013
    Posts:
    2,637
  3. Gurkenmensch

    Gurkenmensch

    Joined:
    Jan 27, 2017
    Posts:
    9
    Hey,

    try

    Code (CSharp):
    1. // [...]
    2. Quaternion toRotation = Quaternion.FromToRotation(transform.forward, direction); // instead of LookRotation( )
    3. transform.rotation = Quaternion.Lerp(transform.rotation, toRotation, speed * Time.deltaTime);
    Also try to put movements in FixedUpdate.
     
    Last edited: Jan 29, 2019
    steril likes this.
  4. GIitch

    GIitch

    Joined:
    Aug 1, 2013
    Posts:
    24
    Hmm. Well, it rotates with that script. But it doesn't seem to be aiming directly at the player. Modifying the rotation doesn't help, it just snaps back to the default rotation transform in Play mode.
     
  5. GIitch

    GIitch

    Joined:
    Aug 1, 2013
    Posts:
    24
    That works perfectly! Thank you so much, Gurkenmensch!
     
  6. steril

    steril

    Joined:
    Nov 30, 2014
    Posts:
    8
    I was running Quaternion.Lerp in LateUpdate and I was wondering why it was not working. Thank you.