当前位置:网站首页>Unity: use ray to detect objects

Unity: use ray to detect objects

2022-06-22 23:26:00 You still have to work hard!

utilize ray Ray Detect objects


Unity ray (Ray) It is to detect a collision body or trigger by emitting a ray . Objects that cannot be detected without impactor components , You can cancel the detection trigger in the physical settings (Edit → Project Setting → Physics/Physics2D).

Physics.Raycast(origin, direction, out hitInfo, distance, mask)

origin: Where the rays are emitted ;

direction: The direction in which the rays are emitted .

hitInfo: Information about the object hit by the ray ;

distance: Ray distance , The default is infinite distance ;

mask: Ray mask , Indicates which... Has been detected layer, The default is to detect all layers . The form of this parameter is required :

Method 1 :

int shootableMask = LayerMask.GetMask("Shootable");
Physics2D.Raycast(Ray, out hitInfo, range, shootableMask);

Method 2 :

int layerNumber;
(1 << layerNumber)  // Only test No  layerNumber  The layer 
~(1 << layerNumber) // No test number is  layerNumber  The layer , The rest of the layers are detected 
(1 << layerNumber) | (1 << layer2Number)  // Only detect  2  Layers 

RaycastHit: Store collision information after emitting rays

Common member variables :

collider: A collider that collides with rays ;

transform: Of an impactor that collides with rays Transform;

distance: The distance from the starting point of the ray to the intersection of the ray and the collider ;

normal: The normal vector of a ray entering a plane ;

point: Coordinates of the intersection of the ray and the collider .

Common usage

  1. Emit a ray from the camera to the mouse ;
  2. Obtain the collision information of the ray ;
  3. Get the colliding object , Manipulate the object .
Code instance
Ray myRay = Camera.main.ScreenPointToRay(Input.mousePosition);// A ray from the camera 
RaycastHit2D hit = Physics2D.Raycast(new Vector2(myRay.origin.x, myRay.origin.y), Vector2.zero);// The ray starts from the point where the mouse clicks on the screen , Shoot to the coordinate system with the current click position as the origin, perpendicular to (0,0) The location of ,

if (hit.collider)// If you encounter Collider2D Component objects , Find the object 
{
    
  Debug.Log(hit.transform.name);// Print out the name of the collision node 
  GameObject obj = GameObject.Find(hit.transform.name);
}
// adopt  obj  To manipulate objects 
原网站

版权声明
本文为[You still have to work hard!]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222103213262.html