Hello, everybody.
So I am trying to create a 3rd person controller.
Ihave a camera controller and player movement, but I can’t find out how to make the player move in the direction of where the camera is facing.
Player movement script
public class PLAYER_Movement : MonoBehaviour
{
public int walkingSpeed, runningSpeed;
public int movementSpeed;
public float turnSmoothTime;
public bool isSprinting;
//Jump Stuff
Vector3 velocity;
public float gravity = -9.8f;
public Transform groundCheck;
public float groundDist;
public LayerMask groundMask;
bool isGrounded;
public float jumpHeight = 3;
CharacterController charController;
public Transform playerCamera;
// Start is called before the first frame update
void Start()
{
charController = GetComponent<CharacterController>();
}
// Update is called once per frame
void Update()
{
Movement();
}
void Movement()
{
float inputX = Input.GetAxisRaw("Horizontal");
float inputZ = Input.GetAxisRaw("Vertical");
isSprinting = Input.GetKey(KeyCode.LeftShift);
Vector3 moveDir = new Vector3(inputX, 0, inputZ).normalized;
movementSpeed = isSprinting ? runningSpeed : walkingSpeed;
Jumping(moveDir);
//Rotate player in direction of camera
transform.rotation = Quaternion.Euler(0f, playerCamera.eulerAngles.y, 0f);
Vector3 moveAmount = moveDir * movementSpeed;
velocity.y += gravity * Time.deltaTime;
moveAmount.y = velocity.y;
charController.Move(moveAmount * Time.deltaTime);
}
void Jumping(Vector3 moveDir)
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDist, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -1f;
}
if (Input.GetKeyDown(KeyCode.Space) && isGrounded && moveDir.magnitude <= 0.05f)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
}
and this is my camera controller script
public class PLAYER_CameraController : MonoBehaviour
{
public float rotationSensitivity;
public Vector2 cameraInput;
public Vector2 maxMinRotation;
public Vector3 cameraPosition_NOaim;
public Transform playerTarget;
public Camera playerCamera;
private void Update()
{
RotateCamera();
}
void RotateCamera()
{
cameraInput.y += Input.GetAxis("Mouse X") * rotationSensitivity;
cameraInput.x += -Input.GetAxis("Mouse Y") * rotationSensitivity;
cameraInput.x = Mathf.Clamp(cameraInput.x, -maxMinRotation.x, maxMinRotation.y);
}
private void LateUpdate()
{
Vector3 dir = cameraPosition_NOaim;
Quaternion rotation = Quaternion.Euler(cameraInput.x, cameraInput.y, 0);
rotation.x = Mathf.Clamp(rotation.x, -maxMinRotation.x, maxMinRotation.y);
transform.position = playerTarget.transform.position + rotation * dir;
transform.LookAt(playerTarget.transform.position);
}
}