-2

I'm making a program, that moves a dot, from the startx, starty to endx, endy. But it moves continuously, even after the x and the y are bigger than endx and endy. Here is the code:

int x, y;
            x = startx; y = starty;
            if(startx<goalx){
                if (starty < goaly) {
                    while (startx < goalx || starty < goaly) {
                        x += sqrt(2)*speedx;
                        y += sqrt(2)*speedy;
                    }
                }
                else {
                    while (startx < goalx || starty > goaly) {
                        x += sqrt(2)*speedx;
                        y -= sqrt(2)*speedy;
                    }
                }
            }
            else {
                if (starty < goaly) {
                    while (startx > goalx || starty < goaly) {
                        x -= sqrt(2)*speedx;
                        y += sqrt(2)*speedy;
                    }
                }
                else {
                    while (startx > goalx || starty > goaly) {
                        x -= sqrt(2)*speedx;
                        y -= sqrt(2)*speedy;
                    }
                }


            }
            cout << x << ", " << y << endl;

startx, starty, goalx and goaly are user inputs.

2 Answers2

1

The control structures depend on startx and starty but these are never changing. Supposedly x and y should be used instead.

ldz
  • 2,217
  • 16
  • 21
0

try this

int x, y;
    x = startx; y = starty;
    int xInc = sqrt(2) * speedx;
    int yInc = sqrt(2) * speedy;
    if(x < goalx && y < goaly)
    {
        while(x < goalx || y < goaly)
        {
            x += xInc;
            y += yInc;
        }
    }
    else if(x < goalx && y > goaly)
    {
        while(x < goalx || y > goaly)
        {
            x += xInc;
            y -= yInc;
        }
    }
    else if(x > goalx && y < goaly)
    {
        while(x > goalx || y < goaly)
        {
            x -= xInc;
            y += yInc;
        }
    }
    else if(x > goalx && y > goaly)
    {
        while(x > goalx || y > goaly)
        {
            x -= xInc;
            y -= yInc;
        }
    }
Shubham Agrawal
  • 559
  • 6
  • 15