BounceAndSound.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using UnityEngine;
  2. using UnityEngine.InputSystem;
  3. public class BounceAndSound : MonoBehaviour
  4. {
  5. public AudioClip clickSound; // drag your sound file here in Inspector
  6. public float bounceHeight = 0.08f; // how high it bounces
  7. public float bounceSpeed = 4f; // how fast it bounces
  8. private AudioSource audioSource;
  9. private bool isBouncing = false;
  10. private Vector3 startPosition;
  11. void Start()
  12. {
  13. startPosition = transform.position;
  14. audioSource = gameObject.AddComponent<AudioSource>();
  15. audioSource.clip = clickSound;
  16. audioSource.loop = false;
  17. audioSource.playOnAwake = false;
  18. }
  19. void Update()
  20. {
  21. // Handle click using raycast
  22. if (Mouse.current.leftButton.wasPressedThisFrame)
  23. {
  24. Ray ray = Camera.main.ScreenPointToRay(Mouse.current.position.ReadValue());
  25. RaycastHit hit;
  26. if (Physics.Raycast(ray, out hit) && hit.transform == this.transform)
  27. {
  28. isBouncing = !isBouncing;
  29. if (isBouncing)
  30. {
  31. startPosition = transform.position;
  32. audioSource.Play();
  33. }
  34. else
  35. {
  36. audioSource.Stop();
  37. transform.position = startPosition;
  38. }
  39. }
  40. }
  41. // Bounce animation using a sine wave
  42. if (isBouncing)
  43. {
  44. float newY = startPosition.y + Mathf.Abs(Mathf.Sin(Time.time * bounceSpeed)) * bounceHeight;
  45. transform.position = new Vector3(startPosition.x, newY, startPosition.z);
  46. }
  47. }
  48. }