-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplayer.lua
More file actions
133 lines (72 loc) · 2.52 KB
/
player.lua
File metadata and controls
133 lines (72 loc) · 2.52 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
Player = Object:extend()
function Player:new()
self.x = love.graphics.getWidth() / 2
self.y = love.graphics.getHeight() / 2
self.speed = 250
self.radius = 25
self.holdingBox = nil
end
function Player:update(dt, boxes)
local oldX = self.x
local oldY = self.y
if love.keyboard.isDown("w") then
self.y = self.y - self.speed * dt
end
if love.keyboard.isDown("s") then
self.y = self.y + self.speed * dt
end
if love.keyboard.isDown("d") then
self.x = self.x + self.speed * dt
end
if love.keyboard.isDown("a") then
self.x = self.x - self.speed * dt
end
-- Prevent the player from moving off the screen
if self.x - self.radius < 0 then
self.x = self.radius
elseif self.x + self.radius > love.graphics.getWidth() then
self.x = love.graphics.getWidth() - self.radius
end
if self.y - self.radius < 0 then
self.y = self.radius
elseif self.y + self.radius > love.graphics.getHeight() then
self.y = love.graphics.getHeight() - self.radius
end
-- Check for collisions and handle box pickup
if love.keyboard.isDown("space") and self.holdingBox == nil then
self:pickUpBox(boxes)
end
-- Collision
for i, box in ipairs(boxes) do
if self.holdingBox ~= box and circleRectangleCollision({x = self.x, y = self.y, radius = self.radius}, box) then
self.x = oldX
self.y = oldY
break
end
end
-- Make the box follow the player when it's being held
if self.holdingBox ~= nil then
self.holdingBox.x = self.x - self.holdingBox.width / 2
self.holdingBox.y = self.y - self.holdingBox.height / 2
end
end
function Player:pickUpBox(boxes)
for i, box in ipairs(boxes) do
if circleRectangleCollision({x = self.x, y = self.y, radius = self.radius}, box) then
self.holdingBox = box
table.remove(boxes, i)
break
end
end
end
function Player:draw()
love.graphics.circle("line", self.x, self.y, self.radius)
if self.holdingBox ~= nil then
self.holdingBox:draw()
end
end
function circleRectangleCollision(circle, rect)
local dx = circle.x - math.max(rect.x, math.min(circle.x, rect.x + rect.width))
local dy = circle.y - math.max(rect.y, math.min(circle.y, rect.y + rect.height))
return (dx * dx + dy * dy) < (circle.radius * circle.radius)
end