CODE FROM THE 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;
Animator playerAnimator;
// 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");
}
}
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("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