Code: Select all
function love.load(arg)
-- create table for the big box:
bigBox = {}
bigBox.width = 80
bigBox.height = 60
bigBox.x = 100
bigBox.y = 40
bigBox_Speed = 120
-- Gamelogic: 'avtarGod' is a god and he has a wepon 'arrows' This arrows is a sub table of
-- 'avtarGod' We are here controlling the subtable object arrows each item separately
avtarGod = {}
avtarGod.x = 740
avtarGod.y = 550
avtarGod.width = 35
avtarGod.height = 25
avtarGod.arrows = {} -- weapons of the avtarGod. This is a sub table of 'avtarGod'.
end
function love.update(dt)
-- move bigBox in a direction as per below codes
bigBox.x = bigBox.x + 10 * dt
bigBox.y = bigBox.y + 15 * dt
-- move the avtarGod towards bigBox enemy
avtarGod.x = avtarGod.x - 12 * dt
avtarGod.y = avtarGod.y - 20 * dt
-- create a table to store arrow's index which hit the bigBox and went outside the screen
local remArrows = {}
-- move avtarGod arrows (we have to do it in loop using 'for' as it is a sub table of avtar)
for i, v in ipairs(avtarGod.arrows) do
if v.y < 0 then -- if arrows moved outside the screen then remember their index numbers
table.insert(remArrows, i)
end
-- move the arrows
v.x = v.x - 115 * dt
v.y = v.y - 30 * dt
-- when collision happened remember the arrows which has collided
if Collision(v.x, v.y, v.width, v.height, bigBox.x, bigBox.y, bigBox.width, bigBox.height) then
-- mark the arrow index for later removal
table.insert(remArrows, i)
end
end
-- remove the collided arrows and the arrows which went out of the screen
for i, v in ipairs(remArrows) do
table.remove(avtarGod.arrows, v)
end
end
function love.draw()
-- draw the bigBox
love.graphics.setColor(200, 200, 60, 255)
love.graphics.rectangle('fill', bigBox.x, bigBox.y, bigBox.width, bigBox.height)
-- draw the avtar avtarGod
love.graphics.setColor(255, 200, 190, math.random(40, 255))
love.graphics.rectangle('fill', avtarGod.x, avtarGod.y, avtarGod.width, avtarGod.height)
-- show weapon1 of avtarGod
love.graphics.setColor(255, 0, 0, 255)
for i, v in ipairs(avtarGod.arrows) do
love.graphics.rectangle('fill', v.x, v.y, v.width, v.height)
end
end
function love.keypressed(key)
if key == '1' then
callWeapon1()
end
end
-- create collision of the objects
function Collision(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 callWeapon1()
weapon = {}
weapon.x = avtarGod.x
weapon.y = avtarGod.y
weapon.width = 2
weapon.height = 5
table.insert(avtarGod.arrows, weapon)
end