So now our player character can move around in the grid but the camera is still. If we want the camera to follow, we need to add some script.
(Edited 28. June 2014 for better camera scale)
First, let's adjust the camera size. You probably have a preference how big everything looks on the screen but I like it in the scale 1 to 1. Let's do some math:
We have 1 unit which is 32 pixels. Let's say our screen height is 768 pixels. All we have to do is count the camera size with this formula:
We have 1 unit which is 32 pixels. Let's say our screen height is 768 pixels. All we have to do is count the camera size with this formula:
screen_height / 2 * 1 / unit_size
=
768/2 * 1/ 32
The answer is 12. This is your camera size.
Now, create another script in the assets and call it CamController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | using UnityEngine; using System.Collections; public class CamController : MonoBehaviour { public GameObject target; // The player private Vector3 offset; void Start () { // Change the z value of the offset // to something below the sprites. // Otherwise you can't see anything: offset = new Vector3(0f, 0f, -10f); } void Update () { } // Let's put the movement in LateUpdate (called after Update function) void LateUpdate() { // Change camera's position to the same as the player (with the z-value of -10) transform.position = target.transform.position + offset; } } |
Now drag the script to the Main Camera -object in the hierarchy view. In the inspector, scroll down to Cam Controller (Script) component and set the target by clicking the small circle:
![]() |
CamController in Main Camera object |
Go back to PlayerController script and change the speed to something higher, like 50 to make the movement snappier.
---
Part 1: Grid movement
Part 2: Camera control
Part 3: Lighting
Part 4: NPC AI
---
Part 1: Grid movement
Part 2: Camera control
Part 3: Lighting
Part 4: NPC AI
Code highlighted with hilite.me