Unity中射线Ray用法

Ray

struct

PropertiesDescription
directionThe direction of the ray.
originThe origin point of the ray.
ConstructorsDescription
RayCreates a ray starting at origin along direction.
Public MethodsDescription
GetPointReturns a point at distance units along the ray.
ToStringReturns a nicely formatted string for this ray.

RaycastHit

struct

PropertiesDescription
barycentricCoordinateThe barycentric coordinate of the triangle we hit.
colliderThe Collider that was hit.
distanceThe distance from the ray’s origin to the impact point.
lightmapCoordThe uv lightmap coordinate at the impact point.
normalThe normal of the surface the ray hit.
pointThe impact point in world space where the ray hit the collider.
rigidbodyThe Rigidbody of the collider that was hit. If the collider is not attached to a rigidbody then it is null.
textureCoordThe uv texture coordinate at the collision location.
textureCoord2The secondary uv texture coordinate at the impact point.
transform射线撞到的collider或者rigidbody所属物体的transform
triangleIndexThe index of the triangle that was hit.
  • 子物体与父物体层级不同, 子物体没rigidbody, 父物体有rigidbody时, RaycastHit内rigidbody和transform是父物体的; 子物体有rigidbody, 父物体有rigidbody时, RaycastHit内rigidbody和transform才是子物体的.

Camera类中提供的用法

  • Ray 始终对应于视图中的一个点,因此 Camera 类提供 ScreenPointToRay 和 ViewportPointToRay函数。两者之间的区别在于 ScreenPointToRay 期望以像素坐标的形式提供该点,而 ViewportPointToRay 则接受0…1 范围内的标准化坐标(其中 0 表示视图的左下角,1 表示右上角)。这些函数中的每一个函数都返回由一个原点和一个矢量(该矢量显示从该原点出发的线条方向)组成的 Ray。
  • Ray源自近裁剪面而不是摄像机 (Camera) 的 transform.position 点。

1、通过鼠标位置点击场景中的物体,“这是一种基于对象在屏幕上的图像来定位对象的非常有用的方法。”

	public class ExampleScript : MonoBehaviour {
	    public Camera camera;
	    void Start(){
	        RaycastHit hit;
	        Ray ray = camera.ScreenPointToRay(Input.mousePosition);
	        if (Physics.Raycast(ray, out hit)) {
	            Transform objectHit = hit.transform;
	            // 对射线投射命中的对象执行一些操作。
	        }
	    }
	}

2、沿着射线移动相机

	public class ExampleScript : MonoBehaviour {
	    public bool zooming;
	    public float zoomSpeed;
	    public Camera camera;
	
	    void Update() {
	        if (zooming) {
	            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
	            float zoomDistance = zoomSpeed * Input.GetAxis("Vertical") * Time.deltaTime;
	            camera.transform.Translate(ray.direction * zoomDistance, Space.World);
	        }
	    }
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值