
引言
Cocos中点地面移动的实例。
在游戏开发中,我们经常会遇到通过点击地面 控制玩家移动到指定点的需求。
本文将介绍一下如何在Cocos 中实现类似LOL 的点地面移动效果。
本文源工程在文末获取,小伙伴们自行前往。
点地面移动知识点

要在Cocos 中实现类似LOL 的点地面移动 效果,有以下2个知识点:
1.屏幕空间坐标转换为射线
在游戏中,当玩家点击屏幕 上的某个点时,你可能希望知道从相机 发射出的射线 穿过屏幕上 的那个点 ,以便进行进一步的交互或检测。
因此我们需要将一个屏幕 空间(左上角为原点)坐标转换为射线。
在Cocos 中我们需要用到的API 为Camera.screenPointToRay
。

2.通过射线检测所有的碰撞盒
射线检测 是一种常用的技术,用于判断一条射线 与游戏场景中的物体 是否相交 ,从而实现例如点击检测、射线投射等功能。
因此我们需要检测 所有的碰撞盒 ,并记录 所有被检测到的结果。
在Cocos 中我们通过PhysicsSystem.instance.raycast(ray)
进行检测和PhysicsSystem.instance.raycastResults
访问结果。

话不多说,一起来做个实例。
点地面移动实例
接下来我们一步一步来 实现类似LOL 的点地面移动效果。
1.环境
引擎版本:Cocos Creator 3.8.1
编程语言:TypeScript
2.资源准备
我们还是直接借用 一下Cocos商城 上麒麟子 的免费资源"KylinsEasyController"创建项目。

然后自己创建 一个圆锥体 用于指示点击地点 (节目组 还是一如既往地扣)。

通过动画编辑器 做个简单的上下移动的效果。

3.编写代码
新建一个TouchMove
组件,并且拖 到Canvas上。
typescript
@ccclass('TouchMove')
export class TouchMove extends Component {
@property(Node)
pointerNode: Node;
}
在start()
方法中通过this.node.on
监听NodeEventType.MOUSE_DOWN
事件。
typescript
start() {
this.node.on(NodeEventType.MOUSE_DOWN, (event: EventMouse) => {
}, this);
}
然后 通过下面的方法 得到点击的物体。
event.getLocation()
获取点击的屏幕坐标。camera.screenPointToRay(uiPos.x, uiPos.y, ray)
通过屏幕坐标产生射线。PhysicsSystem.instance.raycast(ray)
进行射线碰撞检测并记录结果。PhysicsSystem.instance.raycastResults
获取射线检测结果,通过名字或者其他信息得到想要的物体。
typescript
var uiPos = event.getLocation();
var ray = new geometry.Ray();
camera.screenPointToRay(uiPos.x, uiPos.y, ray);
if (PhysicsSystem.instance.raycast(ray)) {
const raycastResults = PhysicsSystem.instance.raycastResults;
for (let i = 0; i < raycastResults.length; i++) {
const item = raycastResults[i];
if (item.collider.node.name == "Plane") {
}
}
} else {
console.log('raycast does not hit the target node !');
}
最后 通过下面的方法 让指标出现 和角色移动。
item.hitPoint
获取点击的坐标。.active = true
和.setWorldPosition(item.hitPoint)
显示并设置指针坐标。player.lookAt
设置角色朝向。skeletalAnimation.crossFade("anim_rig_run", 0.1)
通过skeletalAnimation
组件播放动画。tween(player)
通过tween动画实现角色移动。
typescript
this.pointerNode.active = true;
this.pointerNode.setWorldPosition(item.hitPoint);
player.lookAt(new Vec3(player.worldPosition.x * 2 - item.hitPoint.x, player.position.y, player.worldPosition.z * 2 - item.hitPoint.z));
skeletalAnimation.crossFade("anim_rig_run", 0.1);
let duration = Vec3.distance(player.worldPosition, item.hitPoint) * speed;
if (playerTween) {
playerTween.stop();
}
playerTween = tween(player);
playerTween.to(duration, { worldPosition: item.hitPoint }).call(() => {
skeletalAnimation.crossFade("anim_rig_idle_1", 0.1);
this.pointerNode.active = false;
}).start();
4.效果演示

今天的节目到此为止。帮忙转发一下文章哦,下课!
结语
本文源工程 可通过私信发送TouchMove获取。
更多实用源码 可以扫码 或者阅读原文看看,付费 不仅是知识的获取 ,更是对笔者的支持和认可,感谢!

我是"亿元程序员",一位有着8年游戏行业经验的主程。在游戏开发中,希望能给到您帮助, 也希望通过您能帮助到大家。
AD:笔者线上的小游戏《贪吃蛇掌机经典》《重力迷宫球》《填色之旅》大家可以自行点击搜索体验。
实不相瞒,想要个赞 和在看 !请把该文章分享给你觉得有需要的其他小伙伴。谢谢!
推荐专栏: