假设我有一个使用 16x16 像素的基于图块的系统。您如何找出由浮点像素单元定义的矩形所覆盖的图块?
例如,
rect(x=16.0,y=16.0, w=1.0, h=1.0) -> tile(x=1, y=1, w=1, h=1)
rect(x=16.0,y=16.0, w=16.0, h=16.0) -> tile(x=1, y=1, w=1, h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.0, y=8.0) -> (x=1,y=1,w=1,h=1) (still within same tile)
rect(x=24.0,y=24.0, w=8.1, y=8.1) -> (x=1,y=1,w=2,h=2)
我可以可靠地做到这一点的唯一方法是使用循环。有没有更好的办法?除以 16 给我在边缘情况下的错误答案。这是我在 python 中使用的一些示例代码:
#!/usr/bin/env python
import math
TILE_W = 16
TILE_H = 16
def get_tile(x,y,w,h):
t_x = int(x / TILE_W)
t_x2 = t_x
while t_x2*TILE_W < (x+w):
t_x2 += 1
t_w = t_x2-t_x
t_y = int( y / TILE_H)
t_y2 = t_y
while t_y2*TILE_H < (y+h):
t_y2 += 1
t_h = t_y2-t_y
return t_x,t_y,t_w,t_h
(x,y) = 16.0,16.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 15.0, 15.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.0, 16.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 16.0,16.0
(w,h) = 16.1, 16.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 1.0, 1.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.0, 8.0
assert get_tile(x,y,w,h) == (1,1,1,1)
(x,y) = 24.0, 24.0
(w,h) = 8.1, 8.1
assert get_tile(x,y,w,h) == (1,1,2,2)
(x,y) = 24.0, 24.0
(w,h) = 9.0, 9.0
assert get_tile(x,y,w,h) == (1,1,2,2)