Tag Archives: object

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;
});

 

Moving objects with keyboard input in PlayCanvas

If you watched the previous tutorial you would have learned how to make an object move on its own using JavaScript code. In this tutorial, we will make an object move around using keyboard input. That is, if the left arrow key is pressed on the keyboard then we can make the object move left. If the right arrow key is pressed on the keyboard then we can make the object move right, and so on…

Keyboard input will be very useful in your games eg. to make a player jump, to move around, pick up objects or enter your name in the high score book! Watch the video to find out how to add keyboard input to your games and then try out the sample code further down the page.

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.

In the code, you will see app.keyboard.isPressed – this will check if the key is being pressed during the current frame. If you hold down the key, the object will keep moving. If you use another method called app.keyboard.wasPressed instead it will only check if the key was pressed in the current frame (it will detect one keypress and won’t keep the object moving when you hold the key down).

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) {
 if(app.keyboard.isPressed(pc.input.KEY_RIGHT)){
 this.entity.translateLocal(0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_LEFT)){
 this.entity.translateLocal(-0.1,0,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_UP)){
 this.entity.translateLocal(0,0.1,0);
 }
 
 if(app.keyboard.isPressed(pc.input.KEY_DOWN)){
 this.entity.translateLocal(0,-0.1,0);
 }
 }
 };
 
 return Move;
});

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;
});

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!).

How to create a basic skeleton for an object in Maya

This video explains how to create a basic skeleton for an object in Maya. When you create a skeleton, it is made up of bones and joints as shown below. The skeleton can be placed inside an object and you can then bind to skin (bind the skeleton to the object).

A basic skeleton setup.
A basic skeleton setup.

Watch the video below to find out how to set up a basic skeleton and attach it to an object (bind to skin).

Animate a skeleton on a motion path in Maya

This video explains how to animate an object’s skeleton to a motion path in Maya. When you animate a object with its skeleton attached to a motion path, the object can bend along the curve. This is useful if you are trying to animate the movement of something like a fish or a snake.

An object with its skeleton attached to a motion path.
An object with its skeleton attached to a motion path.

Watch the video to find out how to animate a skeleton to a motion path.

Note: It is important to follow the step where you rotate the object so that it is facing straight towards you when viewing from the right-side view. If you don’t do this then the motion path animation will be a bit buggy. It is also important to remember to click on Modify and Centre Pivot before attaching the object to the motion path.

Introduction to JSON

JSON stands for JavaScript Object Notation. JSON is a light-weight data interchange format that uses JavaScript syntax in text format that can be read and used as data by other programming languages.

In this example, we will use JSON to define an object with an array of records – we will use the Avengers characters for this example. Watch the video below and then scroll down to see the sample code.

Here is the sample code:

<!DOCTYPE html>
<html>
<head>
 <title>JSON</title>
</head>
 
<body>
<h2>The Avengers</h2>
 
<p id="avengerstext"></p>
 
<script>
var text='{"avengers":['+
'{"firstName":"Bruce","lastName":"Banner"},'+
'{"firstName":"Tony","lastName":"Stark"},'+
'{"firstName":"Natalia","lastName":"Romanova"},'+
'{"firstName":"Thor","lastName":"Odinson"}]}';
 
obj = JSON.parse(text);
document.getElementById("avengerstext").innerHTML=obj.avengers[0].firstName+" "+obj.avengers[0].lastName+"<br>"+obj.avengers[1].firstName+" "+obj.avengers[1].lastName+"<br>"+obj.avengers[2].firstName+" "+obj.avengers[2].lastName+"<br>"+obj.avengers[3].firstName+" "+obj.avengers[3].lastName;
 
</script>
 
</body>
</html>

Animating an image using JavaScript

This tutorial shows how to animate (move) an image across the screen. You can combine the code with other code from previous tutorials such as the one on timed image swapping to also get images to swap while they are moving (eg. you could use two images for a character with legs in different positions, so as the images swap it looks like the character is running).

You will need an image to use in your animation. Keep the image file in the same folder as your HTML file. In the sample code below, the image’s file name is image.png (a PNG image file). Start and stop buttons have also been added to start/stop the animation. This is what the animation will look like:

imageanimated

Refer to the comments in the code below to find out what is happening on each line.

<html>
<head>
<title>JavaScript Image Animation</title>
<script type="text/javascript">
<!--
var imgObj ;
var animate ;
function init(){
 imgObj = document.getElementById('myImage');
 imgObj.style.position= 'relative'; 
 imgObj.style.left = '0px'; 
}
function moveRight(){
 imgObj.style.left = parseInt(imgObj.style.left) + 5 + 'px'; // move from the left 5 pixels
 animate = setTimeout(moveRight,20); // call moveRight in 20 milliseconds
}
function stop(){
 clearTimeout(animate); // stops the animation
 // add imgObj.style.left = '0px'; if you want to reset the image back to the left side of screen
}
window.onload =init; // starts animation when page loads
//-->
</script>
</head>
<body>
<form>
<img id="myImage" src="image.png" width="100" height="100"/>
<p>Click the buttons below to start and stop the animation.</p>
<input type="button" value="Play" onclick="moveRight();" />
<input type="button" value="Stop" onclick="stop();" />
</form>
</body>
</html>

Next tutorial: Keyboard events in JavaScript

Using the HTML5 canvas to draw shapes

The code below shows how to use the HTML5 canvas and JavaScript in a webpage to draw objects. In this example, the object will be a simple rectangle shape inside a canvas with a grey border. The rectangle will be filled with red and have a blue border. It will look like this:

Screen Shot 2015-05-04 at 7.53.26 pm

You can use the canvas for drawings, animations, and even games. Watch the video below to see how to create a canvas and draw a rectangle shape, then scroll down to see the code.

Check out the sample code below. You can view all the different HTML colour codes that you can use here.

<!DOCTYPE html>
<html>
<head>
 <title>Simple canvas with rectangle drawing</title>
 <style>
 #myCanvas{
 background-color: white;
 border: 1px solid black;
 }
 </style>
 
 <script>
 function draw(){
 var ctx = document.getElementById("myCanvas").getContext("2d");
 ctx.fillStyle = "red";
 ctx.strokeStyle = "blue";
 ctx.fillRect(0,0,150,75);
 ctx.strokeRect(0,0,150,75);
 }
 window.onload=draw;
 </script>
</head>
<body>
 <canvas id="myCanvas" width="200" height="100">
</body>
</html>

Next tutorial: Drawing lines using the HTML5 canvas element