Creating a coin
As we're just prototyping our game, we're going to create a simple circle 2D sprite, you can do that by right-clicking the project area, then Create > 2D > Sprites > Circle.
Once the sprite is created, Create a new Empty Object in the Hierarchy, rename it to Coin, and drag and drop the sprite into this new game object.
Now, lets add a Circle collider to this game object.
Note that I've marked Is Trigger
to true, and why do we need to set it to true?
This will tell the physics engine to not actually collide with the object, but to be a trigger to an event, this way, the player (or any other object) can pass through.
Coin Controller
Now that we have the basics of our coin in place, let's create a CoinController
to our Coin game object
.
First let's create a new Folder under our scripts folder and call it Objects
, from them, right click it and create a new C# Script, call it CoinController
and add it to our Coin game object
.
The code doesn't do much, just a trigger check. In this scenario, it checks if it collided with the player, if so, it destroys itself.
Tags
If you run the game now, when you move the player around and hit the coin, nothing will happen, that's because we haven't tagged our Player game object
properly! To do that, select the Player game object in the hierarchy view and Tag it as Player
Rotate our coin
That's great! We actually have a collectable in our game! (I mean, it doesn't do anything for now but we'll make it better in the future 😉)
For now, let's create a script to rotate our coin in place, just to add a new animation to it.
First, create a folder in our scripts folder, let's call it, animations. In there, create a new c# script, I've called RotateController
.
The code is pretty simple! in the Update
method, rotate the transform
property of our game object. Note, that this script can be attached to ANY game object, making it reusable.
transfor.Rotate()
accepts 3 parameters, x
, y
and z
, which are the 3 axis from a 3d object.
We're passing 0 to x because we don't want to rotate it on the X axis, we're multiplying our speed
field by Time.deltaTtime
and passing down to the y
parameter, and 0 to z
axis.
Time.deltaTime
Time.deltaTime is a property that provides the time in seconds between the current and previous frame in Unity. You can use it to make something happen at a constant rate regardless of the framerate3. For example, you can use Time.deltaTime
to move a Game Object
at a certain speed per second.
You can read more about it in the official Official Unity documentation for Time.deltaTime
Thanks
That's a wrap on our simple collectable object! We can use this concept of Trigger in many places, not only for objects, but to trigger a cutscene for example!
Hope you're enjoying these series and it's easy to follow. Until next chapter!
Top comments (0)