触摸事件
-
触摸事件类型:
- start 触发事件内
- moved 触发事件移动
- ended 物体内结束事件
- cancel 物体外结束事件
开启关闭监听
node.on(type(cc.node.eventType.TOUCH_START),callback,target,[useCapture])
node.off(type,callback,target,[useCapture])
- 移除所有事件
target.off(target)
- 回调函数的参数设置
function(e(cc.Touch))
- 将世界坐标转换为节点坐标
this.node.convertToNodeSpaceAR(cc.v2)
- 设置节点坐标
this.node.setPosition()
// Learn TypeScript:
// - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
// - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
// - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
const { ccclass, property } = cc._decorator;
@ccclass
export default class nodeEvent extends cc.Component {
@property({ type: cc.Node, tooltip: "要控制的节点" })
player: cc.Node = null
cachePos: cc.Vec2 = null
onLoad() {
console.log("获取节点位置:", this.player.getPosition());
this.cachePos = cc.v2(this.player.getPosition().x, this.player.getPosition().y)
this.node.on(cc.Node.EventType.TOUCH_START, (e: cc.Touch) => {
console.log("鼠标点击事件触发:", e.getLocation());
const worldPos: cc.Vec2 = e.getLocation();
const localPos: cc.Vec2 = this.node.convertToNodeSpaceAR(worldPos)
this.player.setPosition(localPos)
})
this.node.on(cc.Node.EventType.TOUCH_MOVE, (e: cc.Touch) => {
// const worldPos: cc.Vec2 = e.getLocation();
// const localPos: cc.Vec2 = this.node.convertToNodeSpaceAR(worldPos)
// this.player.setPosition(localPos)
// console.log("鼠标移动事件触发:", e, "this:", this);
const origPos = this.player.getPosition();
this.player.setPosition(origPos.add(e.getDelta()))
})
this.node.on(cc.Node.EventType.TOUCH_CANCEL, (e: cc.Touch) => {
this.player.setPosition(this.cachePos);
console.log("鼠标在外边释放", e, "this:", this);
})
this.node.on(cc.Node.EventType.TOUCH_END, (e: cc.Touch) => {
this.player.setPosition(this.cachePos);
console.log("鼠标在里边释放:", e, "this:", this);
})
}
start() {
}
// update (dt) {}
}