Here you go. As you can see, there is a square block of "red" around my player.
This is the full game code:
Code: Select all
function love.keypressed(key)
if key == " " then
-- shoot a bullet (by adding it to the bullets table and passing a .y value)
bullets[#bullets+1] = {
y = 495,
speed = 300,
width = 10,
height = 5,
x = (player.x + player.width/2) - 5
}
end
end
function CheckCollision(ax1,ay1,aw,ah, bx1,by1,bw,bh)
local ax2,ay2,bx2,by2 = ax1 + aw, ay1 + ah, bx1 + bw, by1 + bh
return ax1 < bx2 and ax2 < bx1 and ay1 < by2 and ay2 < by1
end
function love.load()
-- setup the player
player = {}
player.x = 300
player.y = 500
player.speed = 300
player.graphic = love.graphics.newImage('player_small.png')
player.width = player.graphic:getWidth()
player.height = player.graphic:getHeight()
-- setup the bullets
bullets = {}
-- setup the enemies
enemies = {}
for i=0,7 do
enemy = {}
enemy.width = 40
enemy.height = 20
enemy.speed = 20
enemy.x = i * (enemy.width+60) + 100
enemy.y = enemy.height + 100
table.insert(enemies, enemy)
end
-- when a key is pressed, call the function love.keypressed
love.keypressed()
end
function love.update(dt)
-- move our player
if love.keyboard.isDown("right") then
if player.x < (800-player.width) then
player.x = player.x + player.speed *dt
elseif player.x < (800-player.width) then
player.x = (800-player.width)
end
end
if love.keyboard.isDown("left") then
if player.x > 0 then
player.x = player.x - player.speed *dt
elseif player.x < 0 then
player.x = 0
end
end
-- update the position of the enemies in the table 'enemies'
for i,v in ipairs(enemies) do
v.y = v.y + v.speed * dt
end
-- update the position of the bullets in the table 'bullets'
for i,v in ipairs(bullets) do
-- move the bullets upward
v.y = v.y - v.speed * dt
-- Check for collision between bullets and enemies. If they collide, remove both bullets and emies
for ii,vv in ipairs(enemies) do
if v.y < vv.y and (v.x > vv.x and v.x < vv.x+vv.width) then
table.remove(enemies, ii)
table.remove(bullets, i)
end
end
-- remove shots that are out of range
if v.y < 120 then
table.remove(bullets, i)
end
end
end
function love.draw()
love.graphics.setBackgroundColor(255,255,255)
love.graphics.setColor(255, 0, 0)
-- draw the player
love.graphics.draw(player.graphic, player.x, player.y)
-- draw the bullets
love.graphics.setColor(255, 255, 255)
for i, v in ipairs(bullets) do
love.graphics.rectangle("fill", v.x, v.y, v.width, v.height)
end
-- draw the enemies
love.graphics.setColor(0, 255, 255)
for i, v in ipairs(enemies) do
love.graphics.rectangle("fill", v.x, v.y, v.width, v.height)
end
end