-
Notifications
You must be signed in to change notification settings - Fork 2
/
EnemyBehaviour.cs
2184 lines (1726 loc) · 86.9 KB
/
EnemyBehaviour.cs
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEditor;
using UnityEngine;
using NaughtyAttributes;
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(EnemyPathfinder))]
public class EnemyBehaviour : MonoBehaviour, IDamageable
{
//Instead of const int, you should use enum, stupid! Not to mention you can choose an enumeration from the inspector instead of putting a memorized number smh!
const int Hollow = 0, Centaur = 1, Satyr = 2, Minotaur = 3, Harpy = 4, Cyclops = 5, Unknown = 6, Hollow2 = 7, Centaur2 = 8, Satyr2 = 9, Minotaur2 = 10, Harpy2 = 11, Cyclops2 = 12, Unknown2 = 13;
[Tooltip("So monster-exclusive behaviours are defined.")]//Used super rarely lmao.
public int monsterType;
[Header("Actions")]
[ReorderableList]
[Tooltip("The possible attacks this monster can perform")]
public List<BaseEnemyAttack> possibleAttacks = new List<BaseEnemyAttack>();
[Header("Float values")]
[Tooltip("How fast this enemy moves")]
public float movementSpeed;
public float currentMovementSpeed;
[MinValue(0f)]
[Tooltip("In what range the enemy can detect you")]
public float SightRange;
[Range(0, 100)]
[Tooltip("How much %chance, for this enemy to chase/move towards obstructed player, instead of standing")]
public int ChaseObstructedPlayerChance;
[Header("OnTakenDamage Properties")]
[MinValue(0f)]
[Tooltip("For how long after an hit, this monster/enemy cannot act")]
public float hitRecoveryTime;
[Tooltip("The movement multiplier while hit")]
public float hitMovementMultiplier;
[Tooltip("When player jumps right atop this, for how long should hitstun play?")]
public float hitstunPlayerStompsDuration;
[Tooltip("When enemy lands right above player, for how long should hitstun play on the player?")]
public float hitstunStompPlayerDuration;
[Tooltip("When enemy lands right above player, how much power should he apply?")]
public int stompKnockbackPower;
[Tooltip("When player attacks this enemy, how much mana should he take?\n0 is default.")]
public int giveManaOnHit = 0;
[Tooltip("When player kills this enemy, how much mana should he take?\n1 is default.")]
public int giveManaOnDeath = 1;
[Header("Misc")]
[ValidateInput("IsLayerMaskEmpty")]
[Tooltip("Upon jumping, what should the raycast detect to say \"Hey, what i detected is ground! Now, jump is over.\"?")]
public LayerMask WhatIsGround;
[Tooltip("When midair, what force is applied downwards? Literally addForce(vector2.down * midairGravity) xD")]
public float midairGravity;
[Tooltip("Can it in any case, rotate? Like, act like a spinning ball/sphere?")]
public bool canRotate = false;
[Tooltip("Is this a flying enemy/monster?")]
public bool canFly = false;
[ShowIf("CanFly")]
public float movementSpeedY = 0f;
[ShowIf("CanFly")]
public float currentMovementSpeedY;
[MinValue(1)]
[Tooltip("How often per second, the A.I. updates, when in sight range.")]
public int activeRefreshRate;
[MinValue(1)]
[Tooltip("How often per second, the A.I. updates, when NOT in sight range.\nShould be bigger than active.")]
public int passiveRefreshRate;
[MinValue(0f)]
[Tooltip("When is \"almost\" touching the player, so it stops?")]
public float playerTouchRange;
//Properties, mandatory, since interface IDamageable demands them, and Unity doesn't play well with properties.
[Header("Health")]
[SerializeField]
private int maxHealth;
public int MaxHealth
{
get { return maxHealth; }
set
{
if (value < 1) Debug.Log("Cannot be negative or 0, watcha doin?");
else maxHealth = value;
}
}
[SerializeField]
private int currentHealth;
public int CurrentHealth
{
get { return currentHealth; }
set { currentHealth = value; }
}
//"common" adjective/prefix means that the gameobject that "hosts" this component, also "hosts" other components.
//All these components, are common, like Rigidbody2D.
//Common Caching
private Rigidbody2D commonRigidbody;
//[Tooltip("If it should jump, this shouldn't be empty. It literally contains the jump and all its configurations.")]
[HideInInspector]
public EnemyJump jumpAction;//Would rename it to commonJump, but dependencies are established.
//private WarriorMovement warriorBehaviour;
//NO! use commonColider, then collider.bounds.size, you fool!//I think .extents is actually half so it saves 1 calculation.
//private SpriteRenderer commonRenderer;
//Where enemy/this spawned
private Vector3 originPosition;
//Caching
//Self-explanatory
//private Vector3 warriorPosition;
[Header("Read-Only/Debugging")]
//From pathfinding/waypoint distance
[ReadOnly]
[SerializeField]
private Vector2 directionToPlayer;
[ReadOnly]
[SerializeField]
//to check which actions (attack/jump has range)
private float distanceFromPlayer;
[ReadOnly]
[SerializeField]
//IsPlayer behind "Ground"
private bool isPlayerObstructed;
[ReadOnly]
[SerializeField]
//IsPlayer behind hazard?
private bool isPathfindingHazardous;
[ReadOnly]
[SerializeField]
//IsPlayer atop a platform?
private bool isPlayerOnPlatform;
[ReadOnly]
[SerializeField]
//Is origin position blocked/obstructed?
private bool isOriginPositionObstructed = true;
//If the enemy/this that has this script attached, has an <EnemyAttack>
private bool hasAttackAction;
[ReadOnly]
//Is doing an attack, so do not interrupt :D
public bool isAttacking = false;
[ReadOnly]
//Is moving, interrupt freely btw, made for FixedUpdate()
public bool isMoving;
[ReadOnly]
//So as to detect ground without raycasts, and to help with the artificial "gravity"(not Unity's) and also the EnemyJump(so as it won't jump in midair)
public bool isGrounded;
[ReadOnly]
//So it won't go to origin position, if it is already there ;)
public bool isOnOriginPosition;
[ReadOnly]
//Is jumping, so do not interrupt :D
public bool isJumping = false;
[ReadOnly]
[SerializeField]
//So FixedUpdate wont fuck shit up!
public bool isDying;
//30% RNG
[ReadOnly]
public bool chasesObstructions;
[ReadOnly]
[SerializeField]
//If taken damage, so nothing happens for a while
private bool isHit;
[ReadOnly]
//Stores the new hp
public int playerKillerHP = 0;
[ReadOnly]
public GameObject PlayerKillerVFX = null;
[ReadOnly]
public float timeToDeathFreeze = 0.4f;
[ReadOnly]
public float currentTimeToDeathFreeze;
[ReadOnly]
public float currentHitMovementMultiplier;
[ReadOnly]
[Tooltip("Gotta cache the player but not on start otherwise CPU burst. Cache should happen when monster dies")]
public bool playerCollidersCached = false;
[ReadOnly]
[Tooltip("When dead, ignore player.")]
public bool playerCollidersIgnored = false;
[ReadOnly]
[Tooltip("In LevelManager.enemyList")]
public ushort enemyListIndex;
private BoxCollider2D boxPlayerCollider; //Body(Top&Mid)
private CircleCollider2D circlePlayerCollider; //Feet(Bottom)
[ReadOnly]
[Tooltip("Made to excuse my shitty physics detection, so the wall is detected, registered, and then no X velocity will be applied, WHILE MIDAIR!\nLiterally a flag oncollision enter/exit.")]//?
public bool sideWallDetected = false;
[ReadOnly]
public GameObject sideWall;
[ReadOnly]
public int satyrBugfixJumpRight = 0;
private GameObject sidePlatformIgnored;
private Collider2D commonCollider;
//For lerp
private float currentHitTime;
//Used in OnColliderExit for raycasting
private float colliderExtent;
[ReadOnly]
[SerializeField]
//Direction enemy/this is facing
private bool facingRight = true;
//Current attack being used
private BaseEnemyAttack currentAttack;
//Made to find origin of player hit, so this/enemy will be applied force from it.
[ReadOnly]
[SerializeField]
private Vector3 directionHit;
//Calculates the direction to originPos
Vector3 directionToOriginPos;
[ReadOnly]
[SerializeField]
//Boolean that stores when player is midair, subscribed event changes this.
private bool playerIsMidair = false;
[ReadOnly]
[SerializeField]
//Spagghetti but to explain: Each time a dying enemy is hit, it resets the Invoke() function, so I won't have to keep timer for every monster. If hit once, and it reaches DeathFreeze/died.Invoke(), it checks deathreset, if 0, it works, otherwise it decreases by 1 and waits for next Invoke("DeathFreeze").
private int deathResets = 0;
[ReadOnly]
[SerializeField]
//The simple and most elegant way of checking if a coroutine is running/active.
private bool coroutineRunning;
//Indicates current refresh rate, is either active or passive btw.
private int currentRefreshRate;
//On FixedUpdate, stores the last known position.
//private Vector3 lastPosition;
//State-Machine (for animations lel)//Setup animations should be at 4+. Hardcoded even when enum'd hellodarknessmyoldfriend~
public const int IDLE = 0, RUN = 1, MELEE_ATTACK = 2, RANGED_ATTACK = 3, RAM_ATTACK = 4, MELEE_ATTACK2 = 5, MELEE_ATTACK_CHARGE = 6, RANGED_ATTACK_CHARGE = 7, RAM_ATTACK_CHARGE = 8, MELEE_ATTACK2_CHARGE = 9, HITGROUND = 10, HITMIDAIR = 11, JUMP_CHARGE = 12, JUMP = 13, FALLING = 14, DEATH = 15;
[ReadOnly]
public int currentAnimationState;
[ReadOnly]
public int targetAnimationState;
[HideInInspector]
public Animator animatorController;
//This action, is subscribed by EnemyPathfinder, so I can simply invoke this, and DeathFreeze works.
public Action died;
public static Action<ushort> playerKillerEvent;
//FLYING-ONLY (also bad design but yolo at this point)
//////////////////////
[ReadOnly]
[SerializeField]
private int flyingObstructionType;
enum flyingObstructionDirection { NONE, TOPRIGHT, TOPLEFT, BOTTOMRIGHT, BOTTOMLEFT };
private HarpyAuraAttack commonAura;
//RaycastHit2D hit;//To check if hazard when player obstructed when the shitty pseudo-pathfinding algorithm happens
///////////////////
//Initialization for itself.
private void Awake()
{
//commonPathfinder = GetComponent<EnemyPathfinder>();
commonRigidbody = GetComponent<Rigidbody2D>();
animatorController = GetComponentInChildren<Animator>();
//animatorController = transform.FindChild("SpriteVisible").GetComponent<Animator>();//mfw im using string to access children. 2 fucking children and using string instead of an int. smh.
//commonRenderer = GetComponent<SpriteRenderer>();
//Attach the jump action manually ;)
if (GetComponent<EnemyJump>() != null)
jumpAction = GetComponent<EnemyJump>();
//aka, has it collided with any Ground gameobject? :P
isGrounded = false;
//Set origin position, so it can go there when player is away, and to revive there
originPosition = transform.position;
currentTimeToDeathFreeze = timeToDeathFreeze;
currentHitMovementMultiplier = hitMovementMultiplier;
currentMovementSpeed = movementSpeed;
currentMovementSpeedY = movementSpeedY;
commonCollider = GetComponent<Collider2D>();
commonAura = GetComponentInChildren<HarpyAuraAttack>();
//ChaseObstructedPlayerChance% RNG to chase players when obstructed
if (UnityEngine.Random.Range(0, 100) < ChaseObstructedPlayerChance)
chasesObstructions = true;
else
chasesObstructions = false;
//Freeze rotation, so no rotation change on landing, messing up the grounded+animations, or on attack!
if (!canRotate)
commonRigidbody.freezeRotation = true;
//Sets Current Health = MaxHealth
SetStartingHealth();
//Sets variables like bool HasAttackAction, if enemy has any attack, so it won't recalculate a lot
InitializeActionVariables();
coroutineRunning = false;
isOnOriginPosition = true;
//State-Machine(no need to NewStateTransition(), since Idle is default animation.)
currentAnimationState = IDLE;
targetAnimationState = IDLE;
}
//Initialization for others.
void Start()
{
//Subscribe to player's midair status, to detect when player is midair, and when grounded.
GameObject.FindGameObjectWithTag("Player").GetComponent<WarriorMovement>().isMidair += PlayerIsMidair;
GameObject.FindGameObjectWithTag("Player").GetComponent<WarriorMovement>().isGrounded += PlayerIsGrounded;
//warriorBehaviour = GameObject.FindGameObjectWithTag("Player").GetComponent<WarriorMovement<().GetMidair();
//warriorPosition = GameObject.FindGameObjectWithTag("Warrior").transform.position;
//Subscribes the TouchedGround function to EnemyJump.TouchedGround
if (jumpAction != null)
jumpAction.touchedGround.AddListener(TouchedGround);
if (!coroutineRunning)
StartCoroutine(UpdateBehaviour());
}
/*
private void Update()
{
//Debug.Log(commonRigidbody.velocity);
//Debug.Log("Distance from player is: " + distanceFromPlayer);
//DisplayVisionHitbox();
//Debug.Log("IsGrounded? " + isGrounded);
/*
if (isGrounded)
{
Debug.Break();
//Prints the dictionary
foreach (KeyValuePair<int, GameObject> kvp in currentGroundCollisions)
{
Debug.Log("Unique ID is: " + kvp.Key + " and name is: " + kvp.Value.name);
}
}
* /
//Debug.Log("Is on origin position? " + isOnOriginPosition);
//Debug.Log("Is attacking? " + isAttacking + " Is jumping? " + isJumping);
//Debug.Log("The force in Y applied is: ");// + rigidbody2D.speed or whatever.<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
*/
public IEnumerator UpdateBehaviour()
{
coroutineRunning = true;
//Loops so it restarts after 1/RefreshRate seconds :D
while (coroutineRunning)
{
//If online and client, dont do any logic
if (NetworkCommunicationController.globalInstance != null && NetworkCommunicationController.globalInstance.IsServer() == false && NetworkDamageShare.globalInstance.IsSynchronized())
{//Hack, which exits the coroutine entirely.
coroutineRunning = false;
continue;
}
//Determines the refresh rate.
if (distanceFromPlayer < SightRange)
currentRefreshRate = activeRefreshRate;
else
currentRefreshRate = passiveRefreshRate;
//Monster/Enemy is attacking, so no further A.I. calculations needed (or is hit rn, so it doesnt matter)
while (isAttacking || isHit)
yield return new WaitForSeconds(1 / (currentRefreshRate + 1));
//Debug.Log("Distance from player is: " + distanceFromPlayer);
//If enemy "detects" player
if (distanceFromPlayer < SightRange)//warrior health, used so the monsters go back to originPosition when player dead.
{
if (WarriorHealth.dying)
{
//VICTORY TAUNT PLZ!//Cut feature, rip. After release....
StandStill();
yield return new WaitForSeconds(4);
}
if (isPathfindingHazardous)
{
//Maybe a midair check?
isMoving = true;
//and with isPathfindingHazardous at movement, it will go back to originPos ;)
}
else if (isPlayerObstructed)//Ground
{
if (canFly)//Obstruction A.I. is adjusted in FixedUpdate movement.
isMoving = true;
else if (chasesObstructions)//&& warriorIsMidair)//this is usually 30% (from Start)
{
//Debug.Log(directionToPlayer);
//If upwards, jump (everything except the direction.y condition, is copy-pasta'd)
if (directionToPlayer.y > 0.05f && directionToPlayer.y < 0.8f && !isJumping && isGrounded && jumpAction != null && !jumpAction.onCooldown && jumpAction.jumpRange > distanceFromPlayer)
{
TriggerJumpAction();
yield return new WaitForSeconds(jumpAction.castingTime);//So as not to move while charging jump, but I should just have another boolean here ah well
}
//If downwards, can probably run over there.
else if (directionToPlayer.y < -0.1f)
//Will run towards the player
isMoving = true;
else
StandStill();
}
else if (!isJumping)
StandStill();
}
else//Normal = No obstructions/hazards
{
if (canFly)
{
if (hasAttackAction)
DetermineAttackStart();//True means it checks for ranged attacks only
if (!isAttacking)
{
if (playerTouchRange > distanceFromPlayer)//So he won't push the player.
StandStill();
else
isMoving = true;
}
}
else if (playerIsMidair || isPlayerOnPlatform)//(false -> warriorIsMidair)
{
//Debug.Log("Is player midair: " + playerIsMidair + " is player on platform? " + isPlayerOnPlatform);
//TODO: I think it should check if jumpAction has rising/falling, so it can be considered an attack.
//If can do any attack
if (hasAttackAction && isGrounded && !isJumping)//maybe remove isJumping? idk
DetermineAttackStart();
if (!isAttacking)//&& !isjumping, instead of being put below.<--- old one
{
//To jump or not to jump?
if (!isJumping && isGrounded && jumpAction != null && !jumpAction.onCooldown && jumpAction.jumpRange > distanceFromPlayer)
{
TriggerJumpAction();
yield return new WaitForSeconds(jumpAction.castingTime);//So as not to move while charging jump, but I should just have another boolean here ah well
}
else if (!isJumping)
{
isMoving = false;//StandStill() here bugs it, so isMoving = false -> FixedUpdate it does the state transition there.
//StandStill();
//So monster won't look same direction even if player passes right above... it looks like monster is retarded. (And player notices the braindead A.I. xd)
if (directionToPlayer.x < 0 && facingRight)
FlipSprite();
else if (directionToPlayer.x > 0 && facingRight == false)
FlipSprite();
}
}
}
else//Player on the ground or same terrain
{
//If can do any attack
if (hasAttackAction && isGrounded && !isJumping)
DetermineAttackStart();
//Jump
if (!isAttacking && !isJumping && isGrounded && jumpAction != null && !jumpAction.onCooldown && jumpAction.jumpRange > distanceFromPlayer)
{
TriggerJumpAction();
yield return new WaitForSeconds(jumpAction.castingTime);//So as not to move while charging jump, but I should just have another boolean here ah well
}
//If not attack -> Move (except if super small range so it wont push player or w/e)
if (!isAttacking)
{
if (playerTouchRange > distanceFromPlayer)//So he won't push the player.
StandStill();
else
isMoving = true;
}
}
}
}
else//Go back to origin position (if not, stand still)
{
//Debug.Log("Player out of sight, origin position obstructed? " + isOriginPositionObstructed);
//Debug.Log("is on origin? " + isOnOriginPosition + "is obstructed? " + isOriginPositionObstructed);
if (!isOnOriginPosition && !isOriginPositionObstructed)
{
//isMoving = true, in FixedUpdate moves enemy to either target or originPosition
//It goes to originPosition when out of sight, so with this it automatically goes to originPos ;)
isMoving = true;
}
else
StandStill();//Original is line below. No bugs, this just seems better.
//isMoving = false;
}
yield return new WaitForSeconds(1 / currentRefreshRate);
}
}
//Flawed like so many things in this project. It uses only RangeX, but what if the condition is something else? rangeY is the simplest example.
public void DetermineAttackStart(bool exclusivelyRanged = false, bool exclusivelyRam = false, bool exclusivelyMelee = false)//Instead of exclusive, should work with inclusive/possible types. That way, its far easier/better, and you can use "exclusive" attacks, by including only one type.
{
bool attackSelected = false;
//Debug.Log("Attack range is: " + possibleAttacks[0].attackRange + " and distance from player is: " + distanceFromPlayer + "ranged attack: " + ranged);
//Loop through all possible attacks, to see which to attack depending on range
foreach (BaseEnemyAttack pickedAttack in possibleAttacks)
{
//Debug.Log("Picked attack[0]'s range is: " + possibleAttacks[0].attackRange);
//Debug.Log("Picked attack[1]'s range is: " + possibleAttacks[1].attackRange);
//if (gameObject.name == "Hollow (24)")
//Debug.Log("Attackboi is: " + pickedAttack.IsPlayerInAttackDistance(distanceFromPlayer));
//Is inside range, ATTACK!
if (pickedAttack.IsPlayerInAttackDistance(distanceFromPlayer) && pickedAttack.onCooldown == false)
{
//Melee Attack
if (exclusivelyRanged == false && exclusivelyRam == false && exclusivelyMelee == false)
{
attackSelected = true;
}
else if (exclusivelyRanged)//Ranged Attack
{
EnemyRangedAttack tempRangedAttack = pickedAttack as EnemyRangedAttack;
if (tempRangedAttack != null && isPlayerObstructed == false)
{
Debug.Log("Ranged attack selected");
attackSelected = true;
}
}
else if (exclusivelyRam)
{
EnemyRamAttack tempRamAttack = pickedAttack as EnemyRamAttack;
if (tempRamAttack != null)
{
Debug.Log("Ram attack selected");
attackSelected = true;
}
}
else if (exclusivelyMelee)
{
EnemyMeleeAttack tempMeleeAttack = pickedAttack as EnemyMeleeAttack;
if (tempMeleeAttack != null)
{
Debug.Log("Melee attack selected");
attackSelected = true;
}
}
}
//Attack is pickedAttack!
if (attackSelected)
{
TriggerBaseEnemyAttack(pickedAttack);
break;//Returning otherwise it does starts all attacks that are possible within range aylmao
}
}
}
public void TriggerBaseEnemyAttack(BaseEnemyAttack attackToUse)
{
//Debug.Log("Picked attack that got chosen has " + attackToUse.attackRange + " range, and distance from player is: " + distanceFromPlayer);
isAttacking = true;
isMoving = false;
if (canFly == false)
DetermineFlipSprite(directionToPlayer.x);
if (!canFly)
commonRigidbody.velocity = new Vector2(0, commonRigidbody.velocity.y);
else
commonRigidbody.velocity = new Vector2(commonRigidbody.velocity.x, commonRigidbody.velocity.y);//used to be 0,0
currentAttack = attackToUse;
attackToUse.StartAttack();
}
public void TriggerJumpAction()
{
//Woulda make a JumpFunction, but it must be IEnumerator aylmao.
jumpAction.StartJump();//Also sets isJumping -> true
//Otherwise, it "glides", could work for flame level tbh.
isMoving = false;
commonRigidbody.velocity = new Vector2(0f, commonRigidbody.velocity.y);//"Resets" velocity.
}
public void FixedUpdate()
{
if (NetworkCommunicationController.globalInstance != null && NetworkCommunicationController.globalInstance.IsServer() == false && NetworkDamageShare.globalInstance.IsSynchronized())
return;
//Debugging spagghetti, apologies. To explain: Monster is still in Falling animation "sliding in ground" while he is actually in an other state like run/idle.
if (animatorController.GetCurrentAnimatorStateInfo(0).IsName("Falling") && isGrounded)// && isJumping)
{
//jumpAction.JustTouchedGround();
animatorController.Play("Idle");
currentAnimationState = IDLE;
}
//So if dead, it won't try to use physics or whatever.
if (isDying)
{
if (!canFly)
commonRigidbody.velocity = new Vector2(-200 * directionToPlayer.x * currentMovementSpeed / 100, commonRigidbody.velocity.y);//-1 is for opposite of player, 100 is for death to have more impact. 100 shouldn't be hardcoded tho but anyway GOTTA CODE FAST!
else
commonRigidbody.velocity = new Vector2(-200 * directionToPlayer.x * currentMovementSpeed / 100, -200 * directionToPlayer.y * currentMovementSpeedY / 100);
return;
}
//So gravity applies normally
if (!isGrounded && !canFly)
commonRigidbody.AddForce(Vector2.down * midairGravity);
//Rotation for flying: Ignored for now, it can work if you uncomment the below, the rotation in NewStateTransition, and in movement(isMoving&velocity), NEW&Final, everytime the facing changes, adjust rotation as well.
/*
if (canRotate && canFly)
{
if (transform.localEulerAngles.z > 45f || transform.localEulerAngles.z < -45f)
{
if (isMoving)
{
if (transform.localEulerAngles.z > 45f)
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, 45f);
else
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, -45f);
}
else
transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, 0f);
commonRigidbody.freezeRotation = true;
commonRigidbody.freezeRotation = false;
}
}
*/
//So it never "rotates"
/* Fixed on Awake via freezeRotation
if (!canRotate && (int)transform.localEulerAngles.z != 0)
//transform.Rotate(0, 0, transform.localEulerAngles.z * -1);
transform.localEulerAngles = Vector3.zero;
//Debug.Log ((int)transform.localEulerAngles.z);
*/
//Apply forces depending on state
if (isHit)
{
currentHitTime += Time.fixedDeltaTime;
if (currentHitTime > hitRecoveryTime)
currentHitTime = hitRecoveryTime;
//commonRigidbody.velocity = new Vector2(-1 * directionHit.x * hitMovementMultiplier * Time.deltaTime, commonRigidbody.velocity.y);
//if (!canFly)
commonRigidbody.velocity = new Vector2(-1 * directionHit.x * currentHitMovementMultiplier * Mathf.Lerp(1, 0, currentHitTime / hitRecoveryTime), -1 * directionHit.y * currentHitMovementMultiplier * Mathf.Lerp(1, 0, currentHitTime / hitRecoveryTime));
//else
//commonRigidbody.velocity = new Vector2(-1 * directionHit.x * hitMovementMultiplier * Mathf.Lerp(1, 0, currentHitTime / hitRecoveryTime), -1 * directionHit.y * hitMovementMultiplier * Mathf.Lerp(1, 0, currentHitTime / hitRecoveryTime));
//Debug.Log("The math result is: " + Mathf.Lerp(1, 0, currentHitTime / hitRecoveryTime));
//Debug.Log("Current HitTime is: " + currentHitTime + " and hitRecoveryTime is: " + hitRecoveryTime);
isOnOriginPosition = false;
}
else if (isMoving)//TODO: Cache the direction below, so it checks if its the same, and doesnt change the velocity at all ;)
{
targetAnimationState = RUN;
//Debug.Log((originPosition - transform.position).magnitude);
//Moving towards the player
if (distanceFromPlayer < SightRange && !isPathfindingHazardous)//the hazardous pathfinding, ensures it will go below.
{
if (canFly == false)
{
DetermineFlipSprite(directionToPlayer.x);
#region useless complicated spagghetti
//Unknown spagghetti.
/*
bool switchCondition = true;//so it instantly moves on jump, right after leaving the ground.
bool switchCondition2 = false;//demands is Grounded or isRising.
if (jumpAction != null)
{
if (jumpAction.rising)
{
switchCondition = false;
switchCondition2 = true;
}
else
{
switchCondition = true;
switchCondition2 = false;
}
}*/
/*
bool switchCondition = false;
if (sideWallDetected)
{
switchCondition = true;
if (isGrounded)
switchCondition = true;
else if (jumpAction != null)
{
if (jumpAction.GetIsRising())
switchCondition = true;
}
}
//
if (switchCondition == false)
commonRigidbody.velocity = new Vector2(directionToPlayer.x * currentMovementSpeed, commonRigidbody.velocity.y);
else
commonRigidbody.velocity = new Vector2(0, commonRigidbody.velocity.y);
*/
/*
if (isPlayerObstructed == false)
commonRigidbody.velocity = new Vector2(directionToPlayer.x * currentMovementSpeed, commonRigidbody.velocity.y);
else//if player is obstructed, and downwards.
{
}
*/
//
#endregion
//This satyr if-block, is for a bug, where player can just chill forever above his head.
if (distanceFromPlayer < 4.1f && (monsterType == Satyr || monsterType == Satyr2) && directionToPlayer.y > 0.97f)
{
//Set the direction for the first time
if (satyrBugfixJumpRight == 0)
{
if (UnityEngine.Random.value < 0.5f)
satyrBugfixJumpRight = 1;
else
satyrBugfixJumpRight = -1;
}
commonRigidbody.velocity = new Vector2(satyrBugfixJumpRight * currentMovementSpeed, commonRigidbody.velocity.y);
}
else
{
if (sideWallDetected)//Shouldn't it be sideWallDetected && player on same direction?
commonRigidbody.velocity = new Vector2(0, commonRigidbody.velocity.y);
else
commonRigidbody.velocity = new Vector2(directionToPlayer.x * currentMovementSpeed, commonRigidbody.velocity.y);
}
}
else
{
//If player obstructed, made this block, cuz when player was behind a sharp corner, harpy would hug the edge. Breaks immersion cuz user realizes this A.I. is actually braindead. Shhh.. . its a secret.
if (isPlayerObstructed)
{
//If First-Time
if (flyingObstructionType == (int)flyingObstructionDirection.NONE)
{
//DetermineFlyingObstructionDirection();
//Top-Right
if (directionToPlayer.y > 0.01f && directionToPlayer.x > 0.01f)
{
flyingObstructionType = (int)flyingObstructionDirection.TOPRIGHT;
DetermineFlipSprite(1);
//commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, 1 * currentMovementSpeedY);
}
//Top-Left
else if (directionToPlayer.y > 0.01f && directionToPlayer.x < -0.01f)
{
flyingObstructionType = (int)flyingObstructionDirection.TOPLEFT;
DetermineFlipSprite(-1);
//commonRigidbody.velocity = new Vector2(-1 * currentMovementSpeed, 1 * currentMovementSpeedY);
}
//Bottom-Right
else if (directionToPlayer.y < -0.01f && directionToPlayer.x > 0.01f)
{
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMRIGHT;
DetermineFlipSprite(1);
//commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, -1 * currentMovementSpeedY);
}
//Bottom-Left
else if (directionToPlayer.y < -0.01f && directionToPlayer.x < -0.01f)
{
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMLEFT;
DetermineFlipSprite(-1);
//commonRigidbody.velocity = new Vector2(-1 * currentMovementSpeed, -1 * currentMovementSpeedY);
}
//Edge-cases: direction.x or direction.y are 0.
else if (directionToPlayer.x < -0.01f && directionToPlayer.x > 0.01f)
//Topright or left, doesnt matter, as long it goes top->UPwards
flyingObstructionType = (int)flyingObstructionDirection.TOPRIGHT;
else if (directionToPlayer.y < -0.01f && directionToPlayer.y > 0.01f)
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMRIGHT;
}
//Check if hazard on that way.
//if (flyingObstructionType == (int)flyingObstructionDirection.TOPRIGHT)
//hit = Physics2D.Raycast(transform.position, new Vector3(0.5f,0.5f), 50, whatisha);
//Retarded to change the velocity every damn frame, but whatever. I could at least check if the vector matches with the cached velocity vector. Oh wait, possible bugs + I dont cache velocity vector. Fuck.
//DetermineFlyingObstructionVelocity();
//Top-Right
if (flyingObstructionType == (int)flyingObstructionDirection.TOPRIGHT)
commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, 1 * currentMovementSpeedY);
//Top-Left
else if (flyingObstructionType == (int)flyingObstructionDirection.TOPLEFT)
commonRigidbody.velocity = new Vector2(-1 * currentMovementSpeed, 1 * currentMovementSpeedY);
//Bottom-Right
else if (flyingObstructionType == (int)flyingObstructionDirection.BOTTOMRIGHT)
commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, -1 * currentMovementSpeedY);
//Bottom-Left
else if (flyingObstructionType == (int)flyingObstructionDirection.BOTTOMLEFT)
commonRigidbody.velocity = new Vector2(-1 * currentMovementSpeed, -1 * currentMovementSpeedY);
/*
//DetermineFlyingObstructionWallBump();
if (lastPosition == transform.position)
{
Debug.Log("Same Position");
//ReverseFlyingDirection();
if (flyingObstructionType == (int)flyingObstructionDirection.TOPRIGHT)
{
//Your A.I. is crippingly flawed, but you HAVE to finish it, and not make it 100% braindead? No algorithm can save you now? (and no raycasts to check where blocked, because it would make this into superspagghetti?) R N G
if (UnityEngine.Random.Range(0, 2) == 0)
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMRIGHT;
else
flyingObstructionType = (int)flyingObstructionDirection.TOPLEFT;
}
else if (flyingObstructionType == (int)flyingObstructionDirection.TOPLEFT)
{
//Fucking RNG, I resort to this, because it is the END of the A.I. No more!
if (UnityEngine.Random.Range(0, 2) == 0)
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMLEFT;
else
flyingObstructionType = (int)flyingObstructionDirection.TOPRIGHT;
}
else if (flyingObstructionType == (int)flyingObstructionDirection.BOTTOMRIGHT)
{
//50% RNG
if (UnityEngine.Random.Range(0, 2) == 0)
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMLEFT;
else
flyingObstructionType = (int)flyingObstructionDirection.TOPRIGHT;
}
else if (flyingObstructionType == (int)flyingObstructionDirection.BOTTOMLEFT)
{
//Fucking RNG, I resort to this, because it is the END of the A.I. No more!
if (UnityEngine.Random.Range(0, 2) == 0)
flyingObstructionType = (int)flyingObstructionDirection.BOTTOMRIGHT;
else
flyingObstructionType = (int)flyingObstructionDirection.TOPLEFT;
}
//The more I push on, the sadder it gets. Isn't there something that exceeds code spagghetti?
//Retarded to change the velocity every damn frame, but whatever. I could at least check if the vector matches with the cached velocity vector. Oh wait, possible bugs + I dont cache velocity vector. Fuck.
//DetermineFlyingObstructionVelocity();
//Top-Right
if (flyingObstructionType == (int)flyingObstructionDirection.TOPRIGHT)
commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, 1 * currentMovementSpeedY);
//Top-Left
else if (flyingObstructionType == (int)flyingObstructionDirection.TOPLEFT)
commonRigidbody.velocity = new Vector2(-1 * currentMovementSpeed, 1 * currentMovementSpeedY);
//Bottom-Right
else if (flyingObstructionType == (int)flyingObstructionDirection.BOTTOMRIGHT)
commonRigidbody.velocity = new Vector2(1 * currentMovementSpeed, -1 * currentMovementSpeedY);