gpt4 book ai didi

c++ - 矩形弹跳碰撞检测

转载 作者:行者123 更新时间:2023-11-28 03:13:06 25 4
gpt4 key购买 nike

我使用 SDL 创建了一个程序,其中一个矩形在程序的墙内不断发生碰撞,但碰撞检查工作不正常。

这是代码:`

int main(int argc, char *argv[]){
//variable Initialization]
width = height = 45;
srcX = srcY = 0;
destY = destX = 0;
vlc = 1;
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
SDL_WM_SetCaption("Bouncing Balls","./ball.jpg");
backg = IMG_Load("./back.png");
ball = IMG_Load("./ball.jpg");
while (checkBounce){
//Increase velocity
destX += vlc;
destY += vlc;
//Collision Checking
if (destX < 0){
destX = 0;
vlc = -vlc;
destX += vlc;
}
if (destY < 0){
destY = 0;
vlc = -vlc;
destY += vlc;
}
if (destY + height > 480){
destY = 480 - height;
vlc = -vlc;
}
if (destX + width > 640){
destX = 640 - width;
vlc = -vlc;
}
if (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT)
checkBounce = false;
}
//Applying Surfaces
applySurface(0, 0, backg, screen);
applyBall(srcX, srcY, destX, destY, width, height, ball, screen);
SDL_Flip(screen);
}
SDL_Quit();
return 0;
}

这是 gif 图像发生了什么:Bouncing Rectangle.gif

最佳答案

我假设预期结果是矩形从墙壁上正确反弹?

您需要将速度分为 x 和 y 分量,而不是使用单个数字。这是因为速度是二维的。

只要检测到碰撞,您的程序就会导致 x 和 y 分量都变为负值。这会导致矩形沿其路径向后反弹。

这里是一个编辑:

int main(int argc, char *argv[]){
//variable Initialization]
width = height = 45;
srcX = srcY = 0;
destY = destX = 0;
vlcX = 1;
vlcY = 1;
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
SDL_WM_SetCaption("Bouncing Balls","./ball.jpg");
backg = IMG_Load("./back.png");
ball = IMG_Load("./ball.jpg");
while (checkBounce){
//Increase velocity
destX += vlcX;
destY += vlcY;
//Collision Checking
if (destX < 0){
destX = 0;
vlcX = -vlcX;
destX += vlcX;
}
if (destY < 0){
destY = 0;
vlcY = -vlcY;
destY += vlcY;
}
if (destY + height > 480){
destY = 480 - height;
vlcY = -vlcY;
}
if (destX + width > 640){
destX = 640 - width;
vlcX = -vlcX;
}
if (SDL_PollEvent(&event)){
if (event.type == SDL_QUIT)
checkBounce = false;
}
//Applying Surfaces
applySurface(0, 0, backg, screen);
applyBall(srcX, srcY, destX, destY, width, height, ball, screen);
SDL_Flip(screen);
}
SDL_Quit();
return 0;
}

关于c++ - 矩形弹跳碰撞检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17825079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com