3 Feb 2021

Getting started with cannon.js | Three.js | Tutorial #1

In this post I will talk about Cannon JS. Cannon.js is a javascript framework based 3D Physics. Which is Inspired By Ammo.js and three.js. Cannon JS can make your application interactive & realistic with Physics.

Cannon JS can be used in Threejs project to make it interesting by Applying Physics to. It is easier to use, Just need to some basic knowledge to CannonJs's class.

Import CDN - Cannon JS.

Import Cannon JS CDN link to your project. Put Cannon cdn directly under the <body/> tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/cannon.js/0.6.2/cannon.min.js"/>

Cannon JS Hello Word Example

Cannon js World

CANNON.World, A world where physics is going to apply.
And set gravity to world, I set gravity to y axis 9.82 m/s² acordindly Earth's Gravity.

CannonJS Geometry

CannonJS Geometry is a real world object entity.
Creating a sphere with specific radius, CANNON.Sphare Constructor.
Creating a ground object with CANNON.Plane .
Passing this CANNON.Plane to CANNON.Body constructor.
Here, we make it static by passing mass = 0 .
At last, adding the geometry's bodies to CANNON.World by calling its add() method over it.

var world = new CANNON.World();       world.gravity.set(0,0, 9.82);

var mass = 5, radius = 1; 
    var sphereShape = new CANNON.Sphere(radius); 
    // Step 1
     var sphereBody = new CANNON.Body({mass: mass, shape: sphereShape});
      // Step 2
      sphereBody.position.set(0,0,0); world.add(sphereBody); // Step 3
      var groundShape = new CANNON.Plane();
       var groundBody = new CANNON.Body({ mass: 0, shape: groundShape });


No comments:

No Comments