-1

I am trying to rotate my GameObject to be facing in the direction that it is moving. I am not using Rigidbody.Velocity, I am just using transform.position to move the object. Here is my code:

public GameObject player;

void Update () 
{
    Vector3 _origPos = new Vector3(player.transform.position.x,player.transform.position.y, player.transform.position.z);

    if (Input.touchCount > 0) 
    {
        // The screen has been touched so store the touch
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Stationary || touch.phase == TouchPhase.Moved) {
            // If the finger is on the screen, move the object smoothly to the touch position
            Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));                
            transform.position = Vector3.Lerp(transform.position, touchPosition, Time.deltaTime);
            //transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,0), Vector3.up);
            Vector3 moveDirection = gameObject.transform.position - _origPos; 

        }
    }
}

Any suggestions on how to implement rotation? I am completely stumped

apxcode
  • 7,696
  • 7
  • 30
  • 41
Barney Chambers
  • 2,720
  • 6
  • 42
  • 78

3 Answers3

3

You do it using Trigonometry. You will need 3 points of reference, luckily you already have two of those.

Points needed:

  • A) Where you are going to move.
  • B) Current position at center of mass.
  • C) The tip of your object, the front.

Calculate the distance from B to C, call it x. Then calculate the distance from B to A, call it y.

Now use inverse tangent to find the angle.

angle = arctan(y/x)

Then apply it to your object's rotation.

Use world coordinates instead of local.

If you use Mathf for inverse tangent, remember it uses radians.

apxcode
  • 7,696
  • 7
  • 30
  • 41
  • thank you for your input. So there's no premade method for this in Unity3D already? – Barney Chambers Sep 10 '14 at 04:55
  • They have `LookAt()` http://docs.unity3d.com/ScriptReference/Transform.LookAt.html but that never gives me the right result so I use my generic formula above. Mathf will help http://docs.unity3d.com/ScriptReference/Mathf.html – apxcode Sep 10 '14 at 13:17
0

I would assume that you'd use Quaternion.LookRotation to orient your transform.

Something like:

Quaternion rotation = Quaternion.LookRotation(moveDirection);
player.transform.rotation = rotation;

Did a quick test with your code and that works, assuming the player GameObject forward facing direction is Z.

0

This got the desired effect for me in my 2D game.

 transform.LookAt(new Vector3(touchPosition.x,touchPosition.y,transform.position.z), Vector3.up); 

I used the objects own position.z instead of the touchPosition.z so that it stayed on it's 2D axis

Barney Chambers
  • 2,720
  • 6
  • 42
  • 78