0
\$\begingroup\$

I'm making a 3D game and I was trying to make movement relative to player rotation for several hours, but I failed. Here's the code, maybe I made a mistake there. Also, player doesn't rotate.

public class PlayerScript : MonoBehaviour { private Quaternion rotat; //rotation of the camera public Transform cam; //camera bool IsOnGround = true; public float speed = 5; private Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void FixedUpdate() { rotat = Quaternion.Euler(0, cam.rotation.y, 0); IsGrounded(); if (Input.GetKey(KeyCode.W)) { rb.AddForce(rotat * Vector3.forward * speed, ForceMode.Impulse); } if (Input.GetKey(KeyCode.A)) { rb.AddForce(rotat * Vector3.left * speed, ForceMode.Impulse); } if (Input.GetKey(KeyCode.S)) { rb.AddForce(rotat * Vector3.back * speed, ForceMode.Impulse); } if (Input.GetKey(KeyCode.D)) { rb.AddForce(rotat * Vector3.right * speed, ForceMode.Impulse); } if (Input.GetKey(KeyCode.Space) && IsOnGround == true) { IsOnGround = false; rb.AddForce(Vector3.up * (speed / 10), ForceMode.Impulse); } } public bool IsGrounded() { RaycastHit hit; float rayLength = 1.12f; if (Physics.Raycast(transform.position, Vector3.down, out hit, rayLength)) { IsOnGround = true; return true; } IsOnGround = false; return false; } } 
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

Your code applies forces relative to the rotation of the camera, and you're not using the Euler angle:

rotat = Quaternion.Euler(0, cam.rotation.y, 0); 

If you want the rotation to be relative to the Rigidbody, use:

rotat = Quaternion.Euler(0, rb.rotation.eulerAngles.y, 0); 

or just

rotat = rb.rotation; 

Also, player doesn't rotate.

The script that you've shared does not include any code for rotating the player.

\$\endgroup\$
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.