《Cocos Creator游戏实战》非固定摇杆实现原理

为什么要使用非固定摇杆

许多同学在开发摇杆功能时,会将摇杆固定在屏幕左下某一位置,不会让其随着大拇指触摸点改变,而且玩家只有按在了摇杆上才能移动人物(触摸监听事件在摇杆精灵上)。然而,不同玩家的大拇指长度不同,使用这种固定摇杆可能会导致部分玩家无法快速按到摇杆,从而影响了游戏操作性。

非固定摇杆不需要玩家去寻找摇杆位置,玩家的大拇指只要在屏幕左下区域按下,摇杆就会自动被设置到大拇指按下的位置(触摸监听事件在画布上),游戏操作性因此提升。

注:有关固定摇杆的具体实现原理可以前往查看笔者的这篇文章

P.S. 上面的摇杆文章发布的时间是19年10月,时间过得好快。

运行效果和源码获取

Cocos Creator版本: 3.8.4
项目源码获取:搜索公号All Codes ,公号后台发送"非固定摇杆"

实现原理

1: 在摇杆组件生效时记录摇杆的位置。

ts 复制代码
/* 记录摇杆最初位置 */
recordOriginalPos() {
    this.originalPos = new Vec3(this.node.position)
}

2: 在TOUCH_START事件函数中,判断玩家触摸点是否在屏幕左下区域,是的话将摇杆设置到触摸点位置,不是的话则直接返回。

ts 复制代码
onTouchStart(event: EventTouch) {
    // 获取触摸点坐标
    let loc = event.getUILocation()
    let pos = this.canvas.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(loc.x, loc.y, 0))

    // 判断触摸点是否在画布左下区域
    // 不是的话直接返回,是的话设置摇杆底部面板位置
    if (pos.x > 0 || pos.y > 0) {
        return
    }

    this.node.setPosition(pos)
    this.isTouchAreaCorrect = true
}

3: 在TOUCH_MOVE事件函数中,更新摇杆中心按钮在摇杆底部面板上的位置。

ts 复制代码
onTouchMove(event: EventTouch) {
    if (!this.isTouchAreaCorrect) {
        return
    }

    // 在该事件中我们只需要设置摇杆中心按钮的位置
    let posDelta = event.getDelta()
    this.joystickBtn.setPosition(new Vec3(this.joystickBtn.position).add3f(posDelta.x, posDelta.y, 0))
    
    // 获取移动方向和旋转角度
    this.dir = new Vec3(this.joystickBtn.position.x, this.joystickBtn.position.y, 0).normalize()
    if (this.dir.y > 0) {
        this.angle =  Vec3.angle(this.dir, new Vec3(1, 0, 0)) * 180 / Math.PI
    }
    else {
        this.angle =  -Vec3.angle(this.dir, new Vec3(1, 0, 0)) * 180 / Math.PI
    }

    // 设置主角isMoving变量为true
    this.playerComp.isMoving = true 
}

4: 在TOUCH_END和TOUCH_CANCEL事件函数中,重置相关变量并复原摇杆位置。摇杆底部面板回到在第1步中记录的位置,摇杆中心按钮回到摇杆底部面板中心位置。

ts 复制代码
onTouchEnd(event: EventTouch) {
    // 复原摇杆位置,重置相关变量
    this.node.setPosition(this.originalPos)
    this.joystickBtn.setPosition(Vec3.ZERO)
    this.playerComp.isMoving = false
    this.isTouchAreaCorrect = false
}

onTouchCancel(event: EventTouch) {
    // 复原摇杆位置,重置相关变量
    this.node.setPosition(this.originalPos)
    this.joystickBtn.setPosition(Vec3.ZERO)
    this.playerComp.isMoving = false
    this.isTouchAreaCorrect = false
}

王者荣耀中的非固定摇杆

相关推荐
Kang.Charles1 小时前
UE游戏性能优化归结(基于UE5环境)
游戏·ue5
前端不太难2 小时前
鸿蒙 App、PC、游戏,本质是同一套系统吗?
游戏·状态模式·harmonyos
柚要做甚码2 小时前
godot-rust(gdext)2D游戏之旅【flappy-bird】 - 2
游戏·游戏开发
柚要做甚码2 小时前
godot-rust(gdext)2D游戏之旅【flappy-bird】 - 1
游戏·游戏开发
柚要做甚码2 小时前
godot-rust(gdext)2D游戏之旅【flappy-bird】 - 3
游戏·游戏开发
wanhengidc3 小时前
服务器租用的好处
大数据·运维·服务器·游戏·智能手机
LcGero3 小时前
Cocos Creator 业务与原生通信详解
android·ios·cocos creator·游戏开发·jsb
LcGero1 天前
TypeScript 快速上手:前言
typescript·cocos creator·游戏开发
AI_零食1 天前
Flutter 框架跨平台鸿蒙开发 - 社交断舍离应用
运维·服务器·学习·flutter·游戏·开源·harmonyos
雷焰财经1 天前
首都在线MaaS平台:打造企业级AI中枢,驱动游戏产业智变
大数据·人工智能·游戏