1

我试图了解此代码如何用于碰撞检测。我可以说目标是一个边界框,并且我们正在测试实体的每个可能点,但我不确定在这种情况下有符号移位运算符的目的。事实上,我什至不明白为什么它会有用,只是它做了什么。谁能详细说明?

protected boolean move2(int xa, int ya) {
    if (xa != 0 && ya != 0) throw new IllegalArgumentException("Move2 can only move along one axis at a time!");

    int xto0 = ((x) - xr) >> 4;
    int yto0 = ((y) - yr) >> 4;
    int xto1 = ((x) + xr) >> 4;
    int yto1 = ((y) + yr) >> 4;

    int xt0 = ((x + xa) - xr) >> 4;
    int yt0 = ((y + ya) - yr) >> 4;
    int xt1 = ((x + xa) + xr) >> 4;
    int yt1 = ((y + ya) + yr) >> 4;
    boolean blocked = false;
    for (int yt = yt0; yt <= yt1; yt++)
        for (int xt = xt0; xt <= xt1; xt++) {
            if (xt >= xto0 && xt <= xto1 && yt >= yto0 && yt <= yto1) continue;
            level.getTile(xt, yt).bumpedInto(level, xt, yt, this);
            if (!level.getTile(xt, yt).mayPass(level, xt, yt, this)) {
                blocked = true;
                return false;
            }
        }
    if (blocked) return false;

    List<Entity> wasInside = level.getEntities(x - xr, y - yr, x + xr, y + yr);
    List<Entity> isInside = level.getEntities(x + xa - xr, y + ya - yr, x + xa + xr, y + ya + yr);
    for (int i = 0; i < isInside.size(); i++) {
        Entity e = isInside.get(i);
        if (e == this) continue;

        e.touchedBy(this);
    }
    isInside.removeAll(wasInside);
    for (int i = 0; i < isInside.size(); i++) {
        Entity e = isInside.get(i);
        if (e == this) continue;

        if (e.blocks(this)) {
            return false;
        }
    }

    x += xa;
    y += ya;
    return true;
}

值得注意的是,Entity 知道其确切的 x 和 y 位置,但 tile 根本不知道它的位置。世界有一组瓷砖,但只知道它的瓷砖位置......所以当需要进行碰撞检测时,该函数必须确定从玩家位置获取哪个瓷砖位置。

完整来源可在此处获得:http ://www.ludumdare.com/compo/ludum-dare-22/?action=preview&uid=398

请注意,瓷砖是 16x16

4

1 回答 1

2

除以 2 的幂通常表示为右移n位,其中n是幂。

过去在编写 C 或汇编时,您会这样做,因为它比实际除法要快得多。左移与乘以 2 的等效幂相同,也比硬件乘法快得多。如今,大多数编译器都会对此进行特殊处理并发出移位而不是乘/除以获取 2 的幂。

当然,如果您的图块大小不是 2 的幂,则必须改为除法。

于 2012-10-25T06:42:32.827 回答