Home > Net >  Unity - Virtual Joystick - Camera rotation
Unity - Virtual Joystick - Camera rotation

Time:05-31

I have a virtual movement joystick that I'm using to control the movement of a player object which works fine, the code for this is below.

The problem I have is when I rotate the camera within game mode (or device) the direction is not adjusted according to the cameras rotation, exactly like is shown in enter image description here

Mind, that I just put up some random values there, but you get the idea.

Now, your problem is, that this angle you get from your raw input is static in direction, meaning that it doesn't rely on the camera's face direction. You can solve this problem by "locking it to the camera", or in other words, rotate the input direction based on the camera rotation. Here's a quick example:

//Get the input direction
float inputX = joystick.Horizontal();
float inputY = joystick.Vertical();
Vector3 inputDirection = new Vector3(inputX, 0, inputY);

//Get the camera horizontal rotation
Vector3 faceDirection = new Vector3(cameraTransform.forward.x, 0, cameraTransform.forward.z);

//Get the angle between world forward and camera
float cameraAngle = Vector3.SignedAngle(Vector3.forward, faceDirection, Vector3.up);

//Finally rotate the input direction horizontally by the cameraAngle
Vector3 moveDirection = Quaternion.Euler(0, cameraAngle, 0) * inputDirection;

IMPORTANT: The code above should be called in the Update cycle, since that is where you get the input information.

After this, you can work with moveDirection to move your player. (I suggest using physics for moving, instead of modifying its position)

Simple moving example:

public RigidBody rigidbody;
public Vector3 moveDirection;
public float moveSpeed = 5f;

void FixedUpdate()
{
   rigidbody.velocity = moveDirection * moveSpeed;
}
  • Related