2011-03-21 151 views
1

我有以下代碼: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 

回答

2

看一看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 

(這不是我認識的語言,所以我猜了一下)

+0

好,類似這個*應該*的工作。閱讀完指南後,我認爲有幾個方面的改進(指南中的例子提供了一些不太先進的內容,只有少數概念適用,但在閱讀完指南後,我意識到如何去做。爲此,您有*回覆此帖*! – FreeSnow 2011-03-22 00:24:31