- Home /
Rotate/Flip Image in Unity 2d using Virtual Joystick
I have a problem, I have this right arrow, right? and I have made a virtual joystick using Control Freak 1.1.0. My problem is I can make this image move but the problem is that I want to rotate this image based on the movement I make in the Virtual Joystick
[1]: /storage/temp/39980-arrowhead.png
Here is the code for the Image Movement (it's in Javascript):
var power: float =1500;
var moveSpeed: float = 5;
function Update () {
 if (CFInput.GetAxis("Horizontal") || CFInput.GetAxis("Vertical"))
 {
     var h : float = CFInput.GetAxis("Horizontal") * Time.deltaTime * moveSpeed;
     var v : float = CFInput.GetAxis("Vertical") * Time.deltaTime * moveSpeed;
     transform.Translate(h,v,0);
 }
}
I really need help. I just want to make this image facing based on the direction it was moving. Thanks in advance guys!
Answer by moonstruck · Feb 02, 2015 at 02:10 PM
Try something like this if you need rotation in the XY plane:
(C# version)
     Vector3 dir = new Vector3( CFInput.GetAxis( "Horizontal" ), CFInput.GetAxis( "Vertical" ), 0 );
     float dirLen = dir.magnitude;
         
     float angle;
     
     if( dirLen < 0.01f ) {
         angle = 0;
     }
     else {
         dir /= dirLen;
     
         float a = Vector3.Dot( dir, Vector3.right );
         Vector3 x = Vector3.Cross( dir, Vector3.right );
         float b = x.magnitude;
     
         angle = Mathf.Sign( Vector3.Dot( Vector3.forward, x ) ) * Mathf.Rad2Deg * Mathf.Atan2( b, a );
     }
     
     transform.rotation = Quaternion.AngleAxis( angle, Vector3.back );
(JS version)
     var dir : Vector3 = Vector3( CFInput.GetAxis( "Horizontal" ), CFInput.GetAxis( "Vertical" ), 0 );    
     var dirLen : float = dir.magnitude;
         
     var angle : float;
     
     if( dirLen < 0.01f ) {
         angle = 0;
     }
     else {
         dir /= dirLen;
     
         var a : float = Vector3.Dot( dir, Vector3.right );
         var x : Vector3 = Vector3.Cross( dir, Vector3.right );
         var b : float = x.magnitude;
     
         angle = Mathf.Sign( Vector3.Dot( Vector3.forward, x ) ) * Mathf.Rad2Deg * Mathf.Atan2( b, a );
     }
     
     transform.rotation = Quaternion.AngleAxis( angle, Vector3.back );
when I used this code I got an error but its not showing
there is some bug i think when i move right its ok when i move left the image will rotate to left but still going right same with up and down sorry im new to unity
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                