lua - Lua 代码中存在缺陷的游戏逻辑

标签 lua love2d

该代码用于一个简单的蛇克隆,如果蛇已经向右走,我不想让它向左走。

如果我在向右移动时只按向左键,它就会起作用,但如果我在时间范围内按向上键,然后向左键,它就会开始向左移动。

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

最佳答案

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

关于lua - Lua 代码中存在缺陷的游戏逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31280716/

相关文章:

lua - Redis lua什么时候才能真正用上呢?

lua - 我的lua脚本加载.so库,如何用Lua 5.2编写宿主程序?

visual-studio-code - 如何使用 VSCode 调试 Lua Love2D?

oop - 我如何在 lua love2d (OOP) 中使用类

Lua获取最大数量

lua - 从lua中另一个表内的表内调用函数

winapi - Lua Alien - 使用 WinAPI 将消息发送到 Notepad.exe

lua - 如何将 "th"或 "rd"添加到日期

c - Lua c lib Windows : The specified procedure could not be found

lua - 从一个字符串中获取两个字符串