Ayhem
Ayhem

Reputation: 247

Moving in world space while looking at the mouse position

I am trying to move the player using the WASD keys while it always looking at the mouse position. My problem is the W key will always move the player toward the mouse position while i want it to keep moving using the world space. This is the code for moving the player.

private void FixedUpdate()
{ 
    MovementHandler();
    RotationHandler();
}

void MovementHandler()
{
    float hInput = Input.GetAxisRaw("Horizontal");
    float vInput = Input.GetAxisRaw("Vertical");
    float speed = Input.GetButton("Run") ? runSpeed : walkSpeed;

    Vector3 hMovement = characterController.isGrounded == true ? transform.forward * vInput : Vector3.zero;
    Vector3 vMovement = characterController.isGrounded == true ? transform.right * hInput : Vector3.zero;

    characterController.SimpleMove(Vector3.ClampMagnitude(hMovement +    vMovement, 1) * speed);
}

void RotationHandler()
{
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    if (Physics.Raycast(ray, out RaycastHit hit, 100, groundMask))
    {
        transform.LookAt(hit.point);
    }
}

thank you.

Upvotes: 0

Views: 68

Answers (1)

derHugo
derHugo

Reputation: 90630

You are using the objects local space transform.forward and transform.right

If you rather wanted world space axis for the movement I guess you should rather use Vector3.forward and Vector3.right

var hMovement = characterController.isGrounded ? Vector3.forward * vInput : Vector3.zero;
var vMovement = characterController.isGrounded ? Vector3.right * hInput : Vector3.zero;

You should in general use Update for frame based movements and user interactions!

FixedUpdate should only be used for stuff related to the Physics (like e.g. RigidBody movement and forces).

private void Update()
{ 
    MovementHandler();
    RotationHandler();
}

Upvotes: 2

Related Questions