Tuesday, January 26, 2016

Post 2

-Last classes we added a control script to our Player.
-To do this we selected the Player and in the right panel added a component, we added a new script, and we named it PlayerController.
-After opening it in MonoDevelop we added some code to read te input and move the player:

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

Vector3 pos = this.GetComponent<Transform>().position;
if(Input.GetKey(KeyCode.UpArrow))
{
pos.z += 0.1f;
}
if(Input.GetKey(KeyCode.DownArrow))
{
pos.z -= 0.1f;
}
if(Input.GetKey(KeyCode.RightArrow))
{
pos.x += 0.1f;
}
if(Input.GetKey(KeyCode.LeftArrow))
{
pos.x -= 0.1f;
}
this.GetComponent<Transform>().position = pos;
}
}

- Some information about this script:
  • Start and Update are what we call functions, functions are like containers that hold code for some specific function, functions can be called many times from different parts of the code, making them great for taking away redundant code and encapsulating functionality.
  • "void" is what the function must return, which means nothing for Update and Start, functions could return numbers, letters, objects, addresses, and more.
  • The "()" is where we put in data we want to pass to the function, in this case Start and Update don't need any data so the "()" has nothing in between.
  • We use GetComponent to get components from that object, components are what we see in the right panel. In the case of this.GetComponent<Transform>() we are getting the Transform component, this component contains position, rotation and scale of the object.
  • We get the object's position and keep it in pos (which is a 3d vector with x,y,z coordinates, Vector3)
  • with Input.GetKey(KeyCode.UpArrow)) we get the state of the up arrow, if the user is pressing it or not. Input is called an "Object" this object exists for us to get information about any input, it can be keys, mouse, joysticks, screen presses, etc.
  • So once we get the position, and know what the user is doing we update the position coordinate affected and put it back into the component:
    • this.GetComponent<Transform>().position = pos;
  • Once we run the game in unity we should be able to move the player around.


No comments:

Post a Comment