// Renderer
var renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 600);
document.body.appendChild(renderer.domElement);
// Scene
var scene = new THREE.Scene();
// Camera
var camera = new THREE.PerspectiveCamera(35, 800 / 600, 0.1, 10000);
camera.position.set(-15, 10, 10);
camera.lookAt(scene.position);
// Cube
var geometry = new THREE.BoxGeometry(5, 5, 5);
var material = new THREE.MeshLambertMaterial({ color: 0xFF0000 });
var mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// Light
var light = new THREE.PointLight(0xFFFF00);
light.position.set(10, 0, 10);
scene.add(light);
// Clear Color
renderer.setClearColor(0xdddddd, 1);
// Targets
var targets = [];
const NUM_TARGETS = 5;
for (let i = 0; i < NUM_TARGETS; i++) {
let geometry = new THREE.SphereGeometry(0.2, 32, 32);
let material = new THREE.MeshBasicMaterial({ color: Math.random() * 0xffffff });
let sphere = new THREE.Mesh(geometry, material);
sphere.position.x = (Math.random() - 0.5) * 10;
sphere.position.y = (Math.random() - 0.5) * 10;
scene.add(sphere);
targets.push(sphere);
}
// Mouse click event to shoot
window.addEventListener('click', function(event) {
event.preventDefault();
let mouse = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
let raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
let intersects = raycaster.intersectObjects(targets);
if (intersects.length > 0) {
let intersectedObject = intersects[0].object;
// Update score or do something else here
// Remove the hit target and create a new one
scene.remove(intersectedObject);
let index = targets.indexOf(intersectedObject);
targets.splice(index, 1);
let geometry = new THREE.SphereGeometry(0.2, 32, 32);
let material = new THREE.MeshBasicMaterial({ color: Math.random() * 0xffffff });
let sphere = new THREE.Mesh(geometry, material);
sphere.position.x = (Math.random() - 0.5) * 10;
sphere.position.y = (Math.random() - 0.5) * 10;
scene.add(sphere);
targets.push(sphere);
}
});
// Animate
function animate() {
requestAnimationFrame(animate);
// Rotate the cube
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.01;
// Move the targets
targets.forEach(target => {
target.position.x += 0.01;
if (target.position.x > 5) target.position.x = -5;
});
renderer.render(scene, camera);
}
animate()