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. Dismiss Notice

Something very basic

Discussion in 'Scripting' started by DTek, Jun 26, 2014.

  1. DTek

    DTek

    Joined:
    May 29, 2013
    Posts:
    15
    Hello to everyone :)
    I want to make a box look at my character.

    This is my code :

    Code (CSharp):
    1. public GameObject targetIs;
    2.      
    3.     void Update () {
    4.  
    5.         // detects the quaternion angle between this and hero
    6.         Quaternion targetRotation = Quaternion.LookRotation( gameObject.transform.position - targetIs.transform.position);
    7.      
    8.         // rotates to that angle
    9.         transform.rotation = targetRotation;
    10.      
    11.         // moves forward with the speed;
    12.         transform.Translate( gameObject.transform.forward  * Time.deltaTime );
    13.     }
    The problem is that even though the gameObject looks at targetIs always, it doesn't always move in that direction ( forward) . Would you happen to have any clues as why this might happen ?
     
  2. Sharp-Development

    Sharp-Development

    Joined:
    Nov 14, 2013
    Posts:
    353
    transform.Translate does take a second parameter which lets you specify the space which the movement vector is relative to. By default it translate's the object in local space, but transform.forward is infact returned in world space.

    So two solutions:
    Code (csharp):
    1.  
    2. transform.Translate( gameObject.transform.forward * speed * Time.deltaTime, Space.World );
    3. or
    4. transform.Translate( Vector3.forward * speed * Time.deltaTime );
    5.  
     
  3. Ian094

    Ian094

    Joined:
    Jun 20, 2013
    Posts:
    1,548
    Here's an even simpler way of doing it :
    Code (JavaScript):
    1. var speed = 5;
    2.  
    3. transform.LookAt(Player);
    4. transform.Translate(Vector3.forward * Time.deltaTime * speed);
     
  4. Sharp-Development

    Sharp-Development

    Joined:
    Nov 14, 2013
    Posts:
    353
     
  5. katsuragi545

    katsuragi545

    Joined:
    Jun 25, 2014
    Posts:
    38
    Use transform.LookAt to keep the box looking at the character, then you can just move the box forward using its forward vector (the blue arrow).

    Try:
    transform.Translate(box.transform.forward * moveSpeed * Time.deltaTime);
     
  6. Sharp-Development

    Sharp-Development

    Joined:
    Nov 14, 2013
    Posts:
    353
    I guess you would do good by aswell reading my first post in this thread. Your suggestion is wrong.
     
  7. katsuragi545

    katsuragi545

    Joined:
    Jun 25, 2014
    Posts:
    38
    Thanks for pointing that out. If the script is on the box then:
    transform.LookAt(target);
    transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);