contrib: intro action_nitro, a game for the clibre gamejam 2016
[nit.git] / contrib / action_nitro / src / game / ai.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Smart enemies
16 module ai
17
18 import core
19
20 redef class Enemy
21
22 # Square of the range to shoot at the player
23 fun range2: Float do return 32.0*32.0
24
25 redef fun update(dt, world)
26 do
27 super
28
29 var player = world.player
30 if is_alive and player != null and player.is_alive and can_shoot(world) then
31 # Shoot if possible
32 if player.center.dist2(self.center) < range2 then
33 aim_and_shoot(world, player)
34 end
35 end
36 end
37
38 # Aim to shoot at `target`
39 fun aim_and_shoot(world: World, target: Body)
40 do
41 # TODO aim forward of `moving` target
42 var angle = self.center.atan2(target.center)
43
44 shoot(angle, world)
45 end
46
47 # Go to `target` using jetpack-like movement
48 fun go_to(target: Point3d[Float], displacement: Float) do
49 var sc = center
50 var k = 1.0
51 if target.x < sc.x then
52 inertia.x -= k
53 if inertia.x < -displacement then inertia.x = -displacement
54 else
55 inertia.x += k
56 if inertia.x > displacement then inertia.x = displacement
57 end
58 if target.y < sc.y then
59 inertia.y -= k
60 if inertia.y < -displacement then inertia.y = -displacement
61 else
62 inertia.y += k
63 if inertia.y > displacement then inertia.y = displacement
64 end
65 end
66 end
67
68 redef class JetpackEnemy
69 redef fun update(dt, world)
70 do
71 super
72
73 var player = world.player
74 if is_alive and player != null and player.is_alive and can_shoot(world) then
75 # Move towards player
76 var target = player.center
77 go_to(target, 40.0)
78 end
79 end
80 end
81
82 redef class Boss
83 redef fun range2 do return 64.0*64.0
84 end