球会在原点,自由落体运动,落到下面去,没法做成gif,所以截了两张图


import * as THREE from 'three'
import gsap from 'gsap'
import * as dat from 'dat.gui' `导入 cannon-es 引擎`
import * as CANNON from 'cannon-es'const scene = new THREE.Scene()const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 300)
camera.position.set(0, 0, 18)
scene.add(camera)
const renderer = new THREE.WebGLRenderer({ alpha: true })
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.physicallyCorrectLights = true
document.body.appendChild(renderer.domElement)
const sphereGeometry = new THREE.SphereGeometry(1, 20, 20)
const sphereMaterial = new THREE.MeshPhysicalMaterial()
const sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)
sphere.castShadow = true `投射自己的阴影`
scene.add(sphere)
const floor = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), new THREE.MeshStandardMaterial())
floor.position.set(0, -5, 0)
floor.rotation.x = -Math.PI / 2
floor.receiveShadow = true `接受别的物体的阴影`
scene.add(floor)`创建物理世界`
const world = new CANNON.World()
world.gravity.set(0, -9.8, 0)`创建 - 物理小球形状`
const sphereShape = new CANNON.Sphere(1)
`设置物体材质`
const sphereWorldMaterial = new CANNON.Material()
`创建物理世界的物体`
const sphereBody = new CANNON.Body({shape: sphereShape,position: new CANNON.Vec3(0, 0, 0),mass: 1, `小球质量`material: sphereWorldMaterial `物体材质`
})`将 sphereBody 添加到物理世界`
world.addBody(sphereBody)
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
scene.add(ambientLight)
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
directionalLight.castShadow = true
directionalLight.position.set(0, 8, 0)
scene.add(directionalLight)
const directionalLightHelp = new THREE.DirectionalLightHelper(directionalLight)
scene.add(directionalLightHelp)const axesHelper = new THREE.AxesHelper(8)
scene.add(axesHelper)const clock = new THREE.Clock()const render = () => {let deltaTime = clock.getDelta()`world.step():更新物理引擎里的世界物体参数一:指定了,物理引擎内部模拟的时间步长(以秒为单位),在这里,设置为,大约每1/120秒更新一次物理世界,参数二:实际的时间差,它允许物理引擎根据实际的帧率调整其模拟,以保持物理行为的稳定性、一致性,`world.step(1/120, deltaTime)`将,物理引擎的sphereBody的位置,复制给,渲染引擎的sphere`sphere.position.copy(sphereBody.position)renderer.render(scene, camera)requestAnimationFrame(render)
}
render()window.addEventListener('resize', () => {camera.aspect = window.innerWidth / window.innerHeightcamera.updateProjectionMatrix()renderer.setSize(window.innerWidth, window.innerHeight)renderer.setPixelRatio(window.devicePixelRatio)
})