如何限制2D游戏中角色沿地图特定路径移动
实现思路与代码示例
1. 核心逻辑
先把所有允许角色停留的点位坐标整理成合法集合,每次移动前先计算目标位置:
- 若目标在合法集合内:执行移动操作,更新角色当前位置
- 若不在:不执行移动,直接扣除分数
2. 具体落地步骤
第一步:定义合法位置集合与跟踪当前位置
根据你地图上的实际点位,把所有允许的(x,y)坐标存入集合,同时用变量记录角色当前位置(初始为(0,0))。
#include <unordered_set> #include <utility> // 为pair<int,int>实现哈希,用于存入unordered_set struct PairHash { template <class T1, class T2> size_t operator () (const pair<T1,T2>& p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); return hash1 ^ (hash2 << 1); } }; // 替换成你地图上所有合法的点位坐标 unordered_set<pair<int, int>, PairHash> validPositions = { {0, 0}, {1, 0}, {1, 1}, {0, 1}, {2, 0} // 示例点位 }; // 角色当前位置(初始为起点) int currentX = 0; int currentY = 0; int playerScore = 100; // 初始分数,可自定义 int nCollarsFound = 0;
第二步:修改移动函数逻辑
先计算移动后的目标位置,判断合法性后再执行对应操作:
void makeMove(string direction){ int targetX = currentX; int targetY = currentY; // 计算目标位置 if (direction == "East") { targetX += 1; } else if (direction == "West") { targetX -= 1; } else if (direction == "North") { targetY += 1; } else if (direction == "South") { targetY -= 1; } // 判断目标位置是否合法 if (validPositions.count({targetX, targetY})) { // 合法:执行移动,更新位置 currentX = targetX; currentY = targetY; // 调用对应方向的移动渲染函数 if (direction == "East") moveEast(); else if (direction == "West") moveWest(); else if (direction == "North") moveNorth(); else if (direction == "South") moveSouth(); // 若只有特定点位才会找到collar,可在此加判断:比如检查当前位置是否是带collar的点 nCollarsFound++; } else { // 不合法:扣除分数,不移动 playerScore -= 10; // 扣分数值可自定义 // 可选:添加无效移动的提示逻辑 } }
3. 优化方案
如果你的地图是规则网格,可用二维数组代替硬编码的坐标集合,更灵活:
// 示例5x5地图:1表示可走,0表示不可走 int gameMap[5][5] = { {1, 1, 0, 0, 0}, {1, 1, 1, 0, 0}, {0, 1, 1, 1, 0}, {0, 0, 1, 1, 1}, {0, 0, 0, 1, 1} }; // 判断合法性时直接检查数组值(需确保坐标在地图范围内) if (targetX >=0 && targetX <5 && targetY >=0 && targetY <5 && gameMap[targetY][targetX] == 1) { // 合法移动逻辑 }
另外,建议把角色位置、分数、合法点位这些变量封装到类中,避免全局变量,代码更易维护。
内容的提问来源于stack exchange,提问作者agni_ka1
相关产品推荐
相关产品推荐

