如何在C ++中将对象移动到某个边界内

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

我想做一个乒乓球游戏,我被球运动困住了,我不想让它超出边界,万一是 640 x 480.....我不想它离开这个边界,而是再次移动,就像在碰撞的情况下一样...... 以下是代码

#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();
}

边界碰撞效果的一个简单方法是,当 Pong 运动 "hits" 上边界或下边界时,你否定 y-Component 并否定 x-Component 当它 "hits" 左边界或右边界时。

简短示例代码:

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];
}