- 效果展示:
- 代码
const {ccclass, property} = cc._decorator;
@ccclass
export default class Main extends cc.Component {
@property(cc.Node)
private gameNode: cc.Node = null;
@property(cc.Prefab)
private boomPre: cc.Prefab = null;
@property(cc.Prefab)
private boxPre: cc.Prefab = null;
private boomCircle: number = 400;//爆炸半径
private boomAddition: number = 1000000;//效果加成
private boxCollider: cc.Node[] = [];
private boomPos: {x: number,y: number}[] = [{x: -100, y: 200}, {x: 50, y: -50}, {x: 300, y: 280}, {x: -240, y: -190}, {x: 180, y: 80}];
onLoad () {
cc.director.getPhysicsManager().enabled = true;
this.createBox();
this.createBoom();
}
createBoom() {
let boom = cc.instantiate(this.boomPre);
boom.setPosition(0,0,0);
boom.parent = this.gameNode;
cc.tween(boom)
.to(0.1, {scale: 1.1, color: cc.Color.WHITE})
.to(0.1, {scale: 1.0, color: cc.Color.RED})
.union()
.repeat(10)
.call(()=>{
boom.scale = 1.5;
setTimeout(() => {
this.boomEnable(boom.getPosition());
boom.removeFromParent(false);
},200);
})
.start()
}
createBox() {
for(let i=0; i<this.boomPos.length; i++){
let pos = this.boomPos[i];
let node = cc.instantiate(this.boxPre);
node.setPosition(pos.x, pos.y);
this.boxCollider.push(node);
node.parent = this.gameNode;
}
}
boomEnable(pos: cc.Vec2) {
this.boxCollider.forEach((node, index) => {
//boxPos应为传入的pos节点的相对坐标。。(示例中2节点为兄弟节点,且传入pos为{0,0})😀
let boxPos = node.getPosition();
let vec = boxPos.sub(pos);//向量
let distance = vec.mag();//模长
if(distance < this.boomCircle){//判断是否在爆炸冲击范围内
let addition = this.boomAddition / distance;//相距越近的box受到的冲量加成越大,受到的冲量大小
let normalize = vec.normalize();//单位向量
let rigidBody = node.getComponent(cc.RigidBody);
node.color = cc.Color.RED;
rigidBody.applyForceToCenter(cc.v2(normalize.x * addition, normalize.y * addition), true);//给刚体冲量
}else{
node.color = cc.Color.GREEN;
}
});
}
}
先创建出炸弹prefab和物品prefab,其中物品prefab上需要添加物理组件->collider组件。然后将脚本挂载在场景中,挂载需要的prefab及节点。运行即可