Three.js: Farbwechsel nach Kollision

by Cathy:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>three.js: change colour at collision</title>
    <style>
        body {
            margin: 0;
        }
    </style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r123/three.min.js"></script>
<script>
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 5;

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    const geometry = new THREE.BoxGeometry();
    const material = new THREE.MeshBasicMaterial({color: 0x00ff00});
    const cube1 = new THREE.Mesh(geometry, material);
    const cube2 = new THREE.Mesh(geometry, material);
    cube2.position.x = 3;
    scene.add(cube1);
    scene.add(cube2);

    function changeColorAtCollision() {
        const boundingBox1 = new THREE.Box3().setFromObject(cube1); // setFromObject(myMeshObject) is crucial: https://bit.ly/3nXUKOc
        const boundingBox2 = new THREE.Box3().setFromObject(cube2);
        if (boundingBox1.intersectsBox(boundingBox2)) {
            material.color.setRGB(1, 0, 1);
        }
    }

    function animate() {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);

        cube2.position.x -= 0.05;

        changeColorAtCollision();
    }

    animate();
</script>
</body>
</html>

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.