- Home /
Rotate object towards joystick input using c#
Hey all thanks for looking!
I am looking to rotate an object towards the direction the joystick is pressed. I was able to get it to mostly function on the y and z axis but when I try to use the same number on the x angle it seems to not work correctly. Would also appreciate if someone could give me an idea of the best way to set the maximum angle of rotation. Basically I want the object to lean forward if you push forward, lean back if you press back, tilt right for right tilt left for left. Here is my current code:
using UnityEngine;
using System.Collections;
public class InnerMotor : MonoBehaviour {
public GameObject outtershell;
public VirtualJoystick joystick;
private Vector3 shellpos;
private float joypos;
void Update () {
shellpos = outtershell.transform.position;
transform.position = shellpos;
joypos = Mathf.Atan2(joystick.Horizontal(), joystick.Vertical()) * Mathf.Rad2Deg;
transform.eulerAngles = new Vector3(transform.eulerAngles.x,joypos,joypos);
}
Like I mentioned before when I change the eulerangle value of x to joypos it stops working correctly. Forward and backwards don't lean at all. I know I am doing something wrong here and I just dont understand the mathfunction or eulerAngles well enough yet to understand what it is. Any help greatly appreciated, thank you!
Answer by HappySlice · Jan 06, 2018 at 12:06 AM
Transform.eulerAngles = new Vector3( 0, Mathf.Atan2( Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * 180 / Mathf.PI, 0 );
Found from this thread: https://answers.unity.com/questions/361658/precise-rotation-based-on-joystick-axis-input-for.html
Your two years too late. I'm three years too late to be commenting on this.
Your answer
Follow this Question
Related Questions
Rotation Limit 2 Answers
Find the difference between the Z rotation of two GameObjects 2 Answers
Get an eular angle between 0 and 360 after calculations 2 Answers
Mathf.SmoothDamp freeking out? 0 Answers
Clamp Rotation Problem 1 Answer