ovellas/entidades/ovella.lua
2022-06-01 23:37:51 +02:00

85 lines
2.3 KiB
Lua

require("../lib/helpers")
Ovella = {}
local OvellaMT = {__index = Ovella}
function Ovella:new(id, x, y)
local instance = {}
instance.id = id
instance.sprite = love.graphics.newImage("img/ovella.png")
instance.width = instance.sprite:getWidth()
instance.height = instance.sprite:getHeight()
instance.x = x-instance.width/2
instance.y = y-instance.height/2
instance.speed = 1
return setmetatable(instance, OvellaMT)
end
function Ovella:update(pastor, cercado)
-- vector
local X = pastor.x - self.x;
local Y = pastor.y - self.y;
distancia = math.sqrt(math.pow(X, 2) + math.pow(Y, 2));
--normalizase o vector
X = X / distancia;
Y = Y / distancia;
-- redondease ó int máis cercano
if X < 0 then
X = math.floor(X - 0.5);
else
X = math.floor(X + 0.5);
end
if Y < 0 then
Y = math.floor(Y - 0.5);
else
Y = math.floor(Y + 0.5);
end
-- velocidade
dX = X * self.speed;
dY = Y * self.speed;
if distancia < DISTANCIA then
-- movemento
-- FIXME comprobar que non se vai de marxenes e non choca con muros
-- print(Helpers:CheckCollision(self, cercado)) -- comprobaría con todo o cercado
futuro = {}
futuro.x = self.x - dX;
futuro.y = self.y - dY;
futuro.width = self.width--/3;
futuro.height = self.height--/3;
-- futuraOvella = Ovella:new(self.id, self.x-dX, self.y-dY)
-- comprobar colisios con cada baldosa do cercado
local colision = false
for y = 1,cercado.filas do
for x = 1,cercado.columnas do
if cercado.tiles[y][x] ~= 'x' then
-- print(Helpers:CheckCollision(self, cercado.tiles[y][x]))
-- if Helpers:CheckCollision(futuro, cercado.tiles[y][x]) then
if Helpers:CheckCollision( cercado.tiles[y][x],futuro) then
colision = true
end
end
end
end
if not colision then
-- Establece a nova posición
self.x = self.x - dX;
self.y = self.y - dY;
end
end
end
function Ovella:draw()
love.graphics.draw(self.sprite, self.x, self.y)
end
return Ovella