How to change the position of the rotated transfom

I have a question about changing the position of a rotated transform. For example, enter image description here

I rotated the object shown in the picture around the x-axis. Then I want to move it along the y-axis (yellow arrow). For this I use a code like

    transform.localPosition = new Vector3(transform.position.x, newY, transform.position.z);

      

where newY stands for the new y value that I want to pass to the object transformation.

However, the result is obtained as enter image description here

The object appears to be moving around the y-axis. So how can I let it go with my own y-axis (yellow arrow)?

+3


source to share


2 answers


Add transform.up * distance_to_move

in position of an object to move it along its own Y axis.



+1


source


The reason is that the object shown in the figure does not have a parent. In this case, transform.localPosition is the same as transform.position.

You can calculate your own y-axis direction on the world axis and then move it. For example, you can use Transform.TransformDirection to transform a direction from local space to world space.



Vector3 RelativeDirection = gameObject.transform.TransformDirection(0, 1, 0);

      

RelativeDirection may be desirable.

0


source







All Articles