Reputation: 43
I have a 3D game, where my camera is looking at all my terrain, and I have a character that moves with an Xbox controller. I want my character to only move in the direction that it is looking, not to the sides. I have the next code that makes my character move.
void Update()
{
MoveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = MoveInput * MoveSpeed;
Vector3 PlayerDirection = Vector3.right * -Input.GetAxisRaw("RHorizontal") + Vector3.forward * -Input.GetAxisRaw("RVertical");
if (PlayerDirection.sqrMagnitude > 0.0f)
{
transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
}
The character moves with the left side of the controller, and with the right side, I can move the direction that is facing.
Upvotes: 1
Views: 209
Reputation: 43
I found a solution, here is the code:
MoveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical"));
moveVelocity = MoveInput * MoveSpeed;
Vector3 PlayerDirection = Vector3.right * Input.GetAxisRaw("Horizontal") + Vector3.forward * Input.GetAxisRaw("Vertical");
if (PlayerDirection.sqrMagnitude > 0.0f)
{
transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
}
Upvotes: 0
Reputation: 20249
Currently, you're using the inputs as x and z components of a world space direction. It doesn't take into account the rotation of the character at all.
Instead, you should multiply the inputs and the corresponding local direction in world space, and then combine them. In your case, this might look like this:
MoveInput = (
transform.right * Input.GetAxisRaw("Horizontal")
+ transform.forward * Input.GetAxisRaw("Vertical")
).normalized;
moveVelocity = MoveInput * MoveSpeed;
Vector3 PlayerDirection = Vector3.right * -Input.GetAxisRaw("RHorizontal")
+ Vector3.forward * -Input.GetAxisRaw("RVertical");
if (PlayerDirection.sqrMagnitude > 0.0f)
{
transform.rotation = Quaternion.LookRotation(PlayerDirection, Vector3.up);
}
The normalized
is so you don't move faster diagonally.
Upvotes: 2