-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenemy.lua
More file actions
110 lines (72 loc) · 2.23 KB
/
enemy.lua
File metadata and controls
110 lines (72 loc) · 2.23 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
module (..., package.seeall)
local director = require ("director")
local physics = require( "physics" )
local gamestate = require( "gamestate" )
local _H = display.contentHeight
local _W = display.contentWidth
local distance = 400
local pointsPerEnemy = 50
local explosionSound = audio.loadSound("explosion.wav")
local enemiesLayer
function init()
enemiesLayer = display.newGroup()
end
function removeAllEnemies()
for i=1, enemiesLayer.numChildren do
local child = enemiesLayer[i]
if child then
child:removeSelf()
end
end
enemiesLayer:removeSelf()
enemiesLayer = display.newGroup()
end
function new()
local globalLayer = display.newGroup()
globalLayer.name = "enemy"
-- enemy asset
local enemyImage = display.newImage("enemy.png")
globalLayer:insert(enemyImage)
enemyImage.x = 0
enemyImage.y = 0
enemyImage:scale(0.8, 0.8)
-- set random position around the center
local angle = math.random (0, 360)
globalLayer.x = math.cos(angle) * distance + _W/2
globalLayer.y = math.sin(angle) * distance + _H/2
local relativeX = _W/2 - globalLayer.x
local relativeY = _H/2 - globalLayer.y
-- fix for the left quadrant
local newAngle
if(globalLayer.x <= _W/2) then
newAngle = math.deg( math.atan(relativeY/relativeX) + math.pi )
else
newAngle = math.deg( math.atan(relativeY/relativeX) )
end
globalLayer.rotation = newAngle + math.deg(math.pi/2)
physics.addBody(globalLayer, "dynamic", {density = 1.0, friction = 0.3, bounce = 0.2, radius=15})
local forceX = globalLayer.x - _W/2
local forceY = globalLayer.y - _H/2
local enemySpeed = -(math.random(1,20) / 100 )
globalLayer:setLinearVelocity(forceX*enemySpeed, forceY*enemySpeed)
local function onLocalCollision(self, event)
print(event.other.name)
if ( event.phase == "began" ) then
if event.other.name == "projectile" then
event.other:removeSelf()
self:removeSelf()
gamestate.addScore(pointsPerEnemy)
audio.play( explosionSound )
else
if event.other.name == "cannon" then
self:removeSelf()
gamestate.removeHeart()
end
end
end
end
globalLayer.collision = onLocalCollision
globalLayer:addEventListener("collision", globalLayer)
enemiesLayer:insert(globalLayer)
return globalLayer
end