angry_birds/Assets/Scripts/Ball.cs
2025-04-27 19:54:06 +05:30

67 lines
1.8 KiB
C#

using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Ball : MonoBehaviour
{
public Rigidbody2D rb;
public float MaxDistance = 3f;
public Rigidbody2D Hook;
public GameObject NextLevel;
public float releaseTime =0.15f;
private bool isPressed = false;
private void Update()
{
if(isPressed)
{
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
if(Vector2. Distance(mousePos , Hook . transform.position) < MaxDistance)
{
rb.position = mousePos;
}
else
{
Vector2 dir = (mousePos-Hook.position).normalized;
rb.position = Hook.position + (dir * MaxDistance);
}
}
}
private void OnMouseDown()
{
isPressed = true;
rb.isKinematic = true;
}
private void OnMouseUp()
{
isPressed = false;
rb.isKinematic = false;
StartCoroutine(Release());
}
IEnumerator Release ()
{
yield return new WaitForSeconds(releaseTime);
SpringJoint2D hook = GetComponent<SpringJoint2D>().connectedBody.GetComponent<SpringJoint2D>();
hook.enabled=false;
GetComponent<SpringJoint2D>().enabled = false;
this.enabled = false;
yield return new WaitForSeconds(2f);
if(NextLevel != null)
{
NextLevel.SetActive(true);
hook.connectedBody = NextLevel.GetComponent<Rigidbody2D>();
hook.enabled = true;
}else
{
Debug.Log("restaring");
Enemy.EnemiesAlive = 0;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
}