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);
  }
}


 

 

 

 

UNITY : STOMP ENEMY TO ELIMINATE IT (STEP OVER ENEMY)

 Code:

player.cs

 

  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");
    }
  }

 

HTML 5 AND JAVASCRIPT CAMERA API

 I modified the code from our module. This code can now let the user to:

1 - turn on camera

2 - capture image from the camera

3 - turn off camera


Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HCI Webcam</title>
</head>
<body>
  <h2 style="background-color:white;opacity:0.5;">Human  Computer Interaction Webcam</h2>

    <video id="webcam" width="640" height="480" autoplay></video><br/>

    <button onclick="on_cam()" style="background-color:aquamarine;">Turn it ON</button>
    <button onclick="capture_image()" style="background-color:aquamarine;">Capture Image</button>
    <button onclick="off_cam()" style="background-color:aquamarine;">Turn it OFF</button>

    <h1 id='webcamoff'></h1>
    <canvas id="canvas" width="640" height="480" style="display:none;"></canvas>
    <img id="capturedImage" width="640" height="480" />

    <script>
      function on_cam(){
        // Check if the browser supports the getUserMedia API
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia){
          // Access the webcam
          navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
            // Attach the video stream to the video element
            var webcam = document.getElementById('webcam');
            webcam.srcObject = stream;
            webcam.play();
          });
        }
      }

      function off_cam(){
        var stream = document.getElementById('webcam').srcObject;
        stream.getTracks().forEach(function(track) {
          track.stop();
        });
        // Remove the video stream from the video element
        document.getElementById('webcam').srcObject = null;
        var msg = "Your cam is already turned off!";
        document.getElementById('webcamoff').innerHTML = msg;
      }

      function capture_image(){
        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        var webcam = document.getElementById('webcam');

        // Draw the video frame to the canvas
        context.drawImage(webcam, 0, 0, canvas.width, canvas.height);

        // Get the data URL of the image
        var dataUrl = canvas.toDataURL('image/png');

        // Display the captured image
        var capturedImage = document.getElementById('capturedImage');
        capturedImage.src = dataUrl;
      }
    </script>
</body>
</html>




READ/SCAN QR CODE USING jsQR LIBRARY

 Code:

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.js"></script>
  </head>
  <body>
    <h1>QR CODE SCANNER</h1>
    <video id="video" width="640" height="480" style="display: none"></video>
    <canvas id="canvas" width="640" height="480"></canvas>
    <div id="output"></div>

    <script>
      const video = document.createElement("video");
      const canvasElement = document.getElementById("canvas");
      const canvas = canvasElement.getContext("2d");
      const output = document.getElementById("output");

      navigator.mediaDevices
        .getUserMedia({ video: { facingMode: "environment" } })
        .then(function (stream) {
          video.srcObject = stream;
          video.setAttribute("playsinline", true); // required to tell iOS safari we don't want fullscreen
          video.play();
          requestAnimationFrame(tick);
        });

      function tick() {
        if (video.readyState === video.HAVE_ENOUGH_DATA) {
          canvasElement.hidden = false;
          canvasElement.height = video.videoHeight;
          canvasElement.width = video.videoWidth;
          canvas.drawImage(
            video,
            0,
            0,
            canvasElement.width,
            canvasElement.height
          );
          const imageData = canvas.getImageData(
            0,
            0,
            canvasElement.width,
            canvasElement.height
          );
          const code = jsQR(imageData.data, imageData.width, imageData.height, {
            inversionAttempts: "dontInvert",
          });
          // check if a QR code was detected,
          // if there is one, display the value using the code.data property
          if (code) {
            output.innerText = `QR Code Value: ${code.data}`;
            console.log("QR Code detected:", code.data);
          } else {
            console.log("No QR code detected.");
          }
        }
        requestAnimationFrame(tick);
      }
    </script>
  </body>
</html>


 

UNITY2D: SPAWN ENEMIES RANDOMLY/DYNAMICALLY AT RUN TIME

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