7 c# collision-detection collision unity-game-engine unity5
如何在碰撞后正确地将GameObject附加(或"粘贴")到另一个GameObject?问题:我希望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;
}
Run Code Online (Sandbox Code Playgroud)
此代码使GameObject在碰撞后完美连接.但是当GameObject改变比例(当它附着时)时,它在视觉上不再看起来与它碰撞的任何东西相关联.基本上,这段代码使GameObject在碰撞时仅保留原始比例.如何使GameObject始终坚持与碰撞的任何东西?它在过程中的规模是多少?我想避免养育子女:"虽然有点不安全,但是养育对手会造成奇怪的结果,比如随机传送或物体开始疯狂地移动和旋转等等." - SamedTarıkÇETİN:评论.
缩放脚本:
public Transform object1; //this is the object that my future-scaling GameObject collided with.
public Transform object2; //another object, the same scale as object1, somewhere else
//(or vice versa)
void Update ()
{
float distance = Vector3.Distance (object1.position, object2.position);
float original_width = 10;
if (distance <= 10)
{
float scale_x = distance / original_width;
scale_x = Mathf.Min (scale_x, 3.0f);
transform.localScale = new Vector3 (scale_x * 3.0f, 3.0f / scale_x, 3.0f);
}
}
Run Code Online (Sandbox Code Playgroud)
改变全球
protected Collider stuckTo = null;
Run Code Online (Sandbox Code Playgroud)
///// 使用 Collider 而不是变换对象。您可能会得到更好的解决方案。如果它有效或给出任何错误,请通知我,因为我还没有尝试它是否有效,我想知道。
void OnCollisionEnter(Collision col)
{
rb = GetComponent<Rigidbody>();
rb.isKinematic = true;
if(stuckTo == null || stuckTo != col.gameObject.transform)
offset = col.collider.bounds.center - transform.position;
stuckTo = col.collider;
}
public void LateUpdate()
{
if (stuckTo != null)
{
Vector3 distance=stuckTo.bounds.extents + GetComponent<Collider>().bounds.extents;
transform.position = stuckTo.bounds.center + distance;
}
}
Run Code Online (Sandbox Code Playgroud)