74 lines
2.0 KiB
JavaScript

import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
const scene = new THREE.Scene()
scene.background = new THREE.Color(0xf0f0f0)
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 controls = new OrbitControls(camera, renderer.domElement)
const ambientLight = new THREE.AmbientLight(0xffffff, Math.PI / 2)
scene.add(ambientLight)
const pointLight = new THREE.PointLight(0xffffff, Math.PI)
pointLight.position.set(-10, -10, -10)
pointLight.decay = 0
scene.add(pointLight)
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material1 = new THREE.MeshStandardMaterial({ color: 'orange' })
const cube1 = new THREE.Mesh(geometry, material1)
cube1.position.x = -1.2
scene.add(cube1)
const material2 = new THREE.MeshStandardMaterial({ color: 'orange' })
const cube2 = new THREE.Mesh(geometry, material2)
cube2.position.x = 1.2
scene.add(cube2)
const cubes = [cube1, cube2]
const raycaster = new THREE.Raycaster()
const mouse = new THREE.Vector2()
window.addEventListener('pointermove', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
})
function animate() {
requestAnimationFrame(animate)
cube1.rotation.x += 0.01
cube1.rotation.y += 0.01
cube2.rotation.x += 0.01
cube2.rotation.y += 0.01
raycaster.setFromCamera(mouse, camera)
const intersects = raycaster.intersectObjects(cubes)
cube1.material.color.set('orange')
cube2.material.color.set('orange')
if (intersects.length > 0) {
intersects[0].object.material.color.set('hotpink')
}
controls.update()
renderer.render(scene, camera)
}
animate()
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
})