perf: 限制相机移动范围

This commit is contained in:
2025-09-21 21:11:02 +08:00
parent 85d1b54389
commit 35cfabb66b
2 changed files with 71 additions and 6 deletions

View File

@@ -13,6 +13,12 @@ export class PlayerController extends Component {
@property({ range: [1, 20] })
moveSpeed: number = 5; // 移动速度
@property
mapWidth: number = 1080; // 地图宽度
@property
mapHeight: number = 2560; // 地图高度
private isMoving: boolean = false;
private targetPosition: Vec3 = new Vec3();
private originalPosition: Vec3 = new Vec3();
@@ -79,11 +85,28 @@ export class PlayerController extends Component {
private moveToPosition(worldPos: Vec3) {
if (!this.player) return;
// 限制目标位置在地图边界内
const clampedPos = this.clampPlayerPosition(worldPos);
// 设置目标位置保持Z轴不变
this.targetPosition.set(worldPos.x, worldPos.y, this.player.position.z);
this.targetPosition.set(clampedPos.x, clampedPos.y, this.player.position.z);
this.isMoving = true;
console.log(`移动目标: (${worldPos.x.toFixed(2)}, ${worldPos.y.toFixed(2)})`);
console.log(`移动目标: (${clampedPos.x.toFixed(2)}, ${clampedPos.y.toFixed(2)})`);
}
// 限制玩家位置在地图边界内
private clampPlayerPosition(position: Vec3): Vec3 {
// 计算地图边界地图锚点为0.5,0.5,所以范围是-mapWidth/2到+mapWidth/2
const mapHalfWidth = this.mapWidth * 0.5;
const mapHalfHeight = this.mapHeight * 0.5;
// 限制玩家位置
const clampedPosition = position.clone();
clampedPosition.x = Math.max(-mapHalfWidth, Math.min(mapHalfWidth, position.x));
clampedPosition.y = Math.max(-mapHalfHeight, Math.min(mapHalfHeight, position.y));
return clampedPosition;
}
update(deltaTime: number) {
@@ -117,7 +140,10 @@ export class PlayerController extends Component {
// 正常移动
const newPosition = new Vec3();
Vec3.scaleAndAdd(newPosition, currentPos, direction, moveDistance);
this.player.position = newPosition;
// 确保新位置在地图边界内
const clampedNewPosition = this.clampPlayerPosition(newPosition);
this.player.position = clampedNewPosition;
}
}
}