How to rotate my gameObject using Joystick control?
So, I am still a beginner C# game dev. and I am making a 2d airplane game right now and I wanted to know how I can make this feature when the joystick is faced in a direction let us say I moved the joystick to the left or the right. The player will face left or right base on where the player will move the joystick. How do I code this using the script I am using below. I still haven't figured it out yet in using quaternions or other types of rotations because of this. Can you give me the answer using a code?
public float moveSpeed;
Rigidbody2D myBody;
protected Joystick joystick;
public Joystick joysticks;
void Start()
{
joystick = FindObjectOfType<Joystick>();
myBody = GetComponent<Rigidbody2D>();
}
void Update()
{
//MOVEMENT
myBody.velocity = new Vector2(joystick.Horizontal * moveSpeed, joystick.Vertical * moveSpeed);
}
Answer by streeetwalker · Mar 29, 2020 at 12:04 PM
@S4idus , first, here is a tip: do not set rigdibody.velocity in an update function. Use rigdbody.AddForce instead. See the Unity documentation on rigidbody.velocity to learn why.
There are several ways to do rotate. One method is to get the existing rotation and apply the new rotation to it. In vectors, to move one vector by another vector you add them. In Quaternions, you multiply them, but note that Quaternion rotations are not associative. Rotating A by B may not give the same result as rotating B by A. So, A B != B A.
To rotate, you can:
rigidbody.rotation = rigidbody.rotation * Quaternion.AngleAxis( joystick.Horizontal * moveSpeed, Vector3.foward); // in 2d, Up is along the z axis.
So more full code, assuming your plane graphic's forward is the +x axis:
public float turnSpeed = some value you need to set in the inspector
void FixedUpdate()
{
// move forward on local x when moving joystick up or down
float forwardMove = joystick.Vertical;
if( forwardMove >= 0 ){ // don't allow backwards movement
myBody.AddForce( transform.right * forwardMove * moveSpeed );
}
// rotate on z axis when moving joystick left or right.
myBody.rotation = myBody.rotation * Quaternion.AngleAxis( joystick.Horizontal * turnSpeed, Vector3.foward);
}
The issue of backwards movement if you pull down on the joystick is something you'll have to refine.
Your answer
Follow this Question
Related Questions
How to Rotate Y axis of an Object toward virtual joystick direction 0 Answers
gameobject deforms when rotation changes 1 Answer
Update() child rotation first leads to flickering 0 Answers
Rotating an object by the sides 0 Answers
Rotat a GameObject and than shoot it in the New (x) direction 1 Answer