開發(fā)中遇到這樣的問題, 高速運動的小物體在碰到比較薄的墻體時不會觸發(fā) OnCollisionEnter
方法
根據(jù)網(wǎng)上說的將運動物體 Rigidbody
組件的屬性Collision Detection
設置為Continuous
或者Continuous Dynamic
都沒有用. 因為物體的速度太快(100), 而且墻體太薄了(0.03).
所以只能使用射線檢測(Physics.Raycast)
具體的思路是, 獲取物體的運行方向, 并設置成射線的發(fā)射方向, 然后將射線的長度設置成物體(我這邊是球體)的尺寸, 然后通過Physics.Raycast方法返回的值來判斷是否發(fā)生了碰撞, 與什么物體發(fā)生了碰撞.
具體代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 測試代碼2
/// 高速移動的小球去碰撞靜止的非常薄的墻體
/// 當使用射線檢測時
/// </summary>
public class BoneMove_2 : MonoBehaviour
{
//等待子彈發(fā)射時間
float waitTime = 3;
//移動速度
public float speed = 100;
//移動方向
Vector3 moveDir = new Vector3 (-1, 0, 0);
//決定是否發(fā)射子彈(這里是很小的球)
bool isStart = false;
//檢測射線的長度
float rayMaxLen = 0.1f;
// void Awake() {
// rayMaxLen = transform.localScale.x;
// Debug.Log ("rayLen = " + rayMaxLen);
// }
void Start ()
{
//Debug.DrawLine (transform.position, new Vector3 (-10, 0, 0), Color.red);
//Debug.DrawRay (transform.position, new Vector3 (-10, 0, 0), Color.red, 10);
StartCoroutine (beganMove ());
}
// Update is called once per frame
void Update ()
{
if (isStart) {
// Debug.DrawRay (transform.position, moveDir, Color.blue, 1);
Vector3 location = transform.position; //射線發(fā)射點
Vector3 dir = moveDir; //射線發(fā)射方向
RaycastHit hit; //射線碰撞到的物體的信息
if (Physics.Raycast (location, dir, out hit, rayMaxLen)) { //當射線碰撞到有collider的物體時
Debug.DrawLine (location, hit.point, Color.red); //scene視圖中繪制射線
Debug.Log ("發(fā)生碰撞");
// Debug.Log ("hit x = " + hit.transform.position.x);
// Debug.Log (hit.transform.name);
// Debug.Log (hit.transform.tag);
} else {//沒有碰撞時
transform.Translate (moveDir * speed * Time.deltaTime);
}
}
}
IEnumerator beganMove ()
{
yield return new WaitForSeconds (waitTime);
isStart = true;
}
void OnCollisionEnter (Collision collision)
{
Debug.Log ("1");
foreach (ContactPoint contact in collision.contacts) {
Debug.DrawRay (contact.point, contact.normal, Color.white);
}
}
}
遇到的問題:
也不知道是不是電腦的原因, 有時候Physics.Raycast (location, dir, out hit, rayMaxLen)
居然會沒有返回值, 導致檢測不到.
如有更好的解決方法期待共同討論, 共同進步
補充圖片:
-
高速運動的小球
Snip20171115_1.png -
薄的墻體
Snip20171115_2.png -
場景中的位置關系
Snip20171115_3.png -
切換碰撞檢測模式也沒用(如果速度很高時)
Snip20171115_4.png -
使用射線檢測, 檢測到發(fā)送碰撞時的截圖
Snip20171115_5.png
Snip20171115_6.png