[Unity] 交互之双击

本文档介绍了如何在Unity中,通过检测鼠标左键双击事件,结合Raycasting实现对屏幕点击位置的物体进行销毁。通过`GetMouseButtonDown`检查鼠标按下,`Physics.Raycast`进行碰撞检测,配合`TouchPhase`判断是否为双击操作,进而控制`Destroy`函数删除相应的游戏对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))//0 1 2 分别代表鼠标的左右和中间按键
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // 主相机屏幕点转换为朝向鼠标点击处的射线
            RaycastHit hitinfo;//用来接受射线的信息
            if (Physics.Raycast(ray,out hitinfo))//射线碰到了物体
            {
                if (Input.touchCount == 1 && Input.GetTouch(0).phase == TouchPhase.Began)
                {//触摸次数为1,一个触摸点,手指刚触摸到屏幕的时候
                    if (Input.GetTouch(0).tapCount==2)//在触摸点0处的敲击次数=2,意味着双击
                    Destroy(hitinfo.collider.gameObject);//双击摧毁事物
                }
            }
        }
    }
}

直接在update里面写就行, // Update is called once per frame,每一帧调用一次

        //
        // 摘要:
        //     Returns true during the frame the user pressed the given mouse button.
        //
        // 参数:
        //   button:
        [NativeThrows]
        public static bool GetMouseButtonDown(int button);

在用户释放鼠标按钮并再次按下它之前,它不会返回 true。 按钮值为 0 表示主按钮(通常是左按钮),1 表示辅助按钮,2 表示中间按钮。

Physics.Raycast(ray,out hitinfo)
在这里插入图片描述

			//ray	光线的起点和方向。
            //hitInfo	如果返回 true,则 hitInfo 将包含有关最近的碰撞体的命中位置的更多信息。
            //bool 当光线与任何碰撞体相交时,返回 true,否则返回 false。

touchCount为触摸次数,也意味着不同的触摸对象

        //
        // 摘要:
        //     Number of touches. Guaranteed not to change throughout the frame. (Read Only)
        public static int touchCount { get; }

GetTouch(0).phase,获得第一个触摸点的状态

index的真正作用,获取触摸到屏幕的第几个点。要知道同一时刻可能有多个点在被触碰,所以如果当前你只有一个手指在按屏幕,那当然就只有(0)了,如果有两个,那0是一个点,1是一个点。以此类推。
gettouch()并不代表你当前时刻一定有手指在触摸屏幕,它只是从touches列表里获取,如果列表为空,自然报错了。而那个touches列表在哪呢?Input.touches,是有这个方法的,所以其实gettouch(0)和Touch[] touches = Input.touches; touches[0] 的效果是一样的。

在这里插入图片描述

hitinfo.collider
射线撞击,因此撞击的物体也要添加collider组件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值