钩子的碰撞体设置
在钩子下添加空节点,拉一下大小,跟图片里差不多就好
添加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;
}
}
}
搞定,愉快的玩耍吧