im programming a little game and I have a problem. My problem is that the rectangle doesnt go out of the little gap . He can move within the zone. But i want him to move out of the little gap in the right upper corner. How can i do that? Help and suggestions are appreciated.
function love.load()
quadX = 30
quadY = 540
end
function zeichneQuad(x,y,b,h)
love.graphics.rectangle("fill",x,y,b,h)
end
function love.draw()
love.graphics.line(5,5,725,5)
love.graphics.line(5,5,5,595)
love.graphics.line(5,595,795,595)
love.graphics.line(795,5,795,595)
zeichneQuad(quadX,quadY,30,30)
end
function love.keypressed(key)
if key == "up" and quadY +30 > 35 then
quadY = quadY -5
end
if key == "down" and quadY + 5 < 570 then
quadY = quadY + 5
end
if key == "right" and quadX +5 < 770 then
quadX = quadX + 5
end
if key == "left" and quadX +30 > 35 then
quadX = quadX - 5
end
end
Attachments
Screenshot_1.png (3.44 KiB) Viewed 3722 times
Last edited by Dzemal on Wed Sep 28, 2016 6:04 pm, edited 1 time in total.
What you have there is hard-coded boundaries check, you not gonna get far with this. You need a collision detection system. There is a built-in Box2D engine, you can use that if you don't feel like implementing your own system.
I send you a detailed PM regarding that topic.
Here is a small example demonstrating why it is importent to avoid hard-coded values: Fiddle (view in browser)
local screenWidth, screenHeight = love.graphics.getDimensions()
local borderSize
local rect = {}
function love.load()
borderSize = love.math.random(8, 128)
rect.width = love.math.random(8, 64)
rect.height = rect.width
rect.x = screenWidth/2-rect.width/2
rect.y = screenHeight/2-rect.height/2
rect.speed = 400
end
function rect.update(dt)
local keyDown = love.keyboard.isDown
if keyDown("left") then rect.x = rect.x - rect.speed * dt end
if keyDown("right") then rect.x = rect.x + rect.speed * dt end
if keyDown("up") then rect.y = rect.y - rect.speed * dt end
if keyDown("down") then rect.y = rect.y + rect.speed * dt end
rect.x = math.max(rect.x, borderSize)
rect.x = math.min(rect.x, screenWidth-rect.width-borderSize)
rect.y = math.max(rect.y, borderSize)
rect.y = math.min(rect.y, screenHeight-rect.height-borderSize)
end
function rect.draw()
love.graphics.rectangle("fill", rect.x, rect.y, rect.width, rect.height)
end
function love.update(dt)
-- Reduce border Size --
if screenHeight-(borderSize*2) > rect.width then
borderSize = borderSize + 20 * dt
end
rect.update(dt)
end
function love.draw()
love.graphics.rectangle("line", borderSize, borderSize, screenWidth-(borderSize*2), screenHeight-(borderSize*2))
rect.draw()
love.graphics.print("Space - Resize Border/Player", 10, 10)
love.graphics.print("Arrow Keys - Move", 10, 30)
love.graphics.print("Escape - Quit", 10, 50)
end
function love.keypressed(key)
if key == "escape" then love.event.quit()
elseif key == "space" then love.load() end
end