[英]“Stick” gameObject to another gameObject after collision?
Currently, I am using the following code to make objects stick to other gameObjects: 当前,我正在使用以下代码使对象粘在其他gameObjects上:
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
gameObject.transform.SetParent (col.gameObject.transform);
}
It works perfectly, but it causes many other problems. 它可以完美运行,但是会引起许多其他问题。 For example, after colliding, it can no longer detect collisions.
例如,碰撞后,它不再能够检测到碰撞。
Does someone possess an alternative to this code (which makes a gameObject stick to another one after collision)? 有人对此代码有替代方法吗(碰撞后一个gameObject会粘到另一个对象)?
Here's a start for you, please note that this does not take into account rotation, that i'm sure you will be able to figure out, right? 这是您的一个开始,请注意,这没有考虑轮换,我确定您将能够弄清楚,对吗? ;)
;)
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;
}
EDIT: As promised, here is a more advanced version taking rotation into account: 编辑:如所承诺的,这是一个更高级的版本,考虑了轮换:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.