Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by martin101 · Dec 29, 2014 at 05:07 PM · rotationquaternionrotaterotate objectrotatearound

Rotate object in the direction where it is going

I am using horizontal and vertical information from the input and then trying to move object in X and Y plane *there is no use of Z axis now as my player moves in the 2D plane i would like to rotate the front of the player in the respective direction as well

as seen in the image the player moves from UP to RIGHT and hence the front of the Player rotates to Right as well

I am missing out the Implementation of Quaternion. i have tried several approach but its just not working

I need help in rotating the front of the object where the object is going. i have seen some solution but they are not fitting in my case here is my script

 using UnityEngine;
     using System.Collections;
     using UnitySampleAssets.CrossPlatformInput;
     
     public class PlayerController : MonoBehaviour {
     
         public float speed = 5f;
         private Quaternion currentRotation;
         private Quaternion targetRotation;
         private Vector3 relativeRotation;
         public float rotationSpeed = 360f;
         public float h,v;
     
         // Use this for initialization
         void Start () {
         
         }
         
     //    // Update is called once per frame
     //    void Update () {
     //        h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
     //        v = CrossPlatformInputManager.GetAxisRaw("Vertical");
     //
     //        Vector3 movement = new Vector3 (h, v, 0.0f);
     ////        if(movement != Vector3.zero)
     //            Move (movement);
     //    }
     //
     //    public void Move(Vector3 movement) 
     //    {
     ////        rigidbody.velocity = movement * speed;
     //        targetRotation = Quaternion.LookRotation (movement);
     //        transform.eulerAngles = Vector3.up * 
     //                Mathf.MoveTowardsAngle (
     //                transform.eulerAngles.z,
     //                targetRotation.eulerAngles.z,
     //                rotationSpeed * Time.deltaTime);
     //    }
     
         // Update is called once per frame
         void Update () {
             h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
             v = CrossPlatformInputManager.GetAxisRaw("Vertical");
     
     //        Vector3 movement = new Vector3 (h, v, 0.0f);
             Vector2 movement = new Vector2 (h, v);
     
             rigidbody.velocity = movement * speed;
     //        relativeRotation = transform.;
             transform.rotation = Quaternion.LookRotation (relativeRotation);
     
     
         }
     }


alt text

rotation.png (18.0 kB)
Comment
Add comment · Show 9
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image martin101 · Dec 29, 2014 at 05:08 PM 0
Share

@2dkot please refer to this question ( i was unable to edit the previous one UA bug )

avatar image Oliver1135 · Dec 29, 2014 at 06:46 PM 1
Share

this looks like the same problem you are having I just happened to see it, this may be the asnwer you are looking for

http://answers.unity3d.com/questions/630670/rotate-2d-sprite-towards-moving-direction.html

avatar image Scribe · Dec 29, 2014 at 07:07 PM 1
Share

perhaps the following would work:

 transform.rotation = Quaternion.LookRotation(Vector3.forward, new Vector3(movement.x, movement .y, 0f));

Sorry, I hadn't read properly, this should orientate your transform so its 'forward' points along forward and its 'up' (y axis) points along the direction of 'movement'.

avatar image Scribe · Dec 29, 2014 at 10:15 PM 1
Share

No problem! Check the link to documentation here to get started. Transform.rotation is of type 'Quaternion' which is a way of representing an orientation, what you see as rotation in the inspector is not the same, that representation is called an 'Euler angle' (and isn't so good due to ambiguity etc). So this is a Quaternion class method which produces a Quaternion type with an orientation such that the z-axis of a transform points along the first argument, and the y-axis points along the second argument given.

Hence Quaternion.LookRotation(Vector3.forward, new Vector3(movement.x, movement .y, 0f)); creates a rotation that points your objects 'forward' direction along Vector3.forward and points the 'up' direction along new Vector3(movement.x, movement .y, 0f) which is the same as the direction of movement.

As for why it snaps back, in the code there is no refrence to clicking a button at all so I cannot help unless you also post the code concerning the button clicking/releasing!

Glad I could help,

Scribe

avatar image Scribe · Jan 01, 2015 at 01:56 PM 1
Share

Try wrapping it in an if statement, you might have to play with the value of 0.1 that I have used as that it just a guess but it should work:

 if(movement.sqr$$anonymous$$agnitude > 0.1f){
     transform.rotation = Quaternion.LookRotation(Vector3.forward, new Vector3(movement.x, movement.y, 0f));
 }
Show more comments

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Glurth · Dec 29, 2014 at 09:28 PM

I think ArcTangent is the function you are looking for.

Given an x,y point on a plane, ArcTangent defines the angle between the x-axis and a line between the origin and that point as follows: Angle = Arctan(y/x)

(http://en.wikipedia.org/wiki/Inverse_trigonometric_functions check out the section “application: finding the angle of a right triangle.”) Use your velocity vector’s x and y in ArcTangent to get the angle.

 float h = CrossPlatformInputManager.GetAxisRaw("Horizontal");
 float v = CrossPlatformInputManager.GetAxisRaw("Vertical");
 float angle = Mathf.Atan (v / h); 
 //now that we have the angle, it’s easy to generate the quaternion.
 transform.rotation = Quaternion.AngleAxis (angle, new Vector3(0,0,1));

Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image martin101 · Jan 01, 2015 at 09:47 AM 0
Share

Hi @Glurth

 void Update()
     {
         float h = CrossPlatformInput$$anonymous$$anager.GetAxis("Horizontal");
         float v = CrossPlatformInput$$anonymous$$anager.GetAxis("Vertical");
         float angle = $$anonymous$$athf.Atan (v / h);// * $$anonymous$$athf.Rad2Deg; 
         //now that we have the angle, it’s easy to generate the quaternion.
         transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
     }


using this does not rotate the player and

 void Update()
     {
         float h = CrossPlatformInput$$anonymous$$anager.GetAxis("Horizontal");
         float v = CrossPlatformInput$$anonymous$$anager.GetAxis("Vertical");
         float angle = $$anonymous$$athf.Atan (v / h) * $$anonymous$$athf.Rad2Deg; 
         //now that we have the angle, it’s easy to generate the quaternion.
         transform.rotation = Quaternion.AngleAxis (angle, Vector3.forward);
     }

multiplying the player angle with Rad2Deg works but only for first and second quadrant i.e. upto 180 degrees

please take a look

avatar image Glurth · Jan 01, 2015 at 05:37 PM 1
Share

Good call on the Rad2Deg, totally missed that!
I also missed the divide by zero error that will occur if "h" is ZERO. To avoid the divide by zero error use Atan2(x,y), rather than the Atan(x/y) I originally posted. (http://docs.unity3d.com/ScriptReference/$$anonymous$$athf.Atan2.html)

Regarding it only making is half way through a circle: sounds like Rad2Deg, needs to be multiplied by 2.0f (though that is indeed odd, I'll test it out myself & post back what I find).

EDIT: $$anonymous$$y tests show Atan2(x,y)*Rad2Deg does indeed return a full circle, which works with AngleAxis function just fine. I used lots of Debug.Log to confirm this (as well as graphics output), to narrow down any possible issues. (though perhaps simply switching to Atan2, will do the trick (I didn't test Atan). Here is my code, though it works on a different axis from yours it's almost identical otherwise. The last line shows how I animate the rotation to make it smoother.

     Transform t = GetComponent<Transform> ();
     
     speed.x = Input.GetAxis ("Horizontal");
     speed.y = Input.GetAxis ("Vertical");

     Debug.Log ("X,Y :" + speed.x.ToString() +","+speed.y.ToString());
     float ang = $$anonymous$$athf.Atan2 (-speed.x, speed.y);
     Debug.Log ("AngleR :" + ang.ToString());
     ang = ang * $$anonymous$$athf.Rad2Deg;
     Debug.Log ("AngleD :" + ang.ToString());
     Quaternion qtan = Quaternion.AngleAxis (ang, new Vector3 (0, -1, 0));
     t.rotation = Quaternion.RotateTowards (t.rotation, qtan, 700 * Time.deltaTime);

avatar image martin101 · Jan 01, 2015 at 06:32 PM 0
Share

@Glurth thanks so much for that effort ^_^ i love Unity Answers.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

29 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

When applying a 90 degree rotation to Euler Angles, it is over/undershooting sometimes.. 2 Answers

Quaternion, eulerAngles, localEulerAngles Driving me mad 1 Answer

How to turn a car like in real world? 1 Answer

360° Roation in one min 1 Answer

rotate object around another object 1:1 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges