I’ve come up with the code below to find the screen positions of the corners of a plane.
It works, but it feels inefficient and long-winded.
In particular:
- line 10: creating a vec4 this way seems clunky
- line 37: “converting” from vec4 to vec3 this way feels clumsy, is there a direct conversion method available?
- applying the transform to each vertex in a loop, is there a way to apply a matrix to an array of vec4s?
Can anyone suggest any improvements?
TIA
let camera = this.camera.camera;
// get the mesh
let meshInstance = this.entity.render.meshInstances[0];
let mesh = meshInstance.mesh;
// get the vertex positions
let positions = [];
mesh.getPositions(positions);
let toWorldTransform = this.entity.getWorldTransform();
let screenPositions = [];
// temp Vec3 for re-use in loop
let t = new pc.Vec3();
for (let i = 0; i < positions.length; i += 3) {
// create a vec4 from the position
let v0 = new pc.Vec4(positions[i], positions[i + 1], positions[i + 2], 1);
// apply the transfrom to "move" it world co-ords
let worldPosition = toWorldTransform.transformVec4(v0);
// pull back the vec3
t.x = worldPosition.x; t.y = worldPosition.y; t.z = worldPosition.z;
// get its screen space position
let screenPosition = camera.worldToScreen(t);
screenPositions.push(screenPosition);
}