summaryrefslogtreecommitdiff
path: root/entity.lua
blob: c85dc710c8a4e3ba35e6ceca03380e191e7f99ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
local Entity = {}
Entity.__index = Entity

function Entity:new(x, y, width, height, physicsWidth, physicsHeight)
    local self = setmetatable({}, Entity)
    self.x = x
    self.y = y
    self.width = width
    self.height = height
    self.physicsWidth = physicsWidth or width
    self.physicsHeight = physicsHeight or height
    self.texture = love.graphics.newImage("assets/missing8x8.png")
    return self
end

function Entity:update(dt)
end

function Entity:draw()
end

function Entity:enablePhysics(world, bodyType)
    bodyType = bodyType or "dynamic"
    if not world then error("love.physics.World is required") end
    local cx = self.x + self.physicsWidth / 2
    local cy = self.y + self.height - self.physicsHeight / 2
    self.body = love.physics.newBody(world, cx, cy, bodyType)
    local shape = love.physics.newRectangleShape(self.physicsWidth, self.physicsHeight)
    self.fixture = love.physics.newFixture(self.body, shape, 1)
    if self.fixture.setFriction then self.fixture:setFriction(0.3) end
    if self.fixture.setRestitution then self.fixture:setRestitution(0) end
    if self.fixture.setUserData then self.fixture:setUserData(self) end
    self.contact = { floor = 0, wall = 0, ceiling = 0 }
end

function Entity:syncFromPhysicsBody()
  if not self.body then return end
  self.x = self.body:getX() - self.physicsWidth 
  self.y = self.body:getY() - self.height + self.physicsHeight / 2
end

function getEntityCorners(entity)
    local x = entity.x
    local y = entity.y
    local w = entity.physicsWidth
    local h = entity.physicsHeight

    return {
        {x = x,     y = y},     
        {x = x + w, y = y},     
        {x = x,     y = y + h},  
        {x = x + w, y = y + h}   
    }
end

function Entity:getPhysicsBody()
  return self.body
end

function Entity:getPhysicsFixture()
  return self.fixture
end

function Entity:setPropertiesFromOptions(options)
  options = options or {}
  self.properties = {}
  if options.properties then
    for k, v in pairs(options.properties) do
      self.properties[k] = v
    end
  end
  
  for k, v in pairs(options) do
    if self[k] == nil then
      self[k] = v
    end
  end
  
  return self
end

function Entity:has(key)
  return self.properties and self.properties[key] ~= nil
end

function Entity:get(key, default)
  if self.properties and self.properties[key] ~= nil then
    return self.properties[key]
  end
  return default
end

return Entity