2023-06-25 12:04:22 +02:00

67 lines
1.9 KiB
C#

using UnityEngine;
public class FallingDetection : MonoBehaviour
{
private CharController charController;
private Rigidbody2D playerRigidbody;
public bool isFalling;
private Animator animator;
public int counter = 0;
private bool wasFallingbefore = false;
private AudioSource audioSource; // Reference to the AudioSource component
public AudioClip landeSound; // The sound clip to be played
public AudioClip sprungSound; // The sound clip to be played
public bool isJumping = false;
public int counterFall = 0;
public bool didLandDuringJump = false;
private void Start()
{
animator = GetComponent<Animator>();
playerRigidbody = GetComponent<Rigidbody2D>();
charController = gameObject.GetComponent<CharController>();
audioSource = GetComponent<AudioSource>();
}
private void Update()
{
Vector3 velocity = playerRigidbody.velocity;
//Wenn nicht auf boden und geschwindigkeits offset pos
if (!charController.grounded && velocity.y > 0.1f && !isJumping){
didLandDuringJump = charController.grounded;
if(!didLandDuringJump){
audioSource.PlayOneShot(sprungSound);}
isJumping = true;
}
if(charController.grounded){
isJumping = false;
}
//Wenn nicht auf boden und geschwindigkeits offset neg
if (!charController.grounded && velocity.y < -0.1f) {
//Wenn er bereits fällt, oder der counter erreicht ist zum fallen
if (isFalling || counter++>20) {
isFalling = true;
animator.SetBool("IsFalling", true);
counter = 0;
if(counterFall++>35){
wasFallingbefore = true;}
}
} else {
isFalling = false;
counter = 0;
counterFall=0;
animator.SetBool("IsFalling", false);
didLandDuringJump = false;
if(wasFallingbefore){
wasFallingbefore = false;
audioSource.PlayOneShot(landeSound);
}
}
if (charController.grounded && (Mathf.Abs(velocity.y)<0.01f)){
didLandDuringJump = false;
}
}
}