TaiZhouCangChu_VRanime/Assets/动画/Scripts/Morder/SetParentScript.cs

82 lines
2.9 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using UnityEngine;
using System.Collections;
public class SetParentScript : MonoBehaviour
{
public GameObject objectA; // 想要成为子对象并且锁定/解锁的对象
public GameObject objectB; // 想要成为父对象的对象
// Adjustable positions and rotations
public Vector3 positionOffset; // 调整的位置偏移量
public Vector3 rotationOffset; // 调整的旋转偏移量
private Rigidbody rbA; // objectA的Rigidbody组件
private Transform originalParent; // objectA的原始父对象
private RigidbodyConstraints originalConstraints; // objectA原始的Rigidbody约束
private Vector3 originalPosition; // objectA的原始位置
private Quaternion originalRotation; // objectA的原始旋转
void Start()
{
// 获取objectA的Rigidbody组件
rbA = objectA.GetComponent<Rigidbody>();
if (rbA == null)
{
// 如果没有找到Rigidbody组件则记录错误
Debug.LogError("没有在objectA上找到Rigidbody组件");
return;
}
// 保存objectA的原始父对象、位置、旋转和Rigidbody约束
originalParent = objectA.transform.parent;
originalPosition = objectA.transform.position;
originalRotation = objectA.transform.rotation;
originalConstraints = rbA.constraints;
// 锁定Rigidbody并在3秒后改变父对象和解锁
LockMotionAndRotation();
Invoke("ChangeParentAndUnlock", 3f);
}
void ChangeParentAndUnlock()
{
// 改变objectA的父对象并解锁Rigidbody
SetParent();
UnlockMotionAndRotation();
}
void SetParent()
{
// 设置objectA为objectB的子对象
objectA.transform.SetParent(objectB.transform);
}
void LockMotionAndRotation()
{
// 锁定位置和旋转通过设置Rigidbody的约束
rbA.constraints = RigidbodyConstraints.FreezePosition | RigidbodyConstraints.FreezeRotation;
}
void UnlockMotionAndRotation()
{
// 解锁所有Rigidbody约束以允许再次移动和旋转
rbA.constraints = RigidbodyConstraints.None;
}
public void ResetToInitialState()
{
// 将objectA的父对象重置为其原始父对象
objectA.transform.SetParent(originalParent);
// 将objectA的位置重置为其原始位置并应用偏移量
objectA.transform.position = originalPosition + positionOffset;
// 将objectA的旋转重置为其原始旋转并应用偏移量
objectA.transform.rotation = originalRotation * Quaternion.Euler(rotationOffset);
// 将objectA的Rigidbody约束重置为最初的约束
rbA.constraints = originalConstraints;
// 可选重新锁定并准备在3秒后改变父对象和解锁
LockMotionAndRotation();
Invoke("ChangeParentAndUnlock", 3f);
}
}