Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
2

Answer by Statement · Mar 30, 2011 at 04:52 PM

First 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.

// ... (snip) ...
if (Physics.Raycast(ray, hit))           
    hit.transform.position = ray.origin + ray.direction * 10;
// ... (snip) ...

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.

I didn't know if you want to drag while holding down the mouse button or if you want to toggle dragging with a mouse click. I provide a useToggleDrag to switch between the two styles.

var grabbed : Transform; var grabDistance : float = 10.0f;

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 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; } }

function Drag() { var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition); var position : Vector3 = transform.position + transform.forward grabDistance; var plane : Plane = new Plane(-transform.forward, position); var distance : float; if (plane.Raycast(ray, distance)) { grabbed.position = ray.origin + ray.direction distance; grabbed.rotation = transform.rotation; } }

// This drag wasn't like the OP wanted. function OldDrag() { var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition); grabbed.position = ray.origin + ray.direction * grabDistance; }

Comment
Add comment · Show 3 · 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 gilson · Mar 30, 2011 at 06:35 PM 0
Share

I'm still having the problem that i was having before. What happens is that when i click the object, it moves backwards on the Z-Axis or fowards depending on the camera position. I want the object to stays on its original Z-Axis and move on X and Y, without using any fixed joint cause i wanna to be able to move almost all objects. I hope that i was clear enough on my explanation, english is not my main language.

avatar image Statement · Mar 30, 2011 at 07:11 PM 0
Share

Check out my updated Drag function. It moves along the local X/Y axis (Before it moved in X/Y/Z in an arc). Do you want to move it only along the world X/Y axis? Then I can make another update.

avatar image Statement · Mar 30, 2011 at 07:14 PM 0
Share

(You probably want to remove grabbed.rotation = transform.rotation; also)

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
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 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 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
  • 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.

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

How to select one prefab from more ? 0 Answers

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

Problem with Alt + Middle Click Drag for Camera (Windows) 3 Answers


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