Unity3D在2D游戏中获取触屏物体的方法

我们的需求是:

假如屏幕中一个棋盘,每个棋子是button构成的,我们希望手指或者鼠标在哪里,就显示那个位置的button信息。

网上有很多获取触屏物体信息的信息的方法如下面代码所示:

cs 复制代码
Camera cam = Camera.main; // pre-defined
...

if (touch.phase == TouchPhase.Bagan)){ // 如果触控点状态为按下
   Ray ray = cam.ScreenPointToRay(Input.position);
   RaycastHit hit;
   if (Physics.Raycast(ray, out hit))
   {
       Debug.Log(hit.transform.name); // 输出点击物体名称
       startTouchPos = touch.position;
   } 
}

但是在实际测试时,发现可以进入到if (touch.phase == TouchPhase.Bagan))这个分支中,但是Physics.Raycast(ray, out hit)始终返回false。

错误1:Physics.Raycast方法只适用于3D场景

翻阅资料发现:Physics.Raycast方法适用于3D场景下,在2D场景下是不会起作用的。

于是我们找到了2D场景下的替代方法:Physics2D.Raycast()

该方法最简单的定义如下:

public static RaycastHit2D Raycast(Vector2 origin, Vector2 direction)

需要传入两个参数:origin是射线发射的起始位置,direction是射线的方向。

为了测试效果,我们制作了demo如下:

RayHandler对象对应的脚本RayHandler.cs如下:

cs 复制代码
public class RayHandler : MonoBehaviour
{
    // Start is called before the first frame update
    private Camera _camera;

    void Start()
    {
        _camera = Camera.main;  
    }

    // Update is called once per frame
    void Update()
    {

        Vector2 direction = Input.mousePosition - Camera.main.transform.position;
        RaycastHit2D hit = Physics2D.Raycast(Camera.main.transform.position, direction);
        Debug.DrawRay(Camera.main.transform.position, direction, Color.red, 30f);
        if (hit.collider != null)
        {
            Debug.Log("true");
        }
      
    }
}

加入Debug.DrawRay(Camera.main.transform.position, direction, Color.red, 30f);是为了更方便地观察到射线的情况。

我们发现射线(红色线段)穿透button的次数大大多于true日志的次数。

这个方案还有个缺陷:如果从一个点发出射线,当出发点和终点之间有其他物体时,射线检测到的是另一个物体,而不是当前鼠标(触屏点)对应的物体。

错误2:普通UI如Image、Button等一般用射线是不起作用的。

EventSystem.current.RaycastAll()可以将当前屏幕上的所有可检测的物体全部检测到,该方法需要自己构造一个PointerEventData参数传入检测的点坐标。

参考代码如下:

cs 复制代码
 void Update()
 {
     PointerEventData pointerData = new PointerEventData(EventSystem.current);
     pointerData.position = Input.mousePosition;
     List<RaycastResult> results = new List<RaycastResult>();
     EventSystem.current.RaycastAll(pointerData, results);

     if (results.Count > 0) {
         foreach (RaycastResult r in results) {
             if (r.gameObject.layer == LayerMask.NameToLayer("button")) {
                 Debug.Log(r.gameObject.name);
             }
         }
     }
     
 }

针对Button1和Button2添加了button的layer,这样就可以过滤出我们想要的物体。

另外我做了测试,创建了Empty、2D Object,使用Physics2D.RaycastAll也没有生效

测试的代码如下:

cs 复制代码
    void Update()
    {
        Vector3 pos = GetTouchPosition();
        Ray myRay = Camera.main.ScreenPointToRay(pos);
        RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(myRay.origin.x, myRay.origin.y), Vector2.zero);
        if(hits.Length > 0)
        {
            Debug.Log("true");
        }


    }

    public static Vector3 GetTouchPosition()
    {
        return Input.mousePosition;
    }

可能Physics2D.RaycastAll适用于一个游戏Player向另一个物体发射射线,而不是从触屏点发射射线。反正从触屏点通过Physics.Raycast类函数发射射线我始终没有成功过!!!!

相关推荐
2401_841495644 小时前
【LeetCode刷题】跳跃游戏
数据结构·python·算法·leetcode·游戏·贪心算法·数组
呆呆敲代码的小Y5 小时前
【Unity实战篇】| 游戏滑动框添加特殊效果,如实时高亮显示、曲线滑动等
游戏·unity·游戏引擎·实战·u3d·免费游戏·unity实战技巧
技术小甜甜6 小时前
[Godot] 在 Godot 3.1 中配置 ADB 可执行文件的实用指南
游戏·adb·游戏引擎·godot
技术小甜甜6 小时前
【Godot】【入门】Godot 是什么?适合做哪些类型的游戏(附路线图+避坑清单)
游戏·游戏引擎·godot
xiaohai@Linux7 小时前
STM32之移植原生的infoNES nes游戏模拟器源码实现游戏自由!!!(原生纯C版,非汇编版)
stm32·游戏·模拟器·infones·nes游戏机
Sui_Network21 小时前
备受期待的 POP 射击游戏 XOCIETY 正式在 Epic Games Store 开启体验
人工智能·游戏·rpc·区块链·量子计算·graphql
coder-pig1 天前
Holopix AI + TRAE SOLO | 复刻 GBA 游戏-“口袋妖怪“
人工智能·游戏
wanhengidc1 天前
在线服务器的应用场景都有哪些?
运维·服务器·科技·游戏·智能手机·云计算
UWA1 天前
Gears 实测室:第八期・全面透视4X游戏性能瓶颈
游戏·性能优化·游戏开发·uwa
yuegu7771 天前
Electron for鸿蒙PC实战项目之麻将游戏
游戏·electron·harmonyos