feat
This commit is contained in:
79
assets/scripts/CameraFollow.ts
Normal file
79
assets/scripts/CameraFollow.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { _decorator, Component, Node, Vec3, Camera } from 'cc';
|
||||
const { ccclass, property } = _decorator;
|
||||
|
||||
@ccclass('CameraFollow')
|
||||
export class CameraFollow extends Component {
|
||||
|
||||
@property(Node)
|
||||
target: Node | null = null; // 要跟随的目标(玩家)
|
||||
|
||||
@property({ range: [0.1, 10] })
|
||||
followSpeed: number = 5.0; // 跟随速度
|
||||
|
||||
@property(Vec3)
|
||||
offset: Vec3 = new Vec3(0, 0, 10); // 相机相对目标的偏移
|
||||
|
||||
@property({ range: [0, 1] })
|
||||
smoothness: number = 0.1; // 平滑度,0为瞬间跟随,1为最慢跟随
|
||||
|
||||
private camera: Camera | null = null;
|
||||
|
||||
onLoad() {
|
||||
// 获取相机组件
|
||||
this.camera = this.getComponent(Camera);
|
||||
if (!this.camera) {
|
||||
console.error('CameraFollow: 未找到Camera组件');
|
||||
}
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.target) {
|
||||
// 初始化相机位置
|
||||
const initialPos = this.target.position.clone();
|
||||
initialPos.add(this.offset);
|
||||
this.node.position = initialPos;
|
||||
}
|
||||
}
|
||||
|
||||
update(deltaTime: number) {
|
||||
if (!this.target) return;
|
||||
|
||||
// 计算目标位置
|
||||
const targetPosition = this.target.position.clone();
|
||||
targetPosition.add(this.offset);
|
||||
|
||||
// 使用插值实现平滑跟随
|
||||
const currentPosition = this.node.position;
|
||||
const newPosition = new Vec3();
|
||||
|
||||
// 根据平滑度设置插值速度
|
||||
const lerpFactor = Math.min(1.0, this.followSpeed * deltaTime * (1 - this.smoothness + 0.1));
|
||||
|
||||
Vec3.lerp(newPosition, currentPosition, targetPosition, lerpFactor);
|
||||
this.node.position = newPosition;
|
||||
}
|
||||
|
||||
// 设置跟随目标
|
||||
setTarget(target: Node) {
|
||||
this.target = target;
|
||||
if (target) {
|
||||
const initialPos = target.position.clone();
|
||||
initialPos.add(this.offset);
|
||||
this.node.position = initialPos;
|
||||
}
|
||||
}
|
||||
|
||||
// 设置偏移量
|
||||
setOffset(offset: Vec3) {
|
||||
this.offset = offset;
|
||||
}
|
||||
|
||||
// 瞬间移动到目标位置
|
||||
snapToTarget() {
|
||||
if (!this.target) return;
|
||||
|
||||
const targetPosition = this.target.position.clone();
|
||||
targetPosition.add(this.offset);
|
||||
this.node.position = targetPosition;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user