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
0
Question by hollym16 · Nov 01, 2013 at 12:40 PM · gameobjectclick and drag

Click and Drag script

Hi, I have Click and Drag script. However, it currently clicks and drags everything. How can I alter this script to make it only drag a specified GameObject? I've tried everything I can think of with my limited knowledge on scripting grammar.

 #pragma strict
 
 // Attach this script to an orthographic camera.
 
 private var object : Transform;     // The object we will move.
 
 private var offSet : Vector3;       // The object's position relative to the mouse position.
 
  
 
 function Update () {
 
     var ray = camera.ScreenPointToRay(Input.mousePosition);     // Gets the mouse position in the form of a ray.
 
     if (Input.GetButtonDown("Fire1")) {     // If we click the mouse...
 
         if (!object) {      // And we are not currently moving an object...
 
             var hit : RaycastHit;
             
             if (Physics.Raycast(ray, hit, Mathf.Infinity)) {        // Then see if an object is beneath us using raycasting.
     
                 object = hit.transform;     // If we hit an object then hold on to the object.
 
                 offSet = object.position-ray.origin;        // This is so when you click on an object its center does not align with mouse position.
 
             }
 
         }
 
     }
 
     else if (Input.GetButtonUp("Fire1")) {
 
         object = null;      // Let go of the object.
 
     }
 
     if (object) {
 
         object.position = Vector3(ray.origin.x+offSet.x, object.position.y, ray.origin.z+offSet.z);     // Only move the object on a 2D plane.
 
     }
 
 }
Comment
Add comment · Show 1
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 Tomer-Barkan · Nov 01, 2013 at 02:37 PM 0
Share

Just add an IF that checks if the hit transform is this.transform. This way the script will only work if the object you drag has the script.

 if (hit.transform == this.transform) {
     object = hit.transform;
     ...
 }

4 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by hollym16 · Nov 26, 2013 at 12:52 PM

I've continued to research and have found that the following script, that is placed onto the object you want to drag, works best for me:

using UnityEngine;

using System.Collections;

[RequireComponent(typeof(BoxCollider))]

public class Drag : MonoBehaviour { private Vector3 screenPoint; private Vector3 offset; private float _lockedYPosition;

 void OnMouseDown() {
    //screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position); // I removed this line to prevent centring 
    _lockedYPosition = screenPoint.y;
    offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    Screen.showCursor = false;
     

     
           
 }
 
 void OnMouseDrag() 
 { 
    Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    curPosition.x = _lockedYPosition;
    transform.position = curPosition;
 }
 
 void OnMouseUp()
 {
    Screen.showCursor = true;
 }

}

Comment
Add comment · Show 2 · 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 Lakay · Jul 31, 2016 at 08:54 AM 0
Share

i cant drag it. 1.create script, insert this. 2. create empty object, insert script 3. add component "image (script)" 4.and... still not worlking . why?

avatar image FukUBich Lakay · Jun 05, 2017 at 05:18 AM 0
Share

have you add Box Collider ?

avatar image
2

Answer by robertbu · Nov 01, 2013 at 03:26 PM

Here is your script back with a few changes. The code checks for the tag "Draggable". As mentioned above, you could use the name instead, or even check for a specific component. I reworked your drag code a bit to deal with the offset.

 #pragma strict
  
 // Attach this script to an orthographic camera.
  
 private var object : Transform;     // The object we will move.
 private var offSet : Vector3;       // The object's position relative to the mouse position.
 private var dist   : float;
  
 function Update () {
  
     var ray = camera.ScreenPointToRay(Input.mousePosition);     // Gets the mouse position in the form of a ray.
  
     if (Input.GetButtonDown("Fire1")) {     // If we click the mouse...
  
         if (!object) {      // And we are not currently moving an object...
  
             var hit : RaycastHit;
  
             if (Physics.Raycast(ray, hit, Mathf.Infinity) && (hit.collider.tag == "Draggable")) {        // Then see if an object is beneath us using raycasting.
  
                 object = hit.transform;     // If we hit an object then hold on to the object.
  
                 offSet = object.position-hit.point;        // This is so when you click on an object its center does not align with mouse position.
                 
                 dist = (ray.origin - hit.point).magnitude;  // Distance to the object from ray origin.
  
             }
  
         }
  
     }
  
     else if (Input.GetButtonUp("Fire1")) {
  
         object = null;      // Let go of the object.
  
     }
  
     if (object) {
  
         object.position = ray.GetPoint(dist) + offSet;    // Only move the object on a 2D plane.
  
     }
  
 }
Comment
Add comment · Show 2 · 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 robertbu · Nov 01, 2013 at 03:27 PM 0
Share

You will find a script at the following link that you attach to each object you want to make draggable. An alternate to what you are doing.

http://answers.unity3d.com/questions/566327/drag-object-relative-to-camera.html

avatar image enoy · Aug 29, 2017 at 08:43 PM 0
Share

Interesting robertbu

avatar image
0

Answer by mattssonon · Nov 01, 2013 at 12:55 PM

You can make a check around line 23 for the object's name, e.g.:

 if (Physics.Raycast(ray, hit, Mathf.Infinity)) {        // Then see if an object is beneath us using raycasting.
     
     if (hit.transform.name == "Name of object you want to drag") {
         object = hit.transform;     // If we hit an object then hold on to the object.
         
         offSet = object.position-ray.origin;        // This is so when you click on an object its center does not align with mouse position.
     }
 }
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 hollym16 · Nov 01, 2013 at 01:26 PM 0
Share

Yeah thats what I thought. Unfortunately, it makes the objects centre move to the mouse click; it wont drag. I'm not sure why it does this though as theres the bit of code under thats meant to prevent that from happening offSet = object.position-ray.origin;

avatar image
0

Answer by d2clon · Jul 05, 2021 at 02:02 PM

This script works for me: https://gist.github.com/fguillen/2b9d0dbf437e2d723079f122daf391bb

using UnityEngine;

 public class Draggable : MonoBehaviour
 {
     Vector3 offset;
 
     void OnMouseDown()
     {
       offset = transform.position - Camera.main.ScreenToWorldPoint(Input.mousePosition);
     }
 
     void OnMouseDrag()
     {
       transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition) + offset;
     }
 }

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

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

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

The name 'Joystick' does not denote a valid type ('not found') 2 Answers

Message sender...how to know who send the message 1 Answer

how can i move another gameobject from a single script? 1 Answer

Replace variable with new game object after it is made null - not working 0 Answers

How do I handle object selection and GUI response ingame? 5 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