Setting up the project

The character

Drag the character to Assets in Unity project

Background

Scene view

Scripting

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { private Vector2 pos; private bool moving = false ; void Start () { // First store our current position when the // script is initialized. pos = transform.position; } void Update () { CheckInput(); if (moving) { // pos is changed when there's input from the player transform.position = pos; moving = false ; } } private void CheckInput () { // WASD control // We add the direction to our position, // this moves the character 1 unit (32 pixels) if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow)) { pos += Vector2.right; moving = true ; } // For left, we have to subtract the direction else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow)) { pos -= Vector2.right; moving = true ; } else if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow)) { pos += Vector2.up; moving = true ; } // Same as for the left, subtraction for down else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)) { pos -= Vector2.up; moving = true ; } } }

This is my tutorial of making a really simple RPG or roguelike with Unity in 2D mode. I'm not a professional Unity developer (just picked it up) and I'm prototyping as I go. Feel free to comment some good practices.---Part 1: Grid movementFirst, let's decide our cell size in the grid:32 x 32 pixels - done.Then start your new project normally (in 2D mode), let's call it RPGTutorial. Now I made a really simple 32 x 32 pixel square character for this purpose and imported it to Unity:Then use the inspector (click the player sprite) and change theto 32 and hit apply:Then, for prototyping purposes I made a grid background (you will probably make the level with a tile based editor but for this purpose, I just quickly whipped up a single image and imported it to Unity):Also change the pixels to units to 32 for this asset, then drag it to the scene. Also drag the player sprite on top of the grid like so:Change theandin the inspector to 0 (zero) for the grid to center it. For the player change the X and Y to -3.5 to put it in the corner.Create a new C# script in the assets and name it PlayerController. Edit the file like so:Save the script and drag it from the assets to the player object in the Hierarchy view. Hit play and test the movement with WASD keys.---Part 1: Grid movementCode highlighted with hilite.me