Due 17 Oct 2017
Some of these include parts of Unity we'll look at next week. Try them out and come to class with any questions you have.
A common task in game development is reacting to user input. There is no input event or message in Unity, but there is Update
and the Input class. We can check every frame if a key is pressed and react to that. Here's a script that moves up, down, left, right depending on the keys pressed. Look at the documentation on GetKey and Translate for more information.
using UnityEngine;
using System.Collections;
public class Mover : MonoBehaviour {
public void Update () {
if (Input.GetKey ("up")) {
// up key is pressed, move up
transform.Translate (0, 1, 0);
} else if (Input.GetKey ("down")) {
// down key is pressed, move down
transform.Translate (0, -1, 0);
} else if (Input.GetKey ("left")) {
// down key is pressed, move down
transform.Translate (-1, 0, 0);
} else if (Input.GetKey ("left")) {
// down key is pressed, move down
transform.Translate (1, 0, 0);
}
}
}
Another common response to an event is to remove a GameObject. If an object is "picked up" or "destroyed" in the game you might want to do this. Here's a script that removes everything it touches from the game. It needs to be attached to a GameObject that also has a 2D collider component (e.g. a BoxCollider2D or a CircleCollider2D) with Is Trigger
set to true
and a Rigidbody2D. Look at OnTriggerEnter2D, Collider2D, and Destroy for more information.
using UnityEngine;
using System.Collections;
public class RemovesEverything : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other) {
Destroy (other.gameObject);
}
}
Unity scripting is all about coordinating components. Here's a script that plays a sound when an object is moving too fast because of physics.
Rigidbody
component (the built in component responsible for physics) how fast its going, or more specifically what the magnitude of its velocity istooFast
variable), it asks the AudioSource
component to Play whatever clip is has associated with it. You need to set up the Rigidbody and AudioSource components in the Editor.using UnityEngine;
using System.Collections;
public class ScreamWhenTooFast : MonoBehaviour {
public float tooFast;
void Update() {
float howFast = GetComponent<Rigidbody> ().velocity.magnitude;
if (howFast > tooFast) {
GetComponent<AudioSource> ().Play ();
}
}
}