<script setup> import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import * as CANNON from "cannon-es"; // 初始化物理世界 const world = new CANNON.World(); // 设置重力 world.gravity.set(0, -9.82, 0);
// Sweep and prune broadphase world.broadphase = new CANNON.SAPBroadphase(world);
// Disable friction by default world.defaultContactMaterial.friction = 0;
// 初始化3D场景 const scene = new THREE.Scene(); // 初始化相机 const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set(0, 10, 20); camera.lookAt(0, 0, 0);
<script setup> import * as THREE from "three"; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import * as CANNON from "cannon-es"; // 初始化物理世界 const world = new CANNON.World(); // 设置重力 world.gravity.set(0, -9.82, 0);
// Sweep and prune broadphase world.broadphase = new CANNON.SAPBroadphase(world);
// Disable friction by default world.defaultContactMaterial.friction = 0;
// 初始化3D场景 const scene = new THREE.Scene(); // 初始化相机 const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.set(0, 10, 20); camera.lookAt(0, 0, 0);
// 创建地面 let groundShape = new CANNON.Box(new CANNON.Vec3(50, 0.5, 50));
const groundPhyMaterial = new CANNON.Material("groundMaterial"); let groundBody = new CANNON.Body({ mass: 0, shape: groundShape, }); world.addBody(groundBody);
// 创建threejs地面 let groundMesh = new THREE.Mesh( new THREE.BoxGeometry(100, 1, 100), new THREE.MeshBasicMaterial({ color: 0x888888 }) ); scene.add(groundMesh);
// 创建车身 let chassisShape = new CANNON.Box(new CANNON.Vec3(2, 0.5, 1)); let chassisBody = new CANNON.Body({ mass: 150, shape: chassisShape, }); chassisBody.position.set(0, 5, 0); world.addBody(chassisBody); phyMeshes.push(chassisBody);
// 创建threejs车身 let chassisMesh = new THREE.Mesh( new THREE.BoxGeometry(4, 1, 2), new THREE.MeshBasicMaterial({ color: 0x00ff00 }) ); scene.add(chassisMesh); meshes.push(chassisMesh);
// 创建拥有悬架的车辆 const vehicle = new CANNON.RaycastVehicle({ chassisBody: chassisBody, });