A*寻路在cocoscreator中的使用

本文介绍了A*寻路算法在CocosCreator游戏开发中的使用,相较于Dijkstra算法,A*具备更好的性能和易实现性。文章提供了一个简单的实现概述,并附有伪代码,最后给出了GitHub源码链接和在线效果预览。
摘要由CSDN通过智能技术生成
1. 简介

​ a星寻路作为启发式搜索,在游戏开发中经常使用,性能比dps要好,也比较简单好实现,通用原理网上很多这里就不多做详解了,还不熟悉的可以参考:简书链接;

2. 实现

伪码如下

把当前点加入openList
while(openList不为空){
   
    取出f值最小的点作为当前点curGrid
    if(curGrid == endGrid) 查找结束,生成路径
    查找curGrid周围的点,如果不在openList则加入openList并重新排序, 这里要注意如果8方向查找要注意相邻的是不是障碍物
    把curGrid从openList移除并加入closeList
    if (openList为空) 则查找失败,没有路径
}

代码实现

let Grid = cc.Class({
   
    ctor(){
   
        this.x = 0;
        this.y = 0;
        this.f = 0;
        this.g = 0;
        this.h = 0;
        this.parent = null;
        this.type = 0; // -1障碍物, 0正常, 1目标点, 2起点
    }
    
});

let AStar = cc.Class({
   
    extends: cc.Component,

    properties:{
   
        map: cc.Graphics,
    },

    onLoad(){
   
        this._gridW = 50;   // 单元格子宽度
        this._gridH = 50;   // 单元格子高度
        this.mapH = 13;     // 纵向格子数量
        this.mapW = 24;     // 横向格子数量

        this.is8dir = true; // 是否8方向寻路

        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);

        this.initMap();
    },

    onTouchMove(event){
   
        let pos = event.getLocation();
        let x = Math.floor(pos.x / (this._gridW + 2));
        let y = Math.floor(pos.y / (this._gridH + 2));
        if (this.gridsList[x][y].type == 0){
   
            this.gridsLis
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值