101 lines
3.0 KiB
C#
101 lines
3.0 KiB
C#
using System;
|
|
using UnityEngine;
|
|
|
|
namespace NBF
|
|
{
|
|
public class JointPinchController : MonoBehaviour
|
|
{
|
|
// 配置参数
|
|
[SerializeField] private float moveSpeed = 5f;
|
|
[SerializeField] private float snapDistance = 0.1f;
|
|
|
|
// 组件引用
|
|
private ConfigurableJoint originalSpringJoint;
|
|
private FixedJoint pinchJoint;
|
|
private Rigidbody rb;
|
|
|
|
|
|
private float maxCatchupDuration = 0.5f;
|
|
private Transform targetTransform;
|
|
private float originalSpring;
|
|
private float pinchElapsedTime;
|
|
|
|
|
|
public bool isPinched { get; private set; }
|
|
|
|
|
|
private bool moveToTargetDone;
|
|
private float _speed;
|
|
|
|
void Start()
|
|
{
|
|
rb = GetComponent<Rigidbody>();
|
|
originalSpringJoint = GetComponent<ConfigurableJoint>();
|
|
}
|
|
|
|
void FixedUpdate()
|
|
{
|
|
if (isPinched && !moveToTargetDone && targetTransform != null)
|
|
{
|
|
pinchElapsedTime += Time.fixedDeltaTime;
|
|
// transform.position =
|
|
// Vector3.MoveTowards(transform.position, targetTransform.position, Time.deltaTime * _speed);
|
|
rb.MovePosition(Vector3.MoveTowards(transform.position, targetTransform.position,
|
|
Time.deltaTime * _speed));
|
|
if (Vector3.Distance(transform.position, targetTransform.position) < 0.1f ||
|
|
pinchElapsedTime >= maxCatchupDuration)
|
|
{
|
|
moveToTargetDone = true;
|
|
}
|
|
}
|
|
|
|
SyncPosition();
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
SyncPosition();
|
|
}
|
|
|
|
private void SyncPosition()
|
|
{
|
|
if (!isPinched) return;
|
|
if (!moveToTargetDone) return;
|
|
rb.MovePosition(targetTransform.position);
|
|
}
|
|
|
|
// 外部调用:开始捏住流程
|
|
public void StartPinch(Transform fingerTransform, float speed = 3, float _maxCatchupDuration = 0.3f)
|
|
{
|
|
_speed = speed;
|
|
Rigidbody fingerRb = fingerTransform.GetComponent<Rigidbody>();
|
|
if (fingerRb == null)
|
|
{
|
|
Debug.LogError("目标必须带有Rigidbody");
|
|
return;
|
|
}
|
|
|
|
maxCatchupDuration = _maxCatchupDuration;
|
|
pinchElapsedTime = 0f;
|
|
isPinched = true;
|
|
rb.useGravity = false;
|
|
rb.isKinematic = true;
|
|
moveToTargetDone = false;
|
|
targetTransform = fingerTransform;
|
|
}
|
|
|
|
|
|
// 外部调用:释放捏住
|
|
public void ReleasePinch()
|
|
{
|
|
isPinched = false;
|
|
rb.useGravity = true;
|
|
rb.linearVelocity = Vector3.zero;
|
|
rb.angularVelocity = Vector3.zero;
|
|
rb.isKinematic = false;
|
|
rb.linearVelocity = Vector3.zero;
|
|
rb.angularVelocity = Vector3.zero;
|
|
targetTransform = null;
|
|
}
|
|
}
|
|
} |