Creating a Player and Tilemap
Let’s see how well you remember creating GameObjects in a Scene from the Platformer. If you need to review, visit the Platformer’s Creating a Player and Creating a Tilemap tutorials again.
Tilemap
When creating the tilemap, be sure to add a Tilemap Collider 2D
and a Composite Collider 2D
. The Composite Collider will make it so that collision is applied to the tilemap as a whole instead of each tile individually, improving performance.
To ensure that the tilemap remains in place, be sure that you change these properties on the Rigidbody 2D that was added with the Composite Collider.
- Body Type
Kinematic
- Collision Detection
Continuous
.
Player
Add a Player GameObject to the Scene. I used a Circle for mine with a Circle Collider 2D
and Rigidbody 2D
. Be sure to tag the Player as a Player
tag and to add the Main Camera as a child of the player.
Top-Down Player Controller Script
Update()
vs. FixedUpdate()
This time (as opposed to our script in our platformer), we won’t be moving by adding forces to the Player’s Rigidbody in FixedUpdate()
. Instead, we will directly mutate the position of the transform
component, which can be done in Update()
. Rigidbody code MUST go in FixedUpdate()
while everything else can go in Update()
.
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private const int SPEED_UNIT = 1000;
public float speed;
// Start is called before the first frame update
void Start()
{
}
// FixedUpdate is called once per frame
void FixedUpdate()
{
// +1 for right/up, -1 for left/down.
// Example: Vector2(1, -1) = diagonal direction right and down.
Vector2 direction = new Vector2(
Input.GetAxis("Horizontal"),
Input.GetAxis("Vertical")
).normalized;
// Take the previous position and add any change to it
// in the x and y directions.
transform.position = new Vector2(
transform.position.x + speed * direction.x / SPEED_UNIT,
transform.position.y + speed * direction.y / SPEED_UNIT
);
}
}
We have are dividing by SPEED_UNIT
because if we moved by speed
every frame (60x a second), we would go too far too quickly.
Set speed
in the Inspector
I set my Speed
to be 20
as well as the Gravity Scale
of the Rigidbody to be 0
(because we do not have gravity in this game). Also, I set the collision of the Rigidbody to be Continuous
.
Draw some tiles and test out your game’s movement.