Creating Cannon and Camera Movement

Operating System

Creating Cannon

We will now create the object that will shoot the enemy and the structure. To do that first locates the sprite inside the Sprites directory.
  1. Drag the body sprite of the cannon to the Scene View. tut52 After that drag another sprite as a child for the body to complete the cannon GameObject. tut53
  2. Next is to set the component to each of the GameObject. tut54
  3. After setting up the components add a GameObject to Cannon as a child. This will be the spawning point for the bullet. Set its components as shown below. tut55
  4. Then Create two GameObject as child for the Player GameObject. This will be the wheel for the cannon to be able to stand on the ground. Set it component as shown below. tut56
  5. Go to the Scripts folder and create a new folder inside of it called Player.
  6. Create a C# script called Cannon.
  7. Write these block of code inside the Cannon Class:
    1. public GameObject cannonBullet;
    2. public Transform cannonTip;
    3. public Slider powerLevel;
    4. public AudioClip cannonShot;
    5. public int maxShot;
    6. public bool readyToShoot;
    7. public int shot;
    8.  
    9. private int minLevel, maxLevel, timeDelay;
    10. private bool isMax, isCharging;
    11. private AudioSource audioSource;
    12. private float minRot, maxRot;
    13. private Vector3 currentRotation, touchPos;
    14. private int counter = 0;
    15. private Vector2 direction = Vector2.zero;
    16.  
    17.     void Awake(){
    18.         audioSource = GetComponent<AudioSource> ();
    19.     }
    20.  
    21.     // Use this for initialization
    22.     void Start () {
    23.         readyToShoot = true;
    24.         shot = maxShot;
    25.         timeDelay = 50;
    26.         minLevel = 0;
    27.         maxLevel = 50;
    28.         powerLevel.maxValue = maxLevel;
    29.         powerLevel.value = minLevel;
    30.         maxRot = 20;
    31.         minRot = -25;
    32.         Vector3 currentRotation = transform.rotation.eulerAngles;
    33.     }
    34.    
    35.     // Update is called once per frame
    36.     void Update () {
    37.         if (GameplayController.instance.gameInProgress) {
    38.             if (readyToShoot) {
    39.                 if(Application.platform == RuntimePlatform.Android){
    40.                     TouchCannonShoot ();
    41.                 }else if(Application.platform == RuntimePlatform.WindowsEditor){
    42.                     CannonShoot ();
    43.                 }
    44.  
    45.             }
    46.  
    47.             if(Application.platform == RuntimePlatform.Android){
    48.                 TouchCannonMovement ();
    49.             }else if(Application.platform == RuntimePlatform.WindowsEditor){
    50.                 CannonMovement ();
    51.             }
    52.                
    53.         }
    54.     }
    55.  
    56.     void TouchCannonShoot(){
    57.         if(Input.touchCount > 0){
    58.             Touch touch = Input.GetTouch (0);
    59.  
    60.             touchPos = Camera.main.ScreenToWorldPoint (touch.position);
    61.  
    62.             Vector2 touchRayHit = new Vector2 (touchPos.x, touchPos.y);
    63.  
    64.             RaycastHit2D hit = Physics2D.Raycast (touchRayHit , Vector2.zero);
    65.  
    66.             if(hit.collider != null){
    67.                 if(hit.collider.CompareTag("Player")){
    68.                     if(touch.phase == TouchPhase.Stationary){
    69.                         if (shot != 0) {
    70.                             UpdatePowerLevel ();
    71.                             isCharging = true;
    72.                         }
    73.                     }else if(touch.phase == TouchPhase.Ended){
    74.                         if (shot != 0) {
    75.                             GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
    76.                             newCannonBullet.transform.GetComponent<Rigidbody2D> ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
    77.                             if (GameController.instance != null && MusicController.instance != null) {
    78.                                 if (GameController.instance.isMusicOn) {
    79.                                     audioSource.PlayOneShot (cannonShot);
    80.                                 }
    81.                             }
    82.                             shot--;
    83.                             powerLevel.value = 0;
    84.                             readyToShoot = false;
    85.                             isCharging = false;
    86.                         }
    87.                     }
    88.                 }
    89.             }
    90.  
    91.             /*if(touch.phase == TouchPhase.Stationary){
    92.                 if (shot != 0) {
    93.                     UpdatePowerLevel ();
    94.                 }
    95.             }else if(touch.phase == TouchPhase.Ended){
    96.                 if (shot != 0) {
    97.                     GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
    98.                     newCannonBullet.transform.GetComponent<Rigidbody2D> ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
    99.                     if (GameController.instance != null && MusicController.instance != null) {
    100.                         if (GameController.instance.isMusicOn) {
    101.                             audioSource.PlayOneShot (cannonShot);
    102.                         }
    103.                     }
    104.                     shot--;
    105.                     powerLevel.value = 0;
    106.                     readyToShoot = false;
    107.                 }
    108.             }*/
    109.            
    110.         }
    111.     }
    112.  
    113.     void CannonShoot(){
    114.         if (Input.GetKey (KeyCode.Space)) {
    115.             if(shot != 0){
    116.                 UpdatePowerLevel ();
    117.             }
    118.         }else if(Input.GetKeyUp(KeyCode.Space)){
    119.             if (shot != 0) {
    120.                 GameObject newCannonBullet = Instantiate (cannonBullet, cannonTip.position, Quaternion.identity) as GameObject;
    121.                 newCannonBullet.transform.GetComponent<Rigidbody2D> ().AddForce (cannonTip.right * powerLevel.value, ForceMode2D.Impulse);
    122.                 if (GameController.instance != null && MusicController.instance != null) {
    123.                     if (GameController.instance.isMusicOn) {
    124.                         audioSource.PlayOneShot (cannonShot);
    125.                     }
    126.                 }
    127.                 shot--;
    128.                 powerLevel.value = 0;
    129.                 readyToShoot = false;
    130.             }
    131.         }
    132.  
    133.     }
    134.  
    135.     void UpdatePowerLevel(){
    136.         if (!isMax) {
    137.             powerLevel.value += timeDelay * Time.deltaTime;
    138.  
    139.             if(powerLevel.value == maxLevel){
    140.                 isMax = true;
    141.             }
    142.  
    143.         } else {
    144.             powerLevel.value -= timeDelay * Time.deltaTime;
    145.  
    146.             if(powerLevel.value == minLevel){
    147.                 isMax = false;
    148.             }
    149.         }
    150.     }
    151.  
    152.     void CannonMovement(){
    153.  
    154.         if (Input.GetKey (KeyCode.UpArrow)) {
    155.             currentRotation.z += 50f * Time.deltaTime;
    156.         } else if (Input.GetKey (KeyCode.DownArrow)) {
    157.             currentRotation.z -= 50f * Time.deltaTime;
    158.         }
    159.            
    160.         currentRotation.z = Mathf.Clamp(currentRotation.z, minRot, maxRot);
    161.  
    162.         transform.rotation = Quaternion.Euler (currentRotation);
    163.     }
    164.  
    165.     void TouchCannonMovement(){
    166.         if(Input.touchCount > 0){
    167.             Touch touch = Input.GetTouch (0);
    168.  
    169.             if (touch.position.x < 300 && !isCharging && touch.position.y > 160) {
    170.  
    171.                 if (touch.phase == TouchPhase.Moved) {
    172.                     Vector2 touchDeltaPosition = touch.deltaPosition;
    173.                     direction = touchDeltaPosition.normalized;
    174.  
    175.                     if (direction.y > 0 && touchDeltaPosition.x > -10 && touchDeltaPosition.x < 10) {
    176.                         currentRotation.z += 50f * Time.deltaTime;
    177.                     } else if (direction.y < 0 && touchDeltaPosition.x > -10 && touchDeltaPosition.x < 10) {
    178.                         currentRotation.z -= 50f * Time.deltaTime;
    179.                     }
    180.  
    181.                 }
    182.             }
    183.         }
    184.  
    185.         currentRotation.z = Mathf.Clamp(currentRotation.z, minRot, maxRot);
    186.  
    187.         transform.rotation = Quaternion.Euler (currentRotation);
    188.            
    189.     }
  8. After creating the script, drag the script to the Cannon inspector as a component.
  9. Next we will create a power shot indicator for the cannon, this will tell how much force the shot will can reach the enemies. To do that go to GameObject and UI, select then the Slider.
  10. Set all the Components of the Slider as shown below to optimize the game.

    Slider

    tut60

    Background

    tut61

    Fill

    tut62

Creating Cannon Bullet

We will now create the object that will destroy enemies and structures when collide. To do that first locates the sprite inside the Sprites directory.
  1. Drag the sprite GameObject to the Scene View. tut57
  2. Next set the component of the Bomb GameObject. tut58
  3. Go to the Scripts folder and select Player. Create a C# script called Cannon Bullet.
  4. Write these block of code inside the CannonBullet Class:
    1. public GameObject explosionEffect;
    2.         public bool isIdle;
    3.  
    4.         private Rigidbody2D rigidBody2D;
    5.         private bool cannonShot, isExplode;
    6.  
    7.         void Awake(){
    8.                 rigidBody2D = GetComponent<Rigidbody2D> ();
    9.         }
    10.  
    11.         // Use this for initialization
    12.         void Start () {
    13.                 cannonShot = true;
    14.         }
    15.        
    16.         // Update is called once per frame
    17.         void Update () {
    18.                 if (GameplayController.instance.gameInProgress) {
    19.                         if (cannonShot && rigidBody2D.velocity.sqrMagnitude <= 0) {
    20.                                 DestroyBullet ();
    21.                         }
    22.                 }
    23.  
    24.  
    25.         }
    26.                
    27.         void DestroyBullet(){
    28.                 Destroy (gameObject);
    29.                 if (!isExplode) {
    30.                         isExplode = true;      
    31.                         GameObject newExplosionEffect = Instantiate (explosionEffect, transform.position, Quaternion.identity) as GameObject;
    32.                         Destroy (newExplosionEffect, 3f);
    33.                 }
    34.         }
  5. After creating the script, drag the script to the Bomb inspector as a component.
  6. Lastly we will create an effect for the bomb. To do that go to GameObject and Select Particle System. Particle System is a built in module in Unity for creating a stunning effects for the Game.
  7. Rename the Particle System as Explosion Effect and set the components of the Particle System as shown below. tut59
  8. After creating the effect, Create a new Directory inside the Prefabs called FX, this directory will hold all the needed effects for the game. Then drag the effects inside the newly created directory to create a prefab and delete it because we will just spawn the gameobject everytime time the bomb explode.
  9. Next is attach all the needed Gameobject to the Script of the Bomb and Cannon. After that drag the Player and Bomb gameobject to Player directory to create a prefab, and then delete Bomb in the Scene View after that.

    Cannon

    tut63

    Bomb

    tut64
  10. Lastly create a Shot indicator that tells how much bomb is left to be shot. To do that go to the GameObject and UI, then select Image. And also a Text UI as a child for the Image and set there component as shown below.

    Image

    tut65

    Text

    tut66

Creating Camera Movement

We will create the camera that follow the bomb when shot. To that first create two GameObject, this will limit the Camera movement around the screen. Then set the component of the newly created gameobject. tut67 After that go to Scripts directory then create a new directory called Camera. Inside the Camera directory create a C# script called CameraFollow. Inside the CameraFollow script, create a certain variable that we will use. Write these variables inside the CameraFollow class.
  1. public Transform target;
  2. public Transform leftBound;
  3. public Transform rightBound;
  4. public float speed = 5f;
  5. public bool isFollowing;
  6.  
  7.  
  8. private float arrowX;
  9. public bool allowToMove;
  10.  
  11. private float dragSpeed = 0.05f;
  12. private float timeSinceShot;
  13. private Vector3 velocity = Vector3.zero;
  14. private Vector3 startPosition;
  15. private Vector3 camPos;
Note: When using a UI Components in the script you will just need to import some modules. Then write this certain methods to make the camera work perfectly in the game.
  1. // Use this for initialization
  2.         void Start () {
  3.                 startPosition = transform.localPosition;
  4.         }
  5.        
  6.         // Update is called once per frame
  7.         void Update () {
  8.                 if (GameplayController.instance.gameInProgress) {
  9.                         if (isFollowing) {
  10.                                 if (GameObject.FindGameObjectWithTag ("Player Bullet") != null) {
  11.                                         MoveCameraFollow ();
  12.                                 }
  13.                         } else {
  14.                                 if (!GameplayController.instance.player.GetChild (0).transform.GetComponent<Cannon> ().readyToShoot) {
  15.                                         MoveCameraBackToStart ();
  16.                                         AfterShotMoveAgain ();
  17.                                         allowToMove = false;
  18.                                 } else {
  19.                                         timeSinceShot = 0;
  20.                                         allowToMove = true;
  21.                                 }
  22.                                
  23.                         }
  24.                        
  25.                         if (Application.platform == RuntimePlatform.Android) {
  26.                                 TouchMoveCamera ();
  27.                         } else if (Application.platform == RuntimePlatform.WindowsEditor) {
  28.                                 MoveCamera ();
  29.                         }
  30.                 }
  31.  
  32.         }
  33.  
  34.         void MoveCameraFollow(){
  35.                 if(target != null){
  36.                         transform.position = Vector3.Lerp (new Vector3 (transform.position.x, 0, -10f), new Vector3 (Mathf.Clamp (target.transform.position.x, leftBound.position.x, rightBound.position.x), 0, transform.position.z), Time.deltaTime * 10);
  37.                 }
  38.         }
  39.  
  40.         void MoveCameraBackToStart(){
  41.                 transform.position = Vector3.MoveTowards (transform.position, startPosition, Time.deltaTime * 5f);
  42.         }
  43.  
  44.         void AfterShotMoveAgain(){
  45.                 timeSinceShot += Time.deltaTime;
  46.                 if (timeSinceShot > 2f) {
  47.                         if(startPosition == transform.position){
  48.                                 GameplayController.instance.player.GetChild (0).transform.GetComponent<Cannon> ().readyToShoot = true;
  49.                         }
  50.                 }
  51.         }
  52.  
  53.         void MoveCamera(){
  54.                 arrowX = Input.GetAxis ("Horizontal");
  55.  
  56.                 Transform cam = gameObject.transform;
  57.  
  58.                 if (allowToMove) {
  59.                         if (arrowX != 0) {
  60.                                 cam.position = cam.position + (new Vector3 (arrowX, 0, 0) * speed * Time.deltaTime);
  61.                                 float camX = cam.position.x;
  62.                                 camX = Mathf.Clamp (camX, leftBound.transform.position.x, rightBound.transform.position.x);
  63.                                 cam.position = new Vector3 (camX, cam.position.y, cam.position.z);
  64.                         }
  65.                 }
  66.         }
  67.  
  68.         void TouchMoveCamera(){
  69.                 if(allowToMove){
  70.  
  71.                         /*if(Input.touchCount > 0){
  72.                                 Touch touch = Input.GetTouch (0);
  73.                        
  74.                                 Transform cam = gameObject.transform;
  75.  
  76.  
  77.                                 if(touch.phase == TouchPhase.Began){
  78.                                         cam = touch.position;
  79.                                 }else if(touch.phase == TouchPhase.Moved){
  80.                                        
  81.                                 }
  82.                         }*/
  83.  
  84.                         if(Input.touchCount > 0){
  85.                                 Touch touch = Input.GetTouch (0);
  86.  
  87.                                 Transform cam = gameObject.transform;
  88.                                 if (touch.position.x > 300) {
  89.                                         if(touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Stationary){
  90.                                                 camPos = touch.position;
  91.                                         }else if(touch.phase == TouchPhase.Moved){
  92.                                                 cam.position = cam.position + (new Vector3 ((camPos.x - touch.position.x), 0, 0) * dragSpeed * Time.deltaTime);
  93.                                                 float camX = cam.position.x;
  94.                                                 camX = Mathf.Clamp (camX, leftBound.transform.position.x, rightBound.transform.position.x);
  95.                                                 cam.position = new Vector3 (camX, cam.position.y, cam.position.z);
  96.                                         }
  97.                                 }
  98.                                        
  99.                         }
  100.                                
  101.                 }
  102.         }
After that attach the script inside the Camera inspector and then attach all the needed gameobject to the script as shown below. tut68

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment