[SOLVED] How to use the playcanvas.github.co code

I am trying to test the sample code PlayCanvas Examples in my project

The whole thing is a function called function example (). How do I run this function in my project without having to rewrite any of it?

Hi,

Do you want the fly camera functionality in your project? The script can be found here, you can attach this script to your camera and it should behave like in the above example you posted.

If you want to run any of the examples from there in the editor, you will have to port the functionalities in the editor scripts, you can leverage the editor to setup the models in the world and re create it in the editor, unfortunately just copy pasting the whole function won’t work.

Aren’t the github examples just using playcanvas engine? How can I set up an environment to run the same code?

@metame here is the Fly Camera example,
You can copy-paste this into an HTML file and run it.

<html>

<script src="https://code.playcanvas.com/playcanvas-latest.js"></script>

<body>

  <canvas id="application-canvas"></canvas>

  <a id="logo" href="https://playcanvas.com/" target="_blank"><img

      src="http://static.playcanvas.com/images/logo/PLAY_FLAT_ORANGE3_SMALL.png" /></a>

</body>

<script>

  const canvas = document.getElementById('application-canvas');

  // Create the application and start the update loop

  const app = new pc.Application(canvas, {

    mouse: new pc.Mouse(canvas),

    keyboard: new pc.Keyboard(window),

  });

  app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW)

  app.setCanvasResolution(pc.RESOLUTION_AUTO)

  window.addEventListener('resize', () => app.resizeCanvas())

  app.scene.ambientLight = new pc.Color(0.2, 0.2, 0.2);

  app.start();

  // ***********    Helper functions    *******************

  function createMaterial(color) {

    const material = new pc.StandardMaterial();

    material.diffuse = color;

    // we need to call material.update when we change its properties

    material.update();

    return material;

  }

  function createBox(position, size, material) {

    // create an entity and add a model component of type 'box'

    const box = new pc.Entity();

    box.addComponent("render", {

      type: "box",

      material: material,

    });

    // move the box

    box.setLocalPosition(position);

    box.setLocalScale(size);

    // add the box to the hierarchy

    app.root.addChild(box);

  }

  // ***********    Create Boxes    *******************

  // create a few boxes in our scene

  const red = createMaterial(pc.Color.RED);

  for (let i = 0; i < 3; i++) {

    for (let j = 0; j < 2; j++) {

      createBox(new pc.Vec3(i * 2, 0, j * 4), pc.Vec3.ONE, red);

    }

  }

  // create a floor

  const white = createMaterial(pc.Color.WHITE);

  createBox(new pc.Vec3(0, -0.5, 0), new pc.Vec3(10, 0.1, 10), white);

  // ***********    Create lights   *******************

  // make our scene prettier by adding a directional light

  const light = new pc.Entity();

  light.addComponent("light", {

    type: "omni",

    color: new pc.Color(1, 1, 1),

    range: 100,

  });

  light.setLocalPosition(0, 0, 2);

  // add the light to the hierarchy

  app.root.addChild(light);

  // ***********    Create camera    *******************

  // Create an Entity with a camera component

  const camera = new pc.Entity();

  camera.addComponent("camera", {

    clearColor: new pc.Color(0.5, 0.5, 0.8),

    nearClip: 0.3,

    farClip: 30,

  });

  // add the fly camera script to the camera

  camera.addComponent("script");

  var FlyCamera = pc.createScript('flyCamera');

  FlyCamera.attributes.add('speed', {

    type: 'number',

    default: 10

  });

  FlyCamera.attributes.add('fastSpeed', {

    type: 'number',

    default: 20

  });

  FlyCamera.attributes.add('mode', {

    type: 'number',

    default: 0,

    enum: [{

      "Lock": 0

    }, {

      "Drag": 1

    }]

  });

  FlyCamera.prototype.initialize = function () {

    // Camera euler angle rotation around x and y axes

    var eulers = this.entity.getLocalEulerAngles();

    this.ex = eulers.x;

    this.ey = eulers.y;

    this.moved = false;

    this.lmbDown = false;

    this.lastTouchPosition = new pc.Vec2();

    // Disabling the context menu stops the browser displaying a menu when

    // you right-click the page

    this.app.mouse.disableContextMenu();

    this.app.mouse.on(pc.EVENT_MOUSEMOVE, this.onMouseMove, this);

    this.app.mouse.on(pc.EVENT_MOUSEDOWN, this.onMouseDown, this);

    this.app.mouse.on(pc.EVENT_MOUSEUP, this.onMouseUp, this);

    if (this.app.touch) {

      this.app.touch.on(pc.EVENT_TOUCHSTART, this.onTouchStart, this);

      this.app.touch.on(pc.EVENT_TOUCHEND, this.onTouchEnd, this);

      this.app.touch.on(pc.EVENT_TOUCHMOVE, this.onTouchMove, this);

      this.app.touch.on(pc.EVENT_TOUCHCANCEL, this.onTouchCancel, this);

    }

  };

  FlyCamera.prototype.update = function (dt) {

    // Update the camera's orientation

    this.entity.setLocalEulerAngles(this.ex, this.ey, 0);

    var app = this.app;

    var speed = this.speed;

    if (app.keyboard.isPressed(pc.KEY_SHIFT)) {

      speed = this.fastSpeed;

    }

    // Update the camera's position

    if (app.keyboard.isPressed(pc.KEY_UP) || app.keyboard.isPressed(pc.KEY_W)) {

      this.entity.translateLocal(0, 0, -speed * dt);

    } else if (app.keyboard.isPressed(pc.KEY_DOWN) || app.keyboard.isPressed(pc.KEY_S)) {

      this.entity.translateLocal(0, 0, speed * dt);

    }

    if (app.keyboard.isPressed(pc.KEY_LEFT) || app.keyboard.isPressed(pc.KEY_A)) {

      this.entity.translateLocal(-speed * dt, 0, 0);

    } else if (app.keyboard.isPressed(pc.KEY_RIGHT) || app.keyboard.isPressed(pc.KEY_D)) {

      this.entity.translateLocal(speed * dt, 0, 0);

    }

    if (app.keyboard.isPressed(pc.KEY_V)) {

      // check if XR is supported and VR is available

      if (this.app.xr.supported) {

        console.log("IS Supported");

        if (this.app.xr.isAvailable(pc.XRTYPE_VR)) {

          console.log("IS AVAILABLE");

        } else {

          console.log("IS NOT AVAILABLE");

        }

      } else {

        console.log("IS NOT Supported");

      }

      if (this.app.xr.supported && this.app.xr.isAvailable(pc.XRTYPE_VR)) {

        // start VR using a camera component

        this.entity.camera.startXr(pc.XRTYPE_VR, pc.XRSPACE_LOCALFLOOR, function (err) {

          if (err) {

            console.log("Failed to start session");

          }

        });

      }

    } else if (app.keyboard.isPressed(pc.KEY_B)) {

      this.app.xr.end();

    }

  };

  FlyCamera.prototype.rotateCamera = function (dx, dy) {

    this.ex -= dy / 5;

    this.ex = pc.math.clamp(this.ex, -90, 90);

    this.ey -= dx / 5;

  };

  FlyCamera.prototype.onMouseMove = function (event) {

    if (!this.mode) {

      if (!pc.Mouse.isPointerLocked())

        return;

    } else {

      if (!this.lmbDown)

        return;

    }

    // Update the current Euler angles, clamp the pitch.

    if (!this.moved) {

      // first move event can be very large

      this.moved = true;

      return;

    }

    this.rotateCamera(event.dx, event.dy);

  };

  FlyCamera.prototype.onMouseDown = function (event) {

    if (event.button === 0) {

      this.lmbDown = true;

      // When the mouse button is clicked try and capture the pointer

      if (!this.mode && !pc.Mouse.isPointerLocked()) {

        this.app.mouse.enablePointerLock();

      }

    }

  };

  FlyCamera.prototype.onMouseUp = function (event) {

    if (event.button === 0) {

      this.lmbDown = false;

    }

  };

  FlyCamera.prototype.onTouchStart = function (event) {

    if (event.touches.length == 1) {

      this.lmbDown = true;

      var touch = event.touches[0];

      this.lastTouchPosition.set(touch.x, touch.y);

    }

    event.event.preventDefault();

    // check if XR is supported and VR is available

    if (this.app.xr.supported) {

      console.log("IS Supported");

      if (this.app.xr.isAvailable(pc.XRTYPE_VR)) {

        console.log("IS AVAILABLE");

      } else {

        console.log("IS NOT AVAILABLE");

      }

    } else {

      console.log("IS NOT Supported");

    }

    if (this.app.xr.supported && this.app.xr.isAvailable(pc.XRTYPE_VR)) {

      // start VR using a camera component

      this.camera.startXr(pc.XRTYPE_VR, pc.XRSPACE_LOCAL, function (err) {

        if (err) {

          console.log("Failed to start session");

        }

      });

    }

  };

  FlyCamera.prototype.onTouchEnd = function (event) {

    if (event.touches.length === 0) {

      this.lmbDown = false;

    } else if (event.touches.length == 1) {

      var touch = event.touches[0];

      this.lastTouchPosition.set(touch.x, touch.y);

    }

  };

  FlyCamera.prototype.onTouchMove = function (event) {

    var touch = event.touches[0];

    if (event.touches.length == 1) {

      this.rotateCamera((touch.x - this.lastTouchPosition.x), (touch.y - this.lastTouchPosition.y), this.touchLookSensitivity);

    }

    this.lastTouchPosition.set(touch.x, touch.y);

  };

  FlyCamera.prototype.onTouchCancel = function (event) {

    this.lmbDown = false;

  };

  camera.script.create("flyCamera");

  // add the camera to the hierarchy

  app.root.addChild(camera);

  // Move the camera a little further away

  camera.translate(2, 0.8, 9);

</script>

</html>

Here is the editor project having the fly camera script
https://playcanvas.com/editor/scene/1329052

Hi metame. In addition to what Saad_Haider has written, I recently tried to recreate one of the examples in an editor project. I could reuse a fair proportion of the example’s code but not everything eg assets and script loading, and the interaction with the HUD. Here is the result and code

Thank you all!

This is great. In this example, how can I load an FBX file with texture JPGs on a server? Does this HTML file have to be in the same domain as the FBX file?

Hi @metame, PlayCanvas can’t import FBX models on runtime. Those work only in editor and get converted to GLB.

Your best best is to do that, convert your remote models to GLB and load them.

Here is a similar post: Model loads without textures and got HTTPS 403 forbidden error - #4 by yaustar

And here is an example on how that works: Loading glTF GLBs | Learn PlayCanvas

1 Like

Thank you!