I have two lines that will be created by the user at runtime, so the positions of these two lines are dynamic. I want one line to coincide with another line as shown in the below image.
How should I proceed
Here is my code
var camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.z = 15;
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("app").appendChild(renderer.domElement);
let point1 = new THREE.Vector3(14, 25, -159);
let point2 = new THREE.Vector3(-5, 2, 65);
let rightLine = createLine(point1, point2);
let point1LineTwo = new THREE.Vector3(-45, 11, -4);
let point2LineTwo = new THREE.Vector3(-26, -8, -30);
let leftLine = createLine(point1LineTwo, point2LineTwo);
function createLine(point1, point2) {
const linePoints = [];
linePoints.push(new THREE.Vector3(point1.x, point1.y, point1.z));
linePoints.push(new THREE.Vector3(point2.x, point2.y, point2.z));
let lineGeometry = new THREE.BufferGeometry().setFromPoints(linePoints);
var lineMaterial = new THREE.LineBasicMaterial({
color: 0xff5555,
linewidth: 2,
});
let line = new THREE.Line(lineGeometry, lineMaterial);
scene.add(line);
return line;
}
function makeCoincident() {
let rightLineVector = new THREE.Vector3();
const positions = rightLine.geometry.attributes.position.array;
rightLineVector.x = positions[3] - positions[0];
rightLineVector.y = positions[4] - positions[1];
rightLineVector.z = positions[5] - positions[2];
let leftLineVector = new THREE.Vector3();
const lineLeftPosition = leftLine.geometry.attributes.position.array;
leftLineVector.x = lineLeftPosition[3] - lineLeftPosition[0];
leftLineVector.y = lineLeftPosition[4] - lineLeftPosition[1];
leftLineVector.z = lineLeftPosition[5] - lineLeftPosition[2];
//Calulate angle Between leftLineVector and rightLineVector
let angle = leftLineVector.clone().angleTo(rightLineVector);
//calculate cross prduct of lineOneVector and lineTwoVector
let crossPoductVector = new THREE.Vector3();
crossPoductVector.crossVectors(leftLineVector, rightLineVector);
crossPoductVector.normalize();
rightLineVector.applyAxisAngle(crossPoductVector.clone(), angle);
//align right line on left line
var axis = new THREE.Vector3(0, 1, 0);
rightLine.quaternion.setFromUnitVectors(
axis,
rightLineVector.clone().normalize()
);
}
window.addEventListener("keydown", function (event) {
switch (event.keyCode) {
case 81: // Q
makeCoincident();
break;
default:
}
});
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
I created a sandbox [ Link to code sandbox where I created the same problem without dynamic line creation.
I have two lines with random position. one function named makeCoincident() which makes them coincident which gets called when you press Q key. I tried to solve it but it is not working if you can look into sandbox and tell me where I am going wrong and what is the solution It will be big help thanks
The code you gave is confusing because of the right and left naming. I rewrote the makeCoincident function
https://codepen.io/cdeep/pen/dydQKoV
To summarize briefly, I first move the vertices of the green line to make the center of the green line intersect with the center of the red. And then, set the vertices of green to a point on the extension of red corresponding to the length of green line.
There is infact, no need to move the green line to make intersecting centres. It's just for clarity incase there's a requirement to make them intersecting without the need for coinciding. Can be omitted for the current question.
function makeCoincident() {
const greenLinePositions = rightLine.geometry.attributes.position.array;
const redLinePositions = leftLine.geometry.attributes.position.array;
const greenLineCenter = new THREE.Vector3(
(greenLinePositions[3] + greenLinePositions[0]) * 0.5,
(greenLinePositions[4] + greenLinePositions[1]) * 0.5,
(greenLinePositions[5] + greenLinePositions[2]) * 0.5,
);
const redLineCenter = new THREE.Vector3(
(redLinePositions[3] + redLinePositions[0]) * 0.5,
(redLinePositions[4] + redLinePositions[1]) * 0.5,
(redLinePositions[5] + redLinePositions[2]) * 0.5,
);
const translationVector = redLineCenter.clone().sub(greenLineCenter);
// Vector pointing from center of green to center of red
const translationArray = translationVector.toArray();
for(let i = 0; i < 6; i++) {
greenLinePositions[i] = greenLinePositions[i] + translationArray[i % 3];
// Move vertices of green line towards red
}
rightLine.geometry.attributes.position.needsUpdate = true;
// Centres of red and green now intersect
const greenLineLength = new THREE.Vector3(
greenLinePositions[0] - greenLinePositions[3],
greenLinePositions[1] - greenLinePositions[4],
greenLinePositions[2] - greenLinePositions[5],
).length();
const redLineDirection = new THREE.Vector3(
redLinePositions[0] - redLinePositions[3],
redLinePositions[1] - redLinePositions[4],
redLinePositions[2] - redLinePositions[5],
).normalize();
// Get new positions of green on the extension of red
const greenPoint1 = redLineCenter.clone().add(redLineDirection.clone().multiplyScalar(greenLineLength * 0.5));
const greenPoint2 = redLineCenter.clone().add(redLineDirection.clone().multiplyScalar(greenLineLength * -0.5));
// Set the attribute values from the new position vectors
greenLinePositions[0] = greenPoint1.x;
greenLinePositions[1] = greenPoint1.y;
greenLinePositions[2] = greenPoint1.z;
greenLinePositions[3] = greenPoint2.x;
greenLinePositions[4] = greenPoint2.y;
greenLinePositions[5] = greenPoint2.z;
rightLine.geometry.attributes.position.needsUpdate = true;
}
Related
A particle system based on three.js' Points.
Internally I am treating the particles as global (with position and velocity vectors) and update the Points geometry accordingly.
It works nicely if the Points object is global (and static).
I need to change this so the Points object moves through the Scene (as child of the "particle emitter"). That requires converting global coordinates for each particle to local coordinates for the Points object geometry.
I have attempted the following:
local = globalParticle.position.clone().applyMatrix4( movingPointsObject.matrixWorld.invert() );
and
local = movingPointsObject.worldToLocal( globalParticle.position );
with different results.
The former seems to work in principle, but the particles appear to have duplicates depending on the Z-rotation of the Points object (they align when rotation is PI).
The latter causes the particles to rotate quickly, giving the appearance of a ring.
What's going on?
https://jsfiddle.net/b7nLorvf/
or
const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(480, 480);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color("gray");
const camera = new THREE.OrthographicCamera(-2, 2, 2, -2, 1, 2);
camera.position.set(0, 0, 2);
scene.add(camera);
const light = new THREE.AmbientLight(0xffffff, 0.75); // soft white light
scene.add(light);
const bgeometry = new THREE.BoxGeometry(0.1, 0.1, 0.1);
const bmaterial = new THREE.MeshBasicMaterial({
color: 0xff00ff
});
const cube = new THREE.Mesh(bgeometry, bmaterial);
scene.add(cube);
let pgeometry = new THREE.BufferGeometry();
//pgeometry.setAttribute("position", new THREE.Float32BufferAttribute([], 3));
const pmaterial = new THREE.PointsMaterial({
color: 0xff0000,
size: 2
}); //, depthTest:true } );
let points = new THREE.Points(pgeometry, pmaterial);
const axesHelper = new THREE.AxesHelper(1);
points.add(axesHelper);
//const global = true;
const global = false;
if (global) {
scene.add(points); // global
} else {
cube.add(points); // local
}
let particles = [];
let lt = 0,
dt = 0;
function animate(ms) {
dt = (ms - lt) / 1000;
lt = ms;
// move emitter
const a = ms / 1000;
cube.position.x = Math.cos(a) * 1;
cube.position.y = Math.sin(a) * 1;
cube.rotation.z = a;
// particles
particles.push({
position: cube.position.clone(),
velocity: new THREE.Vector3(2, 0, 0).applyEuler(cube.rotation),
life: 1
});
for (let p of particles) {
p.life -= dt;
}
particles = particles.filter(p => {
return p.life > 0.0;
});
let v = [];
for (let p of particles) {
p.position.add(p.velocity.clone().multiplyScalar(dt));
let vertex;
if (global) {
vertex = p.position;
} else {
//vertex = p.position.clone().applyMatrix4( points.matrixWorld.invert() );
vertex = points.worldToLocal( p.position );
}
v.push(vertex.x, vertex.y, vertex.z);
}
pgeometry.setAttribute("position", new THREE.Float32BufferAttribute(v, 3));
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.148.0/three.min.js"></script>
The former works in conjunction with
movingPointsObject.updateWorldMatrix(true, true);
Inspired by worldToLocal, see three.js/Object3D.js#L256.
I'm trying to implement a simple turn-around-and-move feature with Three.js. On mouse click, the object is supposed to first turn around and then move to the clicked location.
Codepen
The rotation is achieved with raycasting and lookAt(). It works by itself and it always works on the first click. If you remove the translation, it works continuously. The issue occurs when rotation and translation are implemented together. If you click a second time, after the object has moved to the previous clicked location, it doesn't rotate as expected. Depending on the mouse location it can flip to the other side without rotating at all.
Clarification: When you click the first time, notice how the object slowly and steadily turns around to face that direction? But the second time, after the object has moved, the rotation is quicker and/or flimsier or it simply flips over and there is no rotation at all. It depends on where you click in relation to the object.
I believe the issue stems from trying to implement lookAt while being located at the current lookAt location? If I stop the translation half way, the next rotation will work better. But of course I need it to go all the way.
I'm somewhat lost on how to proceed with this issue. Any help would be appreciated.
/*** Setup scene ***/
let width = 800
let height = 600
let scene
let renderer
let worldAxis
let box
let angle
let boxAxes
scene = new THREE.Scene()
worldAxis = new THREE.AxesHelper(200);
scene.add(worldAxis);
// Setup renderer
renderer = new THREE.WebGLRenderer({alpha: true, antialias: true})
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(width, height)
document.body.appendChild(renderer.domElement)
// Setup camera
const camera = new THREE.OrthographicCamera(
width / - 2, // left
width / 2, // right
height / 2, // top
height / - 2, // bottom
0, // near
1000 ); // far
camera.position.set(0, 0, 500)
camera.updateProjectionMatrix()
// Setup box
let geometry = new THREE.BoxGeometry( 15, 15, 15 );
let material = new THREE.MeshBasicMaterial( { color: "grey" } );
box = new THREE.Mesh( geometry, material );
box.position.set(100, 150, 0)
box.lookAt(getPointOfIntersection(new THREE.Vector2(0, 0)))
addAngle()
boxAxes = new THREE.AxesHelper(50);
box.add(boxAxes)
scene.add(box)
renderer.render(scene, camera);
/*** Setup animation ***/
let animate = false
let currentlyObservedPoint = new THREE.Vector2();
let rotationIncrement = {}
let translationIncrement = {}
let frameCount = 0
document.addEventListener('click', (event) => {
let mousePosForRotate = getMousePos(event.clientX, event.clientY)
rotationIncrement.x = (mousePosForRotate.x - currentlyObservedPoint.x)/100
rotationIncrement.y = (mousePosForRotate.y - currentlyObservedPoint.y)/100
let mousePosForTranslate = getMousePosForTranslate(event)
translationIncrement.x = (mousePosForTranslate.x - box.position.x)/100
translationIncrement.y = (mousePosForTranslate.y - box.position.y)/100
animate = true
})
function animationLoop() {
if (animate === true) {
if (frameCount < 100) {
rotate()
} else if (frameCount < 200) {
translate()
} else {
animate = false
frameCount = 0
}
frameCount++
renderer.render(scene, camera)
}
requestAnimationFrame(animationLoop)
}
function rotate() {
currentlyObservedPoint.x += rotationIncrement.x
currentlyObservedPoint.y += rotationIncrement.y
let pointOfIntersection = getPointOfIntersection(currentlyObservedPoint)
box.lookAt(pointOfIntersection)
addAngle()
}
function translate() {
box.position.x += translationIncrement.x
box.position.y += translationIncrement.y
}
function getMousePos(x, y) {
let mousePos = new THREE.Vector3(
(x / width) * 2 - 1,
- (y / height) * 2 + 1,
0)
return mousePos
}
function getMousePosForTranslate(event) {
let rect = event.target.getBoundingClientRect();
let mousePos = { x: event.clientX - rect.top, y: event.clientY - rect.left }
let vec = getMousePos(mousePos.x, mousePos.y)
vec.unproject(camera);
vec.sub(camera.position).normalize();
let distance = - camera.position.z / vec.z;
let pos = new THREE.Vector3(0, 0, 0);
pos.copy(camera.position).add(vec.multiplyScalar(distance));
return pos
}
function getPointOfIntersection(mousePos) {
let plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
let pointOfIntersection = new THREE.Vector3()
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mousePos, camera)
raycaster.ray.intersectPlane(plane, pointOfIntersection)
return pointOfIntersection
}
function addAngle() {
let angle = box.rotation.x - 32
box.rotation.x = angle
}
animationLoop()
<script src='https://cdnjs.cloudflare.com/ajax/libs/three.js/105/three.min.js'></script>
To display rack structure, placing one box upon another. But y Position calculation fails.Currently creates gap between boxes. Please inform how could it be fixed, whether camera or light effect creates a problem. As per rack size, altering y position. Data contain size and starting place.
```
var data = [{"id": 10075,"size": 3,"slotNumber": 1},{"id": 10174,"size": 7,"slotNumber": 4}];
var rackListGroup;
init();
function init() {
scene = new THREE.Scene();
scene.background = new THREE.Color( 0x999999 );
var light = new THREE.AmbientLight( 0xffffff );
light.position.set( 0.5, 1.0, 0.5 ).normalize();
scene.add( light );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.fromArray([0, 0, 140]);
scene.add( camera );
rackListGroup = new THREE.Mesh();
rackListGroup.name = "Rack List"
var i;
for (i = 0; i < 1; i++) {
rackListGroup.add(drawRack(10, i))
}
scene.add(rackListGroup);
render();
}
function drawRack(size, rackNo){
var rackGroup = new THREE.Group();
rackGroup.name = "rack "+rackNo;
var yPosition = -42;
var xPosition = -20 + parseInt(rackNo)*40;
var slot = 1, counter = 0;
var slotWidth = 5;
while(slot <= parseInt(size)){
var slotSize = data[counter].size;
slot = slot + slotSize;
yPosition = yPosition + slotSize* slotWidth;
var geometry = new THREE.BoxGeometry( 30, slotWidth*slotSize, 5 );
var material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
var shape = new THREE.Mesh( geometry, material );
shape.name = data[counter].name;
shape.position.set(xPosition, yPosition, 0);
rackGroup.add(shape);
var boxGeometry = new THREE.BoxBufferGeometry( 30, slotWidth*slotSize, 5, 1, 1, 1 );
var boxMaterial = new THREE.MeshBasicMaterial( { wireframe:true } );
var box = new THREE.Mesh( boxGeometry, boxMaterial );
box.name = data[counter].name;
box.position.set(xPosition, yPosition, 0);
rackGroup.add(box);
if(counter+1 < data.length){
counter++;
}
}
return rackGroup;
}
```
I've tried your code and I see a misunderstanding between the objects position and the objects height to be able to stack them on top of each other.
You use one variable for yPosition and you need 2 variables, the reason is that geometries are positioned based on its axes center, so it means a 15 units height mesh positioned at y=0 it will place indeed at -7.5 units below the y=0 position and the upper side of the geometry will be at 7.5. So next slot to stack will be needed to place (conceptually) at y = 7.5 + (topSlotHeight / 2).
That's why your calculation of the next slot to stack y position is wrong. I have created this fiddle with the solution, and I have added a gridHelper at y=0 for your reference and the OrbitControls to be able to check it better. Now it works perfectly doing like this, storing the accumulated base position of the previous slot in yBaseHeight and the yPosition for the slot on top:
var slotHeight = (slotSize * slotWidth);
yPosition = yBaseHeight + (slotHeight / 2);
yBaseHeight = yBaseHeight + slotHeight;
PD.- I saw you start placing objects at y=-42, I started from y=0 to show better the effect.
My image texture is positioned relative to the center of 3d space instead of mesh and I don't quite understand what determines its size.
Here is example showing how the same image is positioned on different meshes:
https://imgur.com/glHE97L
I'd like the image be in the center of the mesh and it's size set similar as 'contain' in css.
The mesh is flat plane created using ShapeBufferGeometry:
const shape = new THREE.Shape( edgePoints );
const geometry = new THREE.ShapeBufferGeometry( shape );
To see any image I have to set:
texture.repeat.set(0.001, 0.001);
Not sure if that matters but after creating the mesh I than set its position and rotation:
mesh.position.copy( position[0] );
mesh.rotation.set( rotation[0], rotation[1], rotation[2] );
I've tried setting those:
mesh.updateMatrixWorld( true );
mesh.geometry.computeBoundingSphere();
mesh.geometry.verticesNeedUpdate = true;
mesh.geometry.elementsNeedUpdate = true;
mesh.geometry.morphTargetsNeedUpdate = true;
mesh.geometry.uvsNeedUpdate = true;
mesh.geometry.normalsNeedUpdate = true;
mesh.geometry.colorsNeedUpdate = true;
mesh.geometry.tangentsNeedUpdate = true;
texture.needsUpdate = true;
I've played with wrapS / wrapT and offset.
I've checked UV's - I don't yet fully understand this concept but it seems fine. Example of UV for one mesh (I understand those are XY coordinates and they seem to reflect the actual corners of my mesh):
uv: Float32BufferAttribute
array: Float32Array(8)
0: -208
1: 188
2: 338
3: 188
4: 338
5: 12
6: -208
7: 12
I've tried setting:
texture.repeat.set(imgHeight/geometryHeight/1000, imgWidth/geometryWidth/1000);
This is how THREE.ShapeGeometry() computes UV coordinate:
https://github.com/mrdoob/three.js/blob/e622cc7890e86663011d12ec405847baa4068515/src/geometries/ShapeGeometry.js#L157
But you can re-compute them, to put in range [0..1].
Here is an example, click the button to re-compute uvs of the shape geometry:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var grid = new THREE.GridHelper(10, 10);
grid.rotation.x = Math.PI * 0.5;
scene.add(grid);
var points = [
new THREE.Vector2(0, 5),
new THREE.Vector2(-5, 4),
new THREE.Vector2(-3, -3),
new THREE.Vector2(2, -5),
new THREE.Vector2(5, 0)
];
var shape = new THREE.Shape(points);
var shapeGeom = new THREE.ShapeBufferGeometry(shape);
var shapeMat = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load("https://threejs.org/examples/textures/uv_grid_opengl.jpg")
});
var mesh = new THREE.Mesh(shapeGeom, shapeMat);
scene.add(mesh);
btnRecalc.addEventListener("click", onClick);
var box3 = new THREE.Box3();
var size = new THREE.Vector3();
var v3 = new THREE.Vector3(); // for re-use
function onClick(event) {
box3.setFromObject(mesh); // get AABB of the shape mesh
box3.getSize(size); // get size of that box
var pos = shapeGeom.attributes.position;
var uv = shapeGeom.attributes.uv;
for (let i = 0; i < pos.count; i++) {
v3.fromBufferAttribute(pos, i);
v3.subVectors(v3, box3.min).divide(size); // cast world uvs to range 0..1
uv.setXY(i, v3.x, v3.y);
}
uv.needsUpdate = true; // set it to true to make changes visible
}
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<button id="btnRecalc" style="position: absolute;">Re-calculate UVs</button>
I want to make camera move along the curve,it works, but when pass the turning corner,camera speed changed,looks like slowly.
curve = new THREE.CatmullRomCurve3(vectors);
curve.type = 'catmullrom';
curve.tension = 0.2;
this.MKY.Camera.current = this.roamCamera;
cameraWrap.add(this.roamCamera);
this.MKY.scene.add(cameraWrap);
this.MKY.update.push(roam);
function roam() {
if(!isAutoRoam){return}
if(progress>1 || progress==1){
progress = 0;
return
}
progress += 0.0005;
var position = curve.getPointAt(progress);
position.y += 1.5;
var tangent = curve.getTangentAt(progress);
cameraWrap.position.copy(position);
cameraWrap.lookAt(position.sub(tangent));
};
getPointAt returns a vector for point at a relative position in curve according to arc length. I think if progress not change ,i will get the average speed,but it is not. I do not understend.
There is the approach, using .getUtoTmapping() method of THREE.Curve() (in the example, it's THREE.CatmullRomCurve3).
The documentation says:
.getUtoTmapping ( u, distance )
Given u in the range ( 0 .. 1 ), returns t also in the range ( 0 .. 1 ). u and t can then be used to give you points which are equidistant from the ends of the curve, using .getPoint.
So, when you provide the second parameter in this method, then, if I got it correctly from the source code, it ignores the first parameter, thus you can find the point on your curve by the distance on it.
In the given picture:
small yellow points - points, taken with .getPoints() method;
big maroon points - points, whose distance between each other along the curve is 1 unit;
The code for the maroon points:
var unitPoints = [];
for (let i = 0; i < spline.getLength(); i++){
let p = spline.getUtoTmapping(0, i);
let p1 = spline.getPoint(p);
unitPoints.push(p1);
}
var unitPointsGeometry = new THREE.Geometry();
unitPointsGeometry.vertices = unitPoints;
var units = new THREE.Points(unitPointsGeometry, new THREE.PointsMaterial({size: .125, color: "maroon"}));
scene.add(units);
Look at the source code of the code snippet and pay attention to the getProgress() function.
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, .1, 1000);
camera.position.set(0, 1.5, 3);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x181818);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper(4, 8));
var spline = new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-2, 0, 0),
new THREE.Vector3(-1.9, .1, .1),
new THREE.Vector3(1, 1, 1),
new THREE.Vector3(0, -1, -2),
new THREE.Vector3(2, 0, 1)
]
);
spline.closed = true;
var splinePoints = spline.getPoints(200);
var lineGeom = new THREE.Geometry();
lineGeom.vertices = splinePoints;
var line = new THREE.Line(lineGeom, new THREE.LineBasicMaterial({
color: "orange"
}));
scene.add(line);
var sPoints = new THREE.Points(lineGeom, new THREE.PointsMaterial({
size: .0312,
color: "yellow"
}));
scene.add(sPoints);
var unitPoints = [];
for (let i = 0; i < spline.getLength(); i++) {
let p = spline.getUtoTmapping(0, i);
let p1 = spline.getPoint(p);
unitPoints.push(p1);
}
var unitPointsGeometry = new THREE.Geometry();
unitPointsGeometry.vertices = unitPoints;
var units = new THREE.Points(unitPointsGeometry, new THREE.PointsMaterial({
size: .125,
color: "maroon"
}));
scene.add(units);
var marker = new THREE.Mesh(new THREE.SphereGeometry(0.125, 4, 2), new THREE.MeshBasicMaterial({
color: "red",
wireframe: true
}));
marker.geometry.translate(0, 0, 0.0625);
marker.geometry.vertices[2].z = 0.25;
marker.geometry.vertices[4].z = 0;
scene.add(marker);
var markerLineGeometry = new THREE.Geometry();
markerLineGeometry.vertices.push(new THREE.Vector3(), new THREE.Vector3());
var line = new THREE.Line(markerLineGeometry, new THREE.LineBasicMaterial({
color: "white"
}));
scene.add(line);
var clock = new THREE.Clock();
var progress = 0;
var totalLength = spline.getLength();
var speed = .66; // unit a second
var ratio = speed / totalLength;
var shift = 0;
var basePoint = 0;
var lookAtPoint = 0;
var oldPosition = spline.getPoint(0);
var speedVector = new THREE.Vector3();
function setProgress(delta) {
if (progress > totalLength) progress = 0;
shift = progress + speed * 2;
shift = shift > totalLength ? shift - totalLength : shift;
basePoint = spline.getUtoTmapping(0, progress);
lookAtPoint = spline.getUtoTmapping(0, shift);
line.geometry.vertices[0].copy(spline.getPoint(basePoint));
line.geometry.vertices[1].copy(spline.getPoint(lookAtPoint));
line.geometry.verticesNeedUpdate = true;
marker.position.copy(line.geometry.vertices[0]);
marker.lookAt(line.geometry.vertices[1]);
progress += speed * delta;
}
render();
function render() {
requestAnimationFrame(render);
setProgress(clock.getDelta());
renderer.render(scene, camera);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>