Hello, I looked up in the reference library: Transform.TransformDirection, though I still don’t understand its use. So it “Transforms direction from local space to world space.” What are these two spaces and how do they interact with one another?
More precisely given this context:
if (grounded)
{
// Calculate how fast we should be moving
Vector3 targetVelocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
targetVelocity = transform.TransformDirection(targetVelocity);
Why is it necessary. I don’t see the point in transforming between local-world space.
World space means the coordinate system relative to your whole game world. Local space means the coordinate system relative to the GameObject/model. In the above example:
- If you use world space to set velocity: the object will only slide left/right along the (world/global) X axis, and forward/back along the (world/global) Z axis.
- If you use convert from local space to world space: the object will slide left/right and forward/back relative to the direction the object is facing.
The TransformDirection method is performing this conversion, so that the input is causing the player to move based on their orientation. Example: player is facing 45 degrees to the ‘right’… world ‘forward’ vector is (0,0,1) (positive Z axis) and local forward vector is (0.7,0,0.7). Moving on the ‘vertical’ input axis will cause the player to move on the diagonal (in world space) if the direction is converted, or just along the world z axis if not.
The script gets values of input axis and puts them into a Vector3. Then this vector is transformed to world space from the character’s point of view. If you press forward the script will result going forward, but in relation to the character.
Since the character will most likely be rotated around Y axis, this will mean to what is “forward” to the character (movement in positive Z direction in to the local space of the character) is not at all movement along just Z axis in world space.
This way you don’t have to calculate the world space movement yourself, the Transform.TransformDirection() does it for you!