【发布时间】:2016-03-02 17:35:45
【问题描述】:
这个脚本让一个立方体“粘”在它碰撞的任何物体上。问题在于,当它以相对较高或中等速度运行时(或者当设备本身速度较慢时),立方体往往会“进入”它所碰撞的物体,然后粘在它上面。我必须进行哪些更改才能解决此问题?
为了让这个脚本工作,一个游戏对象必须有bool _sticksToObjects = true;,另一个必须有bool _sticksToObjects = false;
我尝试将Rigidbody 的Collision Detection 模式转换为Continuous 或Continuous Dynamic
我认为我的脚本取决于帧速率。这可能就是问题所在。
普通“附加”:
异常“附加”:
Rigidbody _rigidBody;
Transform _meshTransform;
bool _sticksToObjects = true;
public Transform _stuckTo = null;
protected Vector3 _offset = Vector3.zero;
void Awake()
{
GameObject CubeMesh = GameObject.FindWithTag ("CubeMesh");
GameObject Cube = GameObject.FindWithTag ("Cube");
_rigidBody = Cube.GetComponent<Rigidbody> ();
_meshTransform = CubeMesh.GetComponent<Transform> ();
}
void Update()
{
if (_stuckTo != null)
{
transform.position = _stuckTo.position - _offset;
}
}
void OnCollisionEnter(Collision collision)
{
if (!_sticksToObjects) {
return;
}
_rigidBody.isKinematic = true;
// Get the approximate collision point and normal, as there
// may be multipled collision points
Vector3 contactPoint = Vector3.zero;
Vector3 contactNormal = Vector3.zero;
for (int i = 0; i < collision.contacts.Length; i++) {
contactPoint += collision.contacts [i].point;
contactNormal += collision.contacts [i].normal;
}
// Get the final, approximate, point and normal of collision
contactPoint /= collision.contacts.Length;
contactNormal /= collision.contacts.Length;
// Move object to the collision point
// This acts as setting the pivot point of the cube mesh to the collision point
transform.position = contactPoint;
// Adjust the local position of the cube so it is flush with the pivot point
Vector3 meshLocalPosition = Vector3.zero;
// Move the child so the side is at the collision point.
// A x local position of 0 means the child is centered on the parent,
// a value of 0.5 means it's to the right, and a value of -0.5 means it to the left
meshLocalPosition.x = (0.5f * contactNormal.x);
_meshTransform.localPosition = meshLocalPosition;
if (_stuckTo == null || _stuckTo != collision.gameObject.transform) {
_offset = collision.gameObject.transform.position - transform.position;
}
_stuckTo = collision.gameObject.transform;
}
以下是 Unity 编辑器的一些截图:
【问题讨论】:
-
@JoeBlow 这不会改变任何东西。 “在检查器中拖动连接”是什么意思?
-
@JoeBlow 我已经编辑了我的问题以使事情更清楚。
-
你要做的这件事很难正确地完成,并且不能使用unity3d的内置物理引擎来完成。
-
@JerrySwitalski 现在关于赏金问题。
-
@JoeBlow 现在关于赏金问题。