"Turn" Unity3d Ray Ray to achieve click Pickup

Source: Internet
Author: User

The game often has the mouse to move to an object to pick up its function, we can use Ray Ray in Unity3d to achieve this effect. The principle is that in the position of our mouse, a ray of the world's space is shot from the screen, and when the ray hits the object we need to pick up, we destroy the object and add it to our backpack.

Let's do a simple demo, we add a cube in the scene, a small ball sphere, when we put the mouse on the block without any reaction, and when we put the mouse on the ball, the ball will disappear.

Create a new project, we name it "Raytest", then create a new ball, block, and add light in the scene, the final result:

Create a new C # script file and rename it as "Rayscript", as shown in the following code:

[CSharp] view plain copy  
  1. <span style="Font-family:microsoft yahei;font-size:14px;"  >using Unityengine;
  2. Using System.Collections;
  3. Public class Rayscript:monobehaviour {
  4. // Use this for initialization
  5. void Start () {
  6. }
  7. //Update is called once per frame
  8. void Update () {
  9. //Create a ray, the resulting ray is in world space, starting from the camera's near clipping face and traversing the screen position (x, y) pixel coordinates (POSITION.Z is ignored)
  10. Ray Ray = camera. Screenpointtoray (input.mouseposition);
  11. //raycasthit is a struct object used to store the information returned by the Ray
  12. Raycasthit hit;
  13. //If the ray collides with the object, store the return information in hit
  14. if (Physics.raycast (Ray, out hit ))
  15. {
  16. //If the colliding object is a small ball, destroy it
  17. if (hit.transform.gameObject.name = = "Sphere")
  18. {
  19. Destroy (Hit.transform.gameObject);
  20. }
  21. }
  22. }
  23. }</span>


Running, we can see that when the mouse is placed on the ball, the ball disappears.

Attached project Source: Click here to download

"Turn" Unity3d Ray Ray to achieve click Pickup

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.