2017-02-09 34 views
-1

我想做一个乒乓球游戏,我被卡在球运动中,我不希望它超出边界,这是在640的情况下是480。 ....我不希望它摆脱这种边界,而是再次移动,就像在发生碰撞的情况下... 以下是代码如何在C++中移动某个边界内的物体

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

缩进的湖泊,使用goto'的'和你所有的图形代码包含使这个例子比较硬理解。你的例子越简单,你就越有可能花时间理解它。您应该正确缩进,并将您的示例缩减为必不可少的组件。此外,使用本地文件('“C:\\ TC \\ BGI”')使这个例子对其他人无法运行,进一步阻碍了帮助。 –

+0

这是你可能拥有的'goto'最糟糕的用法。向上分支到一个标签,从'for'循环转换回'for'循环,使用整数'i'作为循环计数器。在两个循环中,您都会跳出并重新进入。 [意大利面代码](https://en.wikipedia.org/wiki/Spaghetti_code) – PaulMcKenzie

回答

0

在碰撞效果的一种简单方法边界是你否定了Pong运动的y-分量,当它“击中”上限或下限,并且在它“击中”左边界或右边界时否定x-Component。

短示例代码:

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