- Home /
Rotating and moving the player in the direction of camera
I know this question has been asked many times, but I can't find a solution on the internet that works for me.
I am making a third-person game prototype. I have the basic walking animation up and running, as well as rotating the camera around the player using the mouse. What I want to do is to make the player face the direction my camera is facing, and then walk that way.
Here's the code I have written
Player.cs
public class PlayerController : MonoBehaviour
{
Animator animator;
[SerializeField] float forwardMovement = 0f;
// Start is called before the first frame update
void Start()
{
animator = this.gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
forwardMovement = Input.GetAxis("Vertical");
animator.SetFloat("ForwardMovement", forwardMovement);
}
}
Camera.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraRotation : MonoBehaviour
{
[SerializeField] Transform cameraPivot;
[SerializeField] Transform cam;
float heading = 0;
Vector2 playerInput;
// Update is called once per frame
void Update()
{
heading += Input.GetAxis("Mouse X") * Time.deltaTime * 180;
cameraPivot.rotation = Quaternion.Euler(0, heading, 0);
playerInput = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"));
playerInput = Vector2.ClampMagnitude(playerInput, 1);
Vector3 camForward = cam.forward;
camForward.y = 0;
camForward = camForward.normalized;
Vector3 camRight = cam.right;
camRight.y = 0;
camRight = camRight.normalized;
transform.position += (camForward * playerInput.y + camRight * playerInput.x) * Time.deltaTime;
}
}
Any help is greatly appreciated. I've been trying for quite a few hours to get it to work but I just can't.
Answer by xibanya · Dec 24, 2019 at 08:53 AM
it looks like your're setting the player transform position, but not the rotation. You can have the player rotate to face the direction the camera is facing by adding this to the player update loop
if (reference != null)
{
Quaternion targetRotation = Quaternion.LookRotation(reference.forward);
float halfPi = Mathf.PI * 0.5f;
float angle = Mathf.Clamp(Quaternion.Angle(transform.rotation, targetRotation), -halfPi, halfPi);
animator.SetFloat("whatever the rotation parameter is called in the animator controller", angle);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * turnSpeed);
}
be sure to add these to the variable declarations
public Transform reference; //drag the camera here in the inspecctor
public float turnSpeed = 1;
Your answer
![](https://koobas.hobune.stream/wayback/20220612220125im_/https://answers.unity.com/themes/thub/images/avi.jpg)