给我一份cocosCreator 摄像机跟随人物移动的typescript代码,人物拥有边界限制
时间: 2023-08-04 08:04:35 浏览: 202
好的,以下是一份 TypeScript 代码示例:
```typescript
const {ccclass, property} = cc._decorator;
@ccclass
export default class CameraController extends cc.Component {
@property(cc.Node)
target: cc.Node = null; // 需要跟随的目标节点
@property(cc.Rect)
bounds: cc.Rect = new cc.Rect(-100, -100, 200, 200); // 摄像机移动的边界限制
private _camera: cc.Camera = null;
onLoad() {
this._camera = this.getComponent(cc.Camera);
}
lateUpdate() {
if (!this.target) return;
let targetPos = this.target.convertToWorldSpaceAR(cc.Vec2.ZERO);
let cameraPos = this.node.position;
// 计算目标节点与摄像机之间的距离
let distanceX = targetPos.x - cameraPos.x;
let distanceY = targetPos.y - cameraPos.y;
// 根据距离计算新的摄像机位置
let newX = cameraPos.x;
let newY = cameraPos.y;
if (distanceX > this.bounds.width / 2) {
newX = targetPos.x - this.bounds.width / 2;
} else if (distanceX < -this.bounds.width / 2) {
newX = targetPos.x + this.bounds.width / 2;
}
if (distanceY > this.bounds.height / 2) {
newY = targetPos.y - this.bounds.height / 2;
} else if (distanceY < -this.bounds.height / 2) {
newY = targetPos.y + this.bounds.height / 2;
}
this.node.position = cc.v2(newX, newY);
}
}
```
这份代码实现了让摄像机跟随目标节点移动,并且可以设置边界限制,确保摄像机不会移动出指定区域。
阅读全文