X-ray collision test sharing in Unity:

Source: Internet
Author: User


Physics.raycast: Ray projection

Parameters:

Origin: Ray start point

direction: Ray Direction

Distance: Ray length

Layermask: only The collider within the Layermask layer is selected, and the other in-layer collider is ignored.

Returns

Bool-true when the ray intersects any collider,otherwise false.

True if Ray casts intersect with any collider, otherwise false.

Here's a small example to experiment with: Click where you want to move

usingUnityengine;
usingSystem.Collections;

Public classCapsule:Monobehaviour {

     Public Charactercontrollercc;
     Public floatSpeed ;
     Public Cameracamera;
     Public Vector3targetposition;
    voidStart () {
targetposition= This. transform.position; // Assign the initial position to the current coordinates
cc= This.gameobject.getcomponent<Charactercontroller> ();
    }
To define a ray method:
    voidGethitpoint () {
        RayRay; // Create a new Ray ,
        RaycasthitHit ; // Ray casting clash Qi
        if(Input. Getmousebuttondown (0)){ // If I click on the screen to trigger the Ray
Ray=camera. Screenpointtoray (Input. mouseposition); // screen position turn Ray
            if(Physics. Raycast (Ray, outHit , -)){// Ray projection -- true when Ray casts intersect with any collider , the Ray Distance
//Debug.Log (hit.point);

                if(hit.collider.gameobject.name=="Terrain"){
Targetposition=hit.point;
                    //debug.log (targetposition);
                }
            }
        }
    }
    voidWalk () {
        Vector3v=Vector3. Normalize (targetposition- This. transform.position);
cc. Simplemove (v*speed* Time. deltatime);//simple Move method.
    }

    voidUpdate () {
//Vector3 v=new Vector3 (0,0,10*speed*time.deltatime);
if (Input.getkey (Keycode.a)) {
Cc. Simplemove (v);
//        }

walk ();
gethitpoint ();
    }
}

X-ray collision test sharing in Unity:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.