-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaser-cannon.lua
101 lines (86 loc) · 2.32 KB
/
laser-cannon.lua
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
-- The laser cannon can move in the X direction with a fixed Y position.
-- Handle health / movement / laser firing.
local Laser = require('laser')
local glo = require('globals')
local screen = glo.screen
local PADDING = 0
local TEXT_PADDING = 20
-- constants
local SPEED = 7
local dir = ""
-- define body rectangle
local hitsTaken = 0
local maxHealth = 3
local body = display.newRect(screen.xCenter, display.contentHeight + 20, 40, 20)
body.isCannon = true
physics.addBody(body,"kinematic")
function body.onCollision(event)
hitsTaken = hitsTaken + 1
print(hitsTaken)
if hitsTaken > maxHealth then
print("Dead")
end
if hitsTaken > maxHealth then
lifeCounter.text = "GAME OVER!"
else
lifeCounter.text = "Lives: "..maxHealth - hitsTaken
end
end
lifeCounter = display.newText{
text = "Lives: "..maxHealth - hitsTaken,
x = glo.screen.xMax - glo.screen.xCenter/3 - TEXT_PADDING,
y = glo.screen.yMin + TEXT_PADDING,
font = native.systemFont,
fontSize = 20,
}
local function move(direction)
dir = direction
end
local function updateMovement()
if dir == "left" and body.x > body.width / 2 then
body.x=body.x-SPEED
elseif dir == "right" and body.x < screen.width - body.width / 2 then
body.x=body.x+SPEED
end
end
local function moveLeft(event)
if event.phase == "began" then
move("left")
elseif event.phase == "ended" then
move("")
end
end
local function moveRight(event)
if event.phase =="began" then
move("right")
elseif event.phase == "ended" then
move("")
end
end
function shootUp(event)
if event.phase == 'began' then
local l = Laser:new(body.x, body.y - body.height - PADDING, "up")
l:fire()
end
end
--shootUp()
function keyPress(event)
if event.phase == "down" then
if event.keyName == "up" or event.keyName == "space" then
local l = Laser:new(body.x, body.y - body.height - PADDING, "up")
l:fire()
else
move(event.keyName)
end
elseif event.phase == "up" then
move("")
end
end
-- attach the movement function to it's corresponding button in the 'buttons' api.
local buttons = require("buttons")
buttons.left_arrow:addEventListener("touch", moveLeft)
buttons.right_arrow:addEventListener("touch", moveRight)
Runtime:addEventListener("key", keyPress)
Runtime:addEventListener("enterFrame", updateMovement)
-- TODO:
-- Add keyboard functionality to make testing/playing on a computer easier.