- Home /
Using sin and cos to decompose a vector
I want to decompose a vector, being the rotation.y and a float force, and assign to x and z floats. So I made this code:
transform.Rotate(0, Input.GetAxis("Horizontal"), 0);
float rot = transform.rotation.y;
float x = force * Mathf.Cos(rot)* Input.GetAxis("Vertical") * Time.deltaTime;
float z = force * Mathf.Sin(rot)* Input.GetAxis("Vertical") * Time.deltaTime;
rigidbody.AddForce(new Vector3(x,0,z));
I see some problems that are: rotation varies between 0 and 1 instead of 0 and 360 and Cos and Sin methods return in radian. I can not solve that problem. Can someone help?
The result that I want to reach is make a object go to where is facing. Decomposing the force will move the object in x axis and z axis.
Uhm, if you want the forward direction (z direction) you have your sin / cos reversed ^^ You calculate the "right" direction (x direction). Also your rotation will rotate in the wrong direction.
To get the forward direction use:
x = $$anonymous$$athf.Sin(y_Radians)
z = $$anonymous$$athf.Cos(y_Radians)
To get the right direction you have to use
x = $$anonymous$$athf.Cos(y_Radians)
z = -$$anonymous$$athf.Sin(y_Radians)
Note the "-".
But as already mentioned using transform.forward or transform.right is usually way simpler ^^
Answer by tanoshimi · May 11, 2015 at 11:51 AM
transform.rotation.y
gives you the y component of a four-dimensional quaternion rotation. I suspect you wanted transform.rotation.eulerAngles.y
.
But don't forget $$anonymous$$athf.Deg2Rad since $$anonymous$$athf.Sin takes an angle in radians while eulerAngles are in degree
$$anonymous$$ateusSarmento:
ps: transform.right actually gives you that vector that faces to the right of the object just like the one you calculated. $$anonymous$$eep in $$anonymous$$d that transform.right is affected by all rotations of this transform. You're method only rotates around the world y axis.
Answer by MateusSarmento · May 11, 2015 at 09:04 PM
Yeah, thanks man! I got it. The right code is:
transform.Rotate(0, Input.GetAxis("Horizontal"), 0);
float rot = transform.eulerAngles.y * Mathf.Deg2Rad;
float x = force * Mathf.Cos(rot)* Input.GetAxis("Vertical") * Time.deltaTime;
float z = force * Mathf.Sin(rot)* Input.GetAxis("Vertical") * Time.deltaTime;
rigidbody.AddForce(new Vector3(x,0,z));
Your answer
Follow this Question
Related Questions
Cos creates problems with addforce 0 Answers
Camera Rotation 1 Answer
What's wrong with this algorithm? 2 Answers