feat: implement cursor-based camera movement and update camera initialization

This commit is contained in:
sayudhalw
2026-08-23 22:19:32 +07:00
parent 6a8f2e0cb5
commit ad3370d274
+26 -4
View File
@@ -3,6 +3,19 @@ import * as THREE from 'three'
import { Timer } from 'three/addons/misc/Timer.js' import { Timer } from 'three/addons/misc/Timer.js'
// import gsap from 'gsap' // import gsap from 'gsap'
/**
* Cursor
*/
const cursor = {
x: 0,
y: 0
}
window.addEventListener('mousemove', (event) => {
cursor.x = event.clientX / sizes.width - 0.5 // -0.5 to center the cursor coordinates
cursor.y = -(event.clientY / sizes.height - 0.5) // Invert the y-coordinate to match the 3D coordinate system
console.log(cursor.x, cursor.y)
})
// Canvas // Canvas
const canvas = document.querySelector('canvas.webgl') const canvas = document.querySelector('canvas.webgl')
@@ -23,7 +36,10 @@ const sizes = {
// Camera // Camera
const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100) const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height, 0.1, 100)
// camera.position.x = 2
// camera.position.y = 2
camera.position.z = 3 camera.position.z = 3
camera.lookAt(mesh.position)
scene.add(camera) scene.add(camera)
// Renderer // Renderer
@@ -49,10 +65,16 @@ const tick = () => {
const elapsedTime = timer.getElapsed() const elapsedTime = timer.getElapsed()
// Update objects // Update objects
mesh.rotation.y = elapsedTime * Math.PI * 2 // mesh.rotation.y = elapsedTime * Math.PI * 2
mesh.position.y = Math.sin(elapsedTime) // mesh.position.y = Math.sin(elapsedTime)
mesh.position.x = Math.cos(elapsedTime) // mesh.position.x = Math.cos(elapsedTime)
camera.lookAt(mesh.position) // camera.lookAt(mesh.position)
// Update camera position based on cursor
camera.position.x = Math.sin(cursor.x * Math.PI * 2) * 3 // Move the camera in a circular path around the mesh based on cursor x position
camera.position.z = Math.cos(cursor.x * Math.PI * 2) * 3 // Move the camera in a circular path around the mesh based on cursor x position
camera.position.y = cursor.y * 5 // Move the camera up/down based on cursor y position
camera.lookAt(mesh.position) // Make the camera look at the mesh
// Renderer // Renderer
renderer.render(scene, camera) renderer.render(scene, camera)