Unity3D的射線碰撞檢測方法(fǎ)總結(jié)
2019/12/12 點擊:
射線檢測故(gù)名就是通(tōng)過射線去檢測是否和碰撞器產生了交集,和碰撞(zhuàng)器與碰撞器發生交集一樣,如果檢測到了會返回(huí)一個真。
射線的用法很多:比如檢測是否跳(tiào)躍,通過向地麵投射射線控製(zhì)在地麵時候可以跳起。
射擊遊戲中可以通過定長射(shè)線去(qù)判斷目標物體是(shì)否被擊中等
主要用到的工具類有:
- Physics
- RaycastHit 光線投射碰撞
- Ray 射線
第1種方法:Physics.Linecast 線(xiàn)性投射
從開始位置到結束位置做一個光線投射(shè),如果與碰撞(zhuàng)體交互,返回(huí)真(zhēn)。
Debug.DrawLine(transform.position, Line_floor.position, Color.red, 1f);
bool grounded = Physics.Linecast(transform.position, Line_floor.position, 1 << LayerMask.NameToLayer("Ground"));
if (grounded)
{
Debug.LogError("發生了碰撞");
}
else {
Debug.LogError("碰撞結束");
}
第二種方法:在場景中投下可與所(suǒ)有(yǒu)碰撞器碰撞的一條光線。可控製投射方向和投射長度。Vector3 fwd = transform.TransformDirection(-Vector3.up);
bool grounded = Physics.Raycast(transform.position,fwd, 10 );
if (grounded)
{
Debug.LogError("發生了(le)碰撞");
}
else
{
Debug.LogError("碰撞結束");
}
第三種方法:在場景中投下可與所有碰撞(zhuàng)器碰撞的一條光線,並返回碰撞的細節信息。
RaycastHit hit;
bool grounded = Physics.Raycast(transform.position, -Vector3.up, out hit);
// 可控製投射距離bool grounded = Physics.Raycast(transform.position, -Vector3.up, out hit,100.0);
if (grounded)
{
Debug.LogError("發生(shēng)了碰撞(zhuàng)");
Debug.LogError("距離是:" + hit.distance);
Debug.LogError("被碰撞的物體是:" + hit.collider.gameObject.name);
}
else {
Debug.LogError("碰撞結束(shù)");
}
注意:這裏(lǐ)返回的碰撞(zhuàng)器的信(xìn)息是依次的,先返回第一個碰撞的,第一個碰撞結束後才返回第二個。
第四種方法:Physics.RaycastAll 所有光線投射。
投射一條光線並返(fǎn)回所有碰撞,也就是(shì)投射光(guāng)線並返回一個RaycastHit[]結構體。
RaycastHit[] hits;
hits = Physics.RaycastAll(transform.position, -Vector3.up, 100.0F);
int i = 0;
while (i < hits.Length)
{
Debug.LogError("發生了碰撞");
RaycastHit hit = hits[i];
Debug.LogError("被碰撞的物體(tǐ)是:" + hit.collider.gameObject.name);
i++;
}
第(dì)五種方法:控製碰撞的層,可以設置射線的長度(dù),並且(qiě)用debug查看(kàn)射線的長度。
使用層的時候,要注意,要給別的對象也附上層的名字,不能用缺省,會出問題。
RaycastHit hit;
// Debug.DrawLine()
bool grounded = Physics.Raycast(transform.position, transform.up, out hit, 10000f, 1 << LayerMask.NameToLayer("Diren"));
Debug.DrawRay(transform.position, transform.up * 10000f, Color.red);
if (grounded)
{
Debug.LogError("發生了碰撞");
Debug.LogError("距離是:" + hit.distance);
Debug.LogError("被碰撞的物(wù)體(tǐ)是(shì):" + hit.collider.gameObject.name);}
else {
Debug.LogError("碰撞結束");
}
第五種:Physics.OverlapSphere 相交球。返回球型半徑之內(包括半(bàn)徑)的所有碰(pèng)撞(zhuàng)體 collider[]。可用於拾取物品用。此方法在VR交互時為了提高用戶體驗,使用較多。
Collider[] col = Physics.OverlapSphere(transform.position,1f, 1 << LayerMask.NameToLayer("zhuangbei"));
if (col.Length > 0)
{
foreach (Collider zhuangbei in col)
{
zhuangbei.gameObject.GetComponent().material.color = Color.red;
}
}
- 上一篇:Unity3D跨屏幕、全屏顯示方法 2019/12/14
- 下一篇:WISEGLOVE數據手套的部分(fèn)高校客戶(hù) 2019/11/29
