Skip to content
  • Clay 
  • Uncategorized

[Unity] Rotate the Image With the Virtual Joystick

Last Updated on 2021-10-26 by Clay

Today I want to record how to rotate the image with virtual joystick in Unity. The configuration tutorial of virtual joystick you can refer: [Unity] How to Configure The Virtual Joystick and Move Object

You need to know the following two operations for image rotation:

  • How to rotate the image
  • How to get the angle of joystick movement (Hint: It is the angle of two vectors)

The function is usually used in 2D games to operate the player character to rotate direction.


How to rotate the image

Create a Rotation.cs script, and attach it to the image your want to rotate.

using UnityEngine;
using System.Collections.Generic;

public class Rotation : MonoBehaviour {
    private float pr = 0f;

    void Update() {
        transform.localEulerAngles = new Vector3(0, 0, ++pr);
    }
}



Output:


How to get the angle of joystick movement

First at all, it is recommended to configure the virtual joystick according to [Unity] How to Configure The Virtual Joystick and Move Object. You will find that the direction in the program can actually be regarded as a vector.

In the update() function, we can treat the direction of the current time point and the direction of the previous time point as vectors, and then we can use the previous section’s code to rotate the image.

In Unity, the angle can be obtained by using Vector2.SignedAngle().

float angle = Vector2.SignedAngle(newDirection, oldDirection);



Remember to use a signed-angle to rotate, otherwise your image will just rotate clockwise or counterclockwise.


References


Read More

Tags:

Leave a Reply