How To Move My Player With Sin And Cos Functions
I was trying to use Mathf.sin and Mathf.Cos tos move my character in X and Z, but somewhy it only moves within X
this is the messy code im using
if(Input.GetKey(KeyCode.W)) {
Vector3 moveVertical = new Vector3 ((Mathf.Cos (((transform.rotation.z)* 3.14159265358979f)/ 180)), 0, (Mathf.Sin (((transform.rotation.z)* 3.14159265358979f)/ 180)));
rb.AddForce (moveVertical);
}
else if(Input.GetKey(KeyCode.S)) {
Vector3 moveVertical = new Vector3 ((Mathf.Cos (((transform.rotation.z)* 3.14159265358979f)/ 180)), 0, (Mathf.Sin (((transform.rotation.z)* 3.14159265358979f)/ 180)));
rb.AddForce (-moveVertical);
}
Answer by JVene · Aug 25, 2018 at 04:03 PM
I've run into this before, assuming someone posting here is about 25 or 30, only to discover they're 15 or 13 years old. I can only assume you're a student just experimenting, but you're taking a wild guess at this, and quite literally everything in this code is out of place. There's nothing wrong with experimenting, but you're going to need to take one step back and get some bearings as to what is in the code you've posted.
rotation, inside a Transform, is a Quaternion. There is absolutely no use whatsoever using the 'Z' component of the quaternion, unless you know quaternion algebra and have some specific intent, which wouldn't make sense because the Quaternion class does most of that for you.
I wish Unity had built their Quaternion class where members x, y, z and w were inaccessible to user code. I can't image anyone would need access to them for any reason, because if they did they would very well know what they're doing.
You need to understand the basic trigonometric rotation formula. Sin and Cosine have no application in the approach I see here. You should start by searching for a few key points and read on these subjects:
Trigonometric rotations
Unity Quaternion
Mathf.Rad2Deg
Mathf.Deg2Rad
Quaternion.Euler
Quaternion.eulerAngles