- Home /
How can I make my FPS player move towards the direction it is facing
I am trying to make an FPS controller using Character Controller, I can get it to move, but the problem is that it is moving on global space. I watched a lot of videos on youtube but nobody is explaining how the code works, so can someone tell me how can I make it move towards the direction where it is facing and how the code works.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private CharacterController characterController;
public GameObject camera;
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float mouseSensitivity = 2f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
characterController = GetComponent<CharacterController>();
}
void Update()
{
Move();
RotatePlayer();
}
private void Move()
{
float moveLeftAndRight = Input.GetAxisRaw("Horizontal");
float moveForwardAndBackward = Input.GetAxisRaw("Vertical");
Vector3 moveDirection = new Vector3(moveLeftAndRight, 0f, moveForwardAndBackward) * moveSpeed * Time.deltaTime;
characterController.Move(moveDirection);
}
private void RotatePlayer()
{
float mouseX = Input.GetAxisRaw("Mouse X");
float mouseY = Input.GetAxisRaw("Mouse Y");
float mouseXLook = mouseX * mouseSensitivity;
float mouseYLook = mouseY * mouseSensitivity;
transform.Rotate(0, mouseXLook, 0f);
camera.transform.Rotate(-mouseYLook, 0f, 0f);
}
}
Answer by Esteem · Jan 18, 2020 at 11:15 PM
to set the direction in relation to the object that the PlayerController sits on (the player object), you want to add your moveLeftAndRight and moveForwardAndBackward to the forward and right vectors of your player object.
instead of this:
Vector3 moveDirection = new Vector3(moveLeftAndRight, 0f, moveForwardAndBackward) * moveSpeed * Time.deltaTime;
do this:
Vector3 moveDirection =
(transform.forward * moveForwardAndBackward + transform.right * moveLeftAndRight)
* moveSpeed * Time.deltaTime;
Thank you for helping me, and because I am a beginner I'm a little bit confused, why should I use "+" ins$$anonymous$$d of "," since it is a vector3 and it needs 3 values
we're setting the value of Vector3 to the value of (Vector3 * float) + (Vector3 * float) * float * float
You can add two Vector3s together to get another Vector3 and you can multiple a VEctor3 by a float.
what you can't do is multiply a Vector3 by a Vector3 (at least by default)
Your answer
Follow this Question
Related Questions
Carry forward velocity against mouse movements 1 Answer
How do I make the default fps character controller not stick to the mesh it is standing on? 0 Answers
How do I prevent my fps player from flying? 1 Answer
Why does my player just fall through the floor right when I press play? 1 Answer
Player Falls Much Slower While Moving 2 Answers