C# 当父对象移动时,如何防止子对象滑离父对象?
子对象(球)随着父对象(Miffy)的移动而增加距离。似乎C# 当父对象移动时,如何防止子对象滑离父对象?,c#,unity3d,3d,parent-child,C#,Unity3d,3d,Parent Child,子对象(球)随着父对象(Miffy)的移动而增加距离。似乎Ball是一个刚体 您应该不嵌套多个刚体或移动刚体的父对象 而是使用一个 好吧,你可以做一些简单的事情 public GameObject Miffy; void OnTriggerEnter(Collider collider) { //when space key is pressed and collider is miffy(tagged Player) if (Input.GetKey(KeyCode
Ball
是一个刚体
您应该不嵌套多个刚体
或移动刚体
的父对象
而是使用一个
好吧,你可以做一些简单的事情
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);
}
}
private刚体miffy刚体;
专用固定接头;球形固定接头;
void ontriggenter(碰撞器-碰撞器)
{
isColliding=true;
if(对撞机比较标记(“播放器”))
{
miffyRigidbody=collider.AttacheDrigBody;
}
}
void OnTriggerExit(碰撞器-碰撞器)
{
if(对撞机比较标记(“播放器”))
{
miffyRigidbody=null;
}
}
私有void更新()
{
if(miffyRigidbody&&Input.GetKeyDown(KeyCode.P))
{
如果(!球形固定接头)
{
BallFixedJoint=Ball.GetComponent();
如果(!BallFixedJoint)BallFixedJoint=Ball.AddComponent();
}
BallFixedJoint.connectedBody=Miffy.GetComponent();
}
if(Input.GetKeyUp(KeyCode.P))
{
如果(!球形固定接头)
{
BallFixedJoint=Ball.GetComponent();
如果(!BallFixedJoint)BallFixedJoint=Ball.AddComponent();
}
BallFixedJoint.connectedBody=null;
}
}
这不是关于Visual Studio的问题,因此我已删除了标记。恩,OnTiggerEnter将只在一个帧中出现,因此您可能缺少联系点。请尝试相同的代码,但使用OnTiggerStay测试这是否是问题所在。另外,您使用的是KeyCode.P,它不是空格…您是否确保if中的代码实际正在执行?因为我非常怀疑这是真的ontriggenter
将仅针对单个帧触发(帧触点处于打开状态),因此您可能不会按该帧的P
。尝试用OnTriggerStay(碰撞器-碰撞器)
instead@Jax297抱歉,我将关键点更改为P,OnTiggerEnter工作。当父对象移动时,我可以将对象设置为子对象的父对象。子对象也移动了,但最终从父对象滑开,但仍然以与父对象相同的方式移动。球是刚体吗?如果是这样:不要嵌套刚体!宁可使用
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;
}
}