After hours of head scratching and different combinations from googling, I give up!
I’m trying to write joystick for Android to use in my game.
It’s double joystick - left stick will move character, right stick will rotate it.
I have set up UI with new system from 4.6 so I have OnPress and OnDrag events and handlers.
I’m moving whole button using Touch input position - that’s working fine.
So now I want to rotate character in direction where thumbstick is being dragged.
If I understood, I need to pull through Mathf.Atan2 x and y values of position of thumbstick, then multiply this with Rad2Deg which would give me workable angle that I can use, however I couldn’t set it up properly and I never achieved result.
I tried many things and I don’t have working code but it should be along those lines :
var angle = Mathf.Atan2(touchPosition.x, touchPosition.y);// *Mathf.Rad2Deg;
PlayerGO.transform.Rotate(0, angle, 0);
Anyway, here is mess of a code of all different variations I’ve tried - I really did try
//var touchNormalx = touchPosition.x;//Mathf.Clamp(touchPosition.x, -1f, 1f);
//var touchNormaly = touchPosition.y;//Mathf.Clamp(touchPosition.y, -1f, 1f);
// var angle = Mathf.Atan2(touchPosition.x, touchPosition.y);// *Mathf.Rad2Deg;
//float cramp = Mathf.Clamp(touchPosition.x, -1f, 1f);
//float cramp2 = Mathf.Clamp(touchPosition.y, -1f, 1f);
//float angle = Mathf.Atan2(cramp, cramp2) * Mathf.Rad2Deg;
// PlayerGO.transform.rotation *= Quaternion.AngleAxis(angle, Vector3.up);
//PlayerGO.transform.eulerAngles = new Vector3(PlayerGO.transform.eulerAngles.x, Mathf.Atan2(touchNormalx, touchNormaly) * Mathf.Rad2Deg , PlayerGO.transform.eulerAngles.z);
//PlayerGO.transform.RotateAroundLocal( Vector3.up, (Mathf.Atan2(cramp, cramp2) * Mathf.Rad2Deg));
//PlayerGO.transform.Rotate(0, angle, 0);
//PlayerGO.transform.LookAt(new Vector3(0, angle, 0));
Of course, I didn’t use all lines, but tried various options.
Anyway, to sum up - I want my character to face direction of joystick dot when player moves it. I don’t want it to add to rotation - I just want it to keep setting rotation of character to rotation of touch angle.
Here is an example :
Red dot is center of thumbstick.
Arrows show direction.
Blue dot is touch position.
On the right you can see green dot - player, and red arrow, showing direction where player should look. Also, I want this to be dynamic - as in to work with actual position of touch, not just basic transform rotation.
Thank you.