| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869 |
- import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D } from 'cc';
- const { ccclass, property } = _decorator;
- @ccclass('BallController')
- export class BallController extends Component {
- // 球的预制体
- @property({
- type: Prefab,
- tooltip: '拖拽Ball预制体到这里'
- })
- public ballPrefab: Prefab = null;
- // 球的移动速度
- @property
- public speed: number = 50;
- // 子弹发射冷却时间(秒)
- @property
- public bulletCooldown: number = 0.5;
-
- // 反弹随机偏移最大角度(弧度)
- @property
- public maxReflectionRandomness: number = 0.2;
-
- // 脱离卡点的力度
- @property
- public unstuckForce: number = 10;
-
- // 脱离卡点的检测时间(秒)
- @property
- public stuckDetectionTime: number = 0.5;
- // 当前活动的球
- private activeBall: Node = null;
- // 球的方向向量
- private direction: Vec2 = new Vec2();
-
- // GameArea区域边界
- private gameBounds = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0
- };
- // 球的半径
- private radius: number = 0;
- // 是否已初始化
- private initialized: boolean = false;
-
- // 子弹冷却状态
- private canFireBullet: boolean = true;
-
- // 上次位置和时间,用于检测卡住
- private lastPosition: Vec3 = new Vec3();
- private stuckTimer: number = 0;
- private stuckCheckInterval: number = 0.1;
- private lastCheckTime: number = 0;
-
- // 碰撞的方块ID记录,避免重复发射
- private collidedBlockIds: Set<string> = new Set();
- // 子弹预制体
- @property({
- type: Prefab,
- tooltip: '拖拽子弹预制体到这里'
- })
- public bulletPrefab: Prefab = null;
- start() {
- // 计算游戏边界
- this.calculateGameBounds();
-
- // 检查子弹预制体是否已设置
- if (this.bulletPrefab) {
- console.log('子弹预制体已设置:', this.bulletPrefab.name);
- } else {
- console.error('子弹预制体未设置!请在编辑器中设置bulletPrefab属性');
- }
- }
- // 计算游戏边界(使用GameArea节点)
- calculateGameBounds() {
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- console.error('找不到GameArea节点');
- return;
- }
- const gameAreaUI = gameArea.getComponent(UITransform);
- if (!gameAreaUI) {
- console.error('GameArea节点没有UITransform组件');
- return;
- }
- // 获取GameArea的尺寸
- const areaWidth = gameAreaUI.width;
- const areaHeight = gameAreaUI.height;
-
- // 获取GameArea的世界坐标位置
- const worldPos = gameArea.worldPosition;
- // 计算GameArea的世界坐标边界
- this.gameBounds.left = worldPos.x - areaWidth / 2;
- this.gameBounds.right = worldPos.x + areaWidth / 2;
- this.gameBounds.bottom = worldPos.y - areaHeight / 2;
- this.gameBounds.top = worldPos.y + areaHeight / 2;
- console.log('GameArea Bounds:', this.gameBounds);
-
- }
- // 创建小球
- createBall() {
- if (!this.ballPrefab) {
- console.error('未设置Ball预制体');
- return;
- }
- // 如果已经有活动的球,先销毁它
- if (this.activeBall && this.activeBall.isValid) {
- this.activeBall.destroy();
- }
- // 实例化小球
- this.activeBall = instantiate(this.ballPrefab);
-
- // 将小球添加到GameArea中
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- gameArea.addChild(this.activeBall);
- } else {
- this.node.addChild(this.activeBall);
- }
- // 随机位置小球
- this.positionBallRandomly();
- // 设置球的半径
- const transform = this.activeBall.getComponent(UITransform);
- if (transform) {
- this.radius = transform.width / 2;
- console.log('小球半径设置为:', this.radius);
- } else {
- this.radius = 25; // 默认半径
- console.warn('无法获取小球UITransform组件,使用默认半径:', this.radius);
- }
- // 确保有碰撞组件
- this.setupCollider();
- // 初始化方向
- this.initializeDirection();
- this.initialized = true;
- console.log('小球创建完成:', {
- position: this.activeBall.position,
- radius: this.radius,
- initialized: this.initialized
- });
- }
- // 随机位置小球
- positionBallRandomly() {
- if (!this.activeBall) return;
- const transform = this.activeBall.getComponent(UITransform);
- const ballRadius = transform ? transform.width / 2 : 25;
-
- // 计算可生成的范围(考虑小球半径,避免生成在边缘)
- const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
- const maxX = this.gameBounds.right - ballRadius - 20;
- const minY = this.gameBounds.bottom + ballRadius + 20;
- const maxY = this.gameBounds.top - ballRadius - 20;
- // 获取GameArea节点
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (!gameArea) {
- console.error('找不到GameArea节点');
- return;
- }
-
- // 查找GridContainer节点,它包含所有放置的方块
- const gridContainer = gameArea.getChildByName('GridContainer');
- if (!gridContainer) {
- console.log('找不到GridContainer节点,使用默认随机位置');
- this.setRandomPositionDefault(minX, maxX, minY, maxY);
- return;
- }
-
- // 获取所有已放置的方块
- const placedBlocks = [];
- for (let i = 0; i < gridContainer.children.length; i++) {
- const cell = gridContainer.children[i];
- // 检查单元格是否有子节点(放置的方块)
- if (cell.children.length > 0) {
- placedBlocks.push(cell);
- }
- }
-
- console.log(`找到 ${placedBlocks.length} 个已放置的方块`);
-
- // 如果没有方块,使用默认随机位置
- if (placedBlocks.length === 0) {
- this.setRandomPositionDefault(minX, maxX, minY, maxY);
- return;
- }
-
- // 尝试找到一个不与任何方块重叠的位置
- let validPosition = false;
- let attempts = 0;
- const maxAttempts = 50; // 最大尝试次数
- let randomX, randomY;
-
- while (!validPosition && attempts < maxAttempts) {
- // 随机生成位置
- randomX = Math.random() * (maxX - minX) + minX;
- randomY = Math.random() * (maxY - minY) + minY;
-
- // 检查是否与任何方块重叠
- let overlapping = false;
- for (const block of placedBlocks) {
- // 获取方块的世界坐标
- const blockWorldPos = block.worldPosition;
-
- // 计算小球与方块的距离
- const distance = Math.sqrt(
- Math.pow(randomX - blockWorldPos.x, 2) +
- Math.pow(randomY - blockWorldPos.y, 2)
- );
-
- // 获取方块的尺寸
- const blockTransform = block.getComponent(UITransform);
- const blockSize = blockTransform ?
- Math.max(blockTransform.width, blockTransform.height) / 2 : 50;
-
- // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
- const safeDistance = 20; // 额外安全距离
- if (distance < ballRadius + blockSize + safeDistance) {
- overlapping = true;
- break;
- }
- }
-
- // 如果没有重叠,找到了有效位置
- if (!overlapping) {
- validPosition = true;
- }
-
- attempts++;
- }
-
- // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
- if (!validPosition) {
- console.log(`尝试 ${maxAttempts} 次后未找到有效位置,使用默认位置`);
- randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
- randomY = this.gameBounds.bottom + ballRadius + 50; // 底部上方50单位
- }
-
- // 将世界坐标转换为相对于GameArea的本地坐标
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- this.activeBall.position = localPos;
-
- console.log('小球位置已设置:', {
- worldX: randomX,
- worldY: randomY,
- localX: localPos.x,
- localY: localPos.y,
- overlapsWithBlock: !validPosition
- });
- }
- // 设置默认随机位置
- setRandomPositionDefault(minX, maxX, minY, maxY) {
- // 随机生成位置
- const randomX = Math.random() * (maxX - minX) + minX;
- const randomY = Math.random() * (maxY - minY) + minY;
- // 将世界坐标转换为相对于GameArea的本地坐标
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
- this.activeBall.position = localPos;
- } else {
- // 直接设置位置(不太准确,但作为后备)
- this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
- }
-
- console.log('使用默认随机位置设置小球:', {
- worldX: randomX,
- worldY: randomY
- });
- }
- // 设置碰撞组件
- setupCollider() {
- if (!this.activeBall) return;
- // 确保小球有刚体组件
- let rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (!rigidBody) {
- rigidBody = this.activeBall.addComponent(RigidBody2D);
- rigidBody.type = 2; // Dynamic
- rigidBody.gravityScale = 0; // 不受重力影响
- rigidBody.enabledContactListener = true; // 启用碰撞监听
- rigidBody.fixedRotation = true; // 固定旋转
- rigidBody.allowSleep = false; // 不允许休眠
- rigidBody.linearDamping = 0; // 无阻尼
- rigidBody.angularDamping = 0; // 无角阻尼
- } else {
- // 确保已有的刚体组件设置正确
- rigidBody.enabledContactListener = true;
- rigidBody.gravityScale = 0;
- }
- // 确保小球有碰撞组件
- let collider = this.activeBall.getComponent(CircleCollider2D);
- if (!collider) {
- collider = this.activeBall.addComponent(CircleCollider2D);
- collider.radius = this.radius || 25; // 使用已计算的半径或默认值
- collider.tag = 1; // 小球标签
- collider.group = 1; // 碰撞组
- collider.sensor = false; // 非传感器(实际碰撞)
- collider.friction = 0; // 无摩擦
- collider.restitution = 1; // 完全弹性碰撞
- } else {
- // 确保已有的碰撞组件设置正确
- collider.sensor = false;
- collider.restitution = 1;
- }
- console.log('小球碰撞组件设置完成:', {
- hasRigidBody: !!rigidBody,
- hasCollider: !!collider,
- radius: collider ? collider.radius : 'unknown'
- });
- // 移除可能存在的事件监听
- this.activeBall.off(Contact2DType.BEGIN_CONTACT);
- this.activeBall.off(Contact2DType.END_CONTACT);
- this.activeBall.off(Contact2DType.PRE_SOLVE);
- this.activeBall.off(Contact2DType.POST_SOLVE);
-
- // 注册所有类型的碰撞事件
- this.activeBall.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
- this.activeBall.on(Contact2DType.END_CONTACT, this.onEndContact, this);
- this.activeBall.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
- this.activeBall.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
-
- console.log('已注册所有碰撞事件监听器');
- }
- // 碰撞回调中,只需要更新方向向量,物理引擎会处理实际的反弹
- onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- // 获取碰撞点和法线
- if (!contact) {
- console.warn('碰撞事件没有contact对象');
- return;
- }
- // 记录碰撞对象信息
- console.log('碰撞发生:', {
- selfName: selfCollider.node.name,
- otherName: otherCollider.node.name,
- otherPath: this.getNodePath(otherCollider.node)
- });
- // Debug: 检查节点名称是否包含Block
- console.log(`检查节点名称: "${otherCollider.node.name}",是否包含'Block': ${otherCollider.node.name.includes('Block')}`);
- // 获取碰撞点的世界坐标
- const worldManifold = contact.getWorldManifold();
- if (!worldManifold) {
- console.warn('无法获取worldManifold');
- return;
- }
- // 获取碰撞法线
- const normal = worldManifold.normal;
- console.log('碰撞法线:', normal);
-
- // 检查是否碰到墙体
- const nodeName = otherCollider.node.name;
- const nodePath = this.getNodePath(otherCollider.node);
- const nodeParent = otherCollider.node.parent ? otherCollider.node.parent.name : 'unknown';
-
- console.log(`检查墙体碰撞: ${nodeName}, 路径: ${nodePath}, 父节点: ${nodeParent}`);
-
- // 使用多种方式检测墙体碰撞
- const isWall =
- nodeName === 'TopFence' ||
- nodeName === 'BottomFence' ||
- nodeName === 'JiguangL' ||
- nodeName === 'JiguangR' ||
- nodeName.includes('Fence') ||
- nodeName.includes('Jiguang') ||
- nodePath.includes('GameArea/TopFence') ||
- nodePath.includes('GameArea/BottomFence') ||
- nodePath.includes('GameArea/JiguangL') ||
- nodePath.includes('GameArea/JiguangR');
-
- if (isWall) {
- console.log(`球碰到了墙体 ${nodeName},进行反弹,路径: ${nodePath}`);
-
- // 更新方向向量
- this.direction = this.calculateReflection(this.direction, normal);
-
- // 确保球有刚体组件
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (rigidBody) {
- // 立即更新速度方向,确保反弹效果
- rigidBody.linearVelocity = new Vec2(
- this.direction.x * this.speed,
- this.direction.y * this.speed
- );
- console.log('更新后的速度:', rigidBody.linearVelocity);
-
- // 强制设置位置,避免卡在墙内
- const ballPos = this.activeBall.worldPosition;
- const ballRadius = this.radius;
-
- // 根据碰撞法线调整位置
- if (Math.abs(normal.y) > Math.abs(normal.x)) {
- // 上下墙体碰撞
- if (normal.y > 0) {
- // 下墙
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x,
- ballPos.y + ballRadius * 0.5,
- ballPos.z
- ));
- } else {
- // 上墙
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x,
- ballPos.y - ballRadius * 0.5,
- ballPos.z
- ));
- }
- } else {
- // 左右墙体碰撞
- if (normal.x > 0) {
- // 左墙
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x + ballRadius * 0.5,
- ballPos.y,
- ballPos.z
- ));
- } else {
- // 右墙
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x - ballRadius * 0.5,
- ballPos.y,
- ballPos.z
- ));
- }
- }
- }
- }
-
- // 如果碰撞的是方块,发射子弹
- // 修改检测逻辑,使用更宽松的条件
- const isBlock =
- nodeName.includes('Block') ||
- nodePath.includes('Block') ||
- (otherCollider.node.getChildByName('Weapon') !== null);
-
- if (isBlock) {
- console.log(`检测到方块碰撞: ${nodeName}, 路径: ${nodePath}`);
-
- // 检查冷却状态和是否已经对这个方块发射过子弹
- const blockId = otherCollider.node.uuid;
- if (this.canFireBullet && !this.collidedBlockIds.has(blockId)) {
- this.fireBullet(otherCollider.node);
- } else {
- console.log('子弹冷却中或已对此方块发射过子弹');
- }
- }
- }
- // 碰撞结束事件
- onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- console.log('碰撞结束:', otherCollider.node.name);
- }
-
- // 碰撞预处理事件
- onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- console.log('碰撞预处理:', otherCollider.node.name);
- }
-
- // 碰撞后处理事件
- onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
- console.log('碰撞后处理:', otherCollider.node.name);
-
- // 检查是否碰到墙体
- const nodeName = otherCollider.node.name;
- if (nodeName === 'TopFence' || nodeName === 'BottomFence' ||
- nodeName === 'JiguangL' || nodeName === 'JiguangR' ||
- nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
- console.log(`球碰到了墙体 ${nodeName},处理反弹`);
-
- // 获取碰撞点和法线
- if (!contact) return;
-
- const worldManifold = contact.getWorldManifold();
- if (!worldManifold) return;
-
- // 获取碰撞法线
- const normal = worldManifold.normal;
-
- // 更新方向向量
- this.direction = this.calculateReflection(this.direction, normal);
-
- // 确保球有刚体组件
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (rigidBody) {
- // 立即更新速度方向,确保反弹效果
- rigidBody.linearVelocity = new Vec2(
- this.direction.x * this.speed,
- this.direction.y * this.speed
- );
- }
- }
- }
- // 计算反射向量
- calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
- // 使用反射公式: R = V - 2(V·N)N
- const dot = direction.x * normal.x + direction.y * normal.y;
- const reflection = new Vec2(
- direction.x - 2 * dot * normal.x,
- direction.y - 2 * dot * normal.y
- );
- reflection.normalize();
-
- // 添加一些随机性,避免重复的反弹路径
- const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
- const cos = Math.cos(randomAngle);
- const sin = Math.sin(randomAngle);
-
- // 应用随机旋转
- const randomizedReflection = new Vec2(
- reflection.x * cos - reflection.y * sin,
- reflection.x * sin + reflection.y * cos
- );
-
- // 确保反射方向不会太接近水平或垂直方向
- // 这有助于避免球在水平或垂直方向上来回反弹
- const minAngleFromAxis = 0.1; // 约5.7度
-
- // 检查是否接近水平方向
- if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
- // 调整y分量,使其远离水平方向
- const sign = randomizedReflection.y >= 0 ? 1 : -1;
- randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
- // 重新归一化
- randomizedReflection.normalize();
- }
-
- // 检查是否接近垂直方向
- if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
- // 调整x分量,使其远离垂直方向
- const sign = randomizedReflection.x >= 0 ? 1 : -1;
- randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
- // 重新归一化
- randomizedReflection.normalize();
- }
-
- randomizedReflection.normalize();
- console.log('反射方向:', {
- original: direction,
- normal: normal,
- reflection: reflection,
- randomized: randomizedReflection
- });
-
- return randomizedReflection;
- }
- // 发射子弹
- fireBullet(blockNode: Node) {
- console.log('发射子弹!击中方块:', blockNode.name);
-
- // 检查冷却状态
- if (!this.canFireBullet) {
- console.log('子弹冷却中,无法发射');
- return;
- }
-
- // 检查是否已经对这个方块发射过子弹
- const blockId = blockNode.uuid;
- if (this.collidedBlockIds.has(blockId)) {
- console.log('已经对此方块发射过子弹');
- return;
- }
-
- // 记录此方块ID
- this.collidedBlockIds.add(blockId);
-
- // 设置冷却
- this.canFireBullet = false;
- this.scheduleOnce(() => {
- this.canFireBullet = true;
- // 清理碰撞记录
- this.collidedBlockIds.clear();
- }, this.bulletCooldown);
-
- // 检查是否有子弹预制体
- if (!this.bulletPrefab) {
- console.error('未设置子弹预制体');
- return;
- } else {
- console.log('子弹预制体已设置:', this.bulletPrefab.name);
- }
-
- // 查找Weapon节点 - 递归查找,因为Weapon可能在B1子节点下
- let weaponNode = this.findWeaponNode(blockNode);
-
- if (!weaponNode) {
- console.warn(`方块 ${blockNode.name} 没有找到Weapon子节点,创建一个`);
- // 如果没有找到Weapon节点,在B1节点下创建一个
- const b1Node = blockNode.getChildByName('B1');
- if (b1Node) {
- weaponNode = new Node('Weapon');
- // 确保Weapon节点有UITransform组件
- if (!weaponNode.getComponent(UITransform)) {
- weaponNode.addComponent(UITransform);
- }
- // 将Weapon添加到B1节点中
- b1Node.addChild(weaponNode);
- // 放置在B1中心
- weaponNode.position = new Vec3(0, 0, 0);
- } else {
- // 如果连B1节点都没有,直接添加到方块根节点
- weaponNode = new Node('Weapon');
- // 确保Weapon节点有UITransform组件
- if (!weaponNode.getComponent(UITransform)) {
- weaponNode.addComponent(UITransform);
- }
- // 将Weapon添加到方块中
- blockNode.addChild(weaponNode);
- // 放置在方块中心
- weaponNode.position = new Vec3(0, 0, 0);
- }
- } else {
- console.log(`找到方块 ${blockNode.name} 的Weapon子节点:`, weaponNode.name);
- }
-
- // 实例化子弹
- const bullet = instantiate(this.bulletPrefab);
-
- // 将子弹添加到GameArea中
- const gameArea = find('Canvas/GameLevelUI/GameArea');
- if (gameArea) {
- gameArea.addChild(bullet);
-
- // 设置子弹初始位置为Weapon节点的位置
- const weaponWorldPos = weaponNode.worldPosition;
- bullet.worldPosition = weaponWorldPos;
-
- // 子弹已经有BulletController组件,不需要再添加
- // 让子弹自己找到最近的敌人并攻击
- console.log('子弹已创建,将自动寻找并攻击最近的敌人');
- }
- }
-
- // 递归查找Weapon节点
- private findWeaponNode(node: Node): Node | null {
- // 先检查当前节点是否有Weapon子节点
- const weaponNode = node.getChildByName('Weapon');
- if (weaponNode) {
- return weaponNode;
- }
-
- // 如果没有,递归检查所有子节点
- for (let i = 0; i < node.children.length; i++) {
- const child = node.children[i];
- const foundWeapon = this.findWeaponNode(child);
- if (foundWeapon) {
- return foundWeapon;
- }
- }
-
- // 如果都没找到,返回null
- return null;
- }
- // 获取节点的完整路径
- private getNodePath(node: Node): string {
- let path = node.name;
- let current = node;
-
- while (current.parent) {
- current = current.parent;
- path = current.name + '/' + path;
- }
-
- return path;
- }
- update(dt: number) {
- // 如果使用物理引擎,不要手动更新位置
- if (!this.initialized || !this.activeBall || !this.activeBall.isValid) return;
-
- // 使用刚体组件控制小球移动,而不是直接设置位置
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (rigidBody) {
- // 检查速度是否过小或为零,如果是则恢复速度
- const currentVelocity = rigidBody.linearVelocity;
- const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
-
- if (speed < 1.0) {
- console.log('检测到速度过小,恢复速度:', speed);
- // 如果速度太小,恢复到正常速度
- this.direction.normalize();
- rigidBody.linearVelocity = new Vec2(
- this.direction.x * this.speed,
- this.direction.y * this.speed
- );
- }
-
- // 确保方向向量与实际速度方向一致
- if (speed > 1.0) {
- this.direction.x = currentVelocity.x / speed;
- this.direction.y = currentVelocity.y / speed;
- }
-
- // 手动检测墙体碰撞
- this.checkWallCollisions();
- }
- // 手动检测方块碰撞
- this.checkBlockCollisions();
- }
-
- // 手动检测墙体碰撞
- checkWallCollisions() {
- if (!this.activeBall || !this.activeBall.isValid) return;
-
- // 获取小球的世界坐标
- const ballPos = this.activeBall.worldPosition;
- const ballRadius = this.radius;
-
- // 检查是否碰到上下左右边界
- let collided = false;
- let normal = new Vec2(0, 0);
-
- // 上边界碰撞
- if (ballPos.y + ballRadius >= this.gameBounds.top) {
- normal.y = -1;
- collided = true;
- console.log('手动检测到上边界碰撞');
- // 修正位置,避免卡在边界
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x,
- this.gameBounds.top - ballRadius - 0.1,
- ballPos.z
- ));
- }
- // 下边界碰撞
- else if (ballPos.y - ballRadius <= this.gameBounds.bottom) {
- normal.y = 1;
- collided = true;
- console.log('手动检测到下边界碰撞');
- // 修正位置,避免卡在边界
- this.activeBall.setWorldPosition(new Vec3(
- ballPos.x,
- this.gameBounds.bottom + ballRadius + 0.1,
- ballPos.z
- ));
- }
-
- // 左边界碰撞
- if (ballPos.x - ballRadius <= this.gameBounds.left) {
- normal.x = 1;
- collided = true;
- console.log('手动检测到左边界碰撞');
- // 修正位置,避免卡在边界
- this.activeBall.setWorldPosition(new Vec3(
- this.gameBounds.left + ballRadius + 0.1,
- ballPos.y,
- ballPos.z
- ));
- }
- // 右边界碰撞
- else if (ballPos.x + ballRadius >= this.gameBounds.right) {
- normal.x = -1;
- collided = true;
- console.log('手动检测到右边界碰撞');
- // 修正位置,避免卡在边界
- this.activeBall.setWorldPosition(new Vec3(
- this.gameBounds.right - ballRadius - 0.1,
- ballPos.y,
- ballPos.z
- ));
- }
-
- // 如果碰到边界,计算反弹
- if (collided) {
- // 标准化法向量
- if (normal.x !== 0 || normal.y !== 0) {
- normal.normalize();
- }
-
- // 计算反射方向
- this.direction = this.calculateReflection(this.direction, normal);
-
- // 更新速度
- const rigidBody = this.activeBall.getComponent(RigidBody2D);
- if (rigidBody) {
- // 立即更新速度方向,确保反弹效果
- rigidBody.linearVelocity = new Vec2(
- this.direction.x * this.speed,
- this.direction.y * this.speed
- );
- console.log('手动更新速度方向:', this.direction);
- }
- }
- }
- // 手动检测方块碰撞
- checkBlockCollisions() {
- if (!this.activeBall) return;
-
- // 获取场景中所有方块
- const placedBlocks = find('Canvas/PlacedBlocks');
- if (!placedBlocks) return;
-
- const ballPos = this.activeBall.worldPosition;
- const ballRadius = this.radius;
-
- // 检查与每个方块的碰撞
- for (let i = 0; i < placedBlocks.children.length; i++) {
- const block = placedBlocks.children[i];
- if (!block.name.includes('Block')) continue;
-
- // 简单距离检测(可以根据实际情况优化)
- const blockPos = block.worldPosition;
- const distance = Vec3.distance(ballPos, blockPos);
-
- // 如果距离小于某个阈值,认为发生碰撞
- if (distance < ballRadius + 50) { // 50是一个估计值,根据方块大小调整
- console.log('手动检测到与方块碰撞:', block.name);
- this.fireBullet(block);
- break;
- }
- }
- }
- // 初始化方向
- initializeDirection() {
- // 随机初始方向
- const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
- this.direction.x = Math.cos(angle);
- this.direction.y = Math.sin(angle);
- this.direction.normalize();
- console.log('Ball initialized with direction:', this.direction);
- }
- // 初始化球的参数 - 公开方法,供GameManager调用
- initialize() {
- this.calculateGameBounds();
- this.createBall();
- }
- }
|