The first script I’ve written and helped me find the entrance into C# and Unity did one simple, yet powerful thing: It allows the player to move a square freely in two dimensions by using the default keyboard input.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(PlayerPhysics))]
public class PlayerControl : MonoBehaviour {
//Handler Variables
public float h;
public float v;
private Vector2 amount;
private PlayerPhysics playerPhysics;
// Use this for initialization
void Start () {
playerPhysics = GetComponent<PlayerPhysics>();
}
// Update is called once per frame
void Update () {
h = Input.GetAxis (“Horizontal”);
v = Input.GetAxis (“Vertical”);
amount = new Vector2(h, v);
playerPhysics.Move(amount);
}
}
//=== SECOND SCRIPT STARTS HERE ===
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class PlayerPhysics : MonoBehaviour {
public void Move(Vector2 amount) {
transform.Translate(amount);
}
}
The code consists of two scripts that I had to merge here for facility: PlayerControl.cs and PlayerPhysics.cs. Where the first translates the horizontal (h) and vertical (v) arrow-key inputs into a vector (amount), the second shifts the position of the player (i.e. the cube) by just that amount into those directions (Move()).
Through that, simple two-dimensional games can be created that don’t require a lot of special attention. It matters not whether the “player” is a cube, a 2D sprite or a 3D animated model – it will always move with that script and alterations will smoothen it out, give it a more realistic and fluid, stable feeling.
It was very refreshing for me to see many familiar terms and syntax elements again after a “long” time, but I had to rely on some sources to update my memory and teach me this or that, especially when it came to working with physical objects on a plane/in a space and the Unity engine’s terms, usage and architecture. I greatly enjoyed it, though, and feel like I’ve opened the gate to a long, arduous journey of learning, training and perfecting C# programming and video game development.
Recent Comments