1
\$\begingroup\$

I am trying to get my player to shoot a spell and it travels to where ever the player clicked. I can easily accomplish this by doing the following.

    if(position.x >= destination.x - 1 && position.x <= destination.x + 1)
        reachedX = true;
    if(position.y >= destination.y - 1 && position.y <= destination.y + 1)
        reachedY = true;

However if the players origin is at, for example, 0,0 and I click at 10,300 then it travels right and up but when the spell reaches an x of 10 it travels directly upwards. I want the spell to travel at an angle that it will reach the x coordinate at the same time as the y coordinate. Here is an image showing what happens and what I want to happen.

Image example

\$\endgroup\$
2
\$\begingroup\$

The behavior you're currently having is caused by adding to the y and x position step by step until either or both have reached the same x and/or y position of the target. You add one unit to x and y causing a sloped movement not aimed at the target until you hit either the y or x axis the target lies on.

Subtract position from destination to get a vector from initial position to target position. Normalize the resulting vector since we don't care about the length of the vector, just the direction it's pointing towards. We can add the x and y of this normalized vector to current position to reach our target. (To normalize we divide the vector by its length)

direction.x = destination.x - position.x;
direction.y = destination.y - position.y;
direction_length = sqrt(direction.x ^ 2 + direction.y ^2);
direction.x = direction.x / direction_length;
direction.y = direction.y / direction_length;

//for each frame until we reach target
current_position.x += direction.x;
current_position.y += direction.y;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.