I developed a futuristic snake game where snake-like entities move around in an animated fashion using various cube meshes and the THREE.BoxGeometry
:
https://i.sstatic.net/GVDNj.png
To enhance the game, I aim to create each snake with a single mesh and geometry for easy addition of textures and rounded edges.
My current challenge is transforming a set of 3D points into a unified geometry that resembles the segmented box-like snakes seen in the demonstration (similar to multiple connected instances of THREE.BoxGeometry
).
In my attempt to achieve this, I experimented with utilizing THREE.CurvePath
and THREE.ExtrudeGeometry
:
_makeSnakeGeometry(positions) {
const vectors = positions.map(p => new THREE.Vector3(...p));
const curvePath = new THREE.CurvePath();
const first = vectors[1];
const last = vectors[vectors.length - 1];
let curveStart = vectors[0];
let previous = curveStart;
let previousDirection;
// Traversing through the positions. If there's a change in direction, insert a new curve on the path.
for (let vector of vectors.slice(1)) {
let direction = previous.clone().sub(vector);
if (vector.equals(first)) {
curveStart.sub(direction.clone().divideScalar(2));
}
if (vector.equals(last)) {
previous.sub(previousDirection.clone().divideScalar(2));
}
if ((previousDirection && !previousDirection.equals(direction)) || vector.equals(last)) {
curvePath.add(new THREE.LineCurve3(curveStart, previous));
curveStart = previous;
}
previous = vector;
previousDirection = direction;
}
const p = Const.TILE_SIZE / 2;
const points = [[-p, -p], [-p, p], [p, p], [p, -p]];
const shape = new THREE.Shape(points.map(p => new THREE.Vector2(...p)));
const geometry = new THREE.ExtrudeGeometry(shape, {
steps: 20,
extrudePath: curvePath,
amount: 20
});
return geometry;
}
Unfortunately, the result appears unattractive with rounded corners occurring at the intersection points:
https://i.sstatic.net/spUzy.png
Increasing the steps
option improves the visual appeal, yet introduces a high vertex count due to the smoothing effect on the curved edges. This concerns me as recreating this geometry might be required on every animation frame.
For animating the geometry, I tested out geometry.morphTargets
but encountered limited success. While the morphing takes place, it doesn't meet aesthetic standards. Perhaps manual manipulation of the vertices is necessary?
In conclusion, my queries are as follows:
- How can I generate a low-vertex-count geometry resembling interconnected box geometries?
- What's the recommended approach for animating a geometry when the number of vertices could vary?