Hit spaceships

Here, we face something different from the player controller; we need to check what happens once the bullet hits the player or the enemy. Of course, this is something we are going to do within the OnTriggerEnter2D() function. In order to distinguish between whether we hit the player or the enemy, we are going to use a tag. Moreover, we also need to check whether the bullet was shot by the player or by the enemy. In fact, we don't want the player shooting a bullet and immediately exploding. Since in this simple implementation we don't pass any information to the bullet, how can we distinguish between the two? The enemy's bullets will go downwards, and thus they will have a negative speed. So, by checking if the speed is positive or negative, we can determine if the bullet belongs to the player or to the enemy. Once we have checked if the bullet hit the player or an enemy, we need to call the Hit() function on the respective controller and destroy the bullet.

Wrapping up, here is the final code for the OnTriggerEnter2D() function:

    void OnTriggerEnter2D(Collider2D other) { 
        //Check if the player collides with the bullet (and it has been shot by an enemy) 
        if (other.tag == "Player" && speed < 0) { 
            //Send the message to the player that the spaceship has been hit 
            other.GetComponent<PlayerController>().Hit(transform.position); 
 
            //Destroy the bullet 
            Destroy(gameObject); 
        } else if (other.tag == "Enemy" && speed > 0) { 
            //Send the message to the enemy that the spaceship has been hit 
            other.GetComponent<EnemyController>().Hit(transform.position); 
 
            //Destroy the bullet 
            Destroy(gameObject); 
        } 
    } 

You can now save the script, and as a result, you have all the basic gameplay scripts working for our space shooter game. In the next chapter, we will finish it up and make it operative by exploring some interesting UI features and building a world.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset