关于 subpixel 移动代码的问题

这是我的移动代码,带有单独的 subpixel 变量。一个 subpixel 是一个像素的 256 分之一。 velx 和 vely 也会被存储并乘以 256。

function object:move(velx, vely, subpixel)
    subpixel = subpixel or true;
    velx = velx or self.velx or 0;
    vely = vely or self.vely or 0;
    if (velx == 0 and vely == 0) then return end;

    local modx, mody = 0, 0;

    if (velx ~= 0) then
        modx = (velx%(sign(velx)*256));
    end

    if (vely ~= 0) then
        mody = (vely%(sign(vely)*256));
    end

    velx = velx - modx;
    vely = vely - mody;

    if (subpixel) then
        if (self.subx) then
            self.subx = self.subx + modx;
        end
        if (self.suby) then
            self.suby = self.suby + mody;
        end

        if (self.subx >= 256 or self.subx <= -256) then
            velx = velx + (sign(self.subx)*256);
            self.subx = self.subx % (sign(self.subx)*256);
        end
        if (self.suby >= 256 or self.suby <= -256) then
            vely = vely + (sign(self.suby)*256);
            self.suby = self.suby % (sign(self.suby)*256);
        end
    end

    local movex = velx/256;
    local movey = vely/256;

    self:setPosition(self.x+movex, self.y+movey);

    return modx, mody;
end

以下是我的问题:

  • 将物体的速度设置为 -1024(相当于 -4),
  • 将物体的重力设置为 64 (重力在每次对象移动之后应用)
  • 第一帧,它移动了 -4 像素,
  • 下一帧,-3,
  • 接下来一帧,-4,
  • 接下来 3 帧,-3

我很困惑为什么它会移动 -4,-3,-4,-3,-3,-3,然后是 -2,-3,-2 等,而不是我想要的:

  • -4,
  • -3,
  • -3,
  • -3,
  • -2,
  • -2,
  • -2,
  • -1,

如果我使用浮点数,那么需要使用 math.ceil,但由于我没有使用浮点数,所以我不确定在哪里和如何实现它。

编辑:也许它就在我的眼前,但是代码写得有点混乱,即使对我来说也是如此...

点赞