Search code examples
javascriptthree.js3daframeraycasting

A-Frame - Raycast Three.JS 3D Object


I have two objects, one cylinder and one polygon, representing a Three.js 3D Object, in an A-Frame scene. All I want is that the polygon changes when hovering over it, like the cylinder.

I have a working demo here: Demo

When the cursor hovers on the cylinder, the text HOVERED appears on the screen, and the color of the cylinder changes, using the Raycaster component. How can I do the same to the polygon?

The polygon was created with this:

AFRAME.registerComponent('foo', {
    init: function() {
        let points = [];
        points.push(new THREE.Vector2(0, 0));
        points.push(new THREE.Vector2(1.5, 0));
        points.push(new THREE.Vector2(2.5, 1));
        points.push(new THREE.Vector2(2.5, 2.5));
        points.push(new THREE.Vector2(1, 3.5));

        for (let i = 0; i < points.length; i++) {
            points[i].multiplyScalar(0.25);
        }
        let shape = new THREE.Shape(points);


        let extrudedGeometry = new THREE.ExtrudeGeometry(shape, {
            amount: 1,
            bevelEnabled: false
        });

        // Geometry doesn't do much on its own, we need to create a Mesh from it
        let extrudedMesh = new THREE.Mesh(extrudedGeometry, new THREE.MeshPhongMaterial({
            color: 0xff0000
        }));
        this.el.object3D.add(extrudedMesh);

        let geometry = new THREE.ShapeGeometry(shape);
        let material = new THREE.MeshBasicMaterial({
            color: 0x00ff00
        });
        let mesh = new THREE.Mesh(geometry, material);
        this.el.object3D.add(mesh);
    }
});

Thank you.


Solution

  • Raycaster casts rays against the entity's mesh. You set it with setObject3D. Do:

    let mesh = new THREE.Mesh(geometry, material);
    this.el.setObject3D('mesh', mesh);
    

    Corrected code