跳到主要内容

更多相机用法

点击聚焦后,空格缩放,左右方向键切换左右相机。

基础相机介绍实体创建并添加到场景。单个静止相机无需脚本,动态交互或高级用途可附加脚本组件,自行编程。

修改属性​

运行时可改变相机组件属性,与其他组件相同,可通过组件系统的 set() 和 get() 方法操作。

var Zoom = pc.createScript('zoom');

// initialize code called once per entity
Zoom.prototype.initialize = function() {
this.targetFov = 45;
};

// update code called every frame
Zoom.prototype.update = function(dt) {

if (this.app.keyboard.wasPressed(pc.KEY_SPACE) ) {
if (this.targetFov == 10) {
this.targetFov = 45;
} else {
this.targetFov = 10;
}
}

var fov = this.entity.camera.fov;
if (fov < this.targetFov) {
fov += (10 * dt);
if (fov > this.targetFov) {
fov = this.targetFov;
}
}

if (fov > this.targetFov) {
fov -= (10 * dt);
if (fov < this.targetFov) {
fov = this.targetFov;
}
}
this.entity.camera.fov = fov;
};

示例按空格改变 FOV。var fov = this.entity.camera.fov 从脚本所在实体相机读取视野角。

this.app.keyboard.wasPressed() 检测按键并切换目标值。

最后两个嵌套 if 逐步改变 FOV,形成缩放。

this.entity.camera.fov = fov 将新值写回。

缩小时顶部和底部立方体位于屏幕边缘,符合编辑器场景:它们正靠近相机 视锥体的上下边。

当前相机​

也可通过多相机切换创建交互:添加多个实体,只启用一个,运行时修改活动相机。

var CameraManager = pc.createScript('cameraManager');

// initialize code called once per entity
CameraManager.prototype.initialize = function() {
this.activeCamera = this.entity.findByName('Center');
this.app.keyboard.on(pc.EVENT_KEYDOWN, this.onKeyDown, this);

this.on('destroy', function() {
this.app.keyboard.off(pc.EVENT_KEYDOWN, this.onKeyDown, this);
}, this);
};

//prevents default browser actions, such as scrolling when pressing cursor keys
CameraManager.prototype.onKeyDown = function (event) {
event.event.preventDefault();
};

CameraManager.prototype.setCamera = function (cameraName) {
// Disable the currently active camera
this.activeCamera.enabled = false;

// Enable the newly specified camera
this.activeCamera = this.entity.findByName(cameraName);
this.activeCamera.enabled = true;
};

// update code called every frame
CameraManager.prototype.update = function(dt) {
var app = this.app;

if (app.keyboard.wasPressed(pc.KEY_SPACE) ) {
this.setCamera('Center');
} else if (app.keyboard.wasPressed(pc.KEY_LEFT)) {
this.setCamera('Left');
} else if (app.keyboard.wasPressed(pc.KEY_RIGHT)) {
this.setCamera('Right');
}
};

示例方向键切左右相机,空格启用中央相机。

先在父实体上用 findByName() 查名字,因为相机都位于该父节点下,无需从 app.root 搜整个场景。

建立相机名与左右和空格键对应表,参见场景。

遍历按键,触发时查对应实体,调用此前定义的 setCamera(),先禁用原相机,再启用新相机。