在我的游戏中有许多实体,每个实体都有分配给它的路径(Array<Vector2>)。没有要遵循的路径(指示实体应该移动)是由空路径指示的(路径永远不是null)。updateMoveAttributes被称为每个实体的每一个帧,因此它的效率是非常重要的。
注意,我的实体的方向是弧度,范围从- Math.PI到Math.PI,因为这是Math.atan2返回的内容。
下面的代码片段包含updateMoveAttributes及其支持方法。
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;
}发布于 2018-07-09 02:25:55
getXDifference和getYDifference非常相似,您可以将其转换为接受两个变量的单个方法。pastX和pastY。布尔isPastX(变量.){ //逻辑来计算和返回pastX。},if语句将转换为if( isPastX() && isPastY())。这也将有助于在计算pastX或pastY非常昂贵的情况下缩短条件(在本例中不是,只是一个建议)。{}应该总是在条件语句或循环之后使用,即使它只是一行。它可能在某些情况下避免混淆。。如果(getPath().size == 0){返回;}https://codereview.stackexchange.com/questions/198103
复制相似问题