Movement Based On Direction Player is Facing
I am trying to figure out how to make the player's movement controls based on direction using a character controller component. As in, W should always be forwards, S backwards, etc.
The code written below makes it so that the player will only follow the world axis. W = +z, S = -z, etc. How can I make this dependent on direction?
private void PlayerMovement() {
NullifyYSpeed();
Vector3 move = new Vector3(moveInput.x, 0f, moveInput.y);
controller.Move(move * Time.deltaTime * playerSpeed);
}
I am pulling input from the new input system using unity events and callbacks. The WSAD input is placed into a Vector2 where the x component is A & D and the y component is W & S.
Answer by Chromodyne · Jul 11, 2020 at 10:15 PM
Solved it with the following kinda complex script:
private void PlayerMovement() {
NullifyYSpeed();
Vector3 desiredMove = (transform.forward * moveInput.y) + (transform.right * moveInput.x);
RaycastHit hitInfo;
Physics.SphereCast(transform.position,controller.radius,Vector3.down,out hitInfo, (controller.height/2f));
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
controller.Move(desiredMove * Time.deltaTime * playerSpeed);
}
Very nice, thank you. ProjectOnPlane is beautiful. This can also be achieved with a ray, any reason you chose to use a spherecast vrs just a ray?
Your answer
Follow this Question
Related Questions
Player only moves when the key is pressed, not when it's held. 0 Answers
Help changing input to axis 0 Answers
movement speed still changes with FPS; Despite using Time.deltaTime (And GetAxisRaw)! 0 Answers
the player input is jittery seems like glitching 0 Answers
3D space movement: character stuck at edge in free space 0 Answers