libensvivit
libensvivit

Reputation: 93

Rotate a line around a circle in three.js

var lineGeometry  = new THREE.Geometry();
var lineMaterial = new THREE.LineBasicMaterial({
    color: 0x000000
});
lineGeometry.vertices.push(
    new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(0, 10, 0),
);
var line = new THREE.Line(lineGeometry, lineMaterial);
scene.add(line);

I want to update this line's endpoint in a circular fashion. In other languages it is straightforward, I would increase some variable and update the endpoint like radius * cos(dt) and radius * sin(dt). In three.js I tried the following, but it doesn't work:

var dt = 0;
function render(){
    dt += 0.01;
    line.geometry.vertices[1].x = 10*Math.cos(dt);
    line.geometry.vertices[1].z = 10*Math.sin(dt);
    renderer.render(scene, camera);
    requestAnimationFrame(render);
}

edit: I don't want to use line.rotation.z += 0.01 method.

Upvotes: 1

Views: 1054

Answers (1)

TheJim01
TheJim01

Reputation: 8876

line.geometry.verticesNeedUpdate = true;

Add the above line before calling render. This will signal three.js that the vertex buffer has changed, so it will update it appropriately.

Since you mentioned using line.rotation, I must mention that updating the vertices is inefficient compared to rotating the line shape. When you rotate a line shape, you are simply updating the shape's transformation matrix. But when you update vertices, three.js needs to re-upload the entire set of vertices to the GPU. This may seem trivial for a single line segment, but it's a bad habit to get into if you ever intend to use larger shapes later.

Upvotes: 3

Related Questions