-
Notifications
You must be signed in to change notification settings - Fork 29
/
attack.rs
503 lines (458 loc) · 17.2 KB
/
attack.rs
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use std::time::Duration;
use bevy::{
hierarchy::{BuildChildren, Children, DespawnRecursiveExt},
math::{Vec2, Vec3},
prelude::{
default, App, AssetServer, Assets, Bundle, Commands, Component, Entity, EventReader,
Handle, Local, Parent, Plugin, Query, Res, Transform, With, Without,
},
sprite::SpriteBundle,
time::{Time, Timer},
transform::TransformBundle,
};
use bevy_rapier2d::prelude::*;
use iyes_loopless::prelude::*;
use leafwing_input_manager::prelude::ActionState;
use crate::{
animation::{Animation, Facing},
audio::FighterStateEffectsPlayback,
collisions::BodyLayers,
consts::{
self, ATTACK_HEIGHT, ATTACK_LAYER, ATTACK_WIDTH, ITEM_BOTTLE_NAME, ITEM_HEIGHT, ITEM_LAYER,
ITEM_WIDTH, THROW_ITEM_ROTATION_SPEED,
},
input::PlayerAction,
item::item_carried_by_player,
metadata::{FighterMeta, ItemMeta},
movement::{MoveInArc, MoveInDirection, PlayerMovementClamper, Rotate, Target},
state::State,
ArrivedEvent, Enemy, GameState, Player, Stats,
};
pub struct AttackPlugin;
impl Plugin for AttackPlugin {
fn build(&self, app: &mut App) {
app.add_system_set(
ConditionSet::new()
.run_in_state(GameState::InGame)
.with_system(player_projectile_attack)
.with_system(player_throw)
.with_system(player_flop)
.with_system(activate_hitbox)
.with_system(deactivate_hitbox)
.with_system(projectile_cleanup)
.with_system(projectile_tick)
.into(),
)
.add_system(
enemy_attack
.run_in_state(GameState::InGame)
.after("move_to_target"),
);
}
}
#[cfg_attr(feature = "debug", derive(bevy_inspector_egui::Inspectable))]
#[derive(Component)]
pub struct Attack {
pub damage: i32,
}
#[derive(Component)]
pub struct AttackFrames {
pub startup: usize,
pub active: usize,
pub recovery: usize,
}
#[derive(Component)]
pub struct ProjectileLifetime(pub Timer);
#[derive(Bundle)]
pub struct Projectile {
#[bundle]
sprite_bundle: SpriteBundle,
rotate: Rotate,
collider: Collider,
sensor: Sensor,
events: ActiveEvents,
collision_types: ActiveCollisionTypes,
collision_groups: CollisionGroups,
facing: Facing,
move_in_direction: MoveInDirection,
attack: Attack,
attack_timer: ProjectileLifetime,
}
impl Projectile {
pub fn new(
transform: &Transform,
facing: &Facing,
dir: Vec2,
asset_server: &Res<AssetServer>,
) -> Self {
Self {
sprite_bundle: SpriteBundle {
texture: asset_server.load("bottled_seaweed11x31.png"),
transform: Transform::from_xyz(
transform.translation.x,
transform.translation.y,
ATTACK_LAYER,
),
..default()
},
rotate: Rotate {
speed: THROW_ITEM_ROTATION_SPEED,
to_right: !facing.is_left(),
},
collider: Collider::cuboid(ATTACK_WIDTH / 2., ATTACK_HEIGHT / 2.),
sensor: Sensor,
events: ActiveEvents::COLLISION_EVENTS,
collision_types: ActiveCollisionTypes::default() | ActiveCollisionTypes::STATIC_STATIC,
//TODO: define collision layer based on the fighter shooting projectile, load for asset files of fighter which "team" they are on
collision_groups: CollisionGroups::new(BodyLayers::PLAYER_ATTACK, BodyLayers::ENEMY),
facing: facing.clone(),
move_in_direction: MoveInDirection(dir * 300.), //TODO: Put the velocity in a cons,
attack: Attack { damage: 10 },
attack_timer: ProjectileLifetime(Timer::new(Duration::from_secs(1), false)),
}
}
}
#[derive(Bundle)]
pub struct ThrownItem {
#[bundle]
sprite_bundle: SpriteBundle,
rotate: Rotate,
move_in_arc: MoveInArc,
collider: Collider,
sensor: Sensor,
events: ActiveEvents,
collision_types: ActiveCollisionTypes,
collision_groups: CollisionGroups,
attack: Attack,
}
impl ThrownItem {
pub fn new(
angles: (f32, f32),
position: Vec2,
facing: Facing,
asset_server: &AssetServer,
) -> Self {
Self {
sprite_bundle: SpriteBundle {
texture: asset_server.load("bottled_seaweed11x31.png"),
transform: Transform::from_xyz(position.x, position.y, ITEM_LAYER),
..default()
},
rotate: Rotate {
speed: consts::THROW_ITEM_ROTATION_SPEED,
to_right: !facing.is_left(),
},
move_in_arc: MoveInArc {
//TODO: Set in consts
radius: Vec2::new(
50.,
consts::PLAYER_HEIGHT + consts::THROW_ITEM_Y_OFFSET + consts::ITEM_HEIGHT,
),
speed: consts::THROW_ITEM_SPEED,
angle: angles.0,
end_angle: angles.1,
inverse_direction: facing.is_left(),
origin: position,
},
collider: Collider::cuboid(ITEM_WIDTH / 2., ITEM_HEIGHT / 2.),
sensor: Sensor,
events: ActiveEvents::COLLISION_EVENTS,
collision_types: ActiveCollisionTypes::default() | ActiveCollisionTypes::STATIC_STATIC,
//TODO: define collision layer based on the fighter throwing the item, load for asset files of fighter which "team" they are on
collision_groups: CollisionGroups::new(BodyLayers::ITEM, BodyLayers::ENEMY),
attack: Attack {
damage: consts::THROW_ITEM_DAMAGE,
},
}
}
}
fn player_projectile_attack(
player_query: Query<
(
&Children,
&Transform,
&Facing,
&State,
&ActionState<PlayerAction>,
),
With<Player>,
>,
items_meta_query: Query<&Handle<ItemMeta>>,
items_meta: Res<Assets<ItemMeta>>,
mut commands: Commands,
asset_server: Res<AssetServer>,
) {
for (player_children, transform, facing, state, input) in player_query.iter() {
if *state != State::Idle && *state != State::Running {
continue;
}
let carried_item = item_carried_by_player(
player_children,
ITEM_BOTTLE_NAME,
&items_meta_query,
&items_meta,
);
if let Some(bottle_id) = carried_item {
if input.just_pressed(PlayerAction::Shoot) {
let mut dir = Vec2::X;
if facing.is_left() {
dir = -dir;
}
let projectile = Projectile::new(transform, facing, dir, &asset_server);
commands.spawn_bundle(projectile);
commands.entity(bottle_id).despawn();
}
}
}
}
fn player_throw(
mut commands: Commands,
player_query: Query<
(
&Children,
&Transform,
Option<&Facing>,
&ActionState<PlayerAction>,
),
With<Player>,
>,
items_meta_query: Query<&Handle<ItemMeta>>,
items_meta: Res<Assets<ItemMeta>>,
asset_server: Res<AssetServer>,
) {
for (player_children, transform, facing_option, input) in player_query.iter() {
let carried_item = item_carried_by_player(
player_children,
ITEM_BOTTLE_NAME,
&items_meta_query,
&items_meta,
);
if let Some(bottle_id) = carried_item {
if input.just_pressed(PlayerAction::Throw) {
let facing = match facing_option {
Some(f) => f.clone(),
None => Facing::Right,
};
let mut position = transform.translation.truncate();
//Offset the position depending on the facing
if facing.is_left() {
position.x -= consts::THROW_ITEM_X_OFFSET;
} else {
position.x += consts::THROW_ITEM_X_OFFSET;
}
position.y -= consts::PLAYER_HEIGHT / 2.; //Set to the player feet
let angles = match facing {
Facing::Left => (90. - consts::THROW_ITEM_ANGLE_OFFSET, 180.),
Facing::Right => (90. + consts::THROW_ITEM_ANGLE_OFFSET, 0.),
};
let thrown_item = ThrownItem::new(angles, position, facing, &asset_server);
commands.spawn_bundle(thrown_item);
commands.entity(bottle_id).despawn()
}
}
}
}
fn player_flop(
mut commands: Commands,
mut query: Query<
(
Entity,
&mut State,
&mut Transform,
&Stats,
&Animation,
&Facing,
&ActionState<PlayerAction>,
&Handle<FighterMeta>,
),
With<Player>,
>,
player_movement_clamper: PlayerMovementClamper,
fighter_assets: Res<Assets<FighterMeta>>,
time: Res<Time>,
mut start_y: Local<Option<f32>>,
) {
let players_movement = query
.iter_mut()
.map(
|(entity, mut state, transform, stats, animation, facing, input, fighter_meta)| {
if *state != State::Attacking {
if !(*state != State::Idle && *state != State::Running)
&& input.just_pressed(PlayerAction::FlopAttack)
{
state.set(State::Attacking);
let attack_entity = commands
.spawn_bundle(TransformBundle::default())
.insert(Sensor)
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(
ActiveCollisionTypes::default()
| ActiveCollisionTypes::STATIC_STATIC,
)
.insert(CollisionGroups::new(
BodyLayers::PLAYER_ATTACK,
BodyLayers::ENEMY,
))
.insert(Attack {
damage: stats.damage,
})
.insert(AttackFrames {
startup: 0,
active: 3,
recovery: 4,
})
.id();
commands.entity(entity).push_children(&[attack_entity]);
//TODO: define hitbox size and placement through resources
//maybe move audio effects?
if let Some(fighter) = fighter_assets.get(fighter_meta) {
if let Some(effects) = fighter.audio.effect_handles.get(&state) {
let fx_playback =
FighterStateEffectsPlayback::new(*state, effects.clone());
commands.entity(entity).insert(fx_playback);
}
}
// commands.
// commands.entity(entity)
}
(transform.translation, None)
} else {
let mut movement = Vec2::ZERO;
//TODO: Replace with movement intent eventwriter in movement rewrite!
//TODO: Fix hacky way to get a forward jump
if animation.current_frame < 3 {
if facing.is_left() {
movement.x -= 200. * time.delta_seconds();
} else {
movement.x += 200. * time.delta_seconds();
}
}
// For currently unclear reasons, the first Animation frame may run for less Bevy frames
// than expected. When this is the case, the player jumps less then it should, netting,
// at the end of the animation, a slightly negative Y than the beginning, which causes
// problems. This is a workaround.
//
if start_y.is_none() {
*start_y = Some(transform.translation.y);
}
if animation.current_frame < 1 {
movement.y += 180. * time.delta_seconds();
} else if animation.current_frame < 3 {
movement.y -= 90. * time.delta_seconds();
} else if animation.is_finished() {
movement.y = start_y.unwrap();
*start_y = None;
}
(transform.translation, Some(movement))
}
},
)
.collect::<Vec<_>>();
let players_movement = player_movement_clamper.clamp(players_movement);
for ((_, _, mut transform, _, _, _, _, _), player_dir) in query.iter_mut().zip(players_movement)
{
if let Some(player_dir) = player_dir {
transform.translation += player_dir.extend(0.);
}
}
}
fn enemy_attack(
mut query: Query<
(Entity, &mut State, &Facing, &Handle<FighterMeta>),
(With<Enemy>, With<Target>),
>,
mut event_reader: EventReader<ArrivedEvent>,
mut commands: Commands,
fighter_assets: Res<Assets<FighterMeta>>,
) {
for event in event_reader.iter() {
if let Ok((entity, mut state, facing, fighter_handle)) = query.get_mut(event.0) {
if *state != State::Attacking {
if rand::random() && *state != State::Waiting {
state.set(State::Waiting);
} else {
state.set(State::Attacking);
//TODO: remove this offset in favor of offsets defined in fighter assets
let offset = match facing {
Facing::Left => -24.0,
Facing::Right => 24.0,
};
let attack_entity = commands
.spawn_bundle(TransformBundle::from_transform(
Transform::from_translation(Vec3::new(offset, 0.0, 0.0)),
))
.insert(Sensor)
.insert(ActiveEvents::COLLISION_EVENTS)
.insert(
ActiveCollisionTypes::default() | ActiveCollisionTypes::STATIC_STATIC,
)
.insert(CollisionGroups::new(
BodyLayers::ENEMY_ATTACK,
BodyLayers::PLAYER,
))
.insert(Attack { damage: 10 })
.insert(AttackFrames {
startup: 1,
active: 2,
recovery: 3,
})
.id();
commands.entity(event.0).push_children(&[attack_entity]);
if let Some(fighter) = fighter_assets.get(fighter_handle) {
if let Some(effects) = fighter.audio.effect_handles.get(&state) {
let fx_playback =
FighterStateEffectsPlayback::new(*state, effects.clone());
commands.entity(entity).insert(fx_playback);
}
}
}
}
}
}
}
fn activate_hitbox(
attack_query: Query<(Entity, &AttackFrames, &Parent), Without<Collider>>,
fighter_query: Query<&Animation, With<State>>,
mut commands: Commands,
) {
for (entity, attack_frames, parent) in attack_query.iter() {
if let Ok(animation) = fighter_query.get(**parent) {
if animation.current_frame >= attack_frames.startup
&& animation.current_frame <= attack_frames.active
{
//TODO: insert Collider based on size and transform offset in attack asset
commands
.entity(entity)
.insert(Collider::cuboid(ATTACK_WIDTH * 0.8, ATTACK_HEIGHT * 0.8));
}
}
}
}
fn deactivate_hitbox(
query: Query<(Entity, &AttackFrames, &Parent), (With<Attack>, With<Collider>)>,
fighter_query: Query<&Animation, With<State>>,
mut commands: Commands,
) {
for (entity, attack_frames, parent) in query.iter() {
if let Ok(animation) = fighter_query.get(**parent) {
if animation.current_frame >= attack_frames.recovery {
commands.entity(entity).despawn_recursive();
}
}
}
}
fn projectile_cleanup(
query: Query<(Entity, &ProjectileLifetime), With<Attack>>,
mut commands: Commands,
) {
for (entity, timer) in query.iter() {
if timer.0.finished() {
commands.entity(entity).despawn_recursive();
}
}
}
fn projectile_tick(mut query: Query<&mut ProjectileLifetime, With<Attack>>, time: Res<Time>) {
for mut timer in query.iter_mut() {
timer.0.tick(time.delta());
}
}