還記得小時候玩的泡泡龍嗎?用CocosCreator實現它!

摘要

習慣了方格形狀的二維數組擺放模式後對《泡泡龍》這類參差不齊的擺法束手無策?別怕!免費教程、開源源碼全部到位!

正文

效果

數據結構

/**
 * 泡泡數據對象
 */
export interface bubbleData {
    node: cc.Node,
    color: number,
    isLinked: boolean,
    isVisited: boolean
}

用二維數組表示,在json文件中提前配置好

{
    "lv1": [
        [2,2,2,3,3,3,4,4,4],
         [2,2,0,3,3,0,4,4],
        [0,2,0,0,3,0,0,4,0],
         [0,1,1,1,1,1,1,0],
        [0,0,1,1,0,1,1,0,0],
         [0,0,1,0,0,1,0,0],
        [0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0]
    ],
    // 其他關卡省略......
}

座標轉化

一個轉化工具類

public static readonly SCREEN_W: number = 720;
public static readonly SCREEN_H: number = 1280;
public static readonly BUBBLE_R: number = 40;
/** Y 方向偏差爲 40 倍根號 3 */
public static readonly BUBBLE_Y: number = 40 * Math.sqrt(3);

/** 傳入二維數組行列,返回泡泡對應位置座標 */
public static convertRowColToPos (row: number, col: number): cc.Vec2 {
    // 奇數行前方少一個半徑寬
    let posX: number = this.BUBBLE_R * ((row % 2) + 1) + col * this.BUBBLE_R * 2;
    let posY: number = this.SCREEN_H - (this.BUBBLE_R + row * this.BUBBLE_Y);
    return cc.v2(posX, posY);
}

/** 傳入泡泡對應位置座標,返回二維數組行列 */
public static convertPosToRowCol (posX: number, posY: number): cc.Vec2 {
    let row: number = Math.round((this.SCREEN_H - posY - this.BUBBLE_R) / this.BUBBLE_Y);
    let col: number = Math.round((posX - this.BUBBLE_R * ((row % 2) + 1)) / (this.BUBBLE_R * 2));
    return cc.v2(row, col);
}

優化碰撞

大多數情況下,乘法是慢於加法的,所以分段檢測,x y 兩方向都符合要求後再做乘法。

let offsetY = Math.abs(n.y - this.shootBubble.node.y);
if (offsetY > Util.BUBBLE_R * 2) continue;
let offsetX = Math.abs(n.x - this.shootBubble.node.x);
if (offsetX > Util.BUBBLE_R * 2) continue;
let dis = offsetX * offsetX + offsetY * offsetY;
if (dis > Util.BUBBLE_R * 2 * Util.BUBBLE_R * 2) continue;
// 在範圍內,觸發碰撞,停止射擊移動
this.isShooting = false;
// ......

視頻地址

錄了教程放在了 Bilibili 視頻站。
跳轉鏈接:
https://space.bilibili.com/128813294
O(∩_∩)O~~
記得點贊哦!

結語

開源地址:
https://github.com/KuoKuo666/CocosCreator-Bubble

工程源碼在我的微信公衆號回覆關鍵詞【泡泡龍】也可獲得

O(∩_∩)O~~

微信公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章