Lesson 4
Collect coins
Find out when the player touches a coin, then make the coin disappear.
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 when two things touch
- Make a GameObject disappear
- Use one script on many coins
What you will make
Coins that disappear when the player touches them.
1. Make a coin
- Make a sprite called
Coin, with a coin picture. - Add a Circle Collider. That is its shape.
Do not give it a Physics Body. The coin floats, and the player can go through it.
2. Add a script to the coin
Click Add Component, type Coin and choose Create script "Coin". Replace its code with this:
export default class Coin {
private readonly mGameObject: GameObject;
constructor(gameObject: GameObject) {
this.mGameObject = gameObject;
}
initialize(): void { }
update(args: NUpdateArgs): void { }
onCollisionEnter(other: Collider): void {
if (other.GameObject.Name === 'Player') {
GameObject.Destroy(this.mGameObject);
}
}
destroy(): void { }
}
Save, then Play. Walk into the coin. It's gone!
How does it work?
onCollisionEnterruns when something starts touching the coin.otheris the shape that touched it. We check that it is thePlayer.GameObject.Destroy(...)removes the coin from the game.
Many coins
Click the coin and press Ctrl + D a few times. Move the copies around. Every copy has the same script, so every coin works!
Try this
- Make a path of coins that goes up a hill.
- Make a coin that only disappears when you jump into it. (Hard!)
Try it here
Your mission
Put three coins in the level, then collect them all.
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!