";棒“;gameObject到另一个碰撞后的gameObject
本文关键字:gameObject 碰撞 另一个 quot | 更新日期: 2023-09-27 18:19:36
目前,我正在使用以下代码使对象粘附到其他游戏对象:
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
gameObject.transform.SetParent (col.gameObject.transform);
}
它运行得很好,但也会引发许多其他问题。例如,碰撞后,它将无法再检测到碰撞。
是否有人拥有此代码的替代方案(使一个gameObject在碰撞后粘在另一个上)?
这是一个开始,请注意,这不考虑轮换,我相信你会明白的,对吧?)
protected Transform stuckTo = null;
protected Vector3 offset = Vector3.zero;
public void LateUpdate()
{
if (stuckTo != null)
transform.position = stuckTo.position - offset;
}
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
if(stuckTo == null
|| stuckTo != col.gameObject.transform)
offset = col.gameObject.transform.position - transform.position;
stuckTo = col.gameObject.transform;
}
编辑:正如承诺的那样,这里有一个更高级的版本,将轮换考虑在内:
Transform stuckTo;
Quaternion offset;
Quaternion look;
float distance;
public void LateUpdate()
{
if (stuckTo != null)
{
Vector3 dir = offset * stuckTo.forward;
transform.position = stuckTo.position - (dir * distance);
transform.rotation = stuckTo.rotation * look;
}
}
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
if(stuckTo == null
|| stuckTo != col.gameObject.transform)
{
Vector3 diff = col.gameObject.transform.position - transform.position;
offset = Quaternion.FromToRotation (col.gameObject.transform.forward, diff.normalized);
look = Quaternion.FromToRotation (col.gameObject.transform.forward, transform.forward);
distance = diff.magnitude;
stuckTo = col.gameObject.transform;
}
}