- 这里参考kuokuo大佬的代码。链接https://mp.weixin.qq.com/s?__biz=MzI1Nzk1MzExNw==&mid=2247484249&idx=1&sn=9402581f52a9d3eaa5a0c31252d42a53&chksm=ea0edf6bdd79567d7bb50d78e02fa3c82286c613311ba1f39461dec81e9ec524ffd88cac2988&scene=21#wechat_redirect
- joystick代码如下:
+ `
import {
_decorator,
Component,
Node,
EventTouch,
UITransformComponent,
Vec2,
Vec3,
macro,
EventHandler,
} from 'cc'
const { ccclass, property } = _decorator
@ccclass
export default class Joystick extends Component {
@property({ type: Node, tooltip: '移动中心节点' })
midNode: Node = null
@property({ type: Node, tooltip: '摇杆背景节点' })
joyBk: Node = null
@property({ type: Number, tooltip: '摇杆活动半径' })
maxR: number = 100
@property({ type: [EventHandler], tooltip: '摇杆移动回调' })
joyCallBack: EventHandler[] = []
uITransform: UITransformComponent = null
onLoad() {
this.goBackMid()
}
start() {
this.uITransform = this.getComponent(UITransformComponent)
this.joyBk.on(Node.EventType.TOUCH_START, this.onTouchStart, this)
this.joyBk.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this)
this.joyBk.on(Node.EventType.TOUCH_END, this.onTouchEnd, this)
this.joyBk.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this)
}
goBackMid() {
this.midNode.setPosition(0, 0, 0)
}
onTouchStart(e: EventTouch) {
this.onTouchMove(e)
}
onTouchMove(e: EventTouch) {
const location = e.getUILocation()
let pos = this.uITransform.convertToNodeSpaceAR(
new Vec3(location.x, location.y)
)
this.clampPos(pos)
this.midNode.setPosition(pos.x, pos.y, 0)
let angle = this.covertToAngle(pos)
this.joyCallBack.forEach((c) => c.emit([pos, angle]))
}
onTouchEnd(e: EventTouch) {
this.goBackMid()
this.joyCallBack.forEach((c) => c.emit([new Vec3(0, 0, 0)]))
}
clampPos(pos: Vec3) {
let len = pos.length()
if (len > this.maxR) {
let k = this.maxR / len
pos.x *= k
pos.y *= k
}
}
covertToAngle(pos: Vec3) {
let angle = Math.atan2(pos.y, pos.x)
return angle * macro.DEG
}
}
import { _decorator, Component, Node, Vec2, Vec3 } from 'cc'
const { ccclass, property } = _decorator
@ccclass('player')
export class player extends Component {
vector: Vec2 = new Vec2(0, 0)
start() {}
update(deltaTime: number) {
const speed = 0.02
this.node.setPosition(
this.node.position.x + this.vector.x * speed,
this.node.position.y + this.vector.y * speed
)
}
playerMoving(vector, angle) {
this.vector.x = vector.x
this.vector.y = vector.y
if (angle) {
this.node.angle = angle
}
}
}