Related
I am creating a game where players can move around from first-person perspective, where the ground is generated with Perlin noise and therefore uneven. I would like to simulate gravity in the game. Hence, a raycasting thing has been implemented, which is supposed to find the player's distance from the ground and stop them from falling when they hit the ground. Here is my code (if the snipper is unclear visit https://3d.211368e.repl.co):
const scene = new THREE.Scene(), camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000000000000), renderer = new THREE.WebGLRenderer(), canvas = renderer.domElement;
camera.rotation.order = "YXZ";
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
document.body.appendChild(canvas);
const light = new THREE.DirectionalLight( 0xffffff, 1);
light.position.set(0, 10000, 0);
light.castShadow = true;
light.shadow.camera.top = 10000;
light.shadow.camera.right = 10000;
light.shadow.camera.bottom = -10000;
light.shadow.camera.left = -10000;
light.shadow.camera.far = 100000;
wwwww
scene.add(light);
var sky = new THREE.Mesh(new THREE.SphereGeometry(100000, 3, 3, 0, Math.PI, 0, Math.PI), new THREE.MeshBasicMaterial({color: 0x579ebb}));
sky.material.side = THREE.BackSide;
sky.rotateX(-Math.PI / 2);
scene.add(sky);
class Vector2{
constructor(x, y){
this.x = x;
this.y = y;
}
dot(other){
return this.x * other.x + this.y * other.y;
}
}
function Shuffle(tab){
for(let e = tab.length-1; e > 0; e--){
let index = Math.round(Math.random() * (e-1)),
temp = tab[e];
tab[e] = tab[index];
tab[index] = temp;
}
}
function MakePermutation(){
let P = [];
for(let i = 0; i < 256; i++){
P.push(i);
}
Shuffle(P);
for(let i = 0; i < 256; i++){
P.push(P[i]);
}
return P;
}
let P = MakePermutation();
function GetConstantVector(v){
let h = v & 3;
if(h == 0) return new Vector2(1.0, 1.0);
if(h == 1) return new Vector2(-1.0, 1.0);
if(h == 2) return new Vector2(-1.0, -1.0);
return new Vector2(1.0, -1.0);
}
function Fade(t){
return ((6 * t - 15) * t + 10) * t ** 3;
}
function Lerp(t, a1, a2){
return a1 + t*(a2-a1);
}
function Noise2D(x, y){
let X = Math.floor(x) & 255;
let Y = Math.floor(y) & 255;
let xf = x - Math.floor(x);
let yf = y - Math.floor(y);
let topRight = new Vector2(xf - 1, yf - 1);
let topLeft = new Vector2(xf, yf - 1);
let bottomRight = new Vector2(xf - 1, yf);
let bottomLeft = new Vector2(xf, yf);
let valueTopRight = P[P[X+1]+Y+1];
let valueTopLeft = P[P[X]+Y+1];
let valueBottomRight = P[P[X+1]+Y];
let valueBottomLeft = P[P[X]+Y];
let dotTopRight = topRight.dot(GetConstantVector(valueTopRight));
let dotTopLeft = topLeft.dot(GetConstantVector(valueTopLeft));
let dotBottomRight = bottomRight.dot(GetConstantVector(valueBottomRight));
let dotBottomLeft = bottomLeft.dot(GetConstantVector(valueBottomLeft));
let u = Fade(xf);
let v = Fade(yf);
return Lerp(u, Lerp(v, dotBottomLeft, dotTopLeft), Lerp(v, dotBottomRight, dotTopRight));
}
const plane = new THREE.Mesh(new THREE.PlaneGeometry(10000, 10000, 500, 500), new THREE.MeshPhongMaterial({color: 0x00aa00}));
plane.rotateX(-Math.PI / 2 + 0.00001);
plane.receiveShadow = true;
for (let y = 0, i = 0; y < 501; y++){
for(let x = 0; x < 501; x++, i++){
let n = 0.0, a = 1.0, f = 0.005;
for (let o = 0; o < 3; o++){
let v = a*Noise2D(x*f, y*f);
n += v;
a *= 0.5;
f *= 2.0;
}
n += 1;
n /= 2;
plane.geometry.vertices[i].z = n * 1000;
}
}
scene.add(plane);
const point = plane.geometry.vertices[Math.floor(Math.random() * 1000)];
camera.position.set(point.x, point.z + 2, point.y);
const geo = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshBasicMaterial({color: 0xff0000}));
geo.castShadow = true;
scene.add(geo);
const render = () => {
requestAnimationFrame(render);
const below = new THREE.Vector3(camera.position.x, -1000000, camera.position.y), cast = new THREE.Raycaster(camera.position, below), intersect = cast.intersectObject(plane);
if (intersect.length > 0){
if (intersect[0].distance < 3) camera.translateY(-1);
}else{
camera.translateY(-1);
}
renderer.render(scene, camera);
}
render();
onmousemove = () => {
if (camera.rotation._x > -0.8 || camera.rotation._y > -0.8){
camera.rotateX(-Math.atan(event.movementY / 300));
camera.rotateY(-Math.atan(event.movementX / 300));
}else{
if (Math.atan(event.movementY / 300) < 0) camera.rotateX(-Math.atan(event.movementY / 300));
if (Math.atan(event.movementX / 300) < 0) camera.rotateY(-Math.atan(event.movementX / 300));
}
camera.rotation.z = 0;
}
onresize = () => {
renderer.setSize(window.innerWidth, window.innerHeight);
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
onkeydown = (event) => {
if (event.key == "w") camera.translateZ(-10);
if (event.key == "a") camera.translateX(-1);
if (event.key == "s") camera.translateZ(1);
if (event.key == "d") camera.translateX(1);
if (event.key == "ArrowUp") camera.translateY(1);
if (event.key == "ArrowDown") camera.translateY(-1);
}
body{
margin: 0;
background-color: black;
overflow: hidden;
}
canvas{
border: none;
}
<meta name="viewport" content="width=device-width">
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/utils/SceneUtils.js"></script>
<script src="https://cdn.rawgit.com/mrdoob/three.js/0949e59f/examples/js/libs/dat.gui.min.js"></script>
If the ground is not detected at least 3 units below the camera, the player will continue falling. However, sometimes nothing is spotted below the camera, while the player is clearly hovering over the ground. This is extremely frustrating. Is there any reliable alternative method to solve this problem, such as using something other than raycasting? Or is there a bug in the code? TIA
See the Raycaster documentation. The constructor takes the origin, the direction and near and far parameters. So you could do:
const gravityDirection = new THREE.Vector3(0, -1, 0);
cast = new THREE.Raycaster(camera.position, gravityDirection, 0, 3);
and this also makes the distance check redundant, as the far parameter already filters out hits further away than 3 units.
I made vertices using svg path. And I made a text mesh using these vertices.
But the text mesh is not centered. The starting position of a letter is always the same, regardless of the length of the letter.
I always want to see the middle of the text.
If the length of the text is long, the entire text should be displayed on the screen.
How can I solve this problem? Please help me T.T...
The following are gif files that show the current situation.
When I write "hello"
When I write "hello world"
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import { FontLoader } from "three/examples/jsm/loaders/FontLoader";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry";
import { ALPHAMAP } from "../constants/url";
import { load } from "opentype.js";
import UnDotumBold from "../../assets/UnDotumBold.ttf";
class WebGLCanvas {
constructor(canvas) {
this._canvas = canvas;
this._clock = new THREE.Clock();
this._count = 4000;
this._distance = 2;
this._mouseX = 0;
this._mouseY = 0;
this._vertexShader = document.querySelector("#vertex-shader").textContent;
this._fragmentShader =
document.querySelector("#fragment-shader").textContent;
}
async _setupTextModel() {
const font = await load(UnDotumBold);
// 💡 I created a svg and got the svg paths to create vertices.
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const g = document.createElementNS("http://www.w3.org/2000/svg", "g");
svg.setAttribute("viewBox", [0, 0, 1920, 1920].join(" "));
g.setAttribute("fill", "black");
let pathMarkup = "";
const fontPaths = font.getPaths(text, 0, 1000, 1000);
fontPaths.forEach((fontPath) => {
const path = fontPath.toSVG();
pathMarkup += path;
});
g.insertAdjacentHTML("beforeend", pathMarkup);
document.body.appendChild(svg);
svg.appendChild(g);
const paths = svg.querySelectorAll("path");
const svgViewBoxWidth = svg.viewBox.baseVal.width;
const svgViewBoxHeight = svg.viewBox.baseVal.height;
svg.remove();
// 💡 vertices
this._textVertices = [];
const colors = [];
const sizes = [];
const delay = 1;
const gradient = chroma.scale([
"ef476f",
"ffd166",
"06d6a0",
"118ab2",
"073b4c",
]);
const colorRGB = {
r: Math.random() * 100,
g: Math.random() * 100,
b: Math.random() * 100,
};
const positionXYZ = {
x: Math.random() * 3000,
y: Math.random() * 3000,
z: Math.random() * 3000,
};
const timeline = gsap.timeline({
onReverseComplete: () => {
timeline.timeScale(1);
timeline.play(0);
},
});
paths.forEach((path) => {
const length = path.getTotalLength();
for (let i = 0; i < length; i += 30) {
const pointLength = i;
const point = path.getPointAtLength(pointLength);
// 💡 end point ❗❗ => I think this part is the problem..
const vector = new THREE.Vector3(
point.x - svgViewBoxWidth / 2,
-point.y + svgViewBoxHeight / 2,
(Math.random() - 0.5) * 15,
);
// 💡 start point
const start = new THREE.Vector3(
vector.x + (Math.random() - 0.5) * positionXYZ.x,
vector.y + (Math.random() - 0.5) * positionXYZ.y,
vector.z + (Math.random() - 0.5) * positionXYZ.z,
);
const coloursX =
point.x / svgViewBoxWidth + (Math.random() - 0.5) * 0.2;
const color = gradient(coloursX).rgb();
this._textVertices.push(vector);
vector.r = 1 - (vector.z + 7.5) / colorRGB.r;
vector.g = 1 - (vector.z + 7.5) / colorRGB.g;
vector.b = 1 - (vector.z + 7.5) / colorRGB.b;
timeline.from(
vector,
{
x: start.x,
y: start.y,
z: start.z,
r: color[0] / 255,
g: color[1] / 255,
b: color[2] / 255,
duration: "random(0.5, 1.5)",
ease: "power2.out",
},
delay * 0.0012,
);
sizes.push(25 * this.renderer.getPixelRatio());
}
});
// 💡 text mesh
this._textGeometry = new THREE.BufferGeometry().setFromPoints(
this._textVertices,
);
this._textGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(colors, 3),
);
this._textGeometry.setAttribute(
"size",
new THREE.Float32BufferAttribute(sizes, 1),
);
const textMaterial = new THREE.ShaderMaterial({
uniforms: {
pointTexture: {
value: new THREE.TextureLoader().load(ALPHAMAP.CIRCLE),
},
},
vertexShader: this._vertexShader,
fragmentShader: this._fragmentShader,
transparent: true,
depthTest: false,
});
this._textMesh = new THREE.Points(this._textGeometry, textMaterial);
this._textMesh.scale.set(0.1, 0.1, 0.1);
// this._textMesh.geometry.center(); => ❌ It dosen't work..
// this._getCenterPoint(this._textMesh); => ❌ It dosen't work..
this._textGroup = new THREE.Group();
this._textGroup.add(this._textMesh);
this._textGroup.position.set(0, 0, -240);
this._init();
}
/*
_getCenterPoint(mesh) {
const { geometry } = mesh;
const center = new THREE.Vector3();
geometry.computeBoundingBox();
geometry.boundingBox.getCenter(center);
mesh.localToWorld(center);
return center;
}
*/
_init() {
this.scene = new THREE.Scene();
this._sizes = {
width: window.innerWidth,
height: window.innerHeight,
};
this._setupCamera(this._sizes);
this._setupControls(this.camera, this._canvas);
this._render(this._canvas, this._sizes);
this._tick(this._sizes);
window.addEventListener("resize", this._resize);
window.addEventListener("mousemove", this._mousemove.bind(this));
}
_setupCamera(sizes) {
const camera = new THREE.PerspectiveCamera(
25,
sizes.width / sizes.height,
0.01,
5000,
);
this.scene.add(camera);
this.camera = camera;
}
_setupControls(camera, canvas) {
const control = new OrbitControls(camera, canvas);
control.enableDamping = true;
this.control = control;
}
_render(canvas, sizes) {
const renderer = new THREE.WebGL1Renderer({
canvas,
antialias: true,
alpha: true,
});
renderer.setClearColor(0x000000, 0);
renderer.setSize(sizes.width, sizes.height);
renderer.setPixelRatio(window.devicePixelRatio);
this.renderer = renderer;
}
_tick(sizes) {
this.camera.position.z = 400;
this.scene.add(this._textGroup);
this._textGeometry.setFromPoints(this._textVertices);
const colours = [];
this._textVertices.forEach((vector) => {
colours.push(vector.r, vector.g, vector.b);
});
this._textGeometry.setAttribute(
"customColor",
new THREE.Float32BufferAttribute(colours, 3),
);
this.renderer.render(this.scene, this.camera);
this.control.update();
window.requestAnimationFrame(this._tick.bind(this, sizes));
}
_resize() {
const width = window.innerWidth;
const height = window.innerHeight;
this.camera.aspect = width / height;
this.camera.updateProjectionMatrix();
this.renderer.setSize(width, height);
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
_mousemove(event) {
// ...
}
}
export default WebGLCanvas;
I'm trying to make a database of words where the most important words are closer to the top of the sphere and the less important are further away. So I created a sphere with enough vertices for each word, created a list of those vertices in order of distance from the top of the sphere, and placed the text sprites at the positions of the vertices in order of that sorted list.
Video version: https://i.gyazo.com/aabaf0b4a26f4413dc6a0ebafab2b4bd.mp4
Sounded like a good plan in my head, but clearly the geometry of a sphere causes the words to be further spread out the further away from the top they are. I need a result that looks like a somewhat even distribution across the surface. It doesn't have to be perfect, just visually closer than this.
How can I achieve the desired effect?
Here are the relevant methods:
positionDb(db) {
console.log("mostRelated", db.mostRelated);
console.log("depthList", this.depthList);
let mostRelated = db.mostRelated;
let depthList = this.depthList;
for (let i = 0; i < mostRelated.length; i++) {
this.addTextNode(mostRelated[i].data, this.depthList[i].vertice, this.depthList[i].depth);
}
}
addTextNode(text, vert, distance) {
let fontSize = 0.5 * (600 / distance);
let sprite = new THREE.TextSprite({
fillStyle: '#000000',
fontFamily: '"Arial", san-serif',
fontSize: fontSize,
fontWeight: 'bold',
text: text
});
this.scene.add(sprite);
sprite.position.set(vert.x, vert.y, vert.z);
setTimeout(() => {
sprite.fontFamily = '"Roboto", san-serif';
}, 1000)
}
this.scene = scene;
this.geometry = new THREE.SphereGeometry(420, 50, 550);
var material = new THREE.MeshBasicMaterial({
color: 0x0011ff
});
var sphere = new THREE.Mesh(this.geometry, wireframe);
var wireframe = new THREE.WireframeGeometry(this.geometry);
let frontVert = {
x: 0,
y: 100,
z: 0
}
let depthList = [];
this.geometry.vertices.forEach(vertice => {
let depth = getDistance(frontVert, vertice);
if (depthList.length === 0) {
depthList.push({
depth,
vertice
});
} else {
let flag = false;
for (let i = 0; i < depthList.length; i++) {
let item = depthList[i];
if (depth < item.depth) {
flag = true;
depthList.splice(i, 0, {
depth,
vertice
});
break;
}
}
if (!flag) depthList.push({
depth,
vertice
});
}
});
Maybe a fibonacci sphere
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
Example:
function fibonacciSphere(numPoints, point) {
const rnd = 1;
const offset = 2 / numPoints;
const increment = Math.PI * (3 - Math.sqrt(5));
const y = ((point * offset) - 1) + (offset / 2);
const r = Math.sqrt(1 - Math.pow(y, 2));
const phi = (point + rnd) % numPoints * increment;
const x = Math.cos(phi) * r;
const z = Math.sin(phi) * r;
return new THREE.Vector3(x, y, z);
}
function main() {
const fov = 75;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 5;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 2;
const scene = new THREE.Scene();
function addTextNode(text, vert) {
const div = document.createElement('div');
div.className = 'label';
div.textContent = text;
div.style.marginTop = '-1em';
const label = new THREE.CSS2DObject(div);
label.position.copy(vert);
scene.add(label);
}
const renderer = new THREE.CSS2DRenderer();
const container = document.querySelector('#c');
container.appendChild(renderer.domElement);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
const numPoints = 50;
for (let i = 0; i < numPoints; ++i) {
addTextNode(`p${i}`, fibonacciSphere(numPoints, i));
}
function render(time) {
time *= 0.001;
// three's poor choice of how to hanlde size strikes again :(
renderer.setSize(container.clientWidth, container.clientHeight);
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
body {
margin: 0;
overflow: hidden;
}
#c {
width: 100vw;
height: 100vh;
display: block;
}
.label {
color: red;
}
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/build/three.min.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/controls/OrbitControls.js"></script>
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r113/examples/js/renderers/CSS2DRenderer.js"></script>
<div id="c"></div>
I'm looking for a better/faster way to find the neighbor faces (that share the same edge) in my PlaneBufferGeometry. Currently my THREE.Raycaster intersects fine with my object (using intersectObject). But I need to find all surrounding faces.
At this moment I use the following dirty way to find the 'next door' faces. It works well in my scenario, but doesn't feel right:
let rc = new THREE.Raycaster();
let intersects = [];
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
let v = new THREE.Vector3(x + i, y, z + j);
rc.set(v, new THREE.Vector3(0, -1, 0));
rc.near = 0;
rc.far = 2;
let subIntersects = rc.intersectObject(mesh);
for (let n = 0; n < subIntersects.length; n++) {
intersects.push(subIntersects[n]);
}
}
}
Is there for instance a way to quickly find these faces in the mesh.geometry.attributes.position.array?
Any suggestions are welcome. Thanks in advance!
You mentioned 50k items in the position array. That doens't seem too slow to me. This example is only 10x10 so 100 items in the array so it's easy to see it's working, but I had it set to 200x200 which is 40k items and it seemed fast enough?
'use strict';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 60;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#444');
scene.add(camera);
const planeGeometry = new THREE.PlaneBufferGeometry(1, 1, 20, 20);
const material = new THREE.MeshBasicMaterial({color: 'blue'});
const plane = new THREE.Mesh(planeGeometry, material);
scene.add(plane);
const edgeGeometry = new THREE.BufferGeometry();
const positionNumComponents = 3;
edgeGeometry.setAttribute('position', planeGeometry.getAttribute('position'));
edgeGeometry.setIndex([]);
const edgeMaterial = new THREE.MeshBasicMaterial({
color: 'yellow',
wireframe: true,
depthTest: false,
});
const edges = new THREE.Mesh(edgeGeometry, edgeMaterial);
scene.add(edges);
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;
}
class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
}
pick(normalizedPosition, scene, camera, time) {
// cast a ray through the frustum
this.raycaster.setFromCamera(normalizedPosition, camera);
// get the list of objects the ray intersected
const intersectedObjects = this.raycaster.intersectObjects(scene.children, [plane]);
if (intersectedObjects.length) {
// pick the first object. It's the closest one
const intersection = intersectedObjects[0];
const faceIndex = intersection.faceIndex;
const indexAttribute = planeGeometry.getIndex();
const indices = indexAttribute.array;
const vertIds = indices.slice(faceIndex * 3, faceIndex * 3 + 3);
const neighbors = []; // note: self will be added to list
for (let i = 0; i < indices.length; i += 3) {
for (let j = 0; j < 3; ++j) {
const p0Ndx = indices[i + j];
const p1Ndx = indices[i + (j + 1) % 3];
if ((p0Ndx === vertIds[0] && p1Ndx === vertIds[1]) ||
(p0Ndx === vertIds[1] && p1Ndx === vertIds[0]) ||
(p0Ndx === vertIds[1] && p1Ndx === vertIds[2]) ||
(p0Ndx === vertIds[2] && p1Ndx === vertIds[1]) ||
(p0Ndx === vertIds[2] && p1Ndx === vertIds[0]) ||
(p0Ndx === vertIds[0] && p1Ndx === vertIds[2])) {
neighbors.push(...indices.slice(i, i + 3));
break;
}
}
}
const edgeIndices = edgeGeometry.getIndex();
edgeIndices.array = new Uint16Array(neighbors);
edgeIndices.count = neighbors.length;
edgeIndices.needsUpdate = true;
}
}
}
const pickPosition = {x: 0, y: 0};
const pickHelper = new PickHelper();
clearPickPosition();
function render(time) {
time *= 0.001; // convert to seconds;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
pickHelper.pick(pickPosition, scene, camera, time);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
}
function clearPickPosition() {
// unlike the mouse which always has a position
// if the user stops touching the screen we want
// to stop picking. For now we just pick a value
// unlikely to pick something
pickPosition.x = -100000;
pickPosition.y = -100000;
}
window.addEventListener('mousemove', setPickPosition);
window.addEventListener('mouseout', clearPickPosition);
window.addEventListener('mouseleave', clearPickPosition);
window.addEventListener('touchstart', (event) => {
// prevent the window from scrolling
event.preventDefault();
setPickPosition(event.touches[0]);
}, {passive: false});
window.addEventListener('touchmove', (event) => {
setPickPosition(event.touches[0]);
});
window.addEventListener('touchend', clearPickPosition);
}
main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r112/build/three.js"></script>
<canvas id="c"></canvas>
Like I mentioned in the comment. If you know it's PlaneBufferGeometry then you can look in the three.js code and see the exact layout of faces so given a faceIndex you can just compute the neighbors directly. The code above is generic, at least for BufferGeometry with an index.
Looking at the code I'm pretty sure it's
// it looks like this is the grid order for PlaneBufferGeometry
//
// b --c
// |\\1|
// |0\\|
// a-- d
const facesAcrossRow = planeGeometry.parameters.widthSegments * 2;
const col = faceIndex % facesAcrossRow
const row = faceIndex / facesAcrossRow | 0;
const neighboringFaceIndices = [];
// check left face
if (col > 0) {
neighboringFaceIndices.push(row * facesAcrossRow + col - 1);
}
// check right face
if (col < facesAcrossRow - 1) {
neighboringFaceIndices.push(row * facesAcrossRow + col + 1);
}
// check up. there can only be one up if we're in an odd triangle (b,c,d)
if (col % 2 && row < planeGeometry.parameters.heightSegments) {
// add the even neighbor in the next row
neighboringFaceIndices.push((row + 1) * facesAcrossRow + col - 1);
}
// check down. there can only be one down if we're in an even triangle (a,b,d)
if (col % 2 === 0 && row > 0) {
// add the odd neighbor in the previous row
neighboringFaceIndices.push((row - 1) * facesAcrossRow + col + 1);
}
Trying that out
'use strict';
function main() {
const canvas = document.querySelector('#c');
const renderer = new THREE.WebGLRenderer({canvas});
const fov = 60;
const aspect = 2; // the canvas default
const near = 0.1;
const far = 200;
const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.z = 1;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#444');
scene.add(camera);
const planeGeometry = new THREE.PlaneBufferGeometry(1, 1, 20, 20);
const material = new THREE.MeshBasicMaterial({color: 'blue'});
const plane = new THREE.Mesh(planeGeometry, material);
scene.add(plane);
const edgeGeometry = new THREE.BufferGeometry();
const positionNumComponents = 3;
edgeGeometry.setAttribute('position', planeGeometry.getAttribute('position'));
edgeGeometry.setIndex([]);
const edgeMaterial = new THREE.MeshBasicMaterial({
color: 'yellow',
wireframe: true,
depthTest: false,
});
const edges = new THREE.Mesh(edgeGeometry, edgeMaterial);
scene.add(edges);
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;
}
class PickHelper {
constructor() {
this.raycaster = new THREE.Raycaster();
}
pick(normalizedPosition, scene, camera, time) {
// cast a ray through the frustum
this.raycaster.setFromCamera(normalizedPosition, camera);
// get the list of objects the ray intersected
const intersectedObjects = this.raycaster.intersectObjects(scene.children, [plane]);
if (intersectedObjects.length) {
// pick the first object. It's the closest one
const intersection = intersectedObjects[0];
const faceIndex = intersection.faceIndex;
const indexAttribute = planeGeometry.getIndex();
const indices = indexAttribute.array;
// it looks like this is the grid order for PlaneBufferGeometry
//
// b --c
// |\\1|
// |0\\|
// a-- d
const facesAcrossRow = planeGeometry.parameters.widthSegments * 2;
const col = faceIndex % facesAcrossRow
const row = faceIndex / facesAcrossRow | 0;
const neighboringFaceIndices = [];
// check left face
if (col > 0) {
neighboringFaceIndices.push(row * facesAcrossRow + col - 1);
}
// check right face
if (col < facesAcrossRow - 1) {
neighboringFaceIndices.push(row * facesAcrossRow + col + 1);
}
// check up. there can only be one up if we're in an odd triangle (b,c,d)
if (col % 2 && row < planeGeometry.parameters.heightSegments) {
// add the even neighbor in the next row
neighboringFaceIndices.push((row + 1) * facesAcrossRow + col - 1);
}
// check down. there can only be one down if we're in an even triangle (a,b,d)
if (col % 2 === 0 && row > 0) {
// add the odd neighbor in the previous row
neighboringFaceIndices.push((row - 1) * facesAcrossRow + col + 1);
}
const neighbors = [];
for (const faceIndex of neighboringFaceIndices) {
neighbors.push(...indices.slice(faceIndex * 3, faceIndex * 3 + 3));
}
const edgeIndices = edgeGeometry.getIndex();
edgeIndices.array = new Uint16Array(neighbors);
edgeIndices.count = neighbors.length;
edgeIndices.needsUpdate = true;
}
}
}
const pickPosition = {x: 0, y: 0};
const pickHelper = new PickHelper();
clearPickPosition();
function render(time) {
time *= 0.001; // convert to seconds;
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
pickHelper.pick(pickPosition, scene, camera, time);
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
function getCanvasRelativePosition(event) {
const rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top,
};
}
function setPickPosition(event) {
const pos = getCanvasRelativePosition(event);
pickPosition.x = (pos.x / canvas.clientWidth ) * 2 - 1;
pickPosition.y = (pos.y / canvas.clientHeight) * -2 + 1; // note we flip Y
}
function clearPickPosition() {
// unlike the mouse which always has a position
// if the user stops touching the screen we want
// to stop picking. For now we just pick a value
// unlikely to pick something
pickPosition.x = -100000;
pickPosition.y = -100000;
}
window.addEventListener('mousemove', setPickPosition);
window.addEventListener('mouseout', clearPickPosition);
window.addEventListener('mouseleave', clearPickPosition);
window.addEventListener('touchstart', (event) => {
// prevent the window from scrolling
event.preventDefault();
setPickPosition(event.touches[0]);
}, {passive: false});
window.addEventListener('touchmove', (event) => {
setPickPosition(event.touches[0]);
});
window.addEventListener('touchend', clearPickPosition);
}
main();
body { margin: 0; }
canvas { width: 100vw; height: 100vh; display: block; }
<script src="https://threejsfundamentals.org/threejs/resources/threejs/r112/build/three.js"></script>
<canvas id="c"></canvas>
For something more complex than a PlaneBufferGeometry
you could also pre-generate a map of faceIndexs to neighbors if the code at the top is too slow.
I started my first Three.js project. A solar system which you can see here.
I have a function addCelestrialObject() where I create the planets and I want this function to automatically create the orbit circles what it does for the planets but I want it also for moons.
So every Planet (mesh) becomes a name and I want to access this object to get its center position so I can add a circle to this position if I have a moon.
My problem is that the function scene.getObjectByName(parent,true); always delivers an undefined. You can see the console.log(scene) on my example when you inspect the site.
function addCelestrialObject(name, type, parent, surface, bump, specular,
positionX, positionY, positionZ, size, clouds, drawcircle
) {
var loader = new THREE.TextureLoader();
var group = new THREE.Group();
loader.load(surface, function (texture) {
var geometry = new THREE.SphereGeometry(size, 32, 32);
if (type == "sun") {
var material = new THREE.MeshBasicMaterial({ map: texture });
material.shading = true;
} else {
var material = new THREE.MeshPhongMaterial({ map: texture, overdraw: 0.5 });
material.shading = true;
if (bump) {
material.bumpMap = THREE.ImageUtils.loadTexture(bump);
material.bumpScale = 0.5;
}
if (specular) {
material.specularMap = THREE.ImageUtils.loadTexture(specular);
material.specular = new THREE.Color(0x222222);
}
}
var mesh = new THREE.Mesh(geometry, material);
mesh.name = name;
mesh.position.x = positionX;
mesh.position.y = positionY;
mesh.position.z = positionZ;
objectControls.add(mesh);
mesh.select = function () {
var position = { x: controls.target.x, y: controls.target.y, z: controls.target.z };
var target = { x: this.position.x, y: this.position.y, z: this.position.z };
var tween = new TWEEN.Tween(position).to(target, 500);
tween.easing(TWEEN.Easing.Exponential.InOut)
tween.onUpdate(function () {
controls.target.x = position.x;
controls.target.y = position.y;
controls.target.z = position.z;
controls.dollyIn(2);
});
tween.start();
controls.minDistance = size * 5;
}
onRenderFcts.push(function (delta, now) {
mesh.rotateY(1 / 32 * delta)
});
group.add(mesh);
});
if (clouds == true) {
var canvasResult = document.createElement('canvas')
canvasResult.width = 1024
canvasResult.height = 512
var contextResult = canvasResult.getContext('2d')
// load earthcloudmap
var imageMap = new Image();
imageMap.addEventListener("load", function () {
// create dataMap ImageData for earthcloudmap
var canvasMap = document.createElement('canvas')
canvasMap.width = imageMap.width
canvasMap.height = imageMap.height
var contextMap = canvasMap.getContext('2d')
contextMap.drawImage(imageMap, 0, 0)
var dataMap = contextMap.getImageData(0, 0, canvasMap.width, canvasMap.height)
// load earthcloudmaptrans
var imageTrans = new Image();
imageTrans.addEventListener("load", function () {
// create dataTrans ImageData for earthcloudmaptrans
var canvasTrans = document.createElement('canvas')
canvasTrans.width = imageTrans.width
canvasTrans.height = imageTrans.height
var contextTrans = canvasTrans.getContext('2d')
contextTrans.drawImage(imageTrans, 0, 0)
var dataTrans = contextTrans.getImageData(0, 0, canvasTrans.width, canvasTrans.height)
// merge dataMap + dataTrans into dataResult
var dataResult = contextMap.createImageData(canvasMap.width, canvasMap.height)
for (var y = 0, offset = 0; y < imageMap.height; y++) {
for (var x = 0; x < imageMap.width; x++, offset += 4) {
dataResult.data[offset + 0] = dataMap.data[offset + 0]
dataResult.data[offset + 1] = dataMap.data[offset + 1]
dataResult.data[offset + 2] = dataMap.data[offset + 2]
dataResult.data[offset + 3] = 255 - dataTrans.data[offset + 0]
}
}
// update texture with result
contextResult.putImageData(dataResult, 0, 0)
material.map.needsUpdate = true;
})
imageTrans.src = 'textures/earthcloudmaptrans.jpg';
}, false);
imageMap.src = 'textures/earthcloudmap.jpg';
var geometry = new THREE.SphereGeometry(size + 0.5, 32, 32)
var material = new THREE.MeshPhongMaterial({
map: new THREE.Texture(canvasResult),
side: THREE.DoubleSide,
transparent: true,
opacity: 1,
shading: true,
})
var cloudMesh = new THREE.Mesh(geometry, material);
cloudMesh.position.x = positionX;
cloudMesh.position.y = positionY;
cloudMesh.position.z = positionZ;
group.add(cloudMesh);
onRenderFcts.push(function (delta, now) {
cloudMesh.rotateY(1 / 16 * delta)
});
}
if (drawcircle == true) {
//circle
var radius = Math.abs(distance(0, positionX, 0, positionZ));
segments = 64;
materialLine = new THREE.LineBasicMaterial({ color: 0x00a8ff });
geometry = new THREE.CircleGeometry(radius, segments);
// Remove center vertex
geometry.vertices.shift();
circle = new THREE.Line(geometry, materialLine);
circle.rotation.x = 1.571;
if (parent) {
var object = scene.getObjectByName(parent, true);
//circle.position.x=object.position.x;
//circle.position.y=object.position.y;
//circle.position.z=object.position.z;
}
group.add(circle);
}
scene.add(group);
}