komtan
komtan

Reputation: 81

How can I rotate player's arm with a joystick in 2D game?

In desktop version, my character's arm is rotates according to the movement of the mouse. I need the same thing in mobile version but this time I need a joystick to rotate his arm. How can I do that?

enter image description here

 //Here is my code, for rotating arm
 void Update()
{
    float horizontal = Input.GetAxis("Joy Y") * Time.deltaTime;
    float vertical = Input.GetAxis("Joy X") * Time.deltaTime;
    float rotZ = Mathf.Atan2(horizontal, vertical) * Mathf.Rad2Deg;
    transform.rotation = Quaternion.Euler(0f, 0f, rotZ); 
}

I have changed the code a bit, for now player arm is rotating but, this time there is another problem. Arm is doing unexpected movements when I try to move with joystick I think joystick is mixed with mouse. I don't know how to seperate it?

Upvotes: 0

Views: 1105

Answers (1)

Programmer
Programmer

Reputation: 125415

You make a JoyStick then replace the mouse code with JoyStick code.

Unity have Assets called CrossPlatformInputManager that can do that. You have to import it and modify it a little bit in order to use it. Watch this to understand how to import it.

Now, you can replace your Input.GetAxis and Input.GetAxisRaw functions with CrossPlatformInputManager.GetAxis("Horizontal") and CrossPlatformInputManager.GetAxisRaw("Horizontal").

If you get it to work, then can use below to make your code compatible with both mobile and desktop.

#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_WEBGL
//put your Input.GetAxis` and `Input.GetAxisRaw` code here
#elif UNITY_ANDROID || UNITY_IOS 
//Put your `CrossPlatformInputManager.GetAxis("Horizontal")` and `CrossPlatformInputManager.GetAxisRaw("Horizontal")`. here
#endif

Upvotes: 1

Related Questions