74 lines
2.2 KiB
C#
74 lines
2.2 KiB
C#
using System.Collections;
|
||
using System.Collections.Generic;
|
||
using UnityEngine;
|
||
|
||
public class PetDelet : MonoBehaviour
|
||
{
|
||
private Camera mainCamera;
|
||
|
||
// 标记物体是否正在被拖动
|
||
private bool isDragging = false;
|
||
private Vector3 offset;
|
||
|
||
private Vector3 screenPosition;
|
||
|
||
private float initialRotationZ;
|
||
void Start()
|
||
{
|
||
mainCamera = Camera.main; // 获取主相机
|
||
}
|
||
|
||
void Update()
|
||
{
|
||
// 检查萌宠是否超出屏幕
|
||
screenPosition = mainCamera.WorldToViewportPoint(transform.position);
|
||
|
||
// 如果宠物超出屏幕,销毁该对象
|
||
if (screenPosition.x < 0 || screenPosition.x > 1 || screenPosition.y < 0 || screenPosition.y > 1)
|
||
{
|
||
Destroy(gameObject);
|
||
}
|
||
|
||
// 鼠标按下,开始拖动
|
||
if (Input.GetMouseButtonDown(0))
|
||
{
|
||
// 发射Raycast2D,检测鼠标点击的2D物体
|
||
Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
|
||
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, 1000, 1 << LayerMask.NameToLayer("PetObject"));
|
||
|
||
if (hit.collider != null && hit.collider.transform == transform)
|
||
{
|
||
isDragging = true; // 物体进入拖动状态
|
||
offset = transform.position - GetMouseWorldPos(); // 计算物体和鼠标之间的偏移量
|
||
}
|
||
}
|
||
|
||
// 鼠标松开,停止拖动
|
||
if (Input.GetMouseButtonUp(0))
|
||
{
|
||
isDragging = false; // 物体停止拖动
|
||
}
|
||
|
||
// 如果物体正在被拖动,更新物体的位置
|
||
if (isDragging)
|
||
{
|
||
transform.position = GetMouseWorldPos() + offset;
|
||
}
|
||
// 如果物体正在被拖动,更新物体的位置并保持旋转角度不变
|
||
if (isDragging)
|
||
{
|
||
Vector3 newPosition = GetMouseWorldPos() + offset;
|
||
transform.position = newPosition;
|
||
transform.rotation = Quaternion.Euler(0, 0, initialRotationZ); // 保持物体的初始旋转角度
|
||
}
|
||
}
|
||
|
||
// 获取鼠标在世界中的位置
|
||
private Vector3 GetMouseWorldPos()
|
||
{
|
||
Vector3 mousePoint = Input.mousePosition; // 获取鼠标的屏幕坐标
|
||
mousePoint.z = 0; // 因为是2D场景,不需要Z轴
|
||
return mainCamera.ScreenToWorldPoint(mousePoint); // 转换为世界坐标
|
||
}
|
||
}
|