Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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 /
  • Help Room /
avatar image
0
Question by estephan500 · Dec 15, 2019 at 09:31 AM · 2dmobileunity 2dtouchdrag-and-drop

To use touch & raycasting to *drag and drop* a game object...

I am trying to make a simple way to use mobile touch to actually move (i.e., drag and then drop) a game object from one place to another.

To at least detect the touch on the desired object, I was very happy to use the great answer @rob5300 gave to: https://answers.unity.com/questions/1126621/best-way-to-detect-touch-on-a-gameobject.html

It successfully detects the touch on the object, but now I can't quite find the most graceful way to make it so that if the person keeps their finger on the touched object and starts moving the touch around, the object follows their finger, until the person stops the touch.

I will paste my code below.

Key point: The below code sits out in its own GameObject... not inside the draggable object... because later I want it to work with multiple objects the person might try to drag.

You can see where my final debug.log says "At this point I sure wish the object would get dragged around..." Can you tell me how, at that point, I can make the gameobject follow the touch finger's moves until the person stops the touch? THANKS! --Eric

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class RaycastTest : MonoBehaviour
 {
 
     Vector3 touchPosWorld;
     bool carrying;
 
     //Change me to change the touch phase used.
     TouchPhase touchPhase = TouchPhase.Began;
 
     // Update is called once per frame
     void Update()
     {
         //We check if we have more than one touch happening.
         //We also check if the first touches phase is Ended (that the finger was lifted)
         if (Input.touchCount > 0 && Input.GetTouch(0).phase == touchPhase)
         {
             //We transform the touch position into word space from screen space and store it.
             touchPosWorld = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
 
             Vector2 touchPosWorld2D = new Vector2(touchPosWorld.x, touchPosWorld.y);
 
             //We now raycast with this information. If we have hit something we can process it.
             RaycastHit2D hitInformation = Physics2D.Raycast(touchPosWorld2D, Camera.main.transform.forward);
 
             if (hitInformation.collider != null)
             {
                 //We should have hit something with a 2D Physics collider!
                 GameObject touchedObject = hitInformation.transform.gameObject;
                 //touchedObject should be the object someone touched.
                 Debug.Log("Touched " + touchedObject.transform.name);
                 if (touchedObject.transform.name == "p-circle-p")
                 {
                     Debug.Log("Touched the draggable one! I sure wish it would start dragging the item until I let go.");
                 }
 
             }
         }
     }
 }



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

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Larry-Dietz · Dec 15, 2019 at 03:01 PM

Not exactly answering your question, as you asked, but if you just want to be able to drag things around, here is a script I found a while back, can't remember where I got it, or I would give them proper credit.

 using UnityEngine;
 using UnityEngine.EventSystems;
 
 public class Dragger : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
 {
 
     Camera mainCamera;
     float zAxis = 0;
     Vector3 clickOffset = Vector3.zero;
     // Use this for initialization
     void Start()
     {
         mainCamera = Camera.main;
         if (mainCamera.GetComponent<Physics2DRaycaster>() == null)
             mainCamera.gameObject.AddComponent<Physics2DRaycaster>();
     }
 
     public void OnBeginDrag(PointerEventData eventData)
     {
     zAxis=transform.position.z;
         clickOffset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, zAxis)) + new Vector3(0, 3, 0);
         transform.position = new Vector3(transform.position.x, transform.position.y, zAxis);
     }
 
     public void OnDrag(PointerEventData eventData)
     {
         //Use Offset To Prevent Sprite from Jumping to where the finger is
         Vector3 tempVec = mainCamera.ScreenToWorldPoint(eventData.position) + clickOffset;
         tempVec.z = zAxis; //Make sure that the z zxis never change
         
 
         transform.position = tempVec;
     }
 
     public void OnEndDrag(PointerEventData eventData)
     {
         transform.position = new Vector3(transform.position.x, transform.position.y, -1);
     }
 
     //Add Event System to the Camera
     void addEventSystem()
     {
         GameObject eventSystem = new GameObject("EventSystem");
         eventSystem.AddComponent<EventSystem>();
         eventSystem.AddComponent<StandaloneInputModule>();
     }
 }

Attach this script to an object, and you should be able to use touch to drag that object around.

I had modified this script for my game. I just tried to undo the modifications I made. Hopefully I didn't introduce any issues when I did this, but if I did, let me know and I'll figure it out :)

Hope this helps, -Larry

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 rob5300 · Dec 15, 2019 at 09:10 PM 0
Share

This method should work and be more suited! $$anonymous$$y old answer works but I think using the EventSystem is better as assists you with drag events. $$anonymous$$ake sure that there is a Physics Raycaster with the event system to allow use with 3D or 2D physics outside of the UI (this script assumes 2D).

avatar image estephan500 · Dec 15, 2019 at 11:44 PM 0
Share

Giant thanks to both of you, I will look at this closely soon and give it a try!

avatar image maud_unity · Feb 04, 2020 at 09:28 AM 0
Share

For those that would want to use this solution, don't forget to call addEventSystem, or the drag won't work :) . And if you work with 3D object, use PhysicsRaycaster ins$$anonymous$$d of Physics2DRaycaster. Thanks to Larry for this solution :

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

370 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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

Drag UI by touch 2 Answers

How to detect the touch on certain Game Object (UI Panel) 1 Answer

Spawning enemies after death help 0 Answers

Virtual controller and fire bullet shot in 2D 0 Answers

Any one help me in this script? 0 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