A* 在 HTML5 Canvas 中开始路径查找 [英] A* Start path finding in HTML5 Canvas

查看:18
本文介绍了A* 在 HTML5 Canvas 中开始路径查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的游戏(用 JavaScript、HTML5 Canvas 编写)中实现 A* 开始路径查找.A* 开始库找到了这个 -

这是我目前使用的基于我的 a*.不过概念应该是一样的.a* 函数应该将路径作为数组返回,然后您只需要在每个玩家更新时遍历路径并移动它们.

//data 保存了 a* alg 返回的点数组, step 是您所在的当前点.功能移动播放器(数据,步骤){步骤++;if(step >= data.length){返回假;}//将玩家设置为数据数组中的下一个点playerObj.x = 数据[步骤].x;playerObj.y = 数据[步骤].y;//填充玩家所在的矩形ctx.fillStyle = "rgb(200,0,0)";ctx.fillRect(playerObj.x*tileSize, playerObj.y*tileSize, tileSize, tileSize);//再来一遍setTimeout(function(){movePlayer(data,step)},10);}

I'm trying implement A* Start path finding in my games(which are written with JavaScript, HTML5 Canvas). Library for A* Start found this - http://46dogs.blogspot.com/2009/10/star-pathroute-finding-javascript-code.html and now I'm using this library for path finding. And with this library, I'm trying write a simple test, but stuck with one problem. I'm now done when in HTML5 canvas screen click with mouse show path until my mouse.x and mouse.y. Here is a screenshot:

(Pink square: Player, Orange squares: path until my mouse.x/mouse.y) Code how I'm drawing the orange squares until my mouse.x/mouse.y is:

for(var i = 0; i < path.length; i++) {
    context.fillStyle = 'orange';
    context.fillRect(path[i].x * 16, path[i].y * 16, 16, 16);
}

My problem is I do not understand how to move my player until path goal. I've tried:

for(var i = 0; i < path.length; i++) {
    player.x += path[i].x;
    player.y += path[i].y;
}

But with this code my player is not beung drawn.(When I run the code, player.x and player.y are equals to 0 and when I click with the mouse I get the path player blink and disappear)

Maybe anyone know how to solve this problem?

And I'm very very very sorry for my bad English language. :)

解决方案

My Working Fiddle

This is what I currently use which is based off of my a*. The concept should be the same though. The a* function should return the path as an array, then you just need to iterate through the path on each player update and move them.

// data holds the array of points returned by the a* alg, step is the current point you're on.
function movePlayer(data, step){
    step++;
    if(step >= data.length){
        return false;   
    }

    // set the player to the next point in the data array
    playerObj.x = data[step].x;
    playerObj.y = data[step].y; 

    // fill the rect that the player is on
    ctx.fillStyle = "rgb(200,0,0)";
    ctx.fillRect(playerObj.x*tileSize, playerObj.y*tileSize, tileSize, tileSize);

    // do it again
    setTimeout(function(){movePlayer(data,step)},10);
}​

这篇关于A* 在 HTML5 Canvas 中开始路径查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆