67 lines
1.9 KiB
C#
Raw Normal View History

2023-06-18 13:37:19 +02:00
using UnityEngine;
public class FallingDetection : MonoBehaviour
{
private CharController charController;
private Rigidbody2D playerRigidbody;
2023-06-21 16:14:58 +02:00
public bool isFalling;
private Animator animator;
2023-06-21 16:14:58 +02:00
public int counter = 0;
2023-06-24 13:49:28 +02:00
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;
2023-06-25 11:47:17 +02:00
public int counterFall = 0;
2023-06-25 12:04:22 +02:00
public bool didLandDuringJump = false;
2023-06-24 13:49:28 +02:00
2023-06-18 13:37:19 +02:00
private void Start()
{
animator = GetComponent<Animator>();
playerRigidbody = GetComponent<Rigidbody2D>();
charController = gameObject.GetComponent<CharController>();
2023-06-24 13:49:28 +02:00
audioSource = GetComponent<AudioSource>();
}
2023-06-18 13:37:19 +02:00
private void Update()
{
Vector3 velocity = playerRigidbody.velocity;
2023-06-24 13:49:28 +02:00
//Wenn nicht auf boden und geschwindigkeits offset pos
if (!charController.grounded && velocity.y > 0.1f && !isJumping){
2023-06-25 12:04:22 +02:00
didLandDuringJump = charController.grounded;
if(!didLandDuringJump){
audioSource.PlayOneShot(sprungSound);}
2023-06-24 13:49:28 +02:00
isJumping = true;
}
if(charController.grounded){
isJumping = false;
}
//Wenn nicht auf boden und geschwindigkeits offset neg
if (!charController.grounded && velocity.y < -0.1f) {
2023-06-24 13:49:28 +02:00
//Wenn er bereits fällt, oder der counter erreicht ist zum fallen
2023-06-25 11:47:17 +02:00
if (isFalling || counter++>20) {
isFalling = true;
animator.SetBool("IsFalling", true);
counter = 0;
2023-06-25 12:04:22 +02:00
2023-06-25 11:47:17 +02:00
if(counterFall++>35){
2023-06-24 15:03:08 +02:00
wasFallingbefore = true;}
}
} else {
isFalling = false;
counter = 0;
2023-06-24 15:03:08 +02:00
counterFall=0;
animator.SetBool("IsFalling", false);
2023-06-25 12:04:22 +02:00
didLandDuringJump = false;
2023-06-24 13:49:28 +02:00
if(wasFallingbefore){
wasFallingbefore = false;
audioSource.PlayOneShot(landeSound);
}
}
2023-06-25 12:04:22 +02:00
if (charController.grounded && (Mathf.Abs(velocity.y)<0.01f)){
didLandDuringJump = false;
}
}
2023-06-18 13:37:19 +02:00
}