So i have 2 players on screen and a player send a attack, what i want is that
if x,y are different of x,y destPos move only diagonal towards the destination position.
if just x is different well move x only, same with y.

I know i have to some how decrease the shorter movement but have no idea of the equation.
Ima leave some photo to explain better since my english is bad.

problem.jpg

here is my actual code.

Vector2 destPos     = atacando_a.getPosition();

boolean hasToMoveRight  = destPos.x > pos.x;
boolean hasToMoveLeft   = destPos.x < pos.x;
boolean hasToMoveUp     = destPos.y > pos.y;
boolean hasToMoveDown   = destPos.y < pos.y;

if(hasToMoveRight)
    pos.x += speed;
if(hasToMoveLeft)
    pos.x -= speed; 
if(hasToMoveUp)
    pos.y += speed;
if(hasToMoveDown)
    pos.y -= speed;

Thank you!

Edited 1 Year Ago by centenond

If your speed is a constant then you can only make 0, 45, 90 degree movements. To get any other angles you will need to vary the speed.
Eg:

if
deltaX = distance to be moved in the x direction
deltaY = distance to be moved in the y direction

if deltaX > deltaY
go full speed in x direction
but speed in y direction must be slower, ie speed*(deltaY/deltaX)

( and v.v if deltaY > deltaX)

that is what i had in mind a couple hours later when i post this but have no idea of what equation to use...
so let me see if i get this right, can't test it now but the code should look something like this?

boolean hasToMoveUR = destPos.y > pos.y && destPos.x > pos.x;

float distanceX = Math.abs(destPos.x - pos.x);
float distanceY = Math.abs(destPos.y - pos.y);

if(hasToMoveUR){ 
    // Have to move Up-Right
    if(distanceX > distanceY){
        pos.x += speed;
        pos.y += speed*(distanceY/distanceX);
    }
    else if(distanceY > distanceX){
        pos.x += speed*(distanceX/distanceY);
        pos.y += speed;
    }
    else{
        pos.x += speed;
        pos.y += speed;
    }
}

Edited 1 Year Ago by centenond

Yes, something like that. You will need to deal with moving in the other 3 quadrants, of course, but you could set up a test that's up/right to confirm before doing the other 3 cases.

(one tiny thought ... if you are using standard Java graphics convention then positive y speeds are downwards, not upwards)

This question has already been answered. Start a new discussion instead.