射线在2d中用来检测点击
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Ray2DTest : MonoBehaviour
{
[SerializeField]
private GraphicRaycaster graphicRaycaster;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
#region 物体
//鼠标点击测试
//MouseClickTest();
//MouseClickTest2();
//手机触屏测试
//MobileTouchTest();
//点击的点周围一定半径的所有物体
OverlapCircleAll();
#endregion
#region UI
RayUITest();
#endregion
}
private void OverlapCircleAll() {
if (Input.GetMouseButtonDown(0))
{
Vector3 vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//获取射线碰撞信息
Collider2D[] collider2Ds = Physics2D.OverlapCircleAll(vector3, 10);
if (collider2Ds.Length > 0) {
Debug.Log("当前点半径为10的范围内有" + collider2Ds.Length + "个物体");
}
}
}
private void RayUITest() {
if (Input.GetMouseButtonDown(0))
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = Input.mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
graphicRaycaster.Raycast(pointerEventData, raycastResults);
if (raycastResults.Count > 0)
{
GameObject go = raycastResults[0].gameObject;
Debug.Log("点击到了UI上的" + go.name);
}
}
}
private void MobileTouchTest()
{
if (Input.touchCount == 1)
{
Vector2 vector2 = Camera.main.ScreenToWorldPoint(Input.touches[0].position);
RaycastHit2D raycast = Physics2D.Raycast(vector2, Vector2.zero);
if (raycast.collider != null)
{
Debug.Log("点击到了" + raycast.collider.name);
}
}
}
private void MouseClickTest() {
if (Input.GetMouseButtonDown(0))
{
Vector3 vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//获取射线碰撞信息
RaycastHit2D raycast = Physics2D.Raycast(vector3, Vector2.zero);
if (raycast.collider != null)
{
Debug.Log("点击到了" + raycast.collider.name);
}
}
}
private void MouseClickTest2()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 vector3 = Camera.main.ScreenToWorldPoint(Input.mousePosition);
//获取点击到的碰撞体
Collider2D collider2 = Physics2D.OverlapPoint(vector3);
if (collider2 != null)
{
Debug.Log("点击到了" + collider2.name);
}
}
}
}