我正在将 Sprite 渲染到 Canvas 元素,并且我试图避免子像素定位,以避免图像模糊(基于此处的信息:http://seb.ly/2011/02/html5-canvas-sprite-optimisation/)。
当我尝试像这样重新分配 x 位置时,就会出现问题:
this.pos.x = ~~ this.pos.x;
这可以防止我的 Sprite 在屏幕上移动,并将其位置记录到控制台显示我被困在起始位置。
现在,如果我不对我的位置执行按位运算符,而只需记录输出:
console.log(~~ this.pos.x);
我可以看到按位运算符按预期执行,显示:
100
101
102
...
注意:我的动画与帧速率无关,因此我将其乘以增量并得到如下 float :
100.64
101.36
102.04
102.68
103.32000000000001
104.00000000000001
104.68000000000002
...
我在这里更新位置,并且仅在这里:
this.pos.x += BE.delta.getSeconds() * this.accelleration;
因此
this.pos.x += ~~ (BE.delta.getSeconds() * this.accelleration);
不工作
最佳答案
bitwise NOT operator ( ~
)只是 chop 数字的小数部分(例如, ~~100.1
是 100
; ~~-100.1
是 -100
)。因此,如果您添加的值小于1
,那么很自然至this.pos.x
,如果你这样做this.pos.x = ~~this.pos.x
,你永远不会看到它增加,因为你不断地消除那些小数值。
您尚未提供很多的上下文,但您可能希望允许 this.pos.x
保留 float ,但使用它的底版本进行渲染,例如:
var renderX = ~~this.pos.x;
// Use `renderX` rather than `this.pos.x` to render to the canvas;
// `renderX` will remain 100 while `this.pos.x` will gradually climb
// from 100 to 100.1, 100.5, 100.999999, etc. Once `this.pos.x`
// reaches 101 (or 101.1, etc.), `renderX` will become 101.
<小时/>
另外,圆形可能比地板更合适。如果this.pox.x
是 100.999999999
,当然将其渲染在 101
更有意义比100
?
关于Javascript 按位运算符和 Canvas 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10799873/