cocos 躲避球游戏(3) --群组碰撞

原创
2020/11/24 23:04
阅读数 49

 

原文链接: cocos 躲避球游戏(3) --群组碰撞

简单效果如下

随机生成一点, 当点和物体碰撞时, 累加碰撞次数

 

对ball和plane分组

 

一定要勾选允许分组碰撞!!!! 搞了好久

 

在碰撞的时候, 发送事件, 累加碰撞次数

在ball超出界面后销毁, 同时随机生再成一个

const { ccclass, property } = cc._decorator;
const width = 960;
const height = 640;

@ccclass
export default class NewClass extends cc.Component {
  @property(cc.Label)
  label: cc.Label = null;
  // 1-10 表示快到慢
  @property
  speedX: number = 1;
  @property
  speedY: number = 1;
  @property
  x: number = 0;
  @property
  y: number = 0;
  onLoad() {
    const manager = cc.director.getCollisionManager();
    manager.enabled = true;
  }
  // 设置初始位置
  init(x = 0, y = 0, sx = 1, sy = 1) {
    const manager = cc.director.getCollisionManager();
    manager.enabled = true;
    this.x = this.node.x = x;
    this.y = this.node.y = y;
    this.speedX = sx;
    this.speedY = sy;
  }

  // dt 和上一帧的时间间隔, 16ms, 数值为0.016左右
  update(dt) {
    // 全部乘10是同一加速
    this.node.x += this.speedX * dt * 10;
    this.node.y += this.speedY * dt * 10;
    if (
      Math.abs(this.node.x) > width / 2 ||
      Math.abs(this.node.y) > height / 2
    ) {
      // 移除元素
      this.node.destroy();
      this.node.dispatchEvent(new cc.Event.EventCustom("genBall", true));
    }
  }
  onCollisionEnter(other, self) {
    console.error("ball onCollisionEnter", other, self);
    this.node.dispatchEvent(new cc.Event.EventCustom("hitStart", true));
  }
}

 

ballWrap

const { ccclass, property } = cc._decorator;
const initCount = 50;
const width = 960;
const height = 640;
const speedMax = 10;
const randomInt = (min = 0, max = 10) => {
  return (Math.random() * (max - min) + min) | 0;
};

@ccclass
export default class NewClass extends cc.Component {
  @property(cc.Prefab)
  ballFab: cc.Prefab = null;
  @property(cc.Label)
  label: cc.Label = null;
  @property
  count = 0;

  genBall() {
    const node = cc.instantiate(this.ballFab);
    const x = randomInt(-width / 2, width / 2);
    const y = randomInt(-height / 2, height / 2);
    const sx = randomInt(-speedMax, speedMax);
    const sy = randomInt(-speedMax, speedMax);
    node.getComponent("ball").init(x, y, sx, sy);
    this.node.addChild(node);
  }
  start() {
    this.label.string = this.count + "";
    const manager = cc.director.getCollisionManager();
    manager.enabled = true;
    for (let i = 0; i < initCount; i++) {
      this.genBall();
    }
    this.node.on("hitStart", () => {
      console.log("wrap hitStart");
      this.label.string = ++this.count + "";
    });

    this.node.on("genBall", () => this.genBall());
  }
}

 

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部