Create plane from polyline points using threejs - javascript

I am trying to achieve something like this:
I have a Polyline and its points now I want to create a sheet same as shown in the image. Above is polyline and below a sheet created from that polyline points.
I followed solution from this post Extruding a line in three.js but when I try this it renders nothing.
Here is the code which I tried:
let containerThreeJs = document.getElementById('threed-view-container');
let w = containerThreeJs.offsetWidth;
let h = containerThreeJs.offsetHeight;
let renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(w, h);
containerThreeJs.appendChild(renderer.domElement);
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(5, 1, 1, 1000);
camera.position.setScalar(300);
let threeDpoints = [
[88.5, 370],
[229.5, 268],
[300.5, 333],
[373.5, 290],
[426.5, 392]
];
let geometry = extrudePath(threeDpoints, 100);
var material = new THREE.MeshBasicMaterial({
color: 0x00ff00,
side: THREE.DoubleSide
});
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
render();
function resize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resize(renderer)) {
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
function extrudePath(points, depth) {
var geometry = new THREE.PlaneGeometry(10, 10, points.length - 1, 1);
var vertices = geometry.vertices;
// if I comment this loop then the plane is visible
for (var i = 0, l = points.length, p; i < l; i++) {
p = points[i];
vertices[i].x = vertices[i + l].x = p[0];
vertices[i].y = vertices[i + l].y = p[1];
vertices[i].z = p[2];
vertices[i + l].z = p[2] + depth;
}
geometry.computeFaceNormals();
return geometry;
}
<script src="http://mrdoob.github.io/three.js/build/three.min.js"></script>
<script src=http://mrdoob.github.io/three.js/examples/js/controls/OrbitControls.js></script>
<div id="threed-view-container" style="width: 100%; height: 500px"></div>
If I remove the for-loop from extrudePath then the simple plane is visible, but if I keep it nothing seems to render.

I'm not sure, but i see this: In the points array threeDpoints, every point has 2 parts. However in the extrudePath function it's looking for 3. (p[0], p[1], p[2])
`let threeDpoints = [
[88.5, 370],
[229.5, 268],
[300.5, 333],
[373.5, 290],
[426.5, 392]
];
`
`p = points[i];
vertices[i].x = vertices[i + l].x = p[0];
vertices[i].y = vertices[i + l].y = p[1];
vertices[i].z = p[2];
vertices[i + l].z = p[2] + depth;`

Related

How to free-draw a line in three.js r144 on mouse move, and using BufferGeometry?

I'm using code from this repo - scribble, which is using three.js r87. I followed the Updating THREE.Geometry to THREE.BufferGeometry tutorial in order to upgrade the code to three.js r144. I've got one function correct, but the other one is giving me trouble.
The mousePressed function was easy to update:
function mousePressed() {
const point = new THREE.Vector3(mouseX, mouseY, 0);
// const geometry = new THREE.Geometry();
// geometry.vertices.push(point);
let points = [];
points.push(point);
let geometry = new THREE.BufferGeometry().setFromPoints(points);
const line = new THREE.Line(geometry, material);
scene.add(line);
selected = line;
}
But I updated mouseDragged(), and I don't understand why it's not working:
function mouseDragged() {
const line = selected;
const point = new THREE.Vector3(mouseX, mouseY, 0);
const oldgeometry = line.geometry;
// const newgeometry = new THREE.Geometry();
// newgeometry.vertices = oldgeometry.vertices;
// newgeometry.vertices.push(point);
let newgeometry = new THREE.BufferGeometry();
let positions = oldgeometry.attributes.position.array;
for (let i = 0; i < positions.length; i += 3) {
const v = new THREE.Vector3(positions[i], positions[i + 1], positions[i + 2]);
positions[i] = v.x;
positions[i + 1] = v.y;
positions[i + 2] = v.z;
}
positions.push(point); // I should just be able to add the new point, no?
newgeometry.attributes.position.needsUpdate = true;
line.geometry = newgeometry;
scene.add(line); // I re-added the line, just in case. But the line does not show up, whether or not I do this.
selected = line;
}
Help is much appreciated!
Thanks
The code from the resource is highly inefficient since you continuously allocate geometries all the time without disposal management which will lead to a memory leak. Try the following approach:
let camera, scene, renderer, line;
const frustumSize = 4;
let index = 0;
const coords = new THREE.Vector3();
init();
render();
function init() {
const aspect = window.innerWidth / window.innerHeight;
camera = new THREE.OrthographicCamera(frustumSize * aspect / -2, frustumSize * aspect / 2, frustumSize / 2, frustumSize / -2, 0.1, 20);
camera.position.z = 5;
scene = new THREE.Scene();
const geometry = new THREE.BufferGeometry();
const positionAttribute = new THREE.BufferAttribute(new Float32Array(1000 * 3), 3); // allocate large enough buffer
positionAttribute.setUsage(THREE.DynamicDrawUsage);
geometry.setAttribute('position', positionAttribute);
const material = new THREE.LineBasicMaterial()
line = new THREE.Line(geometry, material);
scene.add(line);
// initial points
addPoint(0, 0, 0); // start point
addPoint(1, 0, 0); // current pointer coordinate
//
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.addEventListener('pointerdown', onPointerDown);
renderer.domElement.addEventListener('pointermove', onPointerMove);
window.addEventListener('resize', onWindowResize);
}
function addPoint(x, y, z) {
const positionAttribute = line.geometry.getAttribute('position');
positionAttribute.setXYZ(index, x, y, z);
positionAttribute.needsUpdate = true;
index++;
line.geometry.setDrawRange(0, index);
}
function updatePoint(x, y, z) {
const positionAttribute = line.geometry.getAttribute('position');
positionAttribute.setXYZ(index - 1, coords.x, coords.y, 0);
positionAttribute.needsUpdate = true;
}
function onPointerDown(event) {
coords.x = (event.clientX / window.innerWidth) * 2 - 1;
coords.y = -(event.clientY / window.innerHeight) * 2 + 1;
coords.z = (camera.near + camera.far) / (camera.near - camera.far);
coords.unproject(camera);
addPoint(coords.x, coords.y, 0);
render();
}
function onPointerMove(event) {
coords.x = (event.clientX / window.innerWidth) * 2 - 1;
coords.y = -(event.clientY / window.innerHeight) * 2 + 1;
coords.z = (camera.near + camera.far) / (camera.near - camera.far);
coords.unproject(camera);
updatePoint(coords.x, coords.y, 0)
render();
}
function onWindowResize() {
const aspect = window.innerWidth / window.innerHeight;
camera.left = -frustumSize * aspect / 2;
camera.right = frustumSize * aspect / 2;
camera.top = frustumSize / 2;
camera.bottom = -frustumSize / 2;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
render();
}
function render() {
renderer.render(scene, camera);
}
body {
margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three#0.144/build/three.min.js"></script>
The idea is to allocate a single large buffer to store all current and future points of a line. You then use setDrawRange() to define, what parts of the buffer should be rendered.

three.js BufferGeometry blob code update error

I currently learning three js and I was following this tutorial however noticed that the code is invalid for the current version of threejs and you can see the main change below. Going by this document I've updated the bit of code to:
var k = 1;
const positions = sphere.geometry.attributes.position.array;
for (var i = 0; i < positions.length - 2; i++) {
const v = new THREE.Vector3(
positions[i],
positions[i + 1],
positions[i + 2]
).normalize()
.multiplyScalar(
1 + 0.3 * noise.perlin3(
positions[i] * k + time,
positions[i + 1] * k,
positions[i + 2] * k));
positions[i] = v.x;
positions[i + 1] = v.y;
positions[i + 2] = v.z;
}
sphere.geometry.attributes.position.needsUpdate = true;
However as you can see from the snippet the vertex displacement is not smooth and does not resemble the tutorial. What I'm missing here?
var renderer = new THREE.WebGLRenderer({ canvas : document.getElementById('canvas'), antialias:true});
// default bg canvas color //
renderer.setClearColor(0x7b7b7b);
// use device aspect ratio //
renderer.setPixelRatio(window.devicePixelRatio);
// set size of canvas within window //
renderer.setSize(window.innerWidth, window.innerHeight);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 5;
var sphere_geometry = new THREE.SphereGeometry(1, 128, 128);
const material = new THREE.MeshPhongMaterial({
color: 0x0000FF,
shininess: 1000,
})
var sphere = new THREE.Mesh(sphere_geometry, material);
scene.add(sphere);
const ambientLight = new THREE.AmbientLight(0x798296)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
directionalLight.position.set(5, 10, 7)
scene.add(directionalLight);
sphere.geometry.attributes.position.needsUpdate = true;
var update = function() {
// change '0.003' for more aggressive animation
var time = performance.now() * 0.003;
//console.log(time)
//go through vertices here and reposition them
// change 'k' value for more spikes
var k = 1;
const positions = sphere.geometry.attributes.position.array;
for (var i = 0; i < positions.length - 2; i++) {
const v = new THREE.Vector3(
positions[i],
positions[i + 1],
positions[i + 2]
).normalize()
.multiplyScalar(
1 + 0.3 * noise.perlin3(positions[i] * k + time, positions[i + 1] * k,
positions[i + 2] * k));
positions[i] = v.x;
positions[i + 1] = v.y;
positions[i + 2] = v.z;
}
sphere.geometry.attributes.position.needsUpdate = true;
}
function animate() {
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
update();
/* render scene and camera */
renderer.render(scene,camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
html, body {
margin:0;
overflow:hidden
}
<script src="https://fariskassim.com/stage/rebel9/teaf/blob/v4/js/perlin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<canvas id="canvas"></canvas>
This is how you can deform a sphere with noise, using BufferGeometry:
var renderer = new THREE.WebGLRenderer({ canvas : document.getElementById('canvas'), antialias:true});
// default bg canvas color //
renderer.setClearColor(0x7b7b7b);
// use device aspect ratio //
renderer.setPixelRatio(window.devicePixelRatio);
// set size of canvas within window //
renderer.setSize(window.innerWidth, window.innerHeight);
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 5;
var sphere_geometry = new THREE.SphereGeometry(1, 128, 128);
const material = new THREE.MeshPhongMaterial({
color: 0x0000FF,
shininess: 1000,
})
var sphere = new THREE.Mesh(sphere_geometry, material);
scene.add(sphere);
const ambientLight = new THREE.AmbientLight(0x798296)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
directionalLight.position.set(5, 10, 7)
scene.add(directionalLight);
sphere.geometry.attributes.position.needsUpdate = true;
var update = function() {
// change '0.003' for more aggressive animation
var time = performance.now() * 0.003;
//console.log(time)
//go through vertices here and reposition them
// change 'k' value for more spikes
var k = 1;
var v3 = new THREE.Vector3();
const positions = sphere.geometry.attributes.position;
for (var i = 0; i < positions.count; i++) {
v3.fromBufferAttribute(positions, i).setLength(k);
let n = noise.perlin3(v3.x, v3.y, v3.z);
v3.setLength(1 + 0.3 * n);
positions.setXYZ(i, v3.x, v3.y, v3.z);
}
positions.needsUpdate = true;
sphere.geometry.computeVertexNormals(); // don't forget to call this
}
function animate() {
sphere.rotation.x += 0.01;
sphere.rotation.y += 0.01;
update();
/* render scene and camera */
renderer.render(scene,camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
html, body {
margin:0;
overflow:hidden
}
<script src="https://fariskassim.com/stage/rebel9/teaf/blob/v4/js/perlin.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<canvas id="canvas"></canvas>

Accessing the vertices using the new PlaneBufferGeometry in ThreeJS

I understand PlaneGeometry has been deprecated and we should use PlaneBufferGeometry with the latest releases. The following code worked with the build before R125, I just don't know how to tweak the code to make it work with PlaneBufferGeometry:
var flagGeom = new THREE.PlaneBufferGeometry(4.5, 2.2, 40, 100, 200); // Replaced "PlaneGeometry " with "PlaneBufferGeometry" here.
flagGeom.translate(2.2, 1.1, 0);
flagGeom.vertices.forEach(v => { // Undefined error here.
v.init = v.clone()
});
Looks like your question is related to this forum topic.
You can do the things this way (just an option, not the ultimate solution): use an additional array stored in userData, and use .setXYZ() method.
body{
overflow: hidden;
margin: 0;
}
<script src="https://josephg.github.io/noisejs/perlin.js"></script>
<script type="module">
console.clear();
import * as THREE from 'https://cdn.skypack.dev/three#0.129.0/build/three.module.js';
import { OrbitControls } from 'https://cdn.skypack.dev/three#0.129.0/examples/jsm/controls/OrbitControls.js';
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-1, 0.5, 2).setLength(2.5);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x401000);
document.body.appendChild(renderer.domElement);
var controls = new OrbitControls(camera, renderer.domElement);
var light = new THREE.DirectionalLight(0xff5500, 2);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xff0000, 1));
var loader = new THREE.TextureLoader();
// flag
var flagGeom = new THREE.PlaneGeometry(4, 2, 40, 20);
flagGeom.translate(2, 1, 0);
let pos = flagGeom.attributes.position;
flagGeom.userData = {
init: []
}
for(let i = 0; i < pos.count; i++){
flagGeom.userData.init.push(new THREE.Vector3().fromBufferAttribute(pos, i));
}
console.log(flagGeom.userData.init);
var flagMat = new THREE.MeshStandardMaterial({
color: 0x777777,
map: loader.load("https://cywarr.github.io/small-shop/PW_flag/PW_flag_map.png"),
alphaMap: loader.load("https://cywarr.github.io/small-shop/PW_flag/PW_flag_alphaMap.png"),
alphaTest: 0.5,
side: THREE.DoubleSide,
metalness: 0.5,
roughness: 0.5
});
var flag = new THREE.Mesh(flagGeom, flagMat);
flag.position.set(-2, -1, 0);
flag.rotation.x = THREE.Math.degToRad(-18);
scene.add(flag);
// staff
var staff = new THREE.Mesh(new THREE.CylinderGeometry(0.04, 0.04, 4, 8), new THREE.MeshStandardMaterial({
color: "black"
}));
flag.add(staff);
// background canvas texture
var canvas = document.createElement("canvas");
canvas.width = 128;
canvas.height = 64;
var ctx = canvas.getContext('2d');
var image = ctx.createImageData(canvas.width, canvas.height);
var data = image.data;
var canvasTexture = new THREE.CanvasTexture(canvas);
scene.background = canvasTexture;
window.addEventListener( 'resize', onWindowResize );
var clock = new THREE.Clock();
var delta = 0;
var time = 0;
var v = new THREE.Vector3();
render();
function render() {
requestAnimationFrame(render);
delta = clock.getDelta();
time += delta;
flagGeom.userData.init.forEach( (vi, idx) => {
v.copy(vi);
let yFade = Math.sin(v.y / flagGeom.parameters.height * Math.PI) * 0.25;
v.x = v.x + yFade;
let xFade = (v.x / flagGeom.parameters.width);
v.z = noise.perlin2((v.x - (time * 2)) / flagGeom.parameters.width * 4, v.y / flagGeom.parameters.height * 2) * xFade;
pos.setXYZ(idx, v.x, v.y, v.z);
});
flagGeom.computeVertexNormals();
pos.needsUpdate = true;
drawFrame(time);
canvasTexture.needsUpdate = true;
renderer.render(scene, camera);
}
function drawFrame(time) {
var cWidth = canvas.width;
var cHeight = canvas.height;
for (var x = 0; x < cWidth; x++) {
for (var y = 0; y < cHeight; y++) {
var value = Math.abs(noise.simplex3(x / cWidth, y / cHeight, time * 0.25));
var cell = (x + y * cWidth) * 4;
data[cell] = 128 + Math.floor(128 * value);
data[cell + 1] = Math.floor(256 * value);
data[cell + 2] = 0;
data[cell + 3] = 255; // alpha.
}
}
ctx.fillColor = 'black';
ctx.fillRect(0, 0, 100, 100);
ctx.putImageData(image, 0, 0);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
</script>

ThreeJS: How to replace a cube mesh with a car mesh?

I developed a 3D cube that moves on one axis simulating the accelerometer sensor.
Currently, I have the .obj and .mtl of a toycar which I aim to add to the scene(), but when I remove the
BoxGeometry 3D cube and replace it with the car mesh I got these errors all the time:
I also get this error saying that obj is not defined, even if I defined it globally I still have the same issue:
I checked libraries that exist locally and other function but I can't see where is the problem.
Below is how I load the car model:
const scene = new THREE.Scene();
var loader = new THREE.OBJMTLLoader();
loader.load('https://jyunming-chen.github.io/tutsplus/models/toycar.obj', 'https://jyunming-chen.github.io/tutsplus/models/toycar.mtl',
function (vehicle) {
toycar = vehicle;
toycar.rotateY(-10.99);
scene.add(toycar);
});
and this is my full .HTML code with js implementation:
This is hoq looks like now:
and this is what I am aiming to achieve:
That's my current code:
<html>
<head>
<meta charset="UTF-8">
<script src="./three.min.js"></script>
<script src="./require.js" type="text/javascript"></script>
<script src="./OrbitControls.js"></script>
<script src="./KeyboardState.js"></script>
<script src="./MTLLoader.js"></script>
<script src="./OBJMTLLoader.js"></script>
<script type="module"> import * as THREE from "./three.module.js"</script>
</head>
<body>
<canvas id="canvas" width="1000" height="600" style="border:1px solid #000000;"></canvas>
</body>
<script>
let sensorValue = 0;
let sensorAddr = 0;
var toycar;
StartRetrieveLiveData();
function main() {
const canvas = document.querySelector('#canvas');
const accelPanel = document.querySelector('#accelPanel');
const renderer = new THREE.WebGLRenderer({ alpha: true, canvas });
renderer.setClearColor( 0x626d73, 1 );
var context = canvas.getContext("2d");
var width = window.innerWidth;
var height = window.innerHeight;
const fov = 70;
const aspect = 2;
const near = 20;
const far = 500;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 50, 1.5);
camera.up.set(0, 0, 1);
camera.lookAt(0, 0, 0);
const scene = new THREE.Scene();
// var loader = new THREE.OBJMTLLoader();
// loader.load('https://jyunming-chen.github.io/tutsplus/models/toycar.obj', 'https://jyunming-chen.github.io/tutsplus/models/toycar.mtl',
// function (vehicle) {
// toycar = vehicle;
// toycar.rotateY(-10.99);
// scene.add(toycar);
// });
// An array of objects who's rotation to update
const objects = [];
const radius = 3;
const widthSegments = 3;
const heightSegments = 3;
const sphereGeometry = new THREE.BoxGeometry(radius, widthSegments, heightSegments);
const sunMaterial = new THREE.MeshBasicMaterial({ color: "green", wireframe: false });
const object = new THREE.Mesh(sphereGeometry, sunMaterial);
var cubeAxis = new THREE.AxesHelper(10);
object.add(cubeAxis);
object.scale.set(2, 2, 2);
scene.add(object);
objects.push(object);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
objects.forEach((obj) => {
sensorValueIndex = ((sensorValue / 16384) * 10);
obj.position.z = ((sensorValue / 16384) * 20);
console.log("AccX: ",sensorValueIndex);
// // Here I take accelerometerX and pass them to the 3D model
// if (sensorAddr === 1) {
// }
});
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
function onMsg(event) {
// console.log(`[message] Data received from server: ${event.data}`);
// console.log("event.data = " + JSON.parse(event.data));
var received_msg = event.data;
var obj = JSON.parse(JSON.parse(received_msg));
if (obj !== null) {
if (
obj.hasOwnProperty("DataMapChangedObjectsAddressValue") &&
obj["DataMapChangedObjectsAddressValue"][0]["DataMapAddress"] !==
undefined
) {
sensorAddr =
obj["DataMapChangedObjectsAddressValue"][0]["DataMapAddress"];
sensorValue =
obj["DataMapChangedObjectsAddressValue"][0]["Value"];
// if (sensorAddr === 1) {
// sensorValueIndex = (sensorValue / 16384) * 500;
// }
}
}
}
function onOpen(e) {
console.log("SSE connected");
}
function onError(e) {
// console.log(`[error] ${error.message}`);
if (e.eventPhase == EventSource.CLOSED) this.source.close();
if (e.target.readyState == EventSource.CLOSED) {
console.log("SSE Disconnected");
} else if (e.target.readyState == EventSource.CONNECTING) {
console.log("SSE Connecting ...");
}
}
function StartRetrieveLiveData() {
if (!!window.EventSource) {
this.source = new EventSource("/sse");
} else {
console.log("Your browser doesn't support SSE");
}
this.source.addEventListener("message", e => this.onMsg(e));
this.source.addEventListener("open", e => this.onOpen(e), false);
this.source.addEventListener("error", e => this.onError(e), false);
// Add here (only mozilla)
main();
// Add here
}
</script>
</html>
Note that when I used a public server the whole thing works just fine, but I used the remote server (the actual server) I get these error and the whole thing doesn't work as expected.
Would appreciate a solution for this.
I solved the problem so I am going to answer this.
Firstly, the document.querySelector('#canvas') should be removed to avoid creating two canvas, because I am calling the libraries in the . This was a silly mistake but I found it finally.
Secondly, the camera position was off and it wasn't really pointing at the car so nothing was shown on the screen. I tweaked the camera.position on the X, Y and Z axis to get it right.
There were bunches of other silly mistakes I found while carefully debugging the code, I am not an expert in the language yet so these mistakes serve as a learning experience for me.
The final working code is below:
let sensorValue = 0;
var toycar;
StartRetrieveLiveData();
var scene, renderer, camera;
var controls, keyboard = new KeyboardState();
var toycar;
function init() {
var width = window.innerWidth;
var height = window.innerHeight;
renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
renderer.setClearColor(0x626d73, 1);
renderer.setSize(width, height);
document.body.appendChild(renderer.domElement);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(10, width / height, 1, 10000);
camera.position.y = -150;
camera.lookAt(new THREE.Vector3(0, 0, 0));
var loader = new THREE.OBJMTLLoader();
loader.load('./toycar.obj', './toycar.mtl',
function (object) {
toycar = object;
toycar.rotateZ(10.99); //toycar.rotateZ(-10.99);
scene.add(toycar);
});
var gridXZ = new THREE.GridHelper(350000, 10000);
gridXZ.setColors(new THREE.Color(0xff0000), new THREE.Color(0xffffff));
scene.add(gridXZ);
var pointLight = new THREE.PointLight(0xffffff);
pointLight.position.set(350, 20, 5);
scene.add(pointLight);
var ambientLight = new THREE.AmbientLight(0x111111);
scene.add(ambientLight);
}
function animate() {
var angle = 0;
var speed = 0;
var pos = new THREE.Vector3(0, 0, 0);
var clock = new THREE.Clock();
var dt = clock.getDelta();
var dir = new THREE.Vector3(1, 0, 0);
dir.multiplyScalar(dt * speed);
dir.applyAxisAngle(new THREE.Vector3(0, 0, 0), 10);
pos.add(dir);
if (toycar != undefined) {
sensorValueIndex = ((sensorValue / 16384) * 50);
toycar.scale.set(0.1, 0.1, 0.1);
toycar.position.x = sensorValueIndex;
toycar.position.y = 0;
toycar.position.z = 0;
toycar.rotation.x = (angle + Math.PI);
}
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
function onMsg(event) {
var received_msg = event.data;
var obj = JSON.parse(JSON.parse(received_msg));
if (obj !== null) {
if (
obj.hasOwnProperty("DataMapChangedObjectsAddressValue") &&
obj["DataMapChangedObjectsAddressValue"][0]["DataMapAddress"] !==
undefined
) {
let sensorAddr =
obj["DataMapChangedObjectsAddressValue"][0]["DataMapAddress"];
sensorValue =
obj["DataMapChangedObjectsAddressValue"][0]["Value"];
if (sensorAddr === 1) {
sensorValueIndex = (sensorValue / 16384) * 10;
console.log(sensorValueIndex);
}
}
}
}

Directional/spotlight light in threejs with helper

i m following this guide for the light Light in Threejs
and i already add some light in my scene.
Now i m try to add a light on the character of my game, but still dont work.
i use the same code of the guide changing just the position.set
const color = 0xFFFFFF;
const intensity = 1;
const light2 = new THREE.SpotLight(color, intensity,0,Math.PI/3);
light2.position.set(100,-5000,1000);
light2.target = lightTarget;
light2.castShadow = true;
const helper2 = new THREE.SpotLightHelper(light2);
and after i add in this way to my character
self.flame.add( helper2 );
self.flame.add(lightTarget);
self.flame.add(light2);
I added a helper too, but if I use just the helper in the scene , so if comment
self.flame.add(light2)
I see the position of the light in perfect way, when add the light the helper disappear (in other light don't happened) and the light go as her want.
Someone can help me?
The helpers have to be parented to the scene (or at least the SpotLightHelper does). You may or may not want to parent the target to the scene.
You also need to call helper.update for each helper
'use strict';
/* global THREE, dat */
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 45;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 100;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 10, 20);
const controls = new THREE.OrbitControls(camera, canvas);
controls.target.set(0, 5, 0);
controls.update();
const scene = new THREE.Scene();
scene.background = new THREE.Color('black');
{
const planeSize = 40;
const loader = new THREE.TextureLoader();
const texture = loader.load('https://threejsfundamentals.org/threejs/resources/images/checker.png');
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.RepeatWrapping;
texture.magFilter = THREE.NearestFilter;
const repeats = planeSize / 2;
texture.repeat.set(repeats, repeats);
const planeGeo = new THREE.PlaneBufferGeometry(planeSize, planeSize);
const planeMat = new THREE.MeshPhongMaterial({
map: texture,
side: THREE.DoubleSide,
});
const mesh = new THREE.Mesh(planeGeo, planeMat);
mesh.rotation.x = Math.PI * -.5;
scene.add(mesh);
}
const cubes = [];
let parent = scene;
{
const cubeSize = 1;
const cubeGeo = new THREE.BoxBufferGeometry(cubeSize, cubeSize, cubeSize);
const cubeMat = new THREE.MeshPhongMaterial({
color: '#8AC',
emissive: '#333',
});
for (let i = 0; i < 6; ++i) {
const mesh = new THREE.Mesh(cubeGeo, cubeMat);
mesh.position.set(1, 0, 0);
parent.add(mesh);
cubes.push(mesh);
parent = mesh;
}
}
cubes[0].position.set(-3, 7, 0);
const color = 0xFFFFFF;
const intensity = 1;
const light = new THREE.SpotLight(color, intensity);
light.position.set(0, 0, 0);
light.target.position.set(0, -1, 0);
parent.add(light);
parent.add(light.target);
//scene.add(light.target);
const helper = new THREE.SpotLightHelper(light);
scene.add(helper);
function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}
function render(time) {
time *= 0.001;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
for (const cube of cubes) {
cube.rotation.z = Math.sin(time) * .4;
}
light.angle = THREE.Math.lerp(
THREE.Math.degToRad(20),
THREE.Math.degToRad(80),
Math.sin(time * 0.77) * 0.5 + 0.5);
helper.update();
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
html, body {
margin: 0;
height: 100%;
}
#c {
width: 100%;
height: 100%;
display: block;
}
<canvas id="c"></canvas>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r105/three.min.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r105/js/controls/OrbitControls.js"></script>

Categories