Pages

Wednesday, June 4, 2014

Turn based RPG with Unity 2D - Part 2: Camera control



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:

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

Code highlighted with hilite.me

4 comments:

  1. This is a very simple coding for TBS? It is true that it may not be as complicated as RPG games, but you should remember that TBS games have been incorporated to RPG games as well.

    ReplyDelete
    Replies
    1. Hey, yes I keep it as simple as possible for readability reasons. It's for turn based RPG game (or roguelike), not really TBS.

      Delete
  2. Hey, I am getting this error:
    "Assets/CamController.cs(12,17): error CS0103: The name `tmp' does not exist in the current context"
    I am new to coding and am looking up how to fix, but an answer would be great.
    I am using Unity 4.5.5f1

    ReplyDelete
    Replies
    1. Hey thanks, seems the error is mine. I forgot to remove the tmp from the code when I remade it. Try removing the line altogether, it should work. I'll fix it on the post as well.

      Delete