Ducktor
Ducktor

Reputation: 335

Collision and OOP in lua

So I've made a basic collision system in love2D using basic OOP.

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.

The problem is, I want to be able to make it so in the player:collide function, shown here:

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.

How can I fix that?

Upvotes: 0

Views: 189

Answers (1)

SolarBear
SolarBear

Reputation: 4619

Maybe simply extract the collision behavior outside of the collide method? 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.

Upvotes: 1

Related Questions