mwristine
mwristine

Reputation: 93

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.

Upvotes: 0

Views: 2167

Answers (3)

Andy Mcdowall
Andy Mcdowall

Reputation: 11

A solution similar to Bresanham's Line Algorithm can be implemented. 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

Upvotes: 0

Link19
Link19

Reputation: 606

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

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).

You need to allow it to move further that 1, or use a type which more resolution. e.g. double.

BTW: Instead of using Math.floor I believe a better choice is

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

Upvotes: 2

Related Questions