BallController.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('BallController')
  4. export class BallController extends Component {
  5. // 球的预制体
  6. @property({
  7. type: Prefab,
  8. tooltip: '拖拽Ball预制体到这里'
  9. })
  10. public ballPrefab: Prefab = null;
  11. // 球的移动速度
  12. @property
  13. public speed: number = 50;
  14. // 当前活动的球
  15. private activeBall: Node = null;
  16. // 球的方向向量
  17. private direction: Vec2 = new Vec2();
  18. // GameArea区域边界
  19. private gameBounds = {
  20. left: 0,
  21. right: 0,
  22. top: 0,
  23. bottom: 0
  24. };
  25. // 球的半径
  26. private radius: number = 0;
  27. // 是否已初始化
  28. private initialized: boolean = false;
  29. // 子弹预制体
  30. @property({
  31. type: Prefab,
  32. tooltip: '拖拽子弹预制体到这里'
  33. })
  34. public bulletPrefab: Prefab = null;
  35. start() {
  36. // 计算游戏边界
  37. this.calculateGameBounds();
  38. }
  39. // 计算游戏边界(使用GameArea节点)
  40. calculateGameBounds() {
  41. // 获取GameArea节点
  42. const gameArea = find('Canvas/GameLevelUI/GameArea');
  43. if (!gameArea) {
  44. console.error('找不到GameArea节点');
  45. return;
  46. }
  47. const gameAreaUI = gameArea.getComponent(UITransform);
  48. if (!gameAreaUI) {
  49. console.error('GameArea节点没有UITransform组件');
  50. return;
  51. }
  52. // 获取GameArea的尺寸
  53. const areaWidth = gameAreaUI.width;
  54. const areaHeight = gameAreaUI.height;
  55. // 获取GameArea的世界坐标位置
  56. const worldPos = gameArea.worldPosition;
  57. // 计算GameArea的世界坐标边界
  58. this.gameBounds.left = worldPos.x - areaWidth / 2;
  59. this.gameBounds.right = worldPos.x + areaWidth / 2;
  60. this.gameBounds.bottom = worldPos.y - areaHeight / 2;
  61. this.gameBounds.top = worldPos.y + areaHeight / 2;
  62. console.log('GameArea Bounds:', this.gameBounds);
  63. // 查找并输出墙体节点信息
  64. this.logWallInfo();
  65. }
  66. // 输出墙体节点信息
  67. logWallInfo() {
  68. const gameArea = find('Canvas/GameLevelUI/GameArea');
  69. if (!gameArea) return;
  70. // 查找墙体节点
  71. const walls = ['TopFence', 'BottomFence', 'JiguangL', 'JiguangR'];
  72. walls.forEach(wallName => {
  73. const wall = gameArea.getChildByName(wallName);
  74. if (wall) {
  75. const transform = wall.getComponent(UITransform);
  76. const collider = wall.getComponent(Collider2D);
  77. console.log(`墙体节点 ${wallName} 信息:`, {
  78. position: wall.worldPosition,
  79. size: transform ? { width: transform.width, height: transform.height } : 'unknown',
  80. hasCollider: !!collider,
  81. colliderType: collider ? collider.constructor.name : 'none'
  82. });
  83. } else {
  84. console.warn(`找不到墙体节点 ${wallName}`);
  85. }
  86. });
  87. }
  88. // 创建小球
  89. createBall() {
  90. if (!this.ballPrefab) {
  91. console.error('未设置Ball预制体');
  92. return;
  93. }
  94. // 如果已经有活动的球,先销毁它
  95. if (this.activeBall && this.activeBall.isValid) {
  96. this.activeBall.destroy();
  97. }
  98. // 实例化小球
  99. this.activeBall = instantiate(this.ballPrefab);
  100. // 将小球添加到GameArea中
  101. const gameArea = find('Canvas/GameLevelUI/GameArea');
  102. if (gameArea) {
  103. gameArea.addChild(this.activeBall);
  104. } else {
  105. this.node.addChild(this.activeBall);
  106. }
  107. // 随机位置(在GameArea范围内)
  108. this.positionBallRandomly();
  109. // 设置球的半径
  110. const transform = this.activeBall.getComponent(UITransform);
  111. if (transform) {
  112. this.radius = transform.width / 2;
  113. console.log('小球半径设置为:', this.radius);
  114. } else {
  115. this.radius = 25; // 默认半径
  116. console.warn('无法获取小球UITransform组件,使用默认半径:', this.radius);
  117. }
  118. // 确保有碰撞组件
  119. this.setupCollider();
  120. // 初始化方向
  121. this.initializeDirection();
  122. this.initialized = true;
  123. console.log('小球创建完成:', {
  124. position: this.activeBall.position,
  125. radius: this.radius,
  126. initialized: this.initialized
  127. });
  128. }
  129. // 随机位置小球
  130. positionBallRandomly() {
  131. if (!this.activeBall) return;
  132. const transform = this.activeBall.getComponent(UITransform);
  133. const ballRadius = transform ? transform.width / 2 : 25;
  134. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  135. const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
  136. const maxX = this.gameBounds.right - ballRadius - 20;
  137. const minY = this.gameBounds.bottom + ballRadius + 20;
  138. const maxY = this.gameBounds.top - ballRadius - 20;
  139. // 随机生成位置
  140. const randomX = Math.random() * (maxX - minX) + minX;
  141. const randomY = Math.random() * (maxY - minY) + minY;
  142. // 将世界坐标转换为相对于GameArea的本地坐标
  143. const gameArea = find('Canvas/GameLevelUI/GameArea');
  144. if (gameArea) {
  145. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  146. this.activeBall.position = localPos;
  147. } else {
  148. // 直接设置位置(不太准确,但作为后备)
  149. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  150. }
  151. }
  152. // 设置碰撞组件
  153. setupCollider() {
  154. if (!this.activeBall) return;
  155. // 确保小球有刚体组件
  156. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  157. if (!rigidBody) {
  158. rigidBody = this.activeBall.addComponent(RigidBody2D);
  159. rigidBody.type = 2; // Dynamic
  160. rigidBody.gravityScale = 0; // 不受重力影响
  161. rigidBody.enabledContactListener = true; // 启用碰撞监听
  162. rigidBody.fixedRotation = true; // 固定旋转
  163. rigidBody.allowSleep = false; // 不允许休眠
  164. rigidBody.linearDamping = 0; // 无阻尼
  165. rigidBody.angularDamping = 0; // 无角阻尼
  166. } else {
  167. // 确保已有的刚体组件设置正确
  168. rigidBody.enabledContactListener = true;
  169. rigidBody.gravityScale = 0;
  170. }
  171. // 确保小球有碰撞组件
  172. let collider = this.activeBall.getComponent(CircleCollider2D);
  173. if (!collider) {
  174. collider = this.activeBall.addComponent(CircleCollider2D);
  175. collider.radius = this.radius || 25; // 使用已计算的半径或默认值
  176. collider.tag = 1; // 小球标签
  177. collider.group = 1; // 碰撞组
  178. collider.sensor = false; // 非传感器(实际碰撞)
  179. collider.friction = 0; // 无摩擦
  180. collider.restitution = 1; // 完全弹性碰撞
  181. } else {
  182. // 确保已有的碰撞组件设置正确
  183. collider.sensor = false;
  184. collider.restitution = 1;
  185. }
  186. console.log('小球碰撞组件设置完成:', {
  187. hasRigidBody: !!rigidBody,
  188. hasCollider: !!collider,
  189. radius: collider ? collider.radius : 'unknown'
  190. });
  191. // 移除可能存在的事件监听
  192. this.activeBall.off(Contact2DType.BEGIN_CONTACT);
  193. this.activeBall.off(Contact2DType.END_CONTACT);
  194. this.activeBall.off(Contact2DType.PRE_SOLVE);
  195. this.activeBall.off(Contact2DType.POST_SOLVE);
  196. // 注册所有类型的碰撞事件
  197. this.activeBall.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  198. this.activeBall.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  199. this.activeBall.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  200. this.activeBall.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  201. console.log('已注册所有碰撞事件监听器');
  202. }
  203. // 碰撞回调中,只需要更新方向向量,物理引擎会处理实际的反弹
  204. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  205. // 获取碰撞点和法线
  206. if (!contact) {
  207. console.warn('碰撞事件没有contact对象');
  208. return;
  209. }
  210. // 记录碰撞对象信息
  211. console.log('碰撞发生:', {
  212. selfName: selfCollider.node.name,
  213. otherName: otherCollider.node.name,
  214. otherPath: this.getNodePath(otherCollider.node)
  215. });
  216. // 获取碰撞点的世界坐标
  217. const worldManifold = contact.getWorldManifold();
  218. if (!worldManifold) {
  219. console.warn('无法获取worldManifold');
  220. return;
  221. }
  222. // 获取碰撞法线
  223. const normal = worldManifold.normal;
  224. console.log('碰撞法线:', normal);
  225. // 检查是否碰到墙体
  226. const nodeName = otherCollider.node.name;
  227. const nodePath = this.getNodePath(otherCollider.node);
  228. const nodeParent = otherCollider.node.parent ? otherCollider.node.parent.name : 'unknown';
  229. console.log(`检查墙体碰撞: ${nodeName}, 路径: ${nodePath}, 父节点: ${nodeParent}`);
  230. // 使用多种方式检测墙体碰撞
  231. const isWall =
  232. nodeName === 'TopFence' ||
  233. nodeName === 'BottomFence' ||
  234. nodeName === 'JiguangL' ||
  235. nodeName === 'JiguangR' ||
  236. nodeName.includes('Fence') ||
  237. nodeName.includes('Jiguang') ||
  238. nodePath.includes('GameArea/TopFence') ||
  239. nodePath.includes('GameArea/BottomFence') ||
  240. nodePath.includes('GameArea/JiguangL') ||
  241. nodePath.includes('GameArea/JiguangR');
  242. if (isWall) {
  243. console.log(`球碰到了墙体 ${nodeName},进行反弹,路径: ${nodePath}`);
  244. // 更新方向向量
  245. this.direction = this.calculateReflection(this.direction, normal);
  246. // 确保球有刚体组件
  247. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  248. if (rigidBody) {
  249. // 立即更新速度方向,确保反弹效果
  250. rigidBody.linearVelocity = new Vec2(
  251. this.direction.x * this.speed,
  252. this.direction.y * this.speed
  253. );
  254. console.log('更新后的速度:', rigidBody.linearVelocity);
  255. // 强制设置位置,避免卡在墙内
  256. const ballPos = this.activeBall.worldPosition;
  257. const ballRadius = this.radius;
  258. // 根据碰撞法线调整位置
  259. if (Math.abs(normal.y) > Math.abs(normal.x)) {
  260. // 上下墙体碰撞
  261. if (normal.y > 0) {
  262. // 下墙
  263. this.activeBall.setWorldPosition(new Vec3(
  264. ballPos.x,
  265. ballPos.y + ballRadius * 0.5,
  266. ballPos.z
  267. ));
  268. } else {
  269. // 上墙
  270. this.activeBall.setWorldPosition(new Vec3(
  271. ballPos.x,
  272. ballPos.y - ballRadius * 0.5,
  273. ballPos.z
  274. ));
  275. }
  276. } else {
  277. // 左右墙体碰撞
  278. if (normal.x > 0) {
  279. // 左墙
  280. this.activeBall.setWorldPosition(new Vec3(
  281. ballPos.x + ballRadius * 0.5,
  282. ballPos.y,
  283. ballPos.z
  284. ));
  285. } else {
  286. // 右墙
  287. this.activeBall.setWorldPosition(new Vec3(
  288. ballPos.x - ballRadius * 0.5,
  289. ballPos.y,
  290. ballPos.z
  291. ));
  292. }
  293. }
  294. }
  295. }
  296. // 如果碰撞的是方块,发射子弹
  297. if (otherCollider.node.name.includes('Block')) {
  298. this.fireBullet(otherCollider.node);
  299. }
  300. }
  301. // 碰撞结束事件
  302. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  303. console.log('碰撞结束:', otherCollider.node.name);
  304. }
  305. // 碰撞预处理事件
  306. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  307. console.log('碰撞预处理:', otherCollider.node.name);
  308. }
  309. // 碰撞后处理事件
  310. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  311. console.log('碰撞后处理:', otherCollider.node.name);
  312. // 检查是否碰到墙体
  313. const nodeName = otherCollider.node.name;
  314. if (nodeName === 'TopFence' || nodeName === 'BottomFence' ||
  315. nodeName === 'JiguangL' || nodeName === 'JiguangR' ||
  316. nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  317. console.log(`球碰到了墙体 ${nodeName},处理反弹`);
  318. // 获取碰撞点和法线
  319. if (!contact) return;
  320. const worldManifold = contact.getWorldManifold();
  321. if (!worldManifold) return;
  322. // 获取碰撞法线
  323. const normal = worldManifold.normal;
  324. // 更新方向向量
  325. this.direction = this.calculateReflection(this.direction, normal);
  326. // 确保球有刚体组件
  327. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  328. if (rigidBody) {
  329. // 立即更新速度方向,确保反弹效果
  330. rigidBody.linearVelocity = new Vec2(
  331. this.direction.x * this.speed,
  332. this.direction.y * this.speed
  333. );
  334. }
  335. }
  336. }
  337. // 计算反射向量
  338. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  339. // 使用反射公式: R = V - 2(V·N)N
  340. const dot = direction.x * normal.x + direction.y * normal.y;
  341. const reflection = new Vec2(
  342. direction.x - 2 * dot * normal.x,
  343. direction.y - 2 * dot * normal.y
  344. );
  345. reflection.normalize();
  346. // 添加一些随机性,避免重复的反弹路径
  347. const randomAngle = (Math.random() - 0.5) * 0.2; // -0.1到0.1弧度的随机角度
  348. const cos = Math.cos(randomAngle);
  349. const sin = Math.sin(randomAngle);
  350. // 应用随机旋转
  351. const randomizedReflection = new Vec2(
  352. reflection.x * cos - reflection.y * sin,
  353. reflection.x * sin + reflection.y * cos
  354. );
  355. randomizedReflection.normalize();
  356. console.log('反射方向:', {
  357. original: direction,
  358. normal: normal,
  359. reflection: reflection,
  360. randomized: randomizedReflection
  361. });
  362. return randomizedReflection;
  363. }
  364. // 发射子弹
  365. fireBullet(blockNode: Node) {
  366. console.log('发射子弹!击中方块:', blockNode.name);
  367. // 检查是否有子弹预制体
  368. if (!this.bulletPrefab) {
  369. console.error('未设置子弹预制体');
  370. return;
  371. }
  372. // 查找Weapon节点
  373. const weaponNode = blockNode.getChildByName('Weapon');
  374. if (!weaponNode) {
  375. console.warn(`方块 ${blockNode.name} 没有Weapon子节点`);
  376. return;
  377. }
  378. // 实例化子弹
  379. const bullet = instantiate(this.bulletPrefab);
  380. // 将子弹添加到GameArea中
  381. const gameArea = find('Canvas/GameLevelUI/GameArea');
  382. if (gameArea) {
  383. gameArea.addChild(bullet);
  384. // 设置子弹初始位置为Weapon节点的位置
  385. const weaponWorldPos = weaponNode.worldPosition;
  386. bullet.worldPosition = weaponWorldPos;
  387. // 计算子弹方向 - 从Weapon指向小球
  388. const ballPos = this.activeBall.worldPosition;
  389. const direction = new Vec2(
  390. ballPos.x - weaponWorldPos.x,
  391. ballPos.y - weaponWorldPos.y
  392. );
  393. direction.normalize();
  394. // 添加自动销毁逻辑
  395. this.scheduleOnce(() => {
  396. if (bullet && bullet.isValid) {
  397. bullet.destroy();
  398. }
  399. }, 5); // 5秒后销毁子弹
  400. }
  401. }
  402. // 获取节点的完整路径
  403. private getNodePath(node: Node): string {
  404. let path = node.name;
  405. let current = node;
  406. while (current.parent) {
  407. current = current.parent;
  408. path = current.name + '/' + path;
  409. }
  410. return path;
  411. }
  412. update(dt: number) {
  413. // 如果使用物理引擎,不要手动更新位置
  414. if (!this.initialized || !this.activeBall || !this.activeBall.isValid) return;
  415. // 使用刚体组件控制小球移动,而不是直接设置位置
  416. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  417. if (rigidBody) {
  418. // 检查速度是否过小或为零,如果是则恢复速度
  419. const currentVelocity = rigidBody.linearVelocity;
  420. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  421. if (speed < 1.0) {
  422. console.log('检测到速度过小,恢复速度:', speed);
  423. // 如果速度太小,恢复到正常速度
  424. this.direction.normalize();
  425. rigidBody.linearVelocity = new Vec2(
  426. this.direction.x * this.speed,
  427. this.direction.y * this.speed
  428. );
  429. }
  430. // 确保方向向量与实际速度方向一致
  431. if (speed > 1.0) {
  432. this.direction.x = currentVelocity.x / speed;
  433. this.direction.y = currentVelocity.y / speed;
  434. }
  435. // 手动检测墙体碰撞
  436. this.checkWallCollisions();
  437. // 每隔一段时间输出小球状态信息
  438. if (Math.random() < 0.01) { // 约每100帧输出一次
  439. console.log('小球状态:', {
  440. position: this.activeBall.worldPosition,
  441. velocity: rigidBody.linearVelocity,
  442. speed: speed,
  443. direction: this.direction
  444. });
  445. }
  446. }
  447. }
  448. // 手动检测墙体碰撞
  449. checkWallCollisions() {
  450. if (!this.activeBall || !this.activeBall.isValid) return;
  451. // 获取小球的世界坐标
  452. const ballPos = this.activeBall.worldPosition;
  453. const ballRadius = this.radius;
  454. // 检查是否碰到上下左右边界
  455. let collided = false;
  456. let normal = new Vec2(0, 0);
  457. // 上边界碰撞
  458. if (ballPos.y + ballRadius >= this.gameBounds.top) {
  459. normal.y = -1;
  460. collided = true;
  461. console.log('手动检测到上边界碰撞');
  462. // 修正位置,避免卡在边界
  463. this.activeBall.setWorldPosition(new Vec3(
  464. ballPos.x,
  465. this.gameBounds.top - ballRadius - 0.1,
  466. ballPos.z
  467. ));
  468. }
  469. // 下边界碰撞
  470. else if (ballPos.y - ballRadius <= this.gameBounds.bottom) {
  471. normal.y = 1;
  472. collided = true;
  473. console.log('手动检测到下边界碰撞');
  474. // 修正位置,避免卡在边界
  475. this.activeBall.setWorldPosition(new Vec3(
  476. ballPos.x,
  477. this.gameBounds.bottom + ballRadius + 0.1,
  478. ballPos.z
  479. ));
  480. }
  481. // 左边界碰撞
  482. if (ballPos.x - ballRadius <= this.gameBounds.left) {
  483. normal.x = 1;
  484. collided = true;
  485. console.log('手动检测到左边界碰撞');
  486. // 修正位置,避免卡在边界
  487. this.activeBall.setWorldPosition(new Vec3(
  488. this.gameBounds.left + ballRadius + 0.1,
  489. ballPos.y,
  490. ballPos.z
  491. ));
  492. }
  493. // 右边界碰撞
  494. else if (ballPos.x + ballRadius >= this.gameBounds.right) {
  495. normal.x = -1;
  496. collided = true;
  497. console.log('手动检测到右边界碰撞');
  498. // 修正位置,避免卡在边界
  499. this.activeBall.setWorldPosition(new Vec3(
  500. this.gameBounds.right - ballRadius - 0.1,
  501. ballPos.y,
  502. ballPos.z
  503. ));
  504. }
  505. // 如果碰到边界,计算反弹
  506. if (collided) {
  507. // 标准化法向量
  508. if (normal.x !== 0 || normal.y !== 0) {
  509. normal.normalize();
  510. }
  511. // 计算反射方向
  512. this.direction = this.calculateReflection(this.direction, normal);
  513. // 更新速度
  514. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  515. if (rigidBody) {
  516. // 立即更新速度方向,确保反弹效果
  517. rigidBody.linearVelocity = new Vec2(
  518. this.direction.x * this.speed,
  519. this.direction.y * this.speed
  520. );
  521. console.log('手动更新速度方向:', this.direction);
  522. }
  523. }
  524. }
  525. // 初始化方向
  526. initializeDirection() {
  527. // 随机初始方向
  528. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  529. this.direction.x = Math.cos(angle);
  530. this.direction.y = Math.sin(angle);
  531. this.direction.normalize();
  532. console.log('Ball initialized with direction:', this.direction);
  533. }
  534. // 初始化球的参数 - 公开方法,供GameManager调用
  535. initialize() {
  536. this.calculateGameBounds();
  537. this.createBall();
  538. }
  539. }