英文:
2d Array track player movement into specific spaces around an entity
问题
# 好的,我需要一个数组的帮助,我有一个二维数组,玩家可以在其中移动,
# 目前我正在随机生成一个实体,玩家应该能够与之交互。
# 我有一个相当长的 if 语句,用于跟踪玩家是否靠近实体,
# 但无法增加触发提示的范围。这个 if 语句很长,有时让我感到困惑,
# 但是如下所示;
如果范围增加到两个(从默认值一),这将不再起作用。
我想实现这样一个功能,即具有更大范围的玩家仍然可以与此实体交互。
是否有更简单的方法可以做到这一点,可能更高效?
英文:
Ok, so I need assistance with an array, I have a 2D array that a player can move through, at the moment I'm randomly generating an entity and a player is supposed to be able to interact with it. I have one decently long if statement that tracks if the player approaches the entity however unable to increase the range at what will trigger a prompt. This if statement is long and was frustrating to wrap my head around at times but is as follows;
if(((getPlayerX() == getEntityX() - getPlayerRange()) || (getPlayerX() == getEntityX() + getPlayerRange()) || (getPlayerX() == getEntityX())) && ((getPlayerY() == getEntityY() - getPlayerRange()) || (getPlayerY() == getEntityY() + getPlayerRange()) || (getPlayerY() == getEntityY()))){
However when the range increase to two (from its default which is one), this no longer works. I want to implement this so a player with higher range can still interact with this entity. Is there an easier way to do this that might be more efficient?
答案1
得分: 0
关于这样的写法怎么样:
int xDistance = Math.abs(getPlayerX() - getEntityX());
int yDistance = Math.abs(getPlayerY() - getEntityY());
if (xDistance <= getPlayerRange() && yDistance <= getPlayerRange()){ ... }
计算绝对距离,然后与玩家范围比较。
尽管与您当前的版本相比代码更多,但我认为即使对于范围为1,它也更易读。
英文:
What about something like this:
int xDistance = Math.abs(getPlayerX() - getEntityX());
int yDistance = Math.abs(getPlayerY() - getEntityY());
if (xDistance <= getPlayerRange() && yDistance <= getPlayerRange()){ ... }
Calculate absolute distance and then compare with player range.
Even tho it's more code than your current version, it is more readable even for range of 1 in my opinion.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论