先上效果图:
![在这里插入图片描述](https://img-blog.csdnimg.cn/7873aee0a23f4ebeb964da000c76e445.gif#pic_center)
1、引入插件
...其他必要插件的引入...
import { PointerLockControls } from 'three/examples/jsm/controls/PointerLockControls'
2、定义相关变量
data(){
return{
selControls: null,
moveForward: null,
moveBackward: null,
moveLeft: null,
moveRight: null,
canJump: null,
prevTime: performance.now(),
velocity: new THREE.Vector3(),
direction: new THREE.Vector3(),
}
}
3、初始化控件,并添加键盘监听事件
methods:
selView () {
this.selControls = new PointerLockControls(this.camera, document.body)
this.selControls.lock()
var onKeyDown = (event) => {
switch (event.keyCode) {
case 38:
case 87:
this.moveForward = true
break
case 37:
case 65:
this.moveLeft = true
break
case 40:
case 83:
this.moveBackward = true
break
case 39:
case 68:
this.moveRight = true
break
case 32:
if (this.canJump === true) this.velocity.y += 350
this.canJump = false
break
}
}
var onKeyUp = (event) => {
switch (event.keyCode) {
case 38:
case 87:
this.moveForward = false
break
case 37:
case 65:
this.moveLeft = false
break
case 40:
case 83:
this.moveBackward = false
break
case 39:
case 68:
this.moveRight = false
break
}
}
document.addEventListener('keydown', onKeyDown, false)
document.addEventListener('keyup', onKeyUp, false)
}
4、在循环渲染函数中,实现键盘控制移动
methods:
render(){
requestAnimationFrame(this.render)
const time = performance.now()
if (this.selControls) {
if (this.selControls.isLocked) {
var delta = (time - this.prevTime) / 1000
this.velocity.x -= this.velocity.x * 10.0 * delta
this.velocity.z -= this.velocity.z * 10.0 * delta
this.velocity.y -= 9.8 * 200.0 * delta
this.direction.z = Number(this.moveForward) - Number(this.moveBackward)
this.direction.x = Number(this.moveRight) - Number(this.moveLeft)
this.direction.normalize()
if (this.moveForward || this.moveBackward) this.velocity.z -= this.direction.z * 200.0 * delta
if (this.moveLeft || this.moveRight) this.velocity.x -= this.direction.x * 200.0 * delta
this.selControls.moveRight(-this.velocity.x * delta)
this.selControls.moveForward(-this.velocity.z * delta)
this.selControls.getObject().position.y += (this.velocity.y * delta)
if (this.selControls.getObject().position.y < 5) {
this.velocity.y = 0
this.selControls.getObject().position.y = 5
this.controls.position0.set(0, 5, 10)
this.canJump = true
}
} else {
this.showBtn = true
}
this.prevTime = time
}
this.renderer.render(this.scene, this.camera)
}