UNITY: ADD SOUND OR AUDIO TO YOUR GAME

 Code used in video:

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 = 5.0f;
  LayerMask groundLayer;
  bool playerIsGrounded = false;
  bool doubleJumped = false;

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

  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

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

  }

  void move(float direction){
    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("Obstacle")){
      PlayAudio(1);
    }else if(otherObject.transform.tag.Equals("Enemy")) {
      PlayAudio(2);
    }
  }

  private void OnTriggerEnter2D(Collider2D otherObject) {
    if(otherObject.transform.tag.Equals("Enemy")){
      Debug.Log("Game Over!");
    }
  }

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


}







No comments:

Post a Comment

UNITY: USING FIREBALL TO ELIMINATE ENEMIES

 Code user in the video: Fireball Controller using System . Collections ; using System . Collections . Generic ; using UnityEngine ; publ...