113 lines
3.2 KiB
C#
113 lines
3.2 KiB
C#
using UnityEngine;
|
|
|
|
namespace AibisDream
|
|
{
|
|
public class GearController : MonoBehaviour
|
|
{
|
|
[SerializeField] private GameObject gearPrefab;
|
|
|
|
private ShaftGraph shaftGraph;
|
|
|
|
private Shaft[] shafts;
|
|
|
|
private Vector3 offset; // 鼠标点击位置与物体pos偏移量
|
|
|
|
private Gear draggingGear;
|
|
|
|
private void Awake()
|
|
{
|
|
shafts = GetComponentsInChildren<Shaft>();
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
shaftGraph = new ShaftGraph(shafts);
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
shaftGraph = null;
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
// 鼠标按下
|
|
if (Input.GetMouseButtonDown(0))
|
|
{
|
|
OnMouseClickDown();
|
|
}
|
|
|
|
// 鼠标拖动
|
|
if (Input.GetMouseButton(0) && draggingGear)
|
|
{
|
|
draggingGear.Move(GetMouseAsWorldPoint() + offset);
|
|
}
|
|
|
|
// 鼠标释放
|
|
if (Input.GetMouseButtonUp(0)) // 检查鼠标左键释放
|
|
{
|
|
draggingGear?.StopMove();
|
|
|
|
if (draggingGear && draggingGear.targetShaft)
|
|
{
|
|
shaftGraph.ChangeVertex(draggingGear.targetShaft.GetInstanceID());
|
|
}
|
|
|
|
draggingGear = null;
|
|
}
|
|
}
|
|
|
|
private void OnMouseClickDown()
|
|
{
|
|
// 按下时发出检查射线
|
|
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
|
|
RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
|
|
|
|
// 检测命中的物体
|
|
if (hit.collider && hit.collider.CompareTag("Moveable"))
|
|
{
|
|
offset = hit.collider.transform.position - GetMouseAsWorldPoint();
|
|
draggingGear = hit.collider.gameObject.GetComponent<Gear>();
|
|
draggingGear.StartMove();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 判断吸附位置
|
|
/// </summary>
|
|
/// <param name="pos">齿轮当前位置</param>
|
|
/// <param name="gearRadius">齿轮半径</param>
|
|
/// <returns>能够被吸附的轴</returns>
|
|
public Shaft CheckClosestShaft(Vector3 pos, float gearRadius)
|
|
{
|
|
return shaftGraph.QuerySnapShaft(pos, gearRadius);
|
|
}
|
|
|
|
private Vector3 GetMouseAsWorldPoint()
|
|
{
|
|
Vector3 mousePoint = Input.mousePosition;
|
|
mousePoint.z = Camera.main.nearClipPlane;
|
|
return Camera.main.ScreenToWorldPoint(mousePoint);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 生成齿轮
|
|
/// </summary>
|
|
/// <param name="pos">位置</param>
|
|
/// <param name="gearModel">齿轮数据</param>
|
|
/// <param name="speed">速度</param>
|
|
/// <returns>齿轮Obj</returns>
|
|
public GameObject InitGear(Vector3 pos, GearModel gearModel, float speed)
|
|
{
|
|
GameObject gear = Instantiate(gearPrefab, pos, Quaternion.identity);
|
|
gear.transform.parent = transform.GetChild(0).transform;
|
|
gear.GetComponent<Gear>().Data = gearModel;
|
|
return gear;
|
|
}
|
|
|
|
public void Succeed()
|
|
{
|
|
Debug.Log("达成目标");
|
|
}
|
|
}
|
|
} |