Lesson 9
Your first script
A script is code that tells a GameObject what to do. Write one that makes a sprite move.
Draft lesson: nobody has followed it from start to finish in the editor yet, so a step may not match what you see.
Video coming soon
We are making a video for this lesson. For now, follow the steps below!
In this lesson you will
- Know what a script is
- Make a script and open it
- Write code that moves a sprite
What is a script?
A script is a list of instructions for a GameObject. Like a recipe!
1. Make a script
- Click your sprite.
- Click Add Component.
- Type
Moverin the search box, and choose Create script "Mover".
2. Open it
Go to the Code tab and open Mover. Some code is already there.
3. Make it move
Find this line:
update(args: NUpdateArgs): void { }
Change it to this:
update(args: NUpdateArgs): void {
this.mTransform.position.x += 100 * args.dt;
}
Press Ctrl + S to save. Go back to Design and press Play. Your sprite slides to the right!
How does it work?
updateruns every frame. That is many times every second!this.mTransformis the GameObject's Transform.position.x += ...moves it a little to the right, every frame.args.dtis the time since the last frame. With it, the sprite moves 100 pixels every second, on fast and slow computers.
The parts of a script
| Part | When it runs |
|---|---|
initialize() | Once, when the game starts |
update() | Every frame |
destroy() | When the game stops |
Try this
- Change
100to300. Faster! - Change
+=to-=. Which way does it go now? - Make it move on
ytoo.
Learn more
JavaScript, the basics Variables, choices and functions. A short page from MDN.Opens in a new tabTry it here
Your mission
Change the number in the script, press Play, and make the sprite go faster.
Soon, a small piece of the editor will be right here, so you can practise without leaving the lesson. For now, try it in the editor!