using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static UnityEngine.GraphicsBuffer;

public class PipeZ : MonoBehaviour
{
    public GameObject handle;
    bool hanging;//是否悬空
    public Transform pivot;
    Rigidbody2D rb;
    Vector2 mousePos;
    Vector2 distance;
    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();   
    }

    // Update is called once per frame
    void Update()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        if (hanging)
        {
            Vector3 direction = pivot.position - transform.position;

            // 计算旋转角度
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

            // 让物体旋转到目标方向
            Quaternion targetRotation = Quaternion.Euler(new Vector3(0, 0, angle));
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 7 * Time.deltaTime);
        }
    }

    private void OnMouseDown()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        handle.transform.position = mousePos;
        hanging = true;
        //rb.isKinematic = true;
        rb.gravityScale = 0;
        
        distance = new Vector2(transform.position.x, transform.position.y) - mousePos;

    }

    private void OnMouseDrag()
    {
        transform.position = mousePos + distance;
        rb.velocity = Vector2.zero;

    }

    private void OnMouseUp()
    {
        hanging = false;
        //rb.isKinematic = false;
        rb.gravityScale = 1;
    }
}
