Unity3D笔记 英保通十 射线碰撞器检测

  射线碰撞检测可以用来检测方向和距离: 通过Physics.RayCast光线投射来实现:常用于射击利用发射的射线来判断、还有对战中刀剑交战中。。

一、要涉及到RayCast和RayCastHit

 

1.1、光线投射:Physics.RayCast()

  static function Raycast (origin : Vector3, direction : Vector3, distance : float = Mathf.Infinity, layerMask : int = kDefaultRaycastLayers) : bool 

返回值也是bool

  • origin:在世界坐标,射线的起始点。
  • direction:射线的方向
  • distance:射线的长度
  • layerMask:只选定Layermask层内的碰撞器,其它层内碰撞器忽略。 

 

1.2、RayCastHit() 光线投射检测

  用来获取从raycast函数中得到的信息反馈的结构。

 

 

二、案例

复制代码
using UnityEngine;
using System.Collections;

public class rayCast : MonoBehaviour {

    private RaycastHit rayHit;//光线投射碰撞:用来获取从raycast函数中得到的信息反馈的结构。

    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
        if (Physics.Raycast(transform.position, transform.forward,out rayHit, 10))
        {
            Debug.Log("碰撞检测到第一人称碰撞到了"+rayHit.collider.name);
        }
    }
}
复制代码

 RayCastHit参数:

    • The impact point in world space where the ray hit the collider.
      在世界空间中,射线碰到碰撞器的碰撞点。
    • The normal of the surface the ray hit.
      射线所碰到的表面的法线。
    • The barycentric coordinate of the triangle we hit.
      所碰到的三角形的重心坐标。
    • The distance from the ray's origin to the impact point.
      从光线的原点到碰撞点的距离。
    • The index of the triangle that was hit.
      碰到的三角形的索引。
    • The uv texture coordinate at the impact point.
      在碰撞点的UV纹理坐标。
    • The secondary uv texture coordinate at the impact point.
      碰撞点的第二个UV纹理坐标。
    • The uv lightmap coordinate at the impact point.
      所在碰撞点的光照图UV坐标。
    • The Collider that was hit.
      碰到的碰撞器。
    • The Rigidbody of the collider that was hit. If the collider is not attached to a rigidbody then it is null.
      碰到的碰撞器的Rigidbody。如果该碰撞器没有附加刚体那么它为null。
    • The Transform of the rigidbody or collider that was hit.
      碰到的刚体或碰撞器的变换。

 

 

 

 

 

posted @   PEPE YU  阅读(644)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示