生活随笔
收集整理的這篇文章主要介紹了
cocos creator-js-虚拟摇杆
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
項目源碼
鏈接:https://pan.baidu.com/s/1SQUKpcp65u276QkkV_dicw?
提取碼:h98o?
cc.Class({extends: cc.Component,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);}},
});
?
總結
以上是生活随笔為你收集整理的cocos creator-js-虚拟摇杆的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。