UNITY2D: SPAWN ENEMIES RANDOMLY/DYNAMICALLY AT RUN TIME

 Code:

player.cs

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

public class Player : MonoBehaviour {
  Rigidbody2D playerRB;
  BoxCollider2D playerCollider;

  float moveSpeeed = 200.0f;
  float direction;

  float jumpHeight = 7.0f;
  LayerMask groundLayer;
  bool playerIsGrounded = false;
  bool doubleJumped = false;
  AudioSource[] audioSources;
  Animator playerAnimator;

  [SerializeField] GameObject fireball;
  [SerializeField] Transform firePoint;

  [SerializeField] GameObject dragon;


  // Use this for initialization
  void Start () {
    playerRB = GetComponent<Rigidbody2D>();
    playerCollider = GetComponent<BoxCollider2D>();
    groundLayer = LayerMask.GetMask("Ground");
    audioSources = GetComponents<AudioSource>();
    playerAnimator = GetComponent<Animator>();
  }

  private void FixedUpdate() {
    playerIsGrounded = Physics2D.IsTouchingLayers(playerCollider, groundLayer);
  }
 
  // Update is called once per frame
  void Update () {
    direction = Input.GetAxisRaw("Horizontal");
    move(direction);

    // JUMP ROUTINE
    if(playerIsGrounded){
      doubleJumped = false;
    }
    //for the first jump
    if(Input.GetKeyDown(KeyCode.Space) && playerIsGrounded){
      jump();
    }
    //for the second jump
    if(Input.GetKeyDown(KeyCode.Space) && !playerIsGrounded && !doubleJumped){
      jump();
      doubleJumped = true;
    }
    // END JUMP ROUTINE

    // =============== ANIMATIONS =============================

    playerAnimator.SetFloat("Speed", Mathf.Abs(direction));
    playerAnimator.SetBool("Grounded", playerIsGrounded);

    // =============== END ANIMATIONS =============================

    if(transform.position.y < -3){
      //game over
      SceneManager.LoadScene("GameOverScene");
    }

    if(Input.GetKeyDown(KeyCode.L)){
      //play gunshot audio
     
      //fire the fireball
      Instantiate(fireball, firePoint.position, firePoint.rotation);
    }

  }

  void move(float direction){
    if(direction == 1){
      transform.localScale = new Vector3(1, 1, 1);
    }else if(direction == -1){ //should use this condition so that the character will not always face the left
      transform.localScale = new Vector3(-1, 1, 1);
    }
    float velocity = direction * moveSpeeed * Time.deltaTime;
    playerRB.velocity = new Vector2(velocity,playerRB.velocity.y);
  }
  void jump(){
    playerRB.velocity = new Vector2(playerRB.velocity.x, jumpHeight);
    audioSources[0].Play();

  }

  private void OnCollisionEnter2D(Collision2D otherObject) {
    if(otherObject.transform.tag.Equals("Enemy") && playerRB.velocity.y < 0){
      // stomp or step over the enemy
      otherObject.transform.localScale = new Vector2(1, -1);
      otherObject.gameObject.GetComponent<BoxCollider2D>().enabled = false;
      if(otherObject.gameObject.GetComponent<EnemyAI>() != null){
        otherObject.gameObject.GetComponent<EnemyAI>().enabled = false;
      }
       
      //eliminate enemy
      Destroy(otherObject.gameObject, 2.0f);
      //bounce effect
      playerRB.velocity = new Vector2(playerRB.velocity.x, jumpHeight - 2);
     
    }else if(otherObject.transform.tag.Equals("Obstacle")){
      PlayAudio(1);
    }else if(otherObject.transform.tag.Equals("Enemy")) {
      PlayAudio(2);
      SceneManager.LoadScene("GameOverScene");
    }
  }

  private void OnTriggerEnter2D(Collider2D otherObject) {
    if(otherObject.transform.tag.Equals("Enemy")){
      Debug.Log("Game Over!");
    }else if(otherObject.transform.tag.Equals("EnemyTrigger")){
      Vector2 dragonPosition = new Vector2(otherObject.transform.position.x + 5, otherObject.transform.position.y + 5);
      // spawned enemy mama dragon
      Instantiate(dragon, dragonPosition, Quaternion.identity);
      // destroy the trigger so that the dragon will not spawn again
      Destroy(otherObject.gameObject);
    }
  }

  void PlayAudio(int index){
    StopAllAudio();
    audioSources[index].Play();
  }

  void StopAllAudio(){
    for(int i=0;i<audioSources.Length;i++){
      if(audioSources[i].isPlaying){
        audioSources[i].Stop();
      }
    }
  }


}


 enemyai.cs (mama dragon)

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

public class EnemyAI : MonoBehaviour {
  Transform player;
  Rigidbody2D enemyRB;
  float moveSpeeed = 1.0f;
  float attackRange = 10.0f;
  [SerializeField] GameObject babyDragon;

  void Start () {
    enemyRB = GetComponent<Rigidbody2D>();
    player = GameObject.Find("Player").GetComponent<Transform>();
    StartCoroutine(spawnBabyDragon());
  }
 
  // Update is called once per frame
  void Update () {
    float distanceToPlayer = Vector2.Distance(transform.position, player.position);

    if(distanceToPlayer <= attackRange){
      follow();
    }
  }
  void follow(){
    if(player.transform.position.x < transform.position.x){
      transform.localScale = new Vector3(1, 1, 1);
    }else{
      transform.localScale = new Vector3(-1, 1, 1);
    }

    Vector2 targetPosition = new Vector2(player.position.x, transform.position.y);
    transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeeed * Time.deltaTime);
  }

  IEnumerator spawnBabyDragon(){
    while(true){
      Instantiate(babyDragon, new Vector2(transform.position.x,transform.position.y - 1.5f), Quaternion.identity);
      yield return new WaitForSeconds(2.0f);
    }
  }

}


 BabyDragonController.cs

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

public class BabyDragonController : MonoBehaviour {
  Transform player;
  // Use this for initialization
  void Start () {
    player = GameObject.Find("Player").GetComponent<Transform>();
  }
 
  // Update is called once per frame
  void Update () {
    transform.position = Vector2.MoveTowards(transform.position, player.position, 2.0f * Time.deltaTime);
  }
}


 

 

 

 

No comments:

Post a Comment

UNITY2D: SPAWN ENEMIES RANDOMLY/DYNAMICALLY AT RUN TIME

 Code: player.cs using System . Collections ; using System . Collections . Generic ; using UnityEngine ; using UnityEngine . SceneManage...