如何解决babylonjs 帧动画物体移动过程会闪烁的问题?

发布于 2022-09-12 22:42:55 字数 2726 浏览 33 评论 0

import * as babylon from 'babylonjs'

const canvas = document.getElementById('app') as HTMLCanvasElement
const engine = new babylon.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true  })
const scene = new babylon.Scene(engine)

const createScene = () => {
  const camera = new babylon.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 10, new babylon.Vector3(0, 0, 0), scene);
  // const camera = new babylon.UniversalCamera("Camera", new babylon.Vector3(0, 5, -20), scene);
}

const createDirectionLights = () => {
  const lightName = `light_${Math.random()}`
  new babylon.DirectionalLight(lightName, new babylon.Vector3(0, 0, 10), scene);
}


const createPlane = () => {
  const name = `plane_${Math.random()}`
  const plane = babylon.MeshBuilder.CreateBox(name, {
    width: 4,
    height: 1.5,
    depth: 1
  }, scene);

  const materialName = `material_${Math.random()}`;
  const material = new babylon.StandardMaterial(materialName, scene);
  material.useLogarithmicDepth = true;
  material.diffuseColor = new babylon.Color3(255, 255, 255);
  plane.material = material;
  plane.position = new babylon.Vector3(0, 2, 2);
  plane.rotation = new babylon.Vector3(1.5, 0, 0);

  const frameRate = 10;
  // animation y
  const yKeyFrames = [{
    frame: 0,
    value: 1
  }, {
    frame: 100, 
    value: -1
  }];

  const yAnimationName = `y_${Math.random()}`;
  const yAnimation = new babylon.Animation(yAnimationName, 'position.y',
  frameRate, BABYLON.Animation.ANIMATIONTYPE_FLOAT);
  yAnimation.setKeys(yKeyFrames);

  // animation z
  const zKeyFrames = [{
    frame: 0,
    value: 3
  }, {
    frame: 100,
    value: -5
  }];

  const zAnimationName = `z_${Math.random()}`;
  const zAnimation = new babylon.Animation(zAnimationName, 'position.z',
    frameRate, BABYLON.Animation.ANIMATIONTYPE_FLOAT);
  zAnimation.setKeys(zKeyFrames);
  
  const groupName = `group_${Math.random()}`;
  const group = new babylon.AnimationGroup(groupName);
  group.addTargetedAnimation(yAnimation, plane);
  group.addTargetedAnimation(zAnimation, plane);
  // group.normalize(0, 200 / 60);
  // 增加动画监听器
  group.onAnimationEndObservable.add(() => {
    plane.dispose();
  })
  group.play();
}

const init = () => {
  let startTime = Date.now()
  createScene()
  createDirectionLights();
  createPlane();

  engine.runRenderLoop(() => {
    // const currentTime = Date.now();
    // if (currentTime - startTime > 2000) {
    //   createPlane();
    //   startTime = currentTime;
    // }
    scene.render()
  })
  window.addEventListener('resize', () => {
    engine.resize()
  })
}

init()

const plane = babylon.MeshBuilder.CreateBox,plane在移动过程中会出现抖动和闪烁,该如何解决?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文