Lua代码中存在错误的游戏逻辑。

这段代码是用于一个简单的贪吃蛇克隆游戏,我不希望蛇能够在向右移动时向左移动。

如果我在向右移动时只按下了左箭头,它是有效的,但是如果我在规定时间内先按上箭头然后再按左箭头,它就会开始向左移动。

function self.update(dt)
    如果love.keyboard.isDown(self.left)和self.prevvelocity.x!= 1self.velocity.x = -1
        self.velocity.y = 0
    end
    如果love.keyboard.isDown(self.right)和self.prevvelocity.x!= -1self.velocity.x = 1
        self.velocity.y = 0
    end
    如果love.keyboard.isDown(self.up)和self.prevvelocity.y!= 1self.velocity.x = 0
        self.velocity.y = -1
    end
    如果love.keyboard.isDown(self.down)和self.prevvelocity.y!= -1self.velocity.x = 0
        self.velocity.y = 1
    end

    如果self.timeSinceLastMove <self.speedinverted,
        self.timeSinceLastMove = self.timeSinceLastMove + dt
    else,

        table.removeself.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

原文链接 https://stackoverflow.com/questions/31280716

点赞
stackoverflow用户1847592
stackoverflow用户1847592
    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

self.update(dt)函数:

  • 如果左箭头键被按下且之前的速度不是向右,则将速度设置为向左,并且垂直速度为零;
  • 如果右箭头键被按下且之前的速度不是向左,则将速度设置为向右,并且垂直速度为零;
  • 如果上箭头键被按下且之前的速度不是向下,则将速度设置为垂直向上,并且水平速度为零;
  • 如果下箭头键被按下且之前的速度不是向上,则将速度设置为垂直向下,并且水平速度为零;
  • 距离上次移动时间增加“dt”秒;
  • 如果距离上次移动时间大于等于self.speedinverted,则将其减去self.speedinverted
  • 设置蛇头的位置为当前位置 + 速度 × 瓷砖大小;
  • 移除蛇尾的第一个元素;
  • 创建头节点,并将其添加到蛇尾中;
  • 将之前的速度设置为当前速度。
2015-07-08 12:45:14