Diagonal Movement of an Image

Let’s examine step by step how the logo will move diagonally.

*Step 1: First, we define the logo photo under the “private” line in “header(.h)”.

private:
        gImage logo;

*Step 2: We upload our logo that we defined in “.h” to our code in the setup function under our “.cpp” code page.

logo.loadImage(“gamelab-istanbul_logo_128.png”);
void GameCanvas::setup() {
     logo.loadImage("gamelab-istanbul_logo_128.png");
}

Our logo we uploaded; Located at C: \ dev \ glist \ myglistapp \ GlistApp \ assets \ images.

*Step 3:  In this step, we define a special x and y in “.h”. In the draw function in “.cpp”, we first clean the background, then determine the drawing color and draw our logo.

Code: (.h)

private:
     gImage logo;
     int x, y;
};

Code:(.cpp)
void GameCanvas::draw() {
   clearColor(0, 0, 30);
   setColor(255, 255, 255);
   logo.draw(x, y);
}

 *Step 4:  The deltax (dx) and deltay (dy) values ​​that specify how much the photo will move in a frame are defined in “.h” and given the value in “.cpp”.

private:
    gImage logo;
    int x, y;
    int dx, dy;
};

Code: (.cpp)

GameCanvas:: GameCanvas(gBaseApp *root) : gBaseCanvas(root)() {
   x = 0;
   y = 0;
   dx = 0;
   dy = 0;
}

*Step 5:  We give the first movement to our logo.

Code: (.cpp)

void GameCanvas::setup () {
   logo.loadImage("gamelab-istanbul_logo_128.png");

   // Initial x and y values to draw the image (screen center)
   x = (getWidth() - logo.getWidth()) / 2;
   y = (getHeight() - logo.getHeight()) / 2;

   // Delta values for image animation
   dx = 1;
   dy = 1;
}

In this step, our logo moves but goes out of frame.

*Step 6:  Increase x until reaching left or right side of the screen and increase y until reaching top or bottom side of the screen.

Code:

void GameCanvas::update() {
// Increase x until reaching left or right side of the screen
                    x += dx;
                    if (x <= 0 || x >= getWidth() - logo.getWidth()) dx = -dx; 
// Increase y until reaching top or bottom side of the screen
                    y+= dy;
                    if (y <= 0 || y >= getHeight() - logo.getHeight()) dy = -dy;
}

By doing this step, we ensure that our logo moves and stays on the screen.

*Step 7: And finally, we hit the run button to run our code and we see our logo move diagonally across the screen.