[英]Detect clicks on Object with Physics.Raycast and Physics2D.Raycast
我的場景中有一個帶有零件盒對撞機2D的空游戲對象。
我使用以下命令將腳本附加到此游戲對象:
void OnMouseDown()
{
Debug.Log("clic");
}
但是,當我單擊游戲對象時,沒有任何效果。 你有什么想法 ? 如何檢測盒對撞機的點擊?
使用射線投射。 檢查是否按下了鼠標左鍵。 如果是這樣,請從發生鼠標單擊的位置到發生碰撞的位置發出不可見的光線。 對於3D對象,請使用:
3D模型:
void check3DObjectClicked ()
{
if (Input.GetMouseButtonDown (0)) {
Debug.Log ("Mouse is pressed down");
RaycastHit hitInfo = new RaycastHit ();
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), out hitInfo)) {
Debug.Log ("Object Hit is " + hitInfo.collider.gameObject.name);
//If you want it to only detect some certain game object it hits, you can do that here
if (hitInfo.collider.gameObject.CompareTag ("Dog")) {
Debug.Log ("Dog hit");
//do something to dog here
} else if (hitInfo.collider.gameObject.CompareTag ("Cat")) {
Debug.Log ("Cat hit");
//do something to cat here
}
}
}
}
2D Sprite:
上面的解決方案適用於3D。 如果希望它適用於2D, 則將 Physics.Raycast替換為Physics2D.Raycast 。 例如:
void check2DObjectClicked()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("Mouse is pressed down");
Camera cam = Camera.main;
//Raycast depends on camera projection mode
Vector2 origin = Vector2.zero;
Vector2 dir = Vector2.zero;
if (cam.orthographic)
{
origin = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
origin = ray.origin;
dir = ray.direction;
}
RaycastHit2D hit = Physics2D.Raycast(origin, dir);
//Check if we hit anything
if (hit)
{
Debug.Log("We hit " + hit.collider.name);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.