简体   繁体   English

Java游戏-将对象沿直线移动到另一点

[英]Java Game - moving an object in a straight line to another point

Here is what I have so far: 这是我到目前为止的内容:

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;

I just want x and y to move straight towards playerx and playery but it moves only at a slope of 0, 1, or undefined. 我只希望x和y朝着playerx和playery直接移动,但是它仅以0、1或未定义的斜率移动。

I suspect it because you x and y are int and you have moving such a short distance that you will only be (1, 1) , (1, 0) or (0, 1) . 我怀疑是因为您x和y都是int并且您移动的距离很短,因此您只能是(1, 1)(1, 0)(0, 1)

You need to allow it to move further that 1, or use a type which more resolution. 您需要允许它进一步移至1,或使用分辨率更高的类型。 eg double. 例如双。

BTW: Instead of using Math.floor I believe a better choice is 顺便说一句:我相信不使用Math.floor,而是一个更好的选择

dx = (int) Math.round(doublex);

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. 您将水平距离和垂直距离除以总距离,这将始终导致一个介于1到-1之间的数字,因此,每移动一次,它在一个方向上的移动将为零或为1。 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. 每次发生移动时,您都应该跟踪实际移动的距离和希望移动的距离,因为例如,您可能试图在每个循环中沿y轴移动0.4,并且它永远不会移动,因为它总是向下取整。 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. 因此,如果在第二个循环中您知道应该总共移动0.8,则可以四舍五入为1,然后将所需的设置保留为-0.2并继续循环。

A solution similar to Bresanham's Line Algorithm can be implemented. 可以实现类似于Bresanham的Line算法的解决方案。 IE: 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

Source: Bresanham's Line Algoithm 资料来源: Bresanham的Line算法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM