Move Every Frame
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 10 of 85.
Unity calls Update() once for every frame it draws. Change the position a little in it and the object moves a little on every frame, which on screen looks like smooth motion.
+= on a position adds a Vector3 to it: each of x, y and z grows by the matching number. This balloon rises 0.02 units on every frame and stays where it is on x and z:
void Update()
{
transform.position += new Vector3(0, 0.02f, 0);
}The f is the C# float suffix you already know: Unity works in float, and 0.02 on its own would be a double. At 60 frames a second the balloon rises 0.02 x 60 = 1.2 units every second.
Challenge
EasyMake the red car drive forward.
- In
Update(), addnew Vector3(0, 0, 0.05f)totransform.positionwith+=. - Keep x and y at
0: the car moves only along z.
Press Play: the car drives away from the camera. Then Check.
Try it yourself
using UnityEngine;
public class CarMover : MonoBehaviour
{
void Update()
{
// Move the car forward along z here
}
}
All lessons in Unity Scripting Basics
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground