Bullet actor collisions

This commit is contained in:
MaddoScientisto 2024-04-28 17:06:07 +02:00
commit 0e0a458949
5 changed files with 92 additions and 18 deletions

View file

@ -1,16 +1,16 @@
--M = {}
Actor = {
life=100,
spriteIndex=0,
}
Actor = {}
--actor.__index = actor
function Actor:new(new_x,new_y)
local o = {
x=new_x,
y=new_y,
w=16,
h=16
h=16,
life=100,
shootable=false
--spriteIndex=0
}
return setmetatable(o, {__index=self})
@ -20,6 +20,17 @@ function Actor:update()
end
function Actor:destroy()
end
function Actor:damage(amount)
self.life -= amount
if (self.life <= 0) then
self:destroy()
end
end
function Actor:draw()
spr(self.spriteIndex,self.x,self.y)
end

View file

@ -10,13 +10,29 @@ local Actor = require(make_path("actor2"))
-- return barrel
local Barrel = Actor:new()
Barrel.spriteIndex = 3
function Barrel:new(x,y)
local b = Actor:new(x,y)
b.life = 5
b.shootable = true
b.spriteIndex = 3
return setmetatable(b, {__index=self})
end
--Barrel.spriteIndex = 3
--Barrel.shootable = true
--Barrel.life = 5
function Barrel:update()
end
function Barrel:destroy()
del(actors,self)
end
--function Barrel:draw()
-- spr(self.spriteIndex,self.x,self.y)
--end

View file

@ -91,6 +91,8 @@ function _update()
p:update()
end
check_collisions()
--slidervalue = pgui:component("hslider",{pos=vec(190,20),value=slidervalue})
pgui:component("vstack",{stroke=true,pos=vec(0,0),color={0,18,12,0,7,6},height=0,margin=3,gap=3,contents={
@ -227,4 +229,34 @@ function render_layer(layer)
end
end
end
end
function distance(x1, y1, x2, y2)
return math.sqrt((x2 - x1)^2 + (y2 - y1)^2)
end
function collided(act, bul)
-- Calculate distance between actor and bullet
local dist = distance(act.x, act.y, bul.x, bul.y)
-- Check if distance is less than actor's half size and bullet's radius
return dist < (bul.radius + math.min(act.w, act.h) / 2)
end
function check_collisions()
for _, actor in ipairs(actors) do
if (actor.shootable) then
for _, bullet in ipairs(bullets) do
if collided(actor, bullet) --[[and not bullet.destroyed]] then
-- Destroy bullet
bullet:destroy()
-- Damage actor
actor:damage(bullet.damage)
end
end
end
end
end

View file

@ -10,7 +10,8 @@ local bullets_list = {
spriteIndex=80,
damage=1,
speed=2,
life=100
life=100,
radius=2
}
}
@ -66,8 +67,18 @@ end
-- Particle
Particle = Actor:new()
Particle.life=4
Particle.spriteIndex=81
function Particle:new(x,y)
local p = Actor:new(x,y)
p.life=4
p.spriteIndex=81
p.shootable = false
return setmetatable(p, {__index=self})
end
--Particle.life=4
--Particle.spriteIndex=81
function Particle:update()
self.life-=1
@ -97,6 +108,7 @@ function Bullet:new(bullet_data,x,y,dir_x,dir_y)
obj.damage = bullet_data.damage
obj.life = bullet_data.life
obj.speed = bullet_data.speed
obj.radius = bullet_data.radius
obj.dx = dir_x * obj.speed
obj.dy = dir_y * obj.speed
@ -122,6 +134,9 @@ function Bullet:check_collision()
self:destroy()
end
-- Collision with actors
end
function Bullet:update()