![](/img/trans.png)
[英]Detect clicks on Object with Physics.Raycast and Physics2D.Raycast
[英]How to detect hitting a layer with a ray using Physics2d.raycast
我正在嘗試使用c#為游戲制作一個建築方面。 我需要檢測我是否在某個層上構建。
我曾嘗試多次編輯下面的代碼,但我似乎無法找到問題。 我還觀看了多個視頻,這些視頻解釋了我的代碼應該有效,但也許我只是沒有看到一些東西。 任何幫助都會很棒。
這是我用於圖層檢測的代碼:
[SerializeField]
private LayerMask weaponNoBuildLayer;
[SerializeField]
private LayerMask pathNoBuildLayer;
private bool buildBlocked = false;
private GameObject blockTemplate;
blockTemplate.transform.position = new Vector2(newPosx, newPosy);
RaycastHit2D rayHit;
if(currentBlock.isWeapon == true)
{
rayHit = Physics2D.Raycast(blockTemplate.transform.position, Vector2.zero, Mathf.Infinity, weaponNoBuildLayer);
}
else
{
rayHit = Physics2D.Raycast(blockTemplate.transform.position, Vector2.zero, Mathf.Infinity, pathNoBuildLayer);
}
if(rayHit.collider != null)
{
Debug.Log("yh");
buildBlocked = true;
}
else
{
buildBlocked = false;
}
這應該做的是,如果光線與某些圖層(在代碼中進一步設置為圖層掩碼)發生沖突,則將布爾buildBlocked設置為true,但它不會和buildBlocked永久錯誤。 再次,任何幫助將不勝感激。
來自https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;
// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
RaycastHit hit;
// Does the ray intersect any objects excluding the player layer
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.