using System.Collections; using System.Collections.Generic; using System.Linq; 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(); } 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 != null) { draggingGear.Move(GetMouseAsWorldPoint() + offset); } // 鼠标释放 if (Input.GetMouseButtonUp(0)) // 检查鼠标左键释放 { draggingGear?.StopMove(); if (draggingGear.targetShaft != null) { 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 != null && hit.collider.CompareTag("Moveable")) { offset = hit.collider.transform.position - GetMouseAsWorldPoint(); draggingGear = hit.collider.gameObject.GetComponent(); draggingGear.StartMove(); } } /// /// 判断吸附位置 /// /// 齿轮当前位置 /// 齿轮半径 /// 能够被吸附的轴 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); } /// /// 生成齿轮 /// /// 位置 /// 齿轮数据 /// 速度 /// 齿轮Obj 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().Data = gearModel; return gear; } } public class ShaftPair { public int shaft1; public int shaft2; public float distence; } }