- Home /
"Rotating" the player's movement direction
Hello! I'm quite new to Unity and C#, just started 2-3 days ago
I tried creating a first person movement basescripts, with rotating the camera based on the mouse and moving the player based on the WASD keys, and plus implementing a running mechanic too
It works fine and wonders for my first project, altough i ran into one problem i cant quite work around. Whenever i rotate the camera, the player doesnt move to the direction i'm facing
Example: the player is facing to X (forward), with the camera. When i press W, the player moves forward, towards X. When i rotate the camera to the left, and then press W, i expect it to move forward (to the left), but it moves to the right, based on the camera's direction.
Can someone suggest a way (let it be pseudo code, normal code, or just plain explanation) that i can make this work?
Here's my two scripts One for the player's movement:
using UnityEngine;
public class playerMovement : MonoBehaviour
{
public Transform player;
public Rigidbody rb;
public float walkingSpeed = 50f;
public float runningSpeed = 100f;
float speed;
void Update()
{
if (Input.GetKey("left shift"))
{
speed = runningSpeed;
}
else
{
speed = walkingSpeed;
}
rb.AddForce(0,0,speed*Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(speed*Time.deltaTime,0,0,ForceMode.VelocityChange);
}
if (Input.GetKey("a"))
{
rb.AddForce(-speed*Time.deltaTime,0,0,ForceMode.VelocityChange);
}
if (Input.GetKey("w"))
{
rb.AddForce(0,0,speed*Time.deltaTime,ForceMode.VelocityChange);
}
if (Input.GetKey("s"))
{
rb.AddForce(0,0,-speed*Time.deltaTime,ForceMode.VelocityChange);
}
}
}
And one for the camera's movement/rotation:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cameraMovement : MonoBehaviour
{
public Transform player;
public Vector3 offset;
public float speedH = 2.0f;
public float speedV = 2.0f;
private float yaw = 0.0f;
private float pitch = 0.0f;
void Update()
{
yaw += speedH * Input.GetAxis("Mouse X");
pitch -= speedV * Input.GetAxis("Mouse Y");
transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
transform.position = player.position+offset;
}
}