今天郭先生继续说cannon.js,主演内容就是点对点约束和2D坐标转3D坐标。仍然以一个案例为例,场景由一个地面、若干网格组成的约束体和一些拥有初速度的球体组成,如下图。线案例请点击博客原文。
下面来说说如何使用约束来完成一个这样的物理场景。
1. 创建three场景这一步是基础工作,对于有一定three基础的同学都不会陌生,我就直接上代码了。
initThree() { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 1000 ); camera.position.x = 40; camera.position.y = 52; camera.position.z = 78; scene.add( camera ); scene.add(new THREE.AxesHelper(40)); scene.add(new THREE.AmbientLight(0x888888)); const light = new THREE.DirectionalLight(0xbbbbbb, 1); light.position.set(0, 50, 50); const distance = 200; let texture = new THREE.TextureLoader().load('/static/images/base/ground.png'); texture.wrapS = texture.wrapT = THREE.RepeatWrapping; texture.repeat.copy(new THREE.Vector2(40, 40)); let groundGeom = new THREE.BoxBufferGeometry(100, 0.2, 100); let groundMate = new THREE.MeshPhongMaterial({color: 0xdddddd, map: texture}) ground = new THREE.Mesh(groundGeom, groundMate); ground.position.y = -0.1; ground.receiveShadow = true; scene.add(ground); geometry = new THREE.BoxGeometry( 2, 2, 2 ); renderer = new THREE.WebGLRenderer({antialias: true}); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.shadowMap.enabled = true; renderer.setClearColor(0xbfd1e5); controls = new OrbitControls(camera, renderer.domElement); controls.target.set(0, 10, 0); camera.lookAt(0,10,0); this.$refs.box.appendChild( renderer.domElement ); stats = new Stats(); this.$refs.box.appendChild(stats.dom); },