Unity学习笔记005.射线点击事件(PC/Mobile)

预处理,判断当前平台

void LateUpdate()
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
	PC();
#endif
#if UNITY_EDITOR || UNITY_ANDROID
	Mobile();
#endif
}

[注]
if的作用是程序流控制,会直接编译、执行。
#if是对编译器的指令,其作用是告诉编译器,有些语句行希望在条件满足时才编译。

射线点击事件(PC)

private void PC()
{
    if (Input.GetMouseButtonDown(0))    // 如果鼠标左键按下
    {
        RaycastHit hitInfo;
        // 射线从鼠标点击处射出
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Transform targetTransform = null;
        // 在maxDistance长度之内,射线ray与第一个对象(无论层级)进行的物理碰撞的信息,存储在hitInfo中;如果有碰撞物体,返回true, 反之false;
        if (Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))
        {
            // 获取碰撞到的物体信息
            targetTransform = hitInfo.collider.transform;
        }
        if (targetTransform != null)
        {
            // DoSomething();
        }
    }
}

射线点击事件(Mobile)

private void Mobile()
{
	// 单指触控
	if(Input.touchCount == 1)
	{
		// 存储触摸点信息
		Touch touch = Input.GetTouch(0);		
		// 如果手指触摸屏幕,但并未移动,不做处理
		if(touch.phase == TouchPhase.Stationary)
			return;
		// 判断是否点击在UI上
		if(EventSystem.current.IsPointerOverFameObject(touch.fingerID))
			return;
		
		RaycastHit hitInfo;
		Ray ray = Camera.main.ScreenPointToRay(touch.position);
		Transform targetTransform = null;
		if(Physics.Raycast(ray, out hitInfo, Mathf.Infinity, -1))					
		{
			targetTransform = hitInfo.collider.transform;
		}
		if(targetTransform!= null)
		{
			// DoSomething();
		}		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PaddyH

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值