Issue with subpixel movement code

139 views Asked by At

This is my code for movement, with separate subpixel variables. A subpixel here is a 256th of a pixel. velx and vely are also stored times 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

Here's my issue with it:

  • I set my object's velocity to -1024 (equivalent of -4),
  • I set my object's gravity to 64 (gravity is applied after each object:move)
  • First frame, it moves -4 pixels,
  • Next frame, -3,
  • Next frame, -4,
  • Next 3 frames, -3

I'm confused as to why it's moving -4, -3, -4, -3, -3, -3, then -2, -3, -2 etc. as opposed to what I want it to do, which is:

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

etc. which would require the use math.ceil if I was using floats, but since I'm not, I'm not exactly 100% where and how to implement it.

Edit: It's probably right in front of my face, but the code is written a bit confusing, even for me...

0

There are 0 answers