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
- <span style="Font-family:microsoft yahei;font-size:14px;" >using Unityengine;
- Using System.Collections;
- Public class Rayscript:monobehaviour {
- // Use this for initialization
- void Start () {
- }
- //Update is called once per frame
- void Update () {
- //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)
- Ray Ray = camera. Screenpointtoray (input.mouseposition);
- //raycasthit is a struct object used to store the information returned by the Ray
- Raycasthit hit;
- //If the ray collides with the object, store the return information in hit
- if (Physics.raycast (Ray, out hit ))
- {
- //If the colliding object is a small ball, destroy it
- if (hit.transform.gameObject.name = = "Sphere")
- {
- Destroy (Hit.transform.gameObject);
- }
- }
- }
- }</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