Search Unity

Rotate object based on movement direction

Discussion in 'Scripting' started by Andebass, Sep 2, 2014.

  1. Andebass

    Andebass

    Joined:
    Jan 23, 2014
    Posts:
    2
    I have done a lot of research on the web the last few days, but at no luck on this subject.

    What I'm trying to achieve:
    I am making a top-down shooter game with spaceships.
    I have a script attached to a prefab (enemy) that will make them spawn after a given time.
    They move from top to bottom (z-axis) before being destroyed. They also move along the horizontal axis while moving down. This movement is changed to the oposite direction after 2.5sec.

    The problem here is that the enemy object is allways facing the same way (straight down).
    I want the enemy to look at the direction they are traveling, and when they change to the oposite horizontal direction, the rotation changes with it (with a fast but smooth motion).

    Is this possible without the object having a move-to-target?

    EDIT:
    I am using C# btw.

    thx!
     
  2. Andebass

    Andebass

    Joined:
    Jan 23, 2014
    Posts:
    2
    Bump.

    - Really need this!
     
  3. Kirlim

    Kirlim

    Joined:
    Aug 6, 2012
    Posts:
    126
    There are maaaaaaanyyy ways of achieving this.

    Examples:
    1) Change the object rotation, and move it using the transform.Translate method (with local space)
    http://docs.unity3d.com/ScriptReference/Transform.Translate.html

    2) Get a pair of position (current and next, or previous and current), subtract older from newer, throw it into Mathf.Atan2, convert the radians angle into euler degrees, and set as object rotation.

    Edit:
    About smooth rotation, you can gradually make the current object rotation match the desired angle:
    http://docs.unity3d.com/ScriptReference/Mathf.MoveTowardsAngle.html