Back

Physics

In this tutorial we will experiment how physics work inside nunuStudio, physics are represented as objects in the editor, physics object dont have a visual representation they are just used for physics simulations.

Physics in nunuStudio are powered by cannon.js by schteppe, for more information about the physics engine please consult http://www.cannonjs.org/.

Adding a physics object

To add physics object simply select the desired physics object in the left toolbar and add it to the scene, after that add a mesh object as children of the newly created physics object to make it visible in the scene.

Dont forget to add a ground object so that other physics object don't fall out of the screen.

Physics object can be configured as dynamic, static or kinenamic objects. Dynamic objects are updated dinamically and detect collisions, kinematic objects are updated only based on their speed, and static objects are not updated at all.

Controlling using the keyboard

To interact with physics objects using scrips we need to get the physics body attached to that object. After that we can directly apply forces, change the velocity, etc.

The following code gets an physics object body and using the keyboard WASD keys and the spacebar we add velocity to that body forcing the cube to move around.

var body;

this.initialize = function()
{
	body = scene.getObjectByName("physics").body;
};

this.update = function()
{
	if(Keyboard.keyPressed(Keyboard.A))
	{
		body.velocity.x -= 0.2;
	}
	if(Keyboard.keyPressed(Keyboard.D))
	{
		body.velocity.x += 0.2;
	}
	if(Keyboard.keyPressed(Keyboard.W))
	{
		body.velocity.z -= 0.2;
	}
	if(Keyboard.keyPressed(Keyboard.S))
	{
		body.velocity.z += 0.2;
	}
	
	if(Keyboard.keyJustPressed(Keyboard.SPACEBAR))
	{
		body.velocity.y += 5;
	}
};

Example

The code shown above can be seen running bellow for a physics cube, use the WASD keys to control the cube, and the spacebar to make the cube jump.

You can also download the example project file here, or open it directly inside the Web Editor.