Lua代码中有缺陷的游戏逻辑

时间:2015-07-07 22:49:33

标签: lua love2d

代码是针对一个简单的蛇克隆而且我不想让蛇我能够离开它,如果它已经正确的话。

如果我只是在向右方向按下LEFT但是如果我按下UP然后在时间范围内左转它开始向左移动它是有效的。

function self.update(dt)
    if love.keyboard.isDown(self.left) and self.prevvelocity.x ~= 1 then 
        self.velocity.x = -1
        self.velocity.y = 0
    end 
    if love.keyboard.isDown(self.right) and self.prevvelocity.x ~= -1 then 
        self.velocity.x = 1     
        self.velocity.y = 0
    end     
    if love.keyboard.isDown(self.up) and self.prevvelocity.y ~= 1 then  
        self.velocity.x = 0
        self.velocity.y = -1
    end 
    if love.keyboard.isDown(self.down) and self.prevvelocity.y ~= -1 then   
        self.velocity.x = 0
        self.velocity.y = 1
    end 

    if self.timeSinceLastMove < self.speedinverted then
        self.timeSinceLastMove = self.timeSinceLastMove + dt
    else

        table.remove(self.tail, 1)

        tail = { x = self.position.x, y = self.position.y }

        table.insert(self.tail, tail)

        self.position.x = self.position.x + self.velocity.x * tileSize
        self.position.y = self.position.y + self.velocity.y * tileSize

        self.prevvelocity = self.velocity

        self.timeSinceLastMove = 0;
    end
end

1 个答案:

答案 0 :(得分:2)

function self.update(dt)
    if love.keyboard.isDown(self.left) and self.prevvelocity.x ~= 1 then 
        self.velocity.x = -1
        self.velocity.y = 0
    end 
    if love.keyboard.isDown(self.right) and self.prevvelocity.x ~= -1 then 
        self.velocity.x = 1     
        self.velocity.y = 0
    end     
    if love.keyboard.isDown(self.up) and self.prevvelocity.y ~= 1 then  
        self.velocity.x = 0
        self.velocity.y = -1
    end 
    if love.keyboard.isDown(self.down) and self.prevvelocity.y ~= -1 then   
        self.velocity.x = 0
        self.velocity.y = 1
    end 

    self.timeSinceLastMove = self.timeSinceLastMove + dt

    if self.timeSinceLastMove >= self.speedinverted then
        self.timeSinceLastMove = self.timeSinceLastMove - self.speedinverted

        self.position.x = self.position.x + self.velocity.x * tileSize
        self.position.y = self.position.y + self.velocity.y * tileSize

        table.remove(self.tail, 1)
        local head = { x = self.position.x, y = self.position.y }
        table.insert(self.tail, head)

        self.prevvelocity = { x = self.velocity.x, y = self.velocity.y }
    end
end