Search code examples
c++collision-detectionbgi

how to move a object inside a certain boundry in c++


i want to make a ping pong game, i am stuck at the ball movement i don't want it to get out of the boundaries which in case is 640 by 480..... i don't want it to get out of this boundary but instead move again just like in the case of collision... following is the code

#include <iostream>
#include <graphics.h>
#include <stdio.h>
#include <conio.h>

int main()
{
    int gd = DETECT, gm;
    initgraph(&gd, &gm, "C:\\TC\\BGI");
    int x = 0, y = 0, i;
    setcolor(RED);
    setfillstyle(SOLID_FILL, YELLOW);
    circle(x, y, 20);
    floodfill(x, y, RED);
loop1:
    for (i = 0; i <= 45; i++) {
        cleardevice();
        setcolor(RED);
        setfillstyle(SOLID_FILL, YELLOW);
        circle(x, y, 20);
        floodfill(x, y, RED);
        if (y == 460) {
            break;
        }
        else {
            x += 10;
            y += 10;
        }
        delay(10);
    }

    for (i = 0; i <= 46; i++) {
        cleardevice();
        setcolor(RED);
        setfillstyle(SOLID_FILL, YELLOW);
        circle(x, y, 20);
        floodfill(x, y, RED);
        if (x == 620) {
            break;
        }
        else {
            x += 10;
            y -= 10;
        }
        delay(10);
    }

    for (i = 0; i <= 45; i++) {
        cleardevice();
        setcolor(RED);
        setfillstyle(SOLID_FILL, YELLOW);
        circle(x, y, 20);
        floodfill(x, y, RED);
        if (y == 20) {
            break;
        }
        else {
            x -= 10;
            y -= 10;
        }
        delay(10);
    }

    for (i = 0; i <= 45; i++) {
        cleardevice();
        setcolor(RED);
        setfillstyle(SOLID_FILL, YELLOW);
        circle(x, y, 20);
        floodfill(x, y, RED);
        if (x == 20) {
            goto loop1;
        }
        else {
            x -= 10;
            y += 10;
        }
        delay(10);
    }
    getch();
    closegraph();
}

Solution

  • A simple way for the collision effect at the boundries, is that you negate the y-Component of the Pong movement, when it "hits" the upper or lower boundry and negate the x-Component when it "hits" the left or right boundry.

    Short example code:

    int speedvector[2];
    speedvector[0] = 10;
    speedvector[1] = 10;
    
    int pongposition[2];
    pongposition[0] = 100;
    pongposition[1] = 100;
    
    Main game loop:
    
    while(gameon){
      if(pongposition[0] < 0 || pongposition[0] > 640){
        speedvector[0] = -speedvector[0];
      }
      if(pongposition[1] < 0 || pongposition[1] > 480){
        speedvector[1] = -speedvector[1];
      }
      pongposition[0] += speedvector[0];
      pongposition[1] += speedvector[1];
    }