First, the mouse to pick up the principle of the object
In Unity3d, the way to pick up objects (with collision properties) in the observation surface (Aspect) is generally as follows:
1. Declare an observed camera, a ray ray from the origin of the camera, and a raycasthit for detecting collisions;
2, Ray Ray is defined as starting from the camera origin and point to the current mouse coordinates (screen coordinates);
3. Define the collision point of the collision Raycasthit as Ray Ray and the object with Collision property.
The specific code is implemented as follows (C # code):
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classcamera:monobehaviour{ PublicCamera CA; PrivateRay RA; PrivateRaycasthit hit; //Use this for initialization voidStart () {}//Update is called once per frame voidUpdate () {RA=ca. Screenpointtoray (input.mouseposition); if(Physics.raycast (RA, outHit )) { } }}
Apply one: When the mouse is pressed, move the selected object with the mouse move
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classcamera:monobehaviour{ PublicCamera CA; PrivateRay RA; PrivateRaycasthit hit; //Use this for initialization voidStart () {}//Update is called once per frame voidUpdate () {if(Input.getmousebutton (0) ) {RA=ca. Screenpointtoray (input.mouseposition); if(Physics.raycast (RA, outHit )) {hit.collider.gameObject.transform.position= ca. Screentoworldpoint (NewVector3 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y, hit.collider.gameobject.transform.position.z)); } } }}
Application two: When the mouse clicks on an object, the object moves with the mouse, and when the mouse clicks again, the object is dropped.
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityengine; Public classCamera:monobehaviour { PublicCamera CA; PrivateRay RA; PrivateRaycasthit hit; Private intFlag =0; //Use this for initialization voidStart () {}//Update is called once per frame voidUpdate () {if(Input.getmousebuttondown (0) ) {RA=ca. Screenpointtoray (input.mouseposition); if(Physics.raycast (RA, outHit )) { if(Flag = =0) {flag=1; } Else{flag=0; } } } if(Flag = =1) {hit.collider.gameObject.transform.position= ca. Screentoworldpoint (NewVector3 (input.mouseposition.x, INPUT.MOUSEPOSITION.Y, hit.collider.gameobject.transform.position.z)); } }}
Originated from http://blog.csdn.net/sysujackjiao/article/details/69396274
About the solution of mouse moving specified object in Unity3d