[英]Collision and OOP in lua
因此,我使用基本的OOP在love2D中制作了基本的碰撞系统。
function love.update(dt)
player:update(dt)
for _, rect in pairs(randomRectangles) do
local collides,mtv,side = collider:collidesMTV(player,rect)
if collides then
print(side)
player:collide(collides,mtv,side)
end
end
end
mtv是碰撞零件时移动零件的最小平移,而侧面是碰撞零件的侧面。
问题是,我希望能够在player:collide函数中做到这一点,如下所示:
function player:collide(colliding,mtv,side)
if colliding==true and side=="top" or colliding==true and side == "bottom" then
self.Position=self.Position-mtv
end
if colliding==true and side=="left" or colliding==true and side == "right" then
self.Position=self.Position-mtv
self.Gravity=-0.1
end
if not colliding and self.Gravity ~= -0.95 then
self.Gravity=-0.95
end
end
我可以做到,当它不发生碰撞时,将重力设置回正常,但是如果我在其中添加了elseif / else语句以表示不发生碰撞,那么如果它与一个块发生碰撞,它也会这样做,因为还有30个其他块在屏幕上显示块,并且不会将重力设置为-0.1,因为如果有任何意义,它将始终将其设置为正常重力。
我该如何解决?
也许简单的提取外的碰撞行为collide
的方法? 这是一个主意:
function player:collide(colliding,mtv,side)
if colliding==true and side=="top" or colliding==true and side == "bottom" then
self.Position=self.Position-mtv
end
if colliding==true and side=="left" or colliding==true and side == "right" then
self.Position=self.Position-mtv
self.hasSideCollision = true
end
end
function player:computeGravity()
if player.hasSideCollision then
self.Gravity = -0.1
else
self.Gravity = -0.95
end
end
function love.update(dt)
player:update(dt)
player.hasSideCollision = false
for _, rect in pairs(randomRectangles) do
local collides,mtv,side = collider:collidesMTV(player,rect)
if collides then
print(side)
player:collide(collides,mtv,side)
end
end
player:computeGravity()
end
处理重力应该在玩家级别上处理,而不是在单个碰撞级别上处理。
编辑
考虑了方向,并将重力逻辑移到了自己的方法中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.