您的位置:首页 > 移动开发 > Unity3D

【Unity学习笔记】——射线应用,光点随鼠标移动

2017-07-27 16:16 579 查看
实现一个随鼠标移动的光点,光点指到特定物体上会显示,否则隐藏

①使用tag

②使用Layer

方法① 

用target标签标记场景物体



创建一个Image UI



在相机上添加下列脚本

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

public class RayUI : MonoBehaviour {

private Ray ray;
private RaycastHit hit;//射线碰到的碰撞信息
public RectTransform UI;//准心

private void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100))
{
if (hit.collider.tag == "target")
{
UI.gameObject.SetActive(true);
UI.position = Input.mousePosition;
}
else
UI.gameObject.SetActive(false);
}
else
UI.gameObject.SetActive(false);
}
}
方法②
用target层标记场景物体



在相机上添加下列脚本

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

public class RayUI : MonoBehaviour {

private Ray ray;
private RaycastHit hit;//射线碰到的碰撞信息
public RectTransform UI;//准心
public LayerMask myLayer;

private void Update()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100, myLayer.value))
{
//if (hit.collider.tag == "target")
//{
UI.gameObject.SetActive(true);
UI.position = Input.mousePosition;
//}
//else
// UI.gameObject.SetActive(false);
}
else
UI.gameObject.SetActive(false);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: