GameDev : Enemy Fire Laser (Part II)!
Inside Update, we use the bool to check
Now, we have CalculateMovement()
This method is perfectly ok for Player, but not for the Enemy.
So, change the name to MoveUp() or PlayerLaser()
In “else”, we simply need a method that move the laser down.
We create another method, MoveDown() or EnemyLaser()
and inside we write exactly the same code for Player, but we change the direction.
After this step, we simply need a method that return true if isEnemyLaser.
I create one
Now, we go back to Enemy script
When we instantiate the Laser, we need to think to this :
Enemy fire TWO LASER, so we need a reference to them to call EnemyLaser()
now we have a reference and we can call EnemyLaser().
BUT.
Watch out. The component we try to access is not in the object enemyLaser, but in the children.
and is not ONE, BUT TWO.
So we need to use
GetComponentsInChildren<>
This is plural version of GetComponent<>
We can create an Array of lasers
Then for every elements in the Array we can call AssignEnemyLaser()
Now, as we have seen in previous articles, if we need to do something with all the elements in a collection, we use a Loop.
We can use a For Loop ofa Forech Loop.
For my personale preference I use Foreach Loop.
Now, let’s try and see
Now the Enemy can shot to us.
But we have to set up the EnemyLaser hit the Player, right?
So inside Laser, which is the object that already has the Rigidbody, we need a check.
We create a TriggerEnter2D
Indise here, we check if we collide with Player
A good thing to do here is make another check if isEnemyLaser == true.
I add that part to my if statement
what we need here?
player.Damage()
We take a reference of Player
Now, we can do this
But as always, I prefer the other way and make a check for NULL Reference.
I think is best practice check everytime we FIND or GRAB some component
Honestly guys, is just one or two lines of code more, and we are sure that the component is not NULL, so why don’t do that?
Let’s try if works
How we can it works, it works, but we have a particular behavior : the EnemyLaser takes away TWO LIVES.
For me, it’s ok.
Makes the game little bit more “difficult”, it’s not a problem.
But if for you is not “fair”, or you prefer make EnemyLaser take off only one lives, go on and try to change it!
Here we try to understand how can we do “things”, so if you have a better mechanical or better ideas, try to implement them!
The best thing about programming Games is exactly this :
only your imagination and creativity are your limit.