Collisions :: GameDev Unity3D cookbook

Detect collisions between objects is crucial to any game.
The game engines, always have some collision detection mechanism, and this topic is important to take in account before choose the game engine for your project.

The basic points to watch carefully are:
– How to set the collision detection;
– which basic geometric forms available for colliders(spheres, cudes, planes …) are available;
– If the game engine, support 3D mesh collisions.

When collision are detect, in general, event messages are sent through the system. And those event must be “captured” by some game object, in order to execute game routines, that will provide the game dynamics.

For these tutorial, create a scene, as shown in the image bellow:
CenaCollisions

Attention: In this tutorial I will use the names for the game objects, as the image indicates.

On Unity3D, collision detections are performed by the physics engine, so, the elements for setup your collision can be found in the Componet >> Physics menu, which are Colliders and Rigidbody.

Let’s configure the basic elements to the game objects:
Object SphereTrigger:
– check if it has the component SphereCollider, if positive, check the trigger option. If the sphereCollider is not present, you must include it. go to menu Component >> Physics >> Sphere Collider. Than, check it as trigger.

Object SphereObject:
– Check if the component SphereCollider is present, and uncheck the option “is Trigger”.
– Add a Rigidbody component, if needed (To add the rigidbody, go to menu Component >> Physics >> Rigidbody) . And uncheck the option “Is Kinematic”.

Object Cube:
– Check if it has the Box Collider component, and the “is Trigger” option, unchecked.
– Add the Rigidbody component. To add the rigidbody, go to menu Component >> Physics >> Rigidbody. And check the option “Is Kinematic” – that will allow us to move the object without physics simulations.
– Add the BasicInputHandlerCube script (shown in the user input tutorial).
– Add the BasicCollisionHandlerCube script that you can see bellow:

BasicCollisionHandlerCube:
[code lang=”java”]
private var colisionInfo:String = “Collision info”;

function Update () {
}

function OnCollisionEnter(col : Collision){
colisionInfo = “Collision Enter (Rigidbody) : “;
}

function OnCollisionExit(col : Collision){
colisionInfo = “Collision Exit (Rigidbody) : “;
}

function OnTriggerEnter(col : Collider){
colisionInfo = “Collision Enter (Trigger) : “;
}

function OnTriggerExit(col : Collider){
colisionInfo = “Collision Exit (Trigger) : “;
}

function OnTriggerStay(col : Collider){
colisionInfo = “Collision Stay (Trigger) : “;
}

function OnGUI(){
GUI.Label(Rect(200,75,300,100),colisionInfo);
}
[/code]

This demo is very simple. It will show a message in the screen, about the collision nature. The BasicCollisionHandlerCube script changes the value of the colisionInfo variable, according the collision events, and than it prints the collisionInfo variable on the GUI.

The Unity3D, uses it’s physics engine to calculate the collisions, and the colliders (BoxCollider and SphereCollider components) are the sensors used to detect when one collider touch another collider.
When a collision is detect, the Rigidboby component, is informed, and sends an event message to the game object components according the collision’s nature. If one of the colliders were a trigger it sends the messages OnTriggerEnter, OnTriggerStay, and OnTriggerExit. Otherwise the rigidbody send the messages OnCollisionEnter, OnCollisionStay, and OnCollisionExit.
In this example, when the Cube collides with SphereTrigger, the message OnTriggerEnter, is sent when the collision starts; the message OnTriggerStay, is sent while the objects are colliding; the message OnTriggerExit, is sent once the objects stop colliding.
The same thing happens when the Cube collides with the SphereCollider, but in this case the messages are OnCollisionEnter, OnCollisionStay, and OnCollisionExit, because in this collision none of the colliders are set as triggers.

Check the final sample here.

What do you do with the other spheres?? Have fun!! Set their properties as you want, check how they behave in collisions, try to experiment some scripts… explore!!

Messages :: Gamedev Unity3D cookbook

There are two possible ways to send event messages through game objects on Unity3D: 1 – Send messages to linked objects; 2 – Search for objects on scene, and execute components functions.

Messages
First, let’s see the how to send messagens to linked objects, using Send Message, BroadcastMessage, and SendMessageUpwards.
You shall create a scene with basic elements as described in the image bellow:
imagemCenaMessages
Attention: Use cube elements as shown in the image, use the same names. The fountain, and cannon objects, must have a EllipsoidParticleEmitter, a ParticleRender and a ParticleAnimator, set them as you want.
Attention 2.: In object Cube2, add the BasicInputHandler script, we explored in User Input tutorial.

SendMessage
The method SendMessage will execute a certain function, in any object componen which has the function.

Preparation: In fountain object, set it’s BoxCollider Component as a trigger. Create these two scripts, and drag them to the fountain gameObject.

FountainScript:
[code lang=”java”]
function Update () {
}

function TurnFountainOn( v: boolean){
particleEmitter.emit = v;
}
[/code]

SendSimpleMessageScript:
[code lang=”java”]
function Update () {
}

function OnTriggerEnter(col: Collider){
this.SendMessage(“TurnFountainOn”, true);
}

function OnTriggerExit(col: Collider){
this.SendMessage(“TurnFountainOn”, false);
}
[/code]

The SendSimpleMessageScript will detect collisions, and send the message “TurnFountainOn”, along with the boolean value true or false.
the FountainScript, has the function TurnFountainOn, which will turn the particles on, according the argument recieved:true or false.
See the docs here.

BroadcastMessage
The Method BroadcastMessage will do the same job as SendMessage, but with the possibility to send the message to other game object, as far as they are perental linked, the messages are send to the sender’s children objects.

Preparation: Make the cannon object, child of cannonPlat object (use the panel for that).
Make the FountainScript component of cannon object.
Set the cannonPlat’s BoxCollider as trigger.

Crie um novo script, BroadcastMessageScript:
[code lang=”java”]
function Update () {
}

function OnTriggerEnter(col: Collider){
this.BroadcastMessage(“TurnFountainOn”, true);
}

function OnTriggerExit(col: Collider){
this.BroadcastMessage(“TurnFountainOn”, false);
}
[/code]

As soon as the SendSimpleMessageScript detect collisons, it broadcasts the message TurnFountainOn, to all it’s children objects, and the ones who have the TurnFountaiOn function, can perform actions.

Find Component
Any gameObject on Unity3D can execute the function Find, that will search for gameObjects over the scene. From this search, it´s possible to call for functions on the gameObject found.

Preparation: Set the plat’s BoxCollider as a trigger. Make the FountainScript a component of cannon object.

Create the following script, FindBehaviorScript:
[code lang=”java”]
function Update () {
}

function OnTriggerEnter(col: Collider){
GameObject.Find(“cannon”).GetComponent(“FountainScript”).TurnFountainOn(true);
GameObject.Find(“fountain”).GetComponent(“FountainScript”).TurnFountainOn(true);
}

function OnTriggerExit(col: Collider){
GameObject.Find(“cannon”).GetComponent(“FountainScript”).TurnFountainOn(false);
GameObject.Find(“fountain”).GetComponent(“FountainScript”).TurnFountainOn(false);
}
[/code]

Make the FindBehaviorScript, component of plat object.
Just like the previous scripts, this script will detect collisions, and than search for the cannon and fountain objects. When the object is located, we can access it’s components, and execute their functions.
See the docs for this procedures.

Take aa look to the final sample.

User Inputs :: GameDev Unity3D cookbook

User Inputs are the commands users use to control characters in a game. So, user inputs play a main role in any game development.

User Input ::
You should create a new JavaScript in your Project panel, and name it BasicInputHandler, and insert the following code:
[code lang=”Javascript”]
function Update () {
//Move object through Z axis
if(Input.GetAxis(“Vertical”) > 0){
transform.Translate(Vector3.forward * Time.deltaTime);
}
else if(Input.GetAxis(“Vertical”) < 0){
transform.Translate(- Vector3.forward * Time.deltaTime);
}

//Move object through X axis
if(Input.GetKey("d")){
transform.Translate(Vector3.right * Time.deltaTime);
}
else if(Input.GetKey("a")){
transform.Translate(- Vector3.right * Time.deltaTime);
}
}
[/code]
Add a cube in your scene, drag and drop, the BasicInputHandler script to this cube.

This script check the user input in two ways: through the Vertical axis in Input object, and if keys were pressed.

Veja o exemplo aqui.

Axis option ::
In Unity3D, there is this Input global object, that captures any user input, and make this information available to all other game objects. This Input object has some default settings, like Vertical and Horizontal axis. The Vertical axis is activated by W, S, up-arrow, and down-arrow.
THOSE SETTINGS CAN BE MODIFIED at EDIT >> Project Settings >> Input menus. The Inspector panel will show the axis configurations in the Input object, and you can modify them as you wish.

Keys option
You can also use the GetKey function to capture user inputs. The Input object, captures when keys a pressed, and this information is available to you.

Both ways are valid, and easy to use, but they slightly differ in the results.
Check the sample, and pay attention the at the difference between the controls W/S, and A/D, when you release the keys.

Update :: GameDev Unity3D cookbook

“Update” is a function used in Unity3D, which refer to: “The need to provide for certain game objects, execution loops.”

For example, when creating a character in a game, the programming of this character may have a number of functions that should be checked, and executed in every single frame of the game.

Different game engines have different names, and ways to implement these procedures. Here we’ll see how it works on Unity3D.

Create a scene in Unity, and add two cubes to it, and name them as “Cubo1” and “Cubo2″.

[code lang=”javascript”]
private var teste:int = 0;

function Update () {
Debug.Log(“Frame : “+teste);
teste++;
}
[/code]
Obs.: Create this script, name it as you wish. Drag the script, from the “Project” panel, to one of the game objects in Hierarchy panel (prefer one of the cubes). As soon as you run the game, you will see the output in the Console window.

This script, counts the number of the frames in your game. This code, increments in 1, the value in teste variable. In the first frame it is zero, than it is incremented to one; and so on.

Now, lets make the cube to move:

[code lang=”javascript”]
private var teste:int = 0;

function Update () {

transform.Translate(Vector3.right * Time.deltaTime);
Debug.Log(“Frame: “+teste);
teste++;
}
[/code]

Now, the script makes the cube moves across the X axis.
Take a look at the sample here.