最后更新于
这有帮助吗?
这有帮助吗?
var FirstPersonMovement = pc.createScript('firstPersonMovement');
var fpsCamera = null
var overChat = false
FirstPersonMovement.attributes.add('power', {
type: 'number',
default: 2500,
description: '调整玩家移动速度'
});
FirstPersonMovement.attributes.add('lookSpeed', {
type: 'number',
default: 0.07,
description: '调整视角灵敏度'
});
// 每个实体只调用一次的初始化代码
FirstPersonMovement.prototype.initialize = function() {
this.force = new pc.Vec3();
this.eulers = new pc.Vec3();
var app = this.app;
app.mouse.on("mousemove", this._onMouseMove, this);
app.mouse.on("mousedown", function () {
if(!overChat){
app.mouse.enablePointerLock();
}
},this);
// 检查所需组件
if (!this.entity.collision) {
console.error("First Person Movement 脚本需要有一个 'collision' 组件");
}
if (!this.entity.rigidbody || this.entity.rigidbody.type !== pc.BODYTYPE_DYNAMIC) {
console.error("First Person Movement 脚本需要有一个 DYNAMIC 'rigidbody' 组件");
}
};
// 每帧调用的更新代码
FirstPersonMovement.prototype.update = function(dt) {
// 如果没有从编辑器分配摄像机,则创建一个
if (!this.camera) {
this._createCamera();
}
var force = this.force;
var app = this.app;
fpsCamera = this.camera;
var forward = this.camera.forward;
var right = this.camera.right;
// 移动
var x = 0;
var z = 0;
const convaiFormEl = document.getElementById("convai-input");
// 使用 w-a-s-d
if(app.keyboard.isPressed(pc.KEY_A) && !(document.activeElement === convaiFormEl)){
x -= right.x;
z -= right.z;
}
if (app.keyboard.isPressed(pc.KEY_D) && !(document.activeElement === convaiFormEl)) {
x += right.x;
z += right.z;
}
if (app.keyboard.isPressed(pc.KEY_W) && !(document.activeElement === convaiFormEl)) {
x += forward.x;
z += forward.z;
}
if (app.keyboard.isPressed(pc.KEY_S) && !(document.activeElement === convaiFormEl)) {
x -= forward.x;
z -= forward.z;
}
// 使用按键方向为角色施加力
if (x !== 0 || z !== 0) {
force.set(x, 0, z).normalize().scale(this.power);
this.entity.rigidbody.applyForce(force);
}
// 根据鼠标事件更新摄像机角度
this.camera.setLocalEulerAngles(this.eulers.y, this.eulers.x, 0);
};
FirstPersonMovement.prototype._onMouseMove = function (e) {
// 如果指针被禁用
// 如果按下鼠标左键,则根据鼠标移动更新摄像机
if (pc.Mouse.isPointerLocked() || e.buttons[0]) {
this.eulers.x -= this.lookSpeed * e.dx;
this.eulers.y -= this.lookSpeed * e.dy;
}
const convaiChat = document.getElementById("convai-chat")
convaiChat.addEventListener("mouseover",()=>{
overChat = true;
})
convaiChat.addEventListener("mouseout",()=>{
overChat = false;
})
};
FirstPersonMovement.prototype._createCamera = function () {
// 如果用户尚未分配摄像机,则创建一个新的
this.camera = new pc.Entity();
this.camera.setName("第一人称摄像机");
this.camera.addComponent("camera");
this.entity.addChild(this.camera);
this.camera.translateLocal(0, 0.5, 0);
};