Tag Archives: 3d

Moving an object with force in PlayCanvas

This tutorial explains how to use keyboard input to move an object around. But rather than telling the object how far it needs to move (like in this other tutorial), we will apply force to the object instead. This means that the object your moving can also hit other objects and interact with them rather than just going through them.

Step 1 – Setting up the object you want to move

To begin with, you need to create an object or use a model that you want to move. Then you need to add a Rigid Body component and a Collision component so that this object can collide and interact with other objects in the scene. For this example, I have added a Box entity (click + in the Hierarchy and then click Box) but you can use another 3D shape or model.

3dobject
Then you need to select the object and click on Add Component (in the Inspector panel on the left side of the screen) and choose the Collision component. If you have a box shape (entity) then you should set the Collision Type to Box (if you have a sphere shape, then select Sphere for Type, and so on).

Match your collision settings up so they look like the settings shown below. The numbers in the Half Extents property boxes should be half the numbers in the Scale property boxes above it. Eg. if the scale X property of the box has a value of 4 then the Half Extents X value should be 2.

box_collision

Now click on Add Component again and this time add the Rigid Body component. Change the Type to Dynamic and modify the values so they are the same as those below (experiment with these values later to get the effect you want).

rigid_body
It is important to make sure any other objects that this object will interact with also have Rigid Body and Collision components attached to them. For example, if you don’t want this object to fall through your ground in the scene, then the ground object should have a Static type Rigid Body and a Collision component.

If you want other objects to not be moved by this object, they should have a Static type Rigid Body and Collision component. Otherwise, if you want this object to move other objects when it touches them, add Dynamic type Rigid Body and Collision components to those other objects.

Adding a script to the object

Click on + in the Assets panel and choose Script to create a new script.

create_script
Call the new script moveWithForce.js and hit Enter to create the script.

script_name

Now you need to attach the script to the 3D object or model you want to move or control. Select the 3D object (eg. box) and then click on Add Component and select Script. Drag the moveWithForce.js script onto the Scripts component on the object in the Inspector panel and then let go. The script should now be attached to the object.

script_attached

 

Writing the code

Double-click on the moveWithForce.js script you just created in the Assets panel and replace all of the existing code with the following code in the Code Editor window:

// Add this code to any object you want to move with force
// Object that this script is attached to must have collision component and DYNAMIC rigid body component

pc.script.attribute("power", "number", 1000);  // set power to initial value of 1000
pc.script.create('moveWithForce', function (app) {
    // create force variable
    var force = new pc.Vec3();
    // Creates a new MoveWithForce instance
    var MoveWithForce = function (entity) {
        this.entity = entity;
    };

    MoveWithForce.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
            // Check for required components
            if (!this.entity.collision) {
                console.error("First Person Movement script needs to have a 'collision' component");
            }
            
            if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
                console.error("First Person Movement script needs to have a DYNAMIC 'rigidbody' component");
            }
            
            // Listen for keyboard press events
            app.keyboard.on(pc.EVENT_KEYDOWN, this._onKeyDown, this);
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {

            // movement
            var x = 0;
            var z = 0;
            var y = 0;
            
            // Use W-A-S-D keys to move player around and Space to make player jump
            // Check for key presses
            if (app.keyboard.isPressed(pc.KEY_LEFT)) {
                x -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_RIGHT)) {
                x += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_UP)) {
                z -= 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_DOWN)) {
                z += 0.01;
            }
            
            if (app.keyboard.isPressed(pc.KEY_SPACE)) {
                console.log("space pressed");
                y += 0.05;
            }
            
            // use direction from keypresses to apply a force to the character (x and z axes)
            if (z !== 0) {
                force.set(0, 0, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            if (x !== 0) {
                force.set(x, 0, 0).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
            
            // use direction from keypresses to apply a force to the character (y axis)
            if (y !== 0) {
                force.set(x, y, z).normalize().scale(this.power);
                this.entity.rigidbody.applyForce(force);
            }
        },
        
        _onKeyDown: function (event) {
            // When the space bar is pressed this scrolls the window.
            // Calling preventDefault() on the original browser event stops this.
            event.event.preventDefault();
            console.log("Scrolling disabled");
        }
    };

    return MoveWithForce;
});

Now click on Save and then go back to the game Editor window. That’s it! Launch your game by clicking on the Launch (play) button and you should now be able to control the 3D object/model by using the keyboard to move it around and make it jump. The code is set up to move the object using the arrow keys and space bar to jump. However, you can change these keys and you can also remove the code that makes the object jump if you don’t want to make it jump in the game.

 

 

 

Rotating objects with keyboard input in PlayCanvas

In this tutorial you will learn how to rotate an object using code in PlayCanvas. This means that you can allow users to spin an object when they press a key on the keyboard. You will also be introduced to variables in JavaScript. Watch the video below and then scroll down to view the sample code.

Sample JavaScript code for the rotate.js script:

pc.script.create('rotate', function (app) {
    // Creates a new Rotate instance
    var Rotate = function (entity) {
        this.entity = entity;
    };

    Rotate.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {
        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {
            // set the angle to 0
            var angle = 0;
            
            // change the angle of the box when a key is pressed
            if(app.keyboard.isPressed(pc.KEY_LEFT)){
                angle = -2;
            }
            
            else if(app.keyboard.isPressed(pc.KEY_RIGHT)){
                angle = 2;
            }
            
            // update the angle of the box to make it spin on the y axis
            this.entity.rotateLocal(0,angle,0);
        }
    };

    return Rotate;
});

 

Particle Systems in PlayCanvas

This video tutorial explains how to add particle systems to your PlayCanvas game. A particle system allows you to add a range of animated effects such as smoke, fog, bubbles, flames, and sparks.

Tip: You can also use an image for your particles by dragging an image that you have uploaded to PlayCanvas (eg. JPG or PNG image) onto the Color Map property on the particle system in the Inspector panel.

Make a 3D object move with code in PlayCanvas

In this tutorial we will start writing our very lines of JavaScript code in the PlayCanvas code editor! To start with, we will make a 3D object (eg. a box or sphere) move around the screen on its own. Watch the video below and then scroll down to see the sample code and try it out for yourself.

Here is the sample code for this tutorial. Make sure you create a new script asset called move.js and then add it as a component to your 3D object (eg. a box). Then add the code to the move.js script. Launch your game and then watch the object start moving to the right (if your object moves to the left, then your camera is on the opposite side of the object). Try changing the x, y, and z translateLocal parameters to make your object move in different directions at different speeds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
pc.script.create('move', function (app) {
 // Creates a new Move instance
 var Move = function (entity) {
 this.entity = entity;
 };
 
 Move.prototype = {
 // Called once after all resources are loaded and before the first update
 initialize: function () {
 },
 
 // Called every frame, dt is time in seconds since last update
 update: function (dt) {
 this.entity.translateLocal(0.01,0,0);
 }
 };
 
 return Move;
});

Skyboxes in PlayCanvas

In this tutorial you will be introduced to Skyboxes and CubeMaps in PlayCanvas. A skybox is a method of creating backgrounds to make the environment in a 3D game look bigger than it really is. Sky, distant mountains, hills or buildings are projected onto the six interior faces of the cube using a technique called cube mapping which creates an illusion of distant 3D surroundings.

A CubeMap in PlayCanvas is stored as six square images of textures. You can download images to use as a CubeMap for your game’s skybox (some links are included below). Below is an example of a cube map.

An example of cube mapping. Image by Arieee (redistributed using the CC BY-SA 3.0 license).
An example of cube mapping. Image by Arieee (redistributed using the CC BY-SA 3.0 license).

Watch the video below and then scroll down to find some links to downloadable cube maps for your own project.

Here are some links to free cube maps you can use in your own projects:

Lighting in PlayCanvas

In this tutorial you will learn how to add and modify lighting in your game. You can use different types of lights and have multiple lights in any scenes to change the feel and atmosphere of the game. The three types of lights you can use are:

  • Directional light – light rays come from one direction
  • Point light – a sphere of light that shines in all directions
  • Spot light – a cone of light

Watch the video below to see how you can use lighting in your own PlayCanvas game.

Getting started with PlayCanvas

PlayCanvas is a 3D game development environment in the cloud. You can use PlayCanvas to make your own 3D games and code them in the JavaScript programming language using a web browser like Chrome or Firefox.

In this tutorial you will learn about the PlayCanvas features and tools and how to create, move, rotate, and resize 3D shapes. Watch the video below to get started with PlayCanvas.

Particle systems in Unity

This video tutorial explains how to use particle systems in your Unity game and also an introduction on how to use C# scripts to control a particle system. Watch the video below and then scroll down to see the sample code.

The sample C# code below shows how to play or stop a particle system when a key is pressed. This code should be placed inside the Update() method.

 if (Input.GetKeyDown (KeyCode.E)) {
 if(gameObject.GetComponent<ParticleSystem>().isPlaying == true){
 gameObject.GetComponent<ParticleSystem>().Stop ();
 }
 else{
 gameObject.GetComponent<ParticleSystem>().Play ();
 }
 }

Adding sound to your scene

In this tutorial you will learn how add sound to a scene in your game. You can add sounds that play constantly in a scene such as background music and you can also add sounds that only occur every now and then or that occur after an event. Sounds can also be looped or just play once.

There is also 2D sound (heard everywhere in your scene) and 3D sound (heard only when you are in a specified proximity to an object/sound). Sound can be scripted but you can also add sound without any code at all.

Watch the video below or scroll down to read the step-by-step instructions and sample code.

To add audio to your scene, follow these steps:

  1. Make sure there is one (and only one) Audio Listener component in your scene. It should be attached to the character controller’s camera or main camera. Delete or disable any other audio listeners as there can only be one in any scene.
  2. Add an object (eg. empty object, cube, sphere) or use an existing object in your scene to add the sound to.
  3. Select the object and click ‘Add component’ in the Inspector panel.
  4. Add the ‘Audio source’ component to the object.
  5. Find an audio file (eg. MP3, OGG file) and add it to the ‘audio clip’ property on the audio source component in the inspector panel.
  6. To make the sound play throughout the whole scene, enable ‘Play on awake’. You can also check the ‘Loop’ option to make the sound repeat/loop. Play the scene to test your audio.
  7. To use the audio file as 3D audio, drag the ‘Spatial Blend’ slider from 2D to 3D – this means that you will only hear the sound when you are near the object. You can change some of the properties to specify how it fades away and how close to the object the player needs to be to hear the sound.

To script the audio, add this code to the Start() method:

GetComponent<AudioSource> ().Play();

and to stop the audio:

GetComponent<AudioSource> ().Stop ();

You could also add an ‘if’ statement eg. to make the sound play when a key is pressed. For example, you could add this ‘if’ statement to the Update() method.:

if (Input.GetKey(KeyCode.Space)) {
 GetComponent<AudioSource>().Play();
}

Also, you can check if audio is currently playing by using .isPlaying(). Any looping sound or a song can be turned on and off using an if statement that checks if the audio is currently playing – just add something like this to your Update() method.

if (Input.GetKey (KeyCode.Space)) {
 if(GetComponent<AudioSource>().isPlaying == true){
 GetComponent<AudioSource>().Stop ();
 }
 else{
 GetComponent<AudioSource>().Play ();
 }
 }

How to change the audio clip using code?

If you want to change the audio clip on the audio source during the game (maybe after a certain event or when a key is pressed), you will need to add the following line inside the class (outside of all other methods) in your script:

public AudioClip otherClip;

You will then need to stop the current audio clip from playing before you switch to another audio clip and start playing that one. Inside the Update() method (or whichever method you are controlling the audio from), you will need to add the following code. This code may be placed inside an if statement (eg. if x key is pressed):

GetComponent<AudioSource>().Stop ();

Then, after you have added that line of code you can switch the audio clip and start playing the new audio clip using this code:

GetComponent<AudioSource>().clip = otherClip;
GetComponent<AudioSource>().Play ();

Lastly, you will need to go into Unity and drag the audio clip file (eg. MP3, OGG file) onto the ‘otherClip’ property on the script component (for this script) in the Inspector panel.

Graphical User Interfaces (GUIs)

A Graphical User Interface (GUI) provides a way for the game to provide information to the user or to read information from the user. This can be in the form of labels, buttons, text boxes, sliders, menus, and so on. The GUI can sit on top of the actual game. It is always a good idea to design your GUI before making the game – draw up a storyboard or wireframe with the types of GUI controls you want in the game and where you want to place them.

GUIs are created using code and can be added to any object or script in your game. If you have different parts of the GUI on different objects or scripts, it can become confusing and hard to maintain. It is a good idea to have all the GUI parts in one spot on one object.

In order to add a GUI to your scene, you need to add a special method to the script you have created for your GUI which is attached to an object in your scene eg. the camera. The special method that is used to create a GUI is called OnGUI(). This method takes no parameters and returns no data to whatever called it. The method will draw your GUI components on the screen and is called every single frame, just like the Update() method. Different GUI controls (eg. labels, buttons) will have code that goes inside the OnGUI() method.

Labels

Let’s start making a basic GUI that will draw a label with a short message on the screen. Labels display text on the screen that can be a simple string value, a variable value or a concatenated (joined) string and variable value eg. “Score: ” + scoreVariable.

A label displaying the score.
A label displaying the score.

Watch the video on Labels below or scroll down to read the instructions and sample code.

Create a new scene in your project and a new script called myGUI. Attach this script to the Main Camera. Add the following code to your script inside the class but outside of all other methods (i.e. do not place it inside the Start() or Update() methods).

void OnGUI(){
 GUI.Label (new Rect(0,0,80,20), "Hello");
}

Run the scene and you should see ‘Hello’ displayed on the screen in the top left corner. You have just created a basic GUI with a label that draws in the top left corner of your screen (at position 0 on x axis and position 0 on y axis of screen). The label has a width of 80 and a height of 20. The parameters inside Rect() are x position, y position, width, height. The label can display a string value or variable (or concatenated strings/variables).

Boxes

The box is similar to a label except that a box has a dark border around the label. An example of a box is shown below.

An example of a box.
An example of a box.

Watch the video on Boxes below or scroll down to read the instructions and sample code.

The syntax for creating a box is also similar to creating a label. new Rect() takes the parameters of x position, y position, width, and height). An example of a box containing a “Hello” string message is shown below. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(0,0,80,20), "Hello");

If you want a box at the middle-top area of the screen, you can use code like this. This code would be placed inside the OnGUI() method:

GUI.Box(new Rect(Screen.width / 2 - 20, 0, 80, 20), "Hello");

Buttons

Buttons can be in one of two states. A button can be either pressed down or not pressed down. An if statement can be used to determine whether a button is being pressed (a boolean value of true or false). If you keep the button pressed down with the mouse, it will not behave differently to just clicking once. The image below shows an example of a button.

An example of a button that reloads/resets the current level in a game.
An example of a button that reloads/resets the current level in a game.

Watch the video on Buttons below or scroll down to read the instructions and sample code.

Like labels and boxes, buttons require an x position, y position, a width and a height value. The sample code below shows how to create a button at an x position of 3, a y position of 3, with a width of 80 and height of 20. When the button is clicked it will reload the level (scene) using Application.LoadLevel. In this example the scene is called ‘myScene’. This code would be placed inside the OnGUI() method:

if (GUI.Button (new Rect (3, 3, 80, 20), "Reset")) {
 Application.LoadLevel ("myScene");
 }

Repeat button

A repeat button is like a normal button except that it can be pressed and held down with the mouse click. It can be used to increase the value of a variable while the button is being held down.

repeat_button

The example below increases a variable’s value while the button is being held down. This code would be placed inside the OnGUI() method:

if (GUI.RepeatButton (new Rect (0, 0, 80, 20), "Increase")) {
 myVariable += 1;
 print (myVariable);
 }

Toggle

A toggle button (also known as a ‘stated’ button because it can be in different states) is like a switch – it can be on or off. It can be used to set something in one state or another. It takes a boolean parameter (whether the button is clicked or not) and returns a boolean value (tells the user if the button is clicked).

The two images below show a toggle in two different states (off and on).

Screen Shot 2015-11-15 at 8.45.02 PM Screen Shot 2015-11-15 at 8.45.14 PM

An example of the code is shown below with a boolean variable called ‘mySwitch’.

bool mySwitch = false;
 
void OnGUI(){
 mySwitch = GUI.Toggle(new Rect(290,20,80,20), mySwitch, "My switch");
 }

Toolbar

A toolbar is a row of several buttons. You can have however many buttons you like on a toolbar, but only one button can be selected at any one time. An integer variable is used to keep track of which button is selected and an array of strings is used for the different buttons.

toolbar

The number of items in the array determines how many buttons there are. For example, if there are three items in the array then there will be three buttons. If the first button is selected, the integer value will be 0. If the second button is selected, the integer value will be 1. If the third button is selected, the integer value will be 2, and so on.

The sample code below shows the integer value variable, the array of strings, and the Toolbar GUI control.

int difficulty = 0;
string[] list = {"Easy", "Medium", "Hard"};
 
void OnGUI(){
 difficulty = GUI.Toolbar(new Rect (0,0,200,30), difficulty, list);
 }

 Textfield

A textfield allows the user to input text. The textfield can display text and also accepts text from the user as they click in the box and type in it. A string variable can be used to store text that is displayed inside the textfield, and then store the text that the user types in.

textfield
The code below shows how a textfield can be added to a scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextField(new Rect(600,20,130,30), textInput);
 }

Textarea

A textarea is just like a textfield except that it can store multiple lines of text.

textarea

 

The sample code below shows how to add a textarea control to your scene.

string textInput = "Enter your text here";
void OnGUI(){
 textInput = GUI.TextArea(new Rect(600,20,130,120), textInput);
 }

Sliders

Sliders allow the user to select a value between a range of different values by clicking and dragging a slider with the mouse. You can add horizontal and vertical sliders to your scenes in Unity. The slider takes a float value that is used for the default position of the slider, and returns a float value that contains the value the user changed the slider to. It also takes a minimum and maximum slider value.

sliders

 

The sample code below shows how to add both horizontal and vertical sliders to a scene. In the two examples, there are float variables that are initially set to a value of 0 (inside the main class). Each slider takes a float value and then returns a float value. The x and y positions as well as the width and heigh are specified. Parameters for minimum and maximum values for the sliders are also added at the end of the statement – in this example, the minimum value is 0 and the maximum value is 100.

float horizontalValue = 0;
float verticalValue = 0;
 
void OnGUI(){
 horizontalValue = GUI.HorizontalSlider (new Rect (30, 20, 150, 20), horizontalValue, 0, 100);
 verticalValue = GUI.VerticalSlider (new Rect (5, 5, 20, 150), verticalValue, 0, 100);
 }

In the next tutorial we will look at how to customise and style GUI controls.

Raycasting

Raycasting involves sending out a ‘ray’ and finding out what it hits. Raycasting is used by game developers to find the distance between players and another object, aiming, detecting nearby objects, and finding line of sight.

The code below is one example of using the Raycast method.

bool Raycast(Vector 3 origin, Vector3 direction, float distance, LayerMask mask);

There are a few parameters that this method takes. The first is the Vector3 origin or position of where the ray starts and can hold three floats (the x, y and z coordinates). The second, Vector3 direction, is the direction that the ray will travel. The third, float distance, is the distance that the ray will travel before it stops. The last parameter is mask, which specifies what layers will be hit by the ray. The distance and mask parameters are optional. If they are left out, the ray will travel forever and hit all objects.

The code below could be attached to a camera in your game and used to detect whether an object is in front of the camera.

void Update(){
 if (Physics.Raycast(transform.position, transform.forward, 20))
 {
 print("Something is in front of the camera");
 }
}

There is also another way that the Raycast method can be used. It can be used to find out which object the ray collided with. It can use a type of variable called a RaycastHit. Here is an example of what it can look like:

bool Raycast(Vector3 origin, Vector3 direction, out Raycast hit, float distance);

Where you see ‘out’, it means that whatever object was hit by the raycast will be stored in the ‘hit’ variable when the method finishes running.

Try it out

So let’s give Raycasting a go!

Step 1 – Create a new scene in your project and add a few 3D shapes around the main camera in your scene. The shapes should be close enough to the camera so you can see them clearly when you run the game.

Step 2 – Add at least three or four shapes that are spaced out nicely.

Step 3 – Create a new script called raycastingScript and attach it to your main camera. Add the following code to the Update method inside the script:

float xDirection = Input.GetAxis ("Mouse X");
float yDirection = Input.GetAxis ("Mouse Y");
 
transform.Rotate (-yDirection, xDirection, 0);
 
checkIfRaycastHit ();

Step 4 – Add the following code to your class (outside of all other methods i.e. not inside the Start or Update methods).

void checkIfRaycastHit(){
 RaycastHit hit;
 if(Physics.Raycast(transform.position, transform.forward, out hit)){
 print (hit.collider.gameObject.name + " has been destroyed!");
 Destroy (hit.collider.gameObject);
 }
}

Step 5 – Now run the scene. You will notice that the mouse will now move the camera around. When you center the camera on each object in your scene, those objects will be destroyed and a message will be displayed in the console.

You could extend this game by adding a score or time variable and displaying the score on the screen (something covered in the next tutorial – Graphical User Interfaces!).

Collision detection in Unity

Collision

So what is collision? Collision is knowing when one object has come into contact with another object. In this tutorial, we will look at collision detection, the Rigidbody component, colliders, triggers and physic materials. Scroll down to watch the video on all of these things or read on.

Rigidbody component

For objects to use Unity’s built-in physics engine, they need to include the Rigidbody component. To add it to a selected object, click Component > Physics > Rigidbody from the Inspector panel.

The Rigidbody component gives you several properties to work with including:

  • Mass
  • Drag (the amount of air resistance applied to an object when it is moving – an object with higher mass will need more force to move and will stop at a faster rate)
  • Angular drag (air resistance that is applied when turning)
  • Use Gravity
  • Collision Detection
  • and so on…

Collision detection

In order for objects to detect collision, they both need to use a component called a collider. A collider is a perimeter around an object that can detect when another object enters it.

Note: Objects don’t need rigidbodies to collide – all they need is a collider object. But rigidbodies allow objects to fall and are also needed for trigger collision – we’ll talk about that later.

Colliders

Objects like cubes, spheres and capsules already have collider components when they’re created. You can add a collider to an object by selecting the object and clicking Components > Physics from the Inspector panel, then select the collider shape you want such as box, sphere, capsule, wheel, terrain, or mesh (which takes the exact shape of a 3D model but can greatly reduce game performance).

When a collider is added to a game object the collider will appear in the Inspector panel for that object. Colliders have a number of properties including

  • Is trigger
  • Material (you can apply physic materials to change the way an object behaves – an object can behave like rubber, metal, wood, etc.)
  • Center (the centre of the collider
  • Size
  • and geometric properties eg. radius, if the collider is a sphere

You can try out different colliders with different shapes. For example, you can add a sphere collider to a cube so that it will roll around like a ball, and you can change the size of a collider so that the object either floats above other surfaces or sinks into other surfaces.

Watch the video below to see how you can work with the Rigidbody component, colliders, triggers and physic materials. Then scroll down to see more information on physic materials, triggers and the sample code.

Physic materials

To create a physic material, click Assets > Create > Physic material. You can then modify properties to make the object behave like metal, wood, rubber etc. For example, you can increase bounciness to make it behave like rubber. Once you have created a physic material you can add it to a collider attached to an object from the Inspector panel. Watch the video above to see how.

Triggers

Triggers can call three different methods that allow you to program what a collision event will mean. The three trigger methods are:

  • OnTriggerEnter – this is called when another object enters the trigger
  • OnTriggerStay – this is called when another object stays inside the trigger
  • OnTriggerExit – this is called when another object exits the trigger.

Triggers can be used to program what will happen if a player falls off a map, a player enters water, or an enemy enters a perimeter, for example.

If you added the code below to a script (called triggerScript) attached to a cube, it would display a message in the console whenever another object enters the cube:

using UnityEngine;
using System.Collections;
 
public class triggerScript : MonoBehaviour {
 
 void OnTriggerEnter (Collider other)
 {
 print("Another object has entered the collider");
 }
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

In this code, ‘other’ is referring to “another object”.

You could modify the code to say what specific object has entered the collider, for example:

using UnityEngine;
using System.Collections;
 
public class triggerScript : MonoBehaviour {
 
 void OnTriggerEnter (Collider other)
 {
 print(other.gameObject.name + " has entered the trigger.");
 }
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

Or you could even destroy the other object that has entered the trigger:

using UnityEngine;
using System.Collections;
 
public class triggerScript : MonoBehaviour {
 
 void OnTriggerEnter (Collider other)
 {
 Destroy (other.gameObject);
 }
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 }
}

Remember, you can replace the OnTriggerEnter method with OnTriggerStay and OnTriggerExit too. All of these things are covered in the video.

Why do objects fall through my terrain?

If you add have created objects with colliders that fall through your terrain that has a collider, you might want to disable the collider on your terrain and then use another collider attached to an empty GameObject. Click on GameObject > Create Empty an then attach a collider to that empty object. You can enable ‘Is Trigger’ on that object and then move the object and resize its collider so that it is positioned under your terrain.

Accessing other objects and modifying their components

This tutorial explains how you can write a script in C# that can access other objects and then modify their components. In this example, we will attach a script to the Main Camera and then use that script to access a Cube object and modify it’s position, rotation and scale.

Here is the sample code that is attached to the Main Camera and accessing the Cube object.

using UnityEngine;
using System.Collections;
 
public class moveOtherObject : MonoBehaviour {
 
 // this script accesses another object and modifies its components
 // it can be attached to any other object e.g script and is accessing a Cube
 
 // this is the other game object you want to access
 public GameObject target;
 
 // Use this for initialization
 void Start () {
 target = GameObject.Find ("Cube");
 
 }
 
 // Update is called once per frame
 void Update () {
 target.transform.Translate (0f, 0f, 0.1f);
 target.transform.Rotate (0f, 0f, 1f);
 target.transform.localScale = new Vector3 (1.5f, 1.5f, 1.5f);
 
 }
}

Create a rolling ball game with force and gravity

This tutorial will show you how to create a simple rolling ball game using the Rigidbody physics component in unity to add force and gravity. In this game, we will use the W,A,S,D keys to move the ball left and right, and backwards and forwards. We will also use the Space key to make the ball jump up and gravity will bring the ball back down, as seen in the animated GIF below.

rollingball

Watch the video below to see how you can create a simple rolling ball game with force and gravity. Then scroll down to take a look at the sample code.

Here is the sample code in C# for this game.

using UnityEngine;
using System.Collections;
 
// Simple Rolling Ball Game code - 18 Oct 2015 Daniel Wood
// Add this code to a script called 'move' and then attach the script to a sphere in your game
 
[RequireComponent (typeof(Rigidbody))]
 
public class move : MonoBehaviour {
 
 public float xForce = 10.0f;
 public float zForce = 10.0f;
 public float yForce = 500.0f;
 
 // Use this for initialization
 void Start () {
 
 }
 
 // Update is called once per frame
 void Update () {
 
 // this is for the X axis' movement (moving left and right)
 float x = 0.0f;
 
 if (Input.GetKey (KeyCode.A)) {
 x = x - xForce;
 }
 
 if (Input.GetKey (KeyCode.D)) {
 x = x + xForce;
 }
 
 // this is for the Z axis' movement (moving backwards and forwards)
 float z = 0.0f;
 
 if (Input.GetKey (KeyCode.S)) {
 z = z - zForce;
 }
 
 if (Input.GetKey (KeyCode.W)) {
 z = z + zForce;
 }
 
 // this is for the Y axis' movement (jumping)
 float y = 0.0f;
 
 if (Input.GetKeyDown (KeyCode.Space)) {
 y = yForce;
 }
 
 GetComponent<Rigidbody> ().AddForce (x, y, z);
 
 }
}

This a simple game with no scoring or other objects to interact with, but you could easily extend the game by adding a user interface, scoring, different cameras, and objects to interact with. As an example, you could make a simple pinball game.