• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
3
Question by gilson · Mar 30, 2011 at 04:31 PM · movementmousepickupdrag-and-drop

Picking / Dragging Objects with Mouse

Hi everyone, im trying to make a script that when i click on a mouse with the mouse, the user will be able do drag it around while he holds the button.

Here is my piece of code:

function Update () {
    if (Input.GetMouseButton(0)) {
        var hit : RaycastHit;
        var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
        if (Physics.Raycast(ray, hit)) {
            mousePos = Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
            hit.transform.position = Camera.main.ScreenToWorldPoint(mousePos);
        }
    }
}

'm having some problems, fist problem:

I'm setting a fixed Z to the mouse position and i want the object to stands in its original z axis. Any insights about that? I've tried some other things but it didnt work properly.

Second problem: I want the first click to doesnt move the object, the first just to select and after the click you move the mouse and then the object comes along. This way, any click the objects moves a little.

Thank you,

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

6 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by wsessums · Oct 05, 2016 at 02:46 AM

Another approach is to think of the problem as follows:
A ray from the camera passes through the projection plane and hits an object at some point on the object. The ratio of the distances along ray from the camera to the projection plane and from the camera to the point on the object is constant if the object moves parallel to the projection plane.
If we store the ratio when the object is clicked, we can cast a ray on each update, calculate the distance to the projection plane and multiply that by the ratio to get the new position of the point on the object at it's desired location.
Additionally, you will need to get the vector from point on the object to the origin of the object's transform. There may be ways to write this simpler but here is the basic parts.

     private float ratioObjectToScreen;
     private Vector3 handleToObjectOrigin;
 
     void OnMouseDown () {
         Ray rayFromCameraThroughScreenPoint = Camera.main.ScreenPointToRay (Input.mousePosition);
         RaycastHit handle;
         Physics.Raycast (rayFromCameraThroughScreenPoint, out handle);
         Vector3 cameraToHandle = handle.point - Camera.main.transform.position;
         float distanceCameraToHandle = cameraToHandle.magnitude;
         Vector3 cameraToProjectionPlanePoint = Camera.main.ScreenToWorldPoint (Input.mousePosition + new Vector3 (0, 0, Camera.main.nearClipPlane)) - Camera.main.transform.position;
         float distanceCameraToProjectionPlanePoint = cameraToProjectionPlanePoint.magnitude;
         ratioObjectToScreen = distanceCameraToHandle / distanceCameraToProjectionPlanePoint;
         handleToObjectOrigin = transform.root.position - handle.point;
     }
 
     void OnMouseDrag () {
         Vector3 cameraToProjectionPlanePoint = Camera.main.ScreenToWorldPoint (Input.mousePosition + new Vector3 (0, 0, Camera.main.nearClipPlane)) - Camera.main.transform.position;
         float distanceCameraToProjectionPlanePoint = cameraToProjectionPlanePoint.magnitude;
         float distanceCameraToHandle = distanceCameraToProjectionPlanePoint * ratioObjectToScreen;
         Ray rayFromCameraThroughScreenPoint = new Ray (Camera.main.transform.position, cameraToProjectionPlanePoint);
         Vector3 newHandlePosition = rayFromCameraThroughScreenPoint.GetPoint (distanceCameraToHandle);
         transform.root.position = newHandlePosition + handleToObjectOrigin;
     }

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by reza90 · Oct 24, 2012 at 07:51 PM

hi gilson,i have same problem .do you solve it?could you plz show your complete code?

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by darrelcusey · Jun 14, 2012 at 03:54 AM

The little "jump" that you keep experiencing is due to the grabDistance. what you really want to do is immediately do another raycast to simulate what the next frame would see with the Raycast layer of the grabbed object turned off. Then you can use the difference from the grabbed object's transform and that immediate second raycast as your offset for dragging.

The following is "smooth as silk" and also allows you to grab hierarchical objects -- well, single-layered ones at least :)

 var grabbed : Transform;
 var grabDistance : float = 10.0f;
 var grabLayerMask : int;
 var grabOffset : Vector3; //delta between transform transform position and hit point
 var useToggleDrag : boolean; // Didn't know which style you prefer. 
 
 function Update () {
     if (useToggleDrag){
         UpdateToggleDrag();
     } else {
         UpdateHoldDrag();
     }
 }
 
 // Toggles drag with mouse click
 function UpdateToggleDrag () {
     if (Input.GetMouseButtonDown(0)){ 
         Grab();
     } else {
         if (grabbed) {
             Drag();
         }
     }
 }

 // Drags when user holds down button
 function UpdateHoldDrag () {
     if (Input.GetMouseButton(0)) {
         if (grabbed){
             Drag();
         } else { 
             Grab();
         }
     } else {
         if(grabbed){
             //restore the original layermask
             grabbed.gameObject.layer = grabLayerMask;
         }
         grabbed = null;
     }
 }
 
 function Grab() {
     if (grabbed){ 
        grabbed = null;
     } else {
         var hit : RaycastHit;
         var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
         if (Physics.Raycast(ray, hit)){          
             grabbed = hit.transform;
             if(grabbed.parent){
                 grabbed = grabbed.parent.transform;
             }
             //set the object to ignore raycasts
             grabLayerMask = grabbed.gameObject.layer;
             grabbed.gameObject.layer = 2;
             //now immediately do another raycast to calculate the offset
             if (Physics.Raycast(ray, hit)){
                 grabOffset = grabbed.position - hit.point;
             } else {
                 //important - clear the gab if there is nothing
                 //behind the object to drag against
                 grabbed = null;
             }
         }
     }
 }

 function Drag() {    
     var hit : RaycastHit;
     var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
     if (Physics.Raycast(ray, hit)){      
         grabbed.position = hit.point + grabOffset;
     }
 
 },
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Danielpunct · Mar 11, 2014 at 01:53 PM 0
Share

very nice! works perfect

avatar image
0

Answer by punkorange · May 30, 2011 at 05:42 AM

if (Physics.Raycast(ray, hit)) {
            newPosition = Vector3(Input.mousePosition.x, Input.mousePosition.y, hit.transform.position.z);
            hit.transform.position = Camera.main.ScreenToWorldPoint(newPosition);
}

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by gilson · Mar 30, 2011 at 07:43 PM

I've discovered something that keeps the original Z on the object.

I've noticed that on the mousePos.z i have tu put the difference between my camera.z and my object.z and it works

Like this:


var desiredZ: float = Mathf.Abs(Utils.Round((Camera.main.transform.position.z - hit.transform.position.z),2));
mousePos = Vector3(Input.mousePosition.x, Input.mousePosition.y, desiredZ);
hit.transform.position = Camera.main.ScreenToWorldPoint(mousePos); It works, but does anyone have a more ellegant solution?

One more thing, everytime i click, it already moves a little bit the object, i just want it to moves after the click. Any ideas?

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
  • 1
  • 2
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Problem with click-to-move script 0 Answers

Move Camera According to Mouse Movement While Button is Pressed 1 Answer

Drag and Drop on RTS camera 1 Answer

How to select one prefab from more ? 0 Answers

Having a first person player look at the mouse on the y axis 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges