I am rendering a sprite to a canvas element, and I am trying to avoid sub-pixel positioning in order to avoid blurry images (based on information here: http://seb.ly/2011/02/html5-canvas-sprite-optimisation/).
My problem happens when I try to reassign the x position like such:
this.pos.x = ~~ this.pos.x;
this keeps my sprite from ever moving on the screen, and logging its position to the consol shows I am stuck at my starting position.
Now, if I do not perform the bitwise operator on my position, and simply log the output:
console.log(~~ this.pos.x);
I can see the bitwise operator performing as expecting, showing:
100
101
102
...
Note: My animation is framerate independent, and thus I am multiplying it by a delta and getting floats like:
100.64
101.36
102.04
102.68
103.32000000000001
104.00000000000001
104.68000000000002
...
I update the position here, and only here:
this.pos.x += BE.delta.getSeconds() * this.accelleration;
and thus
this.pos.x += ~~ (BE.delta.getSeconds() * this.accelleration);
is not working
The bitwise NOT operator (
~) just truncates the fractional portion off the number (e.g.,~~100.1is100;~~-100.1is-100). So naturally if you’re adding values of less than1tothis.pos.x, if you dothis.pos.x = ~~this.pos.x, you’re never going to see it increase, because you’re constantly wiping out those fractional values.You haven’t provided a lot of context, but it may be that you want to allow
this.pos.xto remain a floating point number, but use a floored version of it for rendering, e.g.:Separately, it may be more appropriate to round rather than flooring. If
this.pox.xis100.999999999, surely it makes more sense to render it at101than100?