- Home /
Can anybody modify my script so that my player could move related to camera
game developer who is developing a third person shooter game. I made most of the part in the movement script. But I am not able to modify my script so that my player is not moving relative to the camera. The below shown script is the one I made. Can anybody modify the script so that the player moves relative to the camera,Hello. I am having trouble making a third person shooter game. I create a script in which the character look towards the direction it should be moving, and the movement is completely using animation. I would like to modify the below given script so that the player always moves in the direction where the camera is facing. It would be good if anybody could help me. I am just an intermediate to game dev
public class PlayerMovement : MonoBehaviour {
private Animator animator;
public Transform CamLoc;
private Vector3 localCam;
[SerializeField]
private float turnSpeed = 5f;
private void Awake()
{
animator = GetComponentInChildren<Animator>();
}
private void Update()
{
var horizontal = Input.GetAxis("Horizontal");
var vertical = Input.GetAxis("Vertical");
var movement = new Vector3(horizontal, 0, vertical);
animator.SetFloat("Mag", movement.magnitude);
if (movement.magnitude > 0)
{
Quaternion newDirection = Quaternion.LookRotation(movement);
transform.rotation = Quaternion.Slerp(transform.rotation, newDirection, Time.deltaTime * turnSpeed);
}
}
},
Answer by Tario · May 06, 2020 at 02:44 PM
public Camera cam; // a reference to your camera
var verticalMovement = cam.transform.forward; // The forward vector of your camera
verticalMovement.y = 0; // You don't want the character to be moving up or down based on the camera's direction, right?
var movement = horizontal * cam.transform.left + vertical * verticalMovement;
The input at the moment is being applied straight to the worldspace coordinates of the object. You want to apply it to the relative left and forward vectors of the object. Your character will now move -1 to 1 units left of the camera and -1 to 1 units forward relative to the camera each frame.
if the horizontal axis is inverted, swap out transform.left for transform.right.