- Home /
Question by
tuananh01699938640 · Apr 11, 2020 at 10:08 AM ·
c#movement script
Something wrong with the movement and the rotation
I have a piece of code that will allow my character to move by the rotation of the charater:
using UnityEngine;
public class playerMov : MonoBehaviour
{
public float movementSpeed = 5.0f;
public float clockwise = 1000.0f;
public float counterClockwise = -5.0f;
public Camera cam;
void Start()
{
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
transform.position += transform.forward * Time.deltaTime * movementSpeed;
}
else if (Input.GetKey(KeyCode.S))
{
transform.position -= transform.forward * Time.deltaTime * movementSpeed;
}
else if (Input.GetKey(KeyCode.A))
{
transform.position -= transform.right * Time.deltaTime * movementSpeed;
}
else if (Input.GetKey(KeyCode.D))
{
transform.position += transform.right * Time.deltaTime * movementSpeed;
}
transform.Rotate(0, Input.GetAxis("Mouse X") * Time.deltaTime * clockwise, 0 );
cam.transform.position = transform.position;
cam.transform.Rotate(-Input.GetAxis("Mouse Y"), Input.GetAxis("Mouse X"), 0);
Quaternion q = cam.transform.rotation;
q.eulerAngles = new Vector3(q.eulerAngles.x, q.eulerAngles.y, 0);
cam.transform.rotation = q;
}
}
but if I try to rotate my character and move then it will not work correctly (like if I rotate to the left, instead pressing W to move up, it will move the character to other direction) . So what is the problem in my code?
(I just edited my question)
untitled.png
(15.3 kB)
Comment
If you have anything that you don't understand, just comment so I can explain
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
[ C#] Character Movement based on Camera Direction. 2 Answers
Smooth Movement with set distance 1 Answer
Slide in one set direction 1 Answer