地图为45度角的斜地图,依旧是寻找最短路径,在前面的文章中,有一篇正常地图的A*算法,算法思想一致,只是走路方向变成可以横-竖-斜。
直接贴代码吧,若有不懂,请回顾正常地图的A* 算法,或提问。
附地图的节点位置。
节点类:AStartNode
.h
class AStartNode : public Ref
{
public:
AStartNode(int _x = 0,int _y = 0);
AStartNode(AStartNode* node);
~AStartNode();
int x;
int y;
bool isEqualTo(AStartNode* node);
bool isInArray(__Array* array);
AStartNode* getLeftNode();
AStartNode* getRightNode();
AStartNode* getUpNode();
AStartNode* getULNode();
AStartNode* getURNode();
AStartNode* getDownNode();
AStartNode* getDLNode();
AStartNode* getDRNode();
int distanceToNode(AStartNode* node);
Vec2 toPointInView();
int g;
int h;
int hx;
int hy;
private:
AStartNode* useNode;
};
.cpp
AStartNode::AStartNode(int _x,int _y):x(_x),y(_y)
{
useNode = NULL;
g = 0;
h = 0;
}
AStartNode::AStartNode(AStartNode* node)
{
useNode = NULL;
g = 0;
h = 0;
x = node->x;
y = node->y;
}
bool AStartNode::isEqualTo(AStartNode* node)
{
if (x==node->x&&y==node->y) {
return true;
}
return false;
}
bool AStartNode::isInArray(cocos2d::__Array *array)
{
for (int i = 0; i < array->count(); i ++) {
AStartNode* node = (AStartNode*)array->getObjectAtIndex(i);
if (node->isEqualTo(this)) {
return true;
}
}
return false;
}
AStartNode* AStartNode::getLeftNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (x==0) {
return NULL;
}
if (y==YNUM-1) {
return NULL;
}
useNode = new AStartNode(x-1,y+1);
return useNode;
}
AStartNode* AStartNode::getRightNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (y==0||x == XNUM-1) {
return NULL;
}
useNode = new AStartNode(x+1,y-1);
return useNode;
}
AStartNode* AStartNode::getUpNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (x==0||y==0) {
return NULL;
}
useNode = new AStartNode(x-1,y-1);
return useNode;
}
AStartNode* AStartNode::getULNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (x==0) {
return NULL;
}
useNode = new AStartNode(x-1,y);
return useNode;
}
AStartNode* AStartNode::getURNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (y==0) {
return NULL;
}
useNode = new AStartNode(x,y-1);
return useNode;
}
AStartNode* AStartNode::getDownNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (x==XNUM-1||y==YNUM-1) {
return NULL;
}
useNode = new AStartNode(x+1,y+1);
return useNode;
}
AStartNode* AStartNode::getDLNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (y==YNUM) {
return NULL;
}
useNode = new AStartNode(x,y+1);
return useNode;
}
AStartNode* AStartNode::getDRNode()
{
if (useNode!=NULL) {
useNode->release();
useNode = NULL;
}
if (x==XNUM-1) {
return NULL;
}
useNode = new AStartNode(