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 属性)。
由于某种原因,我的代码返回附近不存在的对象的碰撞。有什么想法吗?
编辑:
我已经解决了我的问题,这是任何人谷歌搜索该主题的代码。
(它是用 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
I have the following code:
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, etc. are arguments containing the position of the respective bounding box (box 1 or 2).
dir is a "Vector2" (contains an x and y property).
For some reason, my code is returning collisions for objects no where near by. Any ideas?
EDIT:
I have solved my problem, here is the code for anybody googling the subject.
(It's in Lua, a pretty straight forward and simple to interpret language)
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看这是一个很好的碰撞检测教程/算法。
本质上:
或者,就您的代码而言:(
这不是我知道的语言,所以我猜测了一下)
Have a look at this for a nice collision detection tutorial/algorithm.
Essentially:
Or, in terms of your code:
(this isn't a language I know, so I'm guessing a bit)