ACTIVITY 6: Point and Shoot game

Hello and welcome back to my blog. So in today's tutorial, were going to make a point and shoot game using Unity 2D platform. If you are following my game dev journey, maybe you should check out my previous blog that I made.

LINK OF PREVIOUS BLOG: Life and Death

Authored By: Jen Carlo Napoto
Developed By: John Ray Vino

So without further ado let's begin!

So this time, were making a point and shoot game with added enemies and obstacles for thrill. First we need to make a project in Unity Hub named Point and Shoot. Once done you'll enter now the UI of Unity which is in default blank.

So in order to make a game, first you need to add on your assets these sprites. An object for Player (a turret or gun to be specific), Bullet, Enemy, Background (optional), Barrier(for the edges of the game board), and lastly your Obstacle. 



Now that we have our Sprites in our Assets, lets begin on making our Point and Shoot script. This script must be put on our Main Camera which will assign later our gameObjects. 

So left-click on our Main Camera, go to Inspector, then add component, name it PointAndShoot and set as Script. Once it had appeared in your Assets, click on it and Visual Studio will appear on your screen.

So our code has already been given. Just paste this in your code:


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class PointAndShoot : MonoBehaviour

{

    public GameObject crosshairs;

    public GameObject player;

    public GameObject bulletPrefab;

    public GameObject bulletStart;


    public float bulletSpeed = 60.0f;


    private Vector3 target;


    // Use this for initialization

    void Start()

    {

        Cursor.visible = false;

    }


    // Update is called once per frame

    void Update()

    {

        target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));

        crosshairs.transform.position = new Vector2(target.x, target.y);


        Vector3 difference = target - player.transform.position;

        float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;

        player.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);


        if (Input.GetMouseButtonDown(0))

        {

            float distance = difference.magnitude;

            Vector2 direction = difference / distance;

            direction.Normalize();

            fireBullet(direction, rotationZ);

        }

    }

    void fireBullet(Vector2 direction, float rotationZ)

    {

        GameObject b = Instantiate(bulletPrefab) as GameObject;

        b.transform.position = bulletStart.transform.position;

        b.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);

        b.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;

    }

}


Now we had put this code to our camera, you'll see that we need to put the defined Game Objects to it as this code will act out as the Game Controller for our cursor and alignment for player's turret. 

Now make an empty gameObject then name it turret holder. Here we'll put our player object, resize it and adjust it's position on plane(must be at 0x and 0y). Now that we had our turretHolder, lets put in on our Main Camera by clicking Inspector and dragging turretHolder to our PointAndShoot script indicated to as Player.



After that we need to put out or crosshair in the Scene, this will follow our cursor, and also be followed as Player was put on turretHolder. So put it on out in our Main Camera's Script, drag to inspector then script and put it on the indicated crosshair.

Now lets take our Bullet object by putting it first in Hierarchy, then on Inspector put Rigidbody2D and set angular drag to zero and gravity to zero. After that drag it back to assets to make it a prefab. Assign this prefab to Main Camera's PointAndShoot script identified as bulletPrefab.

The next is making a bulletStart which to be put on turretHolder as child same with player object which will acts as were the bullet comes from which we want it to be on the Player or turret. So to do this, first we have to make a gameObject, name it as bulletStart. 

Then in the inspector, lets change it's icon to an Oblong shaped icon (at any color), once appeared on Scene, move it slightly to the inside of our turret, which will give us an illusion that the bullet comes from the turret or player itself. Once done, drag bulletStart to Main Camera's script which is indicated as bulletStart.

Now that we have put all of these in PointAndShoot script. You may try playing it if the functions are well working to fix if there are some errors shown.



To add thrill to the game, we must also place some Enemies which our Turret or Player needs to destroy. For this we had to put an enemy object to the scene. So we made a script called ObjectMove which we also used in our previous blog which allows us to make the object move randomly, but the difference is that we added an OnTriggerEnter2D script to per say destroy our bullet once it hit the enemy. 

So on each one of the enemy objects, they must have OnTriggerEnter2D. And also we must put RigidBody2D and CircleCollider2D(you may use BoxCollider2D if the shape of the object wasn't a circle) on our EnemyObject which I'll later explain why. 


So for now here's our code for our Enemy Object:


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class ObjectMove : MonoBehaviour

{

    public Rigidbody2D rb;

    public float accelerationTime = 1f;

    public float maxSpeed = 7f;

    private Vector2 movement;

    private float timeLeft;

    // Use this for initialization

    void Start()

    {

        rb = GetComponent<Rigidbody2D>();


    }

    void Update()

    {

        timeLeft -= Time.deltaTime;

        if (timeLeft <= 0)

        {

            movement = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));

            timeLeft += accelerationTime;

        }

    }


    void FixedUpdate()

    {

        rb.AddForce(movement * maxSpeed);

    }

    private void OnTriggerEnter2D(Collider2D collision)

    {

        switch (collision.name)

        {

            case "Bullet(Clone)":

                Destroy(collision.gameObject);

                break;

        }

    }

}

Now that we have that, we need the put a script on our turretHolder. The turretHolder will act as our Player, which will allow us to control it using WASD or Arrowkeys, And also put a RigidBody2d on turretHolder then set angular drag to zero and gravity to zero. 

While on our Player object, add these components that will act as our physical barrier or body to our player object, which is CircleCollider2D for the center or body of turret and BoxCollider2D on the turret itself. Then adjust the size of the Colliders to your preferred size.


Here's our code for turretHolder which is named PlayerController(or Player):


using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class PlayerController : MonoBehaviour

{

    public float speed;

    private Rigidbody2D rb2d;

    private Vector2 moveVelocity;


    void Start()

    {

        rb2d = GetComponent<Rigidbody2D>();

    }

    void Update()

    {

        Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));

        moveVelocity = moveInput.normalized * speed;

    }

    void FixedUpdate()

    {

        rb2d.MovePosition(rb2d.position + moveVelocity * Time.fixedDeltaTime);

    }

}

Well try shooting the enemy now. Wait! still the Enemy object hasn't destroyed. Guess what! we still need to put an OnTriggerEnter2D on our bulletPrefab. We also need to put RigidBody2D which its angular drag and gravity are in zero and Box Collider2D set as "In Trigger" so the bullet destroys our Enemy which I stated earlier why we need a collider to it. 

Which by these case, the bullets are also being cloned (named as "Bullet(clone)") by the PointAndShoot script every time our crosshair or cursor has been clicked. So to our bulletPrefab, let's add component then make a script called Bullet.




So here's the code for our bulletPrefab(named as Bullet):


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bullet : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        switch (collision.name)
        {
            case "Enemy":
                Destroy(collision.gameObject);
                break;
            case "Enemy1":
                Destroy(collision.gameObject);
                break;
            case "Enemy2":
                Destroy(collision.gameObject);
                break;
            case "Enemy3":
                Destroy(collision.gameObject);
                break;
            case "Enemy4":
                Destroy(collision.gameObject);
                break;
            case "Enemy5":
                Destroy(collision.gameObject);
                break;
            case "Enemy6":
                Destroy(collision.gameObject);
                break;
            case "Enemy7":
                Destroy(collision.gameObject);
                break;
            case "Enemy8":
                Destroy(collision.gameObject);
                break;
            case "Enemy9":
                Destroy(collision.gameObject);
                break;
            case "Enemy10":
                Destroy(collision.gameObject);
                break;
        }
    }
}

Now that we have that, try targeting our enemy object to see if the bullet destroys it. 

The next phase is to add our Obstacles and Barriers so the player, and enemy object can't move outside from game. By this we put barriers on each edge of our game and slightly moved them outside the Main Camera so the barrier won't appear. 

Then we put our Obstacles on random places in the scene. Once we had placed them on the precise locations, then we put our BoxCollider2d on each object. 


By shooting bullets inside of the game, we noticed that the bullet bypasses any object, which if the enemy is behind the obstacle they can still get destroyed by our bullet which we don't wanted to happen. 

So same with the enemy object we had to put OnTriggerEnter2D on each Barrier and Obstacle objects to destroy "Bullet(clone)". I made a separate script as just the OnTriggerEnter2D is only what is in it.




Here's the code for each Barrier and Obstacle object(I named this script as BulletDestroy)


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BulletDestroy : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    private void OnTriggerEnter2D(Collider2D collision)
    {
        switch (collision.name)
        {
            case "Bullet(Clone)":
                Destroy(collision.gameObject);
                break;
        }
    }
}

If everything is working well as intended, then we had made a PointAndShoot game in Unity2D.


WATCH THE VIDEO BELOW












Comments

Popular Posts