Tip:
Highlight text to annotate it
X
Translate and Rotate are two functions
that are commonly used to change the
position and rotation of a game object.
In this example we begin by looking at
translate. You can see that the argument
of translate takes a vector3.
So this example simply translates down
the Z axis, so you can see we've used 0
for X and Y,
by 1 every frame because it's inside update.
So let's see how that works. It's applied
to our floorbot object.
And you can see that if I press play
it moves very quickly because it's updating
every frame. Now what we'd normally
do with a translate operation is to
multiply it by Time.DeltaTime.
This means that it will be moved in
metres per second rather than metres per frame.
Then instead of specifically saying
Vector3(0, 0, 1)
we can use vector3.forward as a shortcut to this.
And we can then multiply by another value,
which we can establish as a separate variable.
That way we can control it by using
the variable inside the inspector.
But what if we don't want this to happen
every frame and we want it to be
based on a key press?
Meaning that it only occurs when I press
the up arrow?
Then I could do the exact same,
checking for the down arrow.
This time I've used a negative value of
vector3.forward in order to move
backwards when I press down.
Transform.rotate works in a very similar way.
Again taking in a Vector3 into it's argument.
This time we're using the Vector3 shortcut
Vector3.up.
This represents the axis around which to turn.
This is the first argument, and amount
to turn by is the second argument.
Now we'll add in our variable called TurnSpeed
and when I press play
I can move the object around and
rotate it using the left and right arrows.
And again because I've set these as
public variables I can adjust them
without having to go back to edit the scripts.
It should be noted that these functions work
on the local axis rather than in the world axis.
So where I'm using Vector3.forward
or Vector3.up - this is relative to the
axis of the object it's applied to.
It's also notable that if you want
to move an object with a collider,
so something that's going to be interacting
with physics - then you should not use
translate or rotate.
You should use the physics functions instead.
And you can see these in a separate lesson.
The only time that you would want to effect
transform is if you had a rigid body
that is kinematic.