鈎子的碰撞體設定
在鈎子下添加空節點,拉一下大小,跟圖檔裡差不多就好
添加widget元件,并填寫Bottom值
再給它添加boxCollider元件
Srcipt檔案夾下添加檔案HookCollider.ts,并且挂在給item節點
onLoad編寫代碼
HookCollider.ts
onLoad() {
cc.director.getCollisionManager().enabled = true;
var manager = cc.director.getCollisionManager(); // 擷取碰撞檢測類
manager.enabled = true //開啟碰撞檢測
//擷取父物體鈎子繩索控制腳本,用于控制繩索縮回
this.hookScript = this.node.parent.getComponent(Hook);
}
礦石的碰撞體設定
輕按兩下打開預制體
為其添加boxCollider元件
Scripts檔案夾下建立腳本MineItem.ts,寫2個屬性進去,注意export class MineItem這裡類名要改,不然在其他腳本擷取不到它
MineItem.ts
export class MineItem extends cc.Component {
public score: number; //得分
public speed: number; //拉取速度
}
将腳本挂載到預制體。
給所有要用到的預制體重複以上操作
碰撞分組設定
接着要在設定裡打開允許産生碰撞的分組
依次打開礦石預制體,将其分組設定到item(炸藥桶設定成tnt)
同理,鈎子的碰撞group設定成hook
編寫GameManager存儲全局變量
GameManager.ts
import { Singleton } from "./Singleton";
export class GameManager<T> extends Singleton<T> {
public catchItem: MineItem = null;
public ropeSpeed: number; //繩子速度
public ropeState: number; //繩子伸縮狀态
public score: number; //得分
public catchItem: MineItem = null; //鈎子抓住的物體
}
}
建立Singleton.ts,作為GameManager繼承的單例類,直接複制即可
export class Singleton<T>{
private static instance: any = null;
public static Instance<T>(c: { new(): T }): T {
if (this.instance == null) {
this.instance = new c();
}
return this.instance;
}
}
改寫Hook.ts,從gameManager裡讀取繩子的ropeSpeed和ropeState
Hook.ts
hookLengthen(deltaTime) {
let gameManager = GameManager.Instance(GameManager);
if (this.gameManager.ropeState == ROPE_STATE.ADD) {
this.node.height += 100 * deltaTime;
} else if (this.gameManager.ropeState == ROPE_STATE.REDUCE) {
this.node.height -= gameManager.ropeSpeed * deltaTime;
if (this.node.height <= this.ropeOriginalHeight) {
this.gameManager.ropeState = ROPE_STATE.WAIT;
this.isRotating = true;
this.node.height = this.ropeOriginalHeight;
this.node.angle = 0;
gameManager.ropeSpeed = 100;
if (gameManager.catchItem) {
let score = gameManager.catchItem.score;
gameManager.score+=score; //增加得分
gameManager.catchItem = null; //清除鈎子上抓住的東西
this.hookItem.removeAllChildren();
}
}
}
}
編寫碰撞代碼
HookCollider.ts
onCollisionEnter(other, self) {
//other是鈎子抓到的物體,self是鈎子自己
if (other.node.group == "wall") {
this.hookScript.ropeState = 2; //撞到牆,繩子縮回
} else {
if (!GameManager.Instance(GameManager).catchItem) {
GameManager.Instance(GameManager).catchItem = other.node.getComponent(MineItem);
GameManager.Instance(GameManager).ropeSpeed = GameManager.Instance(GameManager).catchItem.speed; //根據抓取物體,改變繩子速度
other.node.parent = this.node; //抓到的物體變成鈎子子物體,才會跟着繩子走
other.node.x = 0;
other.node.y = 0;
}
}
}
搞定,愉快的玩耍吧