I need help understanding TransformDirection

Hi I’ve looked this question up before but usually the asker gets an answer that works around transform direction. I need to know what TransformDirection does exactly. No need to code just an explanation and an example will do. If possible you can also explain what this code does too.

function WalkForward()
	{
	var direction : Vector3 = Vector3 (1, 0, 0);
	return transform.TransformDirection (direction);
	}

To understand TransformDirection, you must first understand the difference in World and Local space. This answer does a pretty good job at explaining.

Now, TransformDirection, as per the docs, transform a Vector from local space to world space. In the world space, vector (1,0,0) is one unit to the right of the origo, in local space, however that same vector is one step to the right based on the object’s current rotation. What Translatedirection does is it takes that relative movement, and returns how it is in relation to the origo.

You can see this effect for yourself if you imagine your monitor being the center of the world (0,0,0). The direction the back of your screen shows, is the positive z-axis(world forward), the direction the right edge of the screen is the positive x-axis (world right), and up is the positive y-axis (world up). Now, as long as you face your monitor, i.e. your(=local) forward is the same as the world (=your monitor) forward and your(=local) right is the same as the world right.

Now, if you turn so that your left is towards the monitor, the directions don’t match anymore; your(=local) forward is suddenly pointing to the same direction as world right! But say you are blind and want to know which way you’re actually facing in relation to the monitor. You’d need to do you.TransformDirection(you.forward) and that would return (1,0,0), which is equal to the world right.

The code you posted returns the x-axis (i.e. way right) for the current object in world space. The same can be achieved by simply using transform.right, because transform.direction is just shorthand for this translation.

You need to understand the difference between local space and world space. Local is for directions and rotations relative to the object, and world is relative to the game world. This function takes a local direction from an object and finds that direction in world space.
Vector3(1,0,0) is the same as Vector3.right, which in the object’s local space is the direction pointing to the right of the object. Depending on how the object is rotated, the output in world space will change.

This function is actually exactly the same as using transform.right btw

Hope that helps.