Why the translation is laggy in ThreeJS?

Viewed 214

I am new to ThreeJS and still exploring the library.

I have a very basic example of drawing a white dot, with a simple translation force.

let dotGeometry = new THREE.Geometry();
let dotMaterial = new THREE.PointsMaterial({
  size: 10,
  color: 0xffffff,
});
dotGeometry.vertices.push(new THREE.Vector3(1, 0, -1));
let dot = new THREE.Points(dotGeometry, dotMaterial);
scene.add(dot);

function animate() {
  requestAnimationFrame(animate);
  dot.position.x += 0.01;
  renderer.render(scene, camera);
}

animate();

I was wondering why the translation is pretty laggy even with a single point rendered on screen.

Is there a better way to achieve smoother transformations, am I doing something wrong?

Many thanks in advance. Andrea

1 Answers

Actually you should always honor the time delta of a single animation step when transforming objects. In this way, a value like 0.1 gets a better semantic. It's 0.1 world units per second. It also makes the animation more smooth and independent of the framerate. Try this code:

const camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 5;

const scene = new THREE.Scene();

const clock = new THREE.Clock();

const dotGeometry = new THREE.Geometry();
const dotMaterial = new THREE.PointsMaterial({
  size: 10,
  color: 0xffffff,
});
dotGeometry.vertices.push(new THREE.Vector3(1, 0, -1));
const dot = new THREE.Points(dotGeometry, dotMaterial);
scene.add(dot);

const renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

function animate() {
  requestAnimationFrame(animate);
  const delta = clock.getDelta();
  dot.position.x += 0.1 * delta;
  renderer.render(scene, camera);
}

animate();
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.123/build/three.js"></script>

Related