Scripting
Adding Physics to Your Effect With Script Packages

Adding Physics to Your Effect Using Script Packages

In this tutorial we’ll add gravity to a 3D Sphere using a script package available in: AR Library.

You'll use the cannon-js script package in this tutorial, but there are lots of other script packages to choose from depending on the effect you're creating. Browse the Script Packages section in AR Library to find them.

Import the script package

Start by opening Spark AR Studio and importing the script package:

  1. Open Spark AR Studio.
  2. Open AR Library.
  3. Select Script Packages.
  4. Select the cannon-js script package from the menu.
  5. Click Import Free.

The script package will be listed under Packages in the Assets panel.

Import a 3D Object

You'll add the gravity effect to a 3D object. You can use your own 3D object or an object from AR Library - for example, a sphere:

Add the object to the Scene panel.

To add the object to the scene, drag it from the Assets panel into the Scene panel.

Below, we've added the sphere. It's listed as SphereObject in the Scene panel and visible in the Viewport and Simulator:

The script



// script.js

const Scene = require('Scene');
const Time = require('Time')
const CANNON = require('cannon');

// Create cannon world and setting gravity
const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);

// Create sphere body and setting its shape and properties
const radius = 1;
const sphereProps = {
  mass: 5,
  position: new CANNON.Vec3(0, 10, 0),
  radius: radius,
  shape: new CANNON.Sphere(radius),
}

const sphereBody = new CANNON.Body(sphereProps);
world.addBody(sphereBody);

// Reference SphereObject from Scene
const sphere = Scene.root.find('SphereObject');


// Create ground body and settings its shape and properties
const groundProps = {
  mass: 0,
  position: new CANNON.Vec3(0, -sphereProps.radius, 0),
  shape: new CANNON.Plane(),
}
const groundBody = new CANNON.Body(groundProps);

// Rotate the ground so it is flat (facing upwards)
const angle = -Math.PI / 2;
const xAxis = new CANNON.Vec3(1, 0, 0);
groundBody.quaternion.setFromAxisAngle(xAxis, angle);

world.addBody(groundBody);

// Configure time step for Cannon
const fixedTimeStep = 1.0 / 60.0;
const maxSubSteps = 3;
const timeInterval = 30;
let lastTime;

// Create time interval loop for cannon 
Time.setInterval(function (time) {
  if (lastTime !== undefined) {
    let dt = (time - lastTime) / 1000;
    world.step(fixedTimeStep, dt, maxSubSteps)

    sphere.transform.x = sphereBody.position.x;
    sphere.transform.y = sphereBody.position.y;
    sphere.transform.z = sphereBody.position.z;
  }

  lastTime = time
}, timeInterval);

         
    
Was this article helpful?