summaryrefslogtreecommitdiff
path: root/player.lua
blob: e4ef8f6960be003ff13d10e1b94bf74ebeab7282 (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
-- Metatable.
local Player = {
	x = 14,
	y = 12,
	frame = 1,
	animation = "idle",
	moved = false,
	target_x = 14,
	call,
}
Player.__index = Player

-- Craete new empty Player object.
local function newPlayer()
	return setmetatable({}, Player)
end

-- Position related functions.
function Player:getPosition()
	return self.x, self.y
end
function Player:setPosition(x, y)
	self.x, self.y = x, y
	return self
end

-- Facing.
function Player:getFacing()
	if self.animation == "walk" then
		if (self.target_x - self.x) < 0 then
			return -1
		end
	end
	return 1
end

-- Target.
function Player:setTarget(x, y, prop)
	if Game.inRange(x, y) then
		self.target_x = x
		self.prop = prop
	end
end

-- Change animation.
function Player:changeAnimation(name)
	if self.animation ~= name then
		self.animation = name
		self.frame = 1
	end
	return self
end

-- LÖVE2D callbacks.
function Player:update()
	-- Animation.
	local frames = #Game.quads.player[self.animation]
	self.frame = (self.frame%frames)+1
	-- Movement towards target.
	self.moved = false
	if math.abs(self.x - self.target_x) > 2 then
		self:changeAnimation("walk")
	else
		self:changeAnimation("idle")
		if self.prop then
			print("Using prop...")
			self.prop:use()
			self.prop = nil
		end
	end
	-- Walking.
	if self.animation == "walk" and not self.moved and (self.frame == 1 or self.frame == 3 or self.frame == 5) then
		self.x = self.x + self:getFacing()
		self.moved = true
	end
end
function Player:draw(scale)
	local quad = Game.quads.player[self.animation][self.frame]
	local sprite = Game.sprites.player
	local x, y = self:getPosition()
	love.graphics.setColor(255,255,255)
	love.graphics.draw(sprite, quad, (x)*scale, (y)*scale, 0, scale*self:getFacing(), scale, 4)
end

return newPlayer