0

这是我到目前为止所拥有的:

int vx = (playerx - x);
    int vy = (playery - y);

    double distance = Math.sqrt((vx * vx) + (vy * vy));

    double doublex = ((vx / distance));
    double doubley = ((vy / distance));

    dx = (int) Math.floor(doublex + 0.5);
    dy = (int) Math.floor(doubley + 0.5);

    x += dx;
    y += dy;

我只希望 x 和 y 直接向 playerx 和 playery 移动,但它仅以 0、1 或未定义的斜率移动。

4

3 回答 3

2

我怀疑它是因为你 x 和 y 是int,而且你移动的距离很短,你只会是(1, 1)(1, 0)(0, 1)

您需要允许它进一步移动 1,或使用分辨率更高的类型。例如双倍。

顺便说一句:而不是使用 Math.floor 我相信更好的选择是

dx = (int) Math.round(doublex);
于 2012-10-22T15:29:00.663 回答
1

You are dividing horizontal distance and vertical distance by total distance, this will always result in a number between 1 and -1 so each time it moves it will move by either nothing or by 1 in a direction. I guess this is in pixels?

Each time the move happens you should keep track of the actual distance moved and the desired distance moved because, for example, you may be trying to move 0.4 along the y axes in every loop, and it will never move because that will always round down. So if in the second loop you know you should have moved by 0.8 in total, you can round up to one, and leave the desired set to -0.2 and keep looping.

于 2012-10-22T15:39:47.507 回答
0

可以实现类似于 Bresanham 的线算法的解决方案。IE:

function line(x0, y0, x1, y1)
 real deltax := x1 - x0
 real deltay := y1 - y0
 real deltaerr := abs(deltay / deltax)    // Assume deltax != 0 (line is not vertical),
       // note that this division needs to be done in a way that preserves the fractional part
 real error := deltaerr - 0.5
 int y := y0
 for x from x0 to x1 
     plot(x,y)
     error := error + deltaerr
     if error ≥ 0.5 then
         y := y + 1
         error := error - 1.0

资料来源:Bresanham 的线算法

于 2017-06-21T02:39:55.587 回答