效果如下
复制图片资源
网上随便找个图片就行, 先拖进左下角资源管理器, 然后从资源管理器中拖到canvas结点下, 并修改名称
添加拖拽脚本
两个飞机的逻辑相同, 所以可以使用同一个脚本
onLoad() {
console.error("plane", this, this.node);
let mouseDown = false;
this.node.on(cc.Node.EventType.MOUSE_DOWN, (event) => {
mouseDown = true;
});
this.node.on(cc.Node.EventType.MOUSE_MOVE, (event) => {
if (!mouseDown) return;
//获取鼠标距离上一次点的信息
let location = event.getLocation();
this.node.position = this.node.parent.convertToNodeSpaceAR(location);
});
//当鼠标抬起的时候恢复状态
this.node.on(cc.Node.EventType.MOUSE_UP, (event) => {
mouseDown = false;
});
},
开启碰撞检测
使用box即可, 会自动设置为图片大小
碰撞发生后, 将事件抛出去, 在GameScene层做接受和处理
cc.Class({
extends: cc.Component,
properties: {
},
onLoad() {
console.error("plane", this, this.node);
let mouseDown = false;
this.node.on(cc.Node.EventType.MOUSE_DOWN, (event) => {
mouseDown = true;
});
this.node.on(cc.Node.EventType.MOUSE_MOVE, (event) => {
if (!mouseDown) return;
//获取鼠标距离上一次点的信息
let location = event.getLocation();
this.node.position = this.node.parent.convertToNodeSpaceAR(location);
});
//当鼠标抬起的时候恢复状态
this.node.on(cc.Node.EventType.MOUSE_UP, (event) => {
mouseDown = false;
});
const manager = cc.director.getCollisionManager();
manager.enabled = true;
},
// 碰撞产生的时候
onCollisionEnter(other, self) {
console.error("onCollisionEnter", other, self);
this.node.dispatchEvent(new cc.Event.EventCustom("hitStart", true));
},
// 当碰撞产生后,碰撞结束前的情况下,每次计算碰撞结果后调用
onCollisionStay: function (other, self) {
console.log("on collision stay");
this.node.dispatchEvent(new cc.Event.EventCustom("hitStay", true));
},
// 当碰撞结束后调用
onCollisionExit: function (other, self) {
console.log("on collision exit");
this.node.dispatchEvent(new cc.Event.EventCustom("hitEnd", true));
},
start() {},
// update (dt) {},
});
gameScene接受事件并响应, 设置label表示当前状态
onLoad() {
this.backBtn.node.on(
cc.Node.EventType.TOUCH_START,
this.backBtnHandle.bind(this)
);
this.node.on("hitStay", () => {
console.log("相撞", this.label.string, this.label.node.string);
this.label.string = "碰撞中";
});
this.node.on("hitEnd", () => {
console.log("相撞", this.label.string, this.label.node.string);
this.label.string = "碰撞结束";
});
this.node.on("hitStart", () => {
console.log("相撞", this.label.string, this.label.node.string);
this.label.string = "开始碰撞";
});
},