首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >实体路径跟踪算法

实体路径跟踪算法
EN

Code Review用户
提问于 2018-07-08 20:44:52
回答 1查看 56关注 0票数 1

在我的游戏中有许多实体,每个实体都有分配给它的路径(Array<Vector2>)。没有要遵循的路径(指示实体应该移动)是由空路径指示的(路径永远不是null)。updateMoveAttributes被称为每个实体的每一个帧,因此它的效率是非常重要的。

注意,我的实体的方向是弧度,范围从- Math.PIMath.PI,因为这是Math.atan2返回的内容。

下面的代码片段包含updateMoveAttributes及其支持方法。

代码语言:javascript
复制
private final Array<Vector2> path = new Array<>();
private int pathIndex = 0;

private static final float EPSILON = 1e-3f;

private float getXDifference(Vector2 pathComponent) {
    float xDifference = pathComponent.x - getSprite().getX();

    xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

    return xDifference;
}

private float getYDifference(Vector2 pathComponent) {
    float yDifference = pathComponent.y - getSprite().getY();

    yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

    return yDifference;
}

public float orient(Vector2 pathComponent) {
    float xDiff = getXDifference(pathComponent);
    float yDiff = getYDifference(pathComponent);

    return (float) Math.atan2(yDiff, xDiff);
}

void updateMoveAttributes() {
    // No path assigned
    if (getPath().size == 0)
        return;

    // No more path to travel
    if (getPathIndex() == getPath().size) {
        setSpeed(0);

        return;
    }

    Vector2 nextPathComponent = getPath().get(getPathIndex());
    float angleToComponent = orient(nextPathComponent);

    setDirection(angleToComponent);

    float xDiff = getXDifference(nextPathComponent);
    float yDiff = getYDifference(nextPathComponent);

    boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
    boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

    boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
    boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

    // Indicates that we have passed the path component we are on route to, adjust course with respect
    // to next available path component.
    if (pastY && pastX)
        setPathIndex(getPathIndex() + 1);

    // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
    setSpeed(getMovementSpeed());
}

public Array<Vector2> getPath() {
    return path;
}
EN

回答 1

Code Review用户

发布于 2018-07-09 02:25:55

  1. 方法getXDifferencegetYDifference非常相似,您可以将其转换为接受两个变量的单个方法。
  2. 您还可以内联返回语句,因为方法名称足以判断返回的是什么。
  3. 您可以编写方法返回计算值,而不是计算pastXpastY。布尔isPastX(变量.){ //逻辑来计算和返回pastX。},if语句将转换为if( isPastX() && isPastY())。这也将有助于在计算pastXpastY非常昂贵的情况下缩短条件(在本例中不是,只是一个建议)。
  4. 大括号{}应该总是在条件语句或循环之后使用,即使它只是一行。它可能在某些情况下避免混淆。。如果(getPath().size == 0){返回;}
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/198103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档