C++ 如何编写for循环来检查每个像素的冲突?
我正试图在我的敌人类中编写一个for循环来检查与玩家的冲突……我特别想做的是让它检查每一行中的每个像素,所以它应该检查一行中的所有像素,然后转到下一行。我不知道怎么写,所以它会检查每一行…我该怎么做?这是我写的…我非常确定我需要在那里有另一个for循环来遍历每一行,但我不确定如何实现它C++ 如何编写for循环来检查每个像素的冲突?,c++,sdl,collision-detection,collision,C++,Sdl,Collision Detection,Collision,我正试图在我的敌人类中编写一个for循环来检查与玩家的冲突……我特别想做的是让它检查每一行中的每个像素,所以它应该检查一行中的所有像素,然后转到下一行。我不知道怎么写,所以它会检查每一行…我该怎么做?这是我写的…我非常确定我需要在那里有另一个for循环来遍历每一行,但我不确定如何实现它 bool Enemy::checkCollision() { for(i = 0; i < postion.w; i++) { if(position.x + i == pl
bool Enemy::checkCollision()
{
for(i = 0; i < postion.w; i++)
{
if(position.x + i == player.position.x)
{
return true;
}
else if(position.y + i == player.position.y)
{
return true;
}
else
{
return false;
}
}
}
bool敌人::checkCollision()
{
对于(i=0;i
waaa可能很复杂。有一个自由函数,它有两个位置和两个碰撞框,只需使用一个简单的复选框(底部的简明版本,这个解释了它的工作原理):
将进行像素完美的碰撞检测。像素数据的存储方式是否可能重复?它是矢量、平面阵列、2d阵列吗?不确定“像素数据”到底是什么意思…但我使用SDL_Rect表示位置。好的…我大部分都理解这段代码…但是参数到底是什么呢?另外,如果检测到碰撞,我也不清楚它返回的是什么……我希望它返回true。@用户:包含要测试的对象的位置和边界的SDL矩形<代码>碰撞(例如,敌人[i].rect,玩家.rect)。如果在两个轴上碰撞,则输出
true
;如果在两个轴上都不碰撞或仅在一个轴上碰撞,则输出false
。返回条件1和条件2
是如果(条件1和条件2)返回true的缩写;否则返回false代码>。好吧……我想我明白了……如果没有,我会弄明白的。谢谢你的帮助。。。
// y ^
// |
// +----> x
struct SDL_Rect{
unsigned x, y;
int w, h;
};
bool collides(SDL_Rect const& o1, SDL_Rect const& o2){
/* y_max -> +------------+
* | |
* | |
* +------------+ <- x_max
* |-----^------|
* y_min, x_min
*/
unsigned o1_x_min = o1.x, o1_x_max = o1.x + o1.w;
unsigned o2_x_min = o2.x, o2_x_max = o2.x + o2.w;
/* Collision on X axis: o1_x_max > o2_x_min && o1_x_min < o2_x_max
* o1_x_min -> +-----------+ <- o1_x_max
* o2_x_min -> +-------------+ <- o2_x_max
*
* No collision 1: o1_x_max < o2_x_min
* o1_x_min -> +-----------+ <- o1_x_max
* o2_x_min -> +-------------+ <- o2_x_max
*
* No collision 2: o1_x_min > o2_x_max
* o1_x_min -> +-------------+ <- o1_x_max
* o2_x_min -> +-----------+ <- o2_x_max
*/
if(o1_x_max >= o2_x_min && o1_x_min <= o2_x_max)
{ // collision on X, check Y
/* Collision on Y axis: o1_y_max > o2_y_min && o1_y_min < o2_y_max
* o1_y_max -> +
* | + <- o2_y_max
* | |
* o1_y_min -> + |
* + <- o2_y_min
* No collision: o1_y_min > o2_y_max
* o1_y_max -> +
* |
* |
* o1_y_min -> +
* + <- o2_y_max
* |
* |
* + <- o2_y_min
*/
unsigned o1_y_min = o1.y, o1_y_max = o1.y + o1.h;
unsigned o2_y_min = o2.y, o2_y_max = o2.y + o2.h;
return o1_y_max >= o2_y_min && o1_y_min <= o2_y_max;
}
return false;
}
bool collides(SDL_Rect const& o1, SDL_Rect const& o2){
unsigned o1_x_min = o1.x, o1_x_max = o1.x + o1.w;
unsigned o2_x_min = o2.x, o2_x_max = o2.x + o2.w;
if(o1_x_max >= o2_x_min && o1_x_min <= o2_x_max)
{ // collision on X, check Y
unsigned o1_y_min = o1.y, o1_y_max = o1.y + o1.h;
unsigned o2_y_min = o2.y, o2_y_max = o2.y + o2.h;
return o1_y_max >= o2_y_min && o1_y_min <= o2_y_max;
}
return false;
}