简体   繁体   English

lua中的冲突和OOP

[英]Collision and OOP in lua

So I've made a basic collision system in love2D using basic OOP. 因此,我使用基本的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 being the minimum translation to move the part when it collides and the side being the side it collides on. mtv是碰撞零件时移动零件的最小平移,而侧面是碰撞零件的侧面。

The problem is, I want to be able to make it so in the player:collide function, shown here: 问题是,我希望能够在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

I can make it so when it's NOT colliding, it sets the gravity back to normal, but if I add an elseif/else statement inside for when it's not colliding, it'll also do that if it's colliding with one block since there's 30 other blocks on the screen and won't set gravity to -0.1 since it'll be always setting it back to normal gravity, if that makes any sense. 我可以做到,当它不发生碰撞时,将重力设置回正常,但是如果我在其中添加了elseif / else语句以表示不发生碰撞,那么如果它与一个块发生碰撞,它也会这样做,因为还有30个其他块在屏幕上显示块,并且不会将重力设置为-0.1,因为如果有任何意义,它将始终将其设置为正常重力。

How can I fix that? 我该如何解决?

Maybe simply extract the collision behavior outside of the collide method? 也许简单的提取外的碰撞行为collide的方法? Here's an idea: 这是一个主意:

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

Dealing with gravity should be dealt with at the player level, not the individual collision's. 处理重力应该在玩家级别上处理,而不是在单个碰撞级别上处理。

EDIT 编辑

Took direction into account and moved gravity logic into its own method. 考虑了方向,并将重力逻辑移到了自己的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM