2D碰撞问题
问题描述:
我有以下代码:2D碰撞问题
function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
local left,right,top,bottom=false,false,false,false
if left1<right2 then left=true end
if right1>left2 then right=true end
if top1>bottom2 then top=true end
if bottom1<top2 then bottom=true end
if dir.x>0 and (top or bottom) then
if right then return 1 end
elseif dir.x<0 and (top or bottom) then
if left then return 2 end
elseif dir.y>0 and (left or right) then
if bottom then return 3 end
elseif dir.y<0 and (left or right) then
if top then return 4 end
end
return 0
end
LEFT1,RIGHT1等是包含各自边界框的位置参数(框1或2)。
dir是“Vector2”(包含x和y属性)。
出于某种原因,我的代码返回碰撞对象没有在附近。有任何想法吗?
编辑:
我已经解决了我的问题,这里是任何人使用Google主题的代码。
(这是在Lua,一个非常简单的和简单的解释语言)
function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
local insideHorizontal=false
local insideVertical=false
if left1<right2 then insideHorizontal=true end
if right1>left2 then insideHorizontal=true end
if top1>bottom2 then insideVertical=true end
if bottom1<top2 then insideVertical=true end
if insideHorizontal and insideVertical then
return true
end
return false
end
答
看一看this for a nice collision detection tutorial/algorithm。
本质:
bool check_collision(SDL_Rect A, SDL_Rect B)
{
//...
//Work out sides
//...
//If any of the sides from A are outside of B
if(bottomA <= topB)
{
return false;
}
if(topA >= bottomB)
{
return false;
}
if(rightA <= leftB)
{
return false;
}
if(leftA >= rightB)
{
return false;
}
//If none of the sides from A are outside B
return true;
}
或者,在你的代码的条款:
function collisionDetect(left1,right1,top1,bottom1,left2,right2,top2,bottom2,dir)
if bottom1<=top2 then return true end
if top1>=bottom2 then return true end
if right1<=left2 then return true end
if left1<=right2 then return true end
return false
end
(这不是我认识的语言,所以我猜了一下)
好,类似这个*应该*的工作。阅读完指南后,我认为有几个方面的改进(指南中的例子提供了一些不太先进的内容,只有少数概念适用,但在阅读完指南后,我意识到如何去做。为此,您有*回复此帖*! – FreeSnow 2011-03-22 00:24:31