1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > cocos creator-js-虚拟摇杆

cocos creator-js-虚拟摇杆

时间:2019-01-01 00:27:39

相关推荐

cocos creator-js-虚拟摇杆

项目源码

链接:/s/1SQUKpcp65u276QkkV_dicw

提取码:h98o

cc.Class({extends: ponent,properties: {bg: cc.Node,//--移动节点可移动范围 以及触摸范围 可进行分开moveNode: cc.Node,//--待移动节点handNode: cc.Node,//--摇杆节点hand: cc.Node,//--摇杆上小圆圈},onLoad() {this.bg.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);this.bg.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);this.bg.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);this.bg.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);//--可移动节点最大范围this.moveMax_X = this.bg.width / 2 - this.moveNode.width / 2;this.moveMax_Y = this.bg.height / 2 - this.moveNode.height / 2;//--小圆圈可移动半径this.hand_r = this.handNode.width / 2;},onTouchStart(event) {//--摇杆显示this.handNode.active = true;//--坐标转换let pos_local = this.node.parent.convertToNodeSpaceAR(cc.v2(event.getLocation().x, event.getLocation().y));this.pos_local = pos_local;//--摇杆拿到初始位置 点击哪里 摇杆在哪this.handNode.position = cc.v2(pos_local.x, pos_local.y);//--摇杆上小圆圈位置归位this.hand.position = cc.v2(0, 0);},onTouchMove(event) {//根据坐标差计算位置let pos = this.handNode.convertToNodeSpaceAR(cc.v2(event.getLocation().x, event.getLocation().y));let distance = this.getTwoPointDis(pos, cc.v2(0, 0));this.pos_local = pos;if (distance > this.hand_r) {//--超出范围时 等比例缩小拉回来pos = cc.v2(pos.x * this.hand_r / distance, pos.y * this.hand_r / distance);}this.hand.position = cc.v2(pos.x, pos.y);},onTouchEnd(event) {this.handNode.active = false;this.hand.position = cc.v2(0, 0);},/*** 计算两个坐标点间的距离* @param {*} pos1 * @param {*} pos2 * @returns */getTwoPointDis(pos1, pos2) {var a = pos1.x - pos2.x;var b = pos1.y - pos2.y;return Math.sqrt(a * a + b * b);},update(dt) {if (this.handNode.active) {//--x轴部分let posX = this.moveNode.position.x;if (this.hand.position.x >= 5 || this.hand.position.x <= -5) {//--5算是一个容错范围 可以归0posX += (this.hand.position.x > 0 ? 1 : -1) * 200 * dt;}//--y轴部分let posY = this.moveNode.position.y;if (this.hand.position.y >= 5 || this.hand.position.y <= -5) {posY += (this.hand.position.y > 0 ? 1 : -1) * 200 * dt;}this.moveNode.position = cc.v2(posX >= this.moveMax_X ? this.moveMax_X : posX <= -this.moveMax_X ? -this.moveMax_X : posX,posY >= this.moveMax_Y ? this.moveMax_Y : posY <= -this.moveMax_Y ? -this.moveMax_Y : posY);}},});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。