-1
\$\begingroup\$

Ive made this 'game' where you can fire an aibility (a fire ball for instance) from the player towards the mouse (to the point where the mouse was at the time of casting/fireing/shooting the ball), now Id like to know how I could implement it so that if it reaches its destination that it stops, and also how I could make it travel in the direction of the mouse but for a ciurtant distance only.

Here's the code for the fire ball thing:

life += 0.05f;
float dx = (mx - x);
float dy = ((Launcher.GAME_HEIGHT - my) - y);

double direct = Math.atan2(dy, dx);

xv = (float) (spd * Math.cos(direct));
yv = (float) (spd * Math.sin(direct));

x += xv;
y += yv;

Note: xv and yv are velocities, and mx and my are the mouse x and y

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

If your projectile has a consistent velocity throughout, here is how to make it stop exactly on the target when it reaches the target:

First measure the distance between the starting point of the projectile and the target.

float len = (float) Math.sqrt(Math.pow(dx-tx,2)+Math.pow(dy-ty,2));

Where tx and ty represent the position of the target.

You'll also need to keep track of the distance travelled, so just make a variable like float t = 0.

Then, whenever you update the position of the projectile, you'll need to add its spd value to t. When t exceeds len, you know the projectile must have gone through the target point.

void update(){

    projectileX += xv;
    projectileY += yv;

    t += spd;
    if (t >= len){

        // make the projectile stop moving.
        xv = 0;
        yv = 0;

        // since the projectile probably went
        // a little bit past the target, we
        // will have to "snap" the projectile
        // to the position of the target.
        projectileX = tx;
        projectileY = ty;

    }   

}
\$\endgroup\$
1
  • \$\begingroup\$ This was helpfull, but I still can't figure out how to make it go in the direction from the player towards the mouse only for a ciurtent lengh/path distance, so this would just make it stop at its target (or it would stop after a ciurtent distance if its set to be one), but if the target (The cursor/mouse) is within the distance or range then it would stop at the mouse's x and y, and I don't want that to happen. Thanks anyway EDIT: I figured it out I just had to initialize the velocities only once! xD Thank you :D \$\endgroup\$ Commented Jan 2, 2016 at 15:07

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.