- Home /
How to control a 2d character in an top-down android game with the standard joystick?
So I'm building a 2d top-down game and I need to control my character using unity cross-platform standard asset single joystick.
The problem is with the rotation, I don't want to use the dual-stick for some idea related reasons and the designs and the game mechanics that was considered for this game.
So I want the character to have the same rotation as the joystick and since the joystick only has the horizontal and the vertical axies it's hard to get a descent rotation.
So any ideas how to do this? if you need further clarification let me know.
You can solve this in different ways. you can use Atan2(x, y) for the angle of the joystick and set the y angle of the player. or if you also move you can do something like Quaternion.LookDirection(your direction, up).
Atan2(x,y) Fixed my problem thank you. I didn't know what it does so I ignored it.
Answer by ahmadian · Jan 09, 2017 at 05:54 AM
as @hoekkii said, in the mathf class there is a function called Atan2, which is exactly what is needed here.
So all that is needed to be done is to use the mobile single stick control in the cross-platform standard assets and get the Horizontal and Vertical axis from that and use the Atan2 to get the radiant and then turn it to degrees and use it to set the z angle of the player.
Player.transform.eulerAngles = new Vector3(0, 0, -(Mathf.Atan2(CrossPlatformInputManager.GetAxis("Horizontal"), CrossPlatformInputManager.GetAxis("Vertical")) * Mathf.Rad2Deg));
or for simplicity :
float Haxis = CrossPlatformInputManager.GetAxis("Horizontal");
float Vaxis = CrossPlatformInputManager.GetAxis("Vertical");
float Zangle = Mathf.Atan2(Haxis, Vaxis) * Mathf.Rad2Deg;
Player.transform.eulerAngles = new Vector3(0, 0, -Zangle);
Thanks a lot I've been trying to solve this for over 3 days.
Your answer
Follow this Question
Related Questions
2D mobile: Need my character to rotate Z axis towards touch position 0 Answers
Rotating a 2D object when the phone is rotated 1 Answer
I'm attempting to make a character face the joystick in a top down unity2d game. 1 Answer
Rotate GameObject Z axis only relative to Joystick 0 Answers
Please can someone explain how i use the joystick prefab for 2d. 0 Answers