c# - 当父对象移动时,如何防止子对象滑离父对象?
问题描述
public GameObject Miffy;
void OnTriggerEnter(Collider collider)
{
//when space key is pressed and collider is miffy(tagged Player)
if (Input.GetKey(KeyCode.P) && collider.gameObject.tag == "Player")
{
Ball.transform.parent = Miffy.transform;
Ball.transform.localPosition = new Vector3(0, 0, 0);
}
}
private void Update()
{
//when key D is pressed miffy is no longer parent to ball object.
if (Input.GetKeyDown(KeyCode.D))
{
Ball.transform.SetParent(null);
}
}
子对象(球)随着父对象(Miffy)的移动而增加距离。
解决方案
似乎Ball
是一个Rigidbody
.
您根本不应该嵌套多个Rigidbody
或移动 a 的父级Rigidbody
。
而是使用FixedJoint
.
Afaik 你可以简单地做类似的事情
private Rigidbody miffyRigidbody;
private FixedJoint BallFixedJoint;
void OnTriggerEnter(Collider collider)
{
isColliding = true;
if (collider.CompareTag("Player"))
{
miffyRigidbody = collider.attachedRigidbody;
}
}
void OnTriggerExit(Collider collider)
{
if (collider.CompareTag("Player"))
{
miffyRigidbody = null;
}
}
private void Update()
{
if(miffyRigidbody && Input.GetKeyDown(KeyCode.P))
{
if(!BallFixedJoint)
{
BallFixedJoint = Ball.GetComponent<FixedJoint>();
if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
}
BallFixedJoint.connectedBody = Miffy.GetComponent<Rigidbody>();
}
if(Input.GetKeyUp(KeyCode.P))
{
if(!BallFixedJoint)
{
BallFixedJoint = Ball.GetComponent<FixedJoint>();
if(!BallFixedJoint) BallFixedJoint = Ball.AddComponent<FixedJoint>();
}
BallFixedJoint.connectedBody = null;
}
}
推荐阅读
- flutter - 如何使用 mockito 测试空值?
- typescript - 如何重命名 Typescript 类型的某些键
- c# - NavMeshAgent 首先旋转到目标方向然后移动到它?
- python - PyAutoGui 鼠标不会移动
- firebase - Flutter Web 支持 - Firebase 集成问题
- python - 我如何计算 FICO 分数的权重?
- python - 可以使用 Pandas read_csv 更改原始文件吗?
- ruby-on-rails - 收到错误“错误:参数数量错误(给定 0,预期 1;所需关键字:url)”
- kubernetes - 使用多个代理配置 kafka 连接
- html - 如何使用htmlparser2转换html中的内容