2

The code is for a simple snake clone and I don't want to let the snake me able to go left if it's going right already.

It works if I just press LEFT when going RIGHT but if I for example presses UP then LEFT within the time frame it starts to move left.

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 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.