74 lines
2.7 KiB
C#
74 lines
2.7 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
[RequireComponent(typeof(LinearMapping))]
|
|
public class MouseLinearObj : MonoBehaviour
|
|
{
|
|
public Transform startPos, endPos;
|
|
LinearMapping linearMapping;
|
|
Vector3 m_Offset;
|
|
Vector3 m_TargetScreenVec;
|
|
Camera cam;
|
|
private void Start()
|
|
{
|
|
cam = Camera.main;
|
|
linearMapping = GetComponent<LinearMapping>();
|
|
CalculateLinearMapping();
|
|
}
|
|
private void OnEnable()
|
|
{
|
|
transform.localPosition = startPos.localPosition;
|
|
}
|
|
private IEnumerator OnMouseDown()
|
|
{
|
|
if (!cam)
|
|
{
|
|
cam = Camera.main;
|
|
}
|
|
m_TargetScreenVec = cam.WorldToScreenPoint(transform.position);
|
|
m_Offset = transform.position - cam.ScreenToWorldPoint(new Vector3
|
|
(Input.mousePosition.x, Input.mousePosition.y, m_TargetScreenVec.z));
|
|
while (Input.GetMouseButton(0))
|
|
{
|
|
Vector3 temp = cam.ScreenToWorldPoint(new Vector3(Input.mousePosition.x,
|
|
Input.mousePosition.y, m_TargetScreenVec.z)) + m_Offset;
|
|
transform.position = LineMapping(startPos.position,endPos.position, temp);
|
|
linearMapping.value = Mathf.Round(CalculateLinearMapping() * 100) / 100f;
|
|
yield return new WaitForFixedUpdate();
|
|
}
|
|
}
|
|
private void OnMouseDrag()
|
|
{
|
|
if (TryGetComponent(out PC_DragEvent dragEvent))
|
|
{
|
|
dragEvent.stay?.Invoke(gameObject);
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// 直线映射
|
|
/// </summary>
|
|
/// <param name="mAPoint">直线的开始点</param>
|
|
/// <param name="mBPoint">直线的结束点</param>
|
|
/// <param name="mCurrentPoint">当前点位置</param>
|
|
/// <returns>映射位置</returns>
|
|
Vector3 LineMapping(Vector3 mAPoint, Vector3 mBPoint, Vector3 mCurrentPoint)
|
|
{
|
|
Vector3 vectorAB = mBPoint - mAPoint;
|
|
float dotProduct = vectorAB.x * (mCurrentPoint.x - mAPoint.x) + vectorAB.y * (mCurrentPoint.y - mAPoint.y) + vectorAB.z * (mCurrentPoint.z - mAPoint.z);
|
|
float lengthSquared = vectorAB.x * vectorAB.x + vectorAB.y * vectorAB.y + vectorAB.z * vectorAB.z;
|
|
if (dotProduct > lengthSquared) dotProduct = lengthSquared; if (dotProduct < 0) dotProduct = 0; //限制
|
|
Vector3 PointA = mAPoint + vectorAB * dotProduct / lengthSquared;
|
|
Vector3 PointB = mCurrentPoint + (PointA - mCurrentPoint);
|
|
return PointB;
|
|
}
|
|
protected float CalculateLinearMapping()
|
|
{
|
|
Vector3 direction = endPos.position - startPos.position;
|
|
float length = direction.magnitude;
|
|
direction.Normalize();
|
|
|
|
Vector3 displacement = transform.position - startPos.position;
|
|
|
|
return Vector3.Dot(displacement, direction) / length;
|
|
}
|
|
}
|