2017-01-24 86 views
0

所以我在使用基本OOP的love2D中做了一個基本的碰撞系統。lua中的碰撞和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是碰撞時移動零件的最小平移量,側面碰撞時是最小平移量。

的問題是,我希望能夠使它所以在玩家:碰撞功能,如下圖所示:

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,如果這是有道理的話,你總會把它設置回正常的重力。

我該如何解決這個問題?

回答

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 

處理重力應該在玩家層面處理,而不是在單個碰撞的情況下處理。

EDIT

注意到方向考慮在內,並移動重力邏輯到它自己的方法。

+0

但我在玩家級別處理它(如果你的意思是在player.lua文件中)? love.update位於完全不同的文件main.lua文件中。 – Ducktor

+0

對不起,我的評論不是很清楚!我的意思是這不應該在每次單獨的碰撞中處理。我會更新我的解決方案,因爲我沒有注意到碰撞方向很重要。 – SolarBear

+0

謝謝,它現在工作正常! – Ducktor