Tag Archives: apply

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.

 

 

 

How to apply materials, shaders and textures to objects in Unity

This video tutorial explains how to create materials in Unity so that you can change the colour of 3D objects. The video also explains how to use shaders and image textures textures in Unity.

Before you watch the video, here is a brief rundown of the differences between materials, shaders and textures:

  • Materials contain properties and textures. Materials can be directly applied to a 3D object.
  • Shaders dictate which properties and which textures that a material can have. Shaders are not directly applied to models but are instead applied to materials.
  • Textures are also applied to materials. Textures are flat images that can be wrapped around 3D objects. These images often contain repeating patterns such as a brick wall.

The images below show three different materials. The first material has a standard shader applied to it. The second material has a specular shader applied to it for increased shininess. The third material has a diffuse shader and a brick wall texture applied to it.

Standard shader with red colour.
Standard shader with red colour.
Specular shader with red colour.
Specular shader with red colour.
Diffuse shader with brick wall image texture.
Diffuse shader with brick wall image texture.