Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
2
Question by LAFI · Feb 01, 2015 at 08:01 AM · 2dcanvasdrag

how to move an UI image just in the surface of the canvas???

i have an ui image draggable , but I want to move it just inside the canvas. the code i have allows me to move the image but not within the limits of canvas. i use unity 4.6 This is my code:

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.EventSystems;
 using System.Collections;
 
 public class DragUI : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
     public Vector2 Canvas_Size;
     public Vector2 a;
     //public float b;
     public RectTransform Rt; /***/
     public GameObject bot; /****/
     private bool mouseDown = false;
     private Vector3 startMousePos;
     private Vector3 startPos;
     
     
     public void OnPointerDown(PointerEventData ped) 
     {
         //BoxCollider2D.widht = 
         //Canvas.
         mouseDown = true;
         startPos = transform.position;
         startMousePos = Input.mousePosition;
     }
     /*******************************************/
     void Get()
     {
         Rt = bot.GetComponent<RectTransform>();
         a.x = Rt.rect.height;
         a.y = Rt.rect.width;
         //Rt.rect.center = a;
     }
 
     /***********************************************/
     
     public void OnPointerUp(PointerEventData ped) 
     {
         mouseDown = false;
     }
     
     
     void Update () 
     {
         if (mouseDown) {
             Vector3 currentPos = Input.mousePosition;
             Vector3 diff = currentPos - startMousePos;
             Vector3 pos = startPos + diff;
             transform.position = pos;
         }
 //it is the test on the canvas  limits
 
         
         if(transform.position.x <= -(Rt.rect.width/2 ))
         {
             transform.position = new Vector2(-(Rt.rect.width/2), transform.position.y);
         }
         else if (transform.position.x >= (Rt.rect.width/2))
         {
             transform.position = new Vector2((Rt.rect.width/2), transform.position.y);
             //transform.position.x = b; //Rt.rect.width;
             
         }
         if(transform.position.y <= -(Rt.rect.width /2))
         {
             transform.position = new Vector2(transform.position.x, -(Rt.rect.width/2 ));
         }
         else if(transform.position.y >= (Rt.rect.width/2 ))
         {
             transform.position = new Vector2(transform.position.x, (Rt.rect.width/2));
         }
         //a = new Vector2(0, 0);
         
     }
 }

help me please

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

2 Replies

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

Answer by Mmmpies · Feb 01, 2015 at 12:21 PM

Hey @LAFI that code I updated in the last question works perfectly well for canvases as well as panels, in fact it'll work with any two objects that have a RectTransform in the new UI.

I'll post the updated code here as well just make the Canvas the ParentRT and the image MyRect.

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.EventSystems;
 using System.Collections;
 
 public class DragUI : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
 
     private bool mouseDown = false;
     private Vector3 startMousePos;
     private Vector3 startPos;
     private bool restrictX;
     private bool restrictY;
     private float fakeX;
     private float fakeY;
     private float myWidth;
     private float myHeight;
 
     public RectTransform ParentRT;
     public RectTransform MyRect;
 
     void Start()
     {
         myWidth = (MyRect.rect.width + 5) / 2;
         myHeight = (MyRect.rect.height + 5) / 2;
     }
 
     
     public void OnPointerDown(PointerEventData ped) 
     {
         mouseDown = true;
         startPos = transform.position;
         startMousePos = Input.mousePosition;
     }
     
     public void OnPointerUp(PointerEventData ped) 
     {
         mouseDown = false;
     }
     
 
     void Update () 
     {
         if (mouseDown) {
             Vector3 currentPos = Input.mousePosition;
             Vector3 diff = currentPos - startMousePos;
             Vector3 pos = startPos + diff;
             transform.position = pos;
 
             if(transform.localPosition.x < 0 - ((ParentRT.rect.width / 2)  - myWidth) || transform.localPosition.x > ((ParentRT.rect.width / 2) - myWidth))
                 restrictX = true;
             else
                 restrictX = false;
 
             if(transform.localPosition.y < 0 - ((ParentRT.rect.height / 2)  - myHeight) || transform.localPosition.y > ((ParentRT.rect.height / 2) - myHeight))
                 restrictY = true;
             else
                 restrictY = false;
 
             if(restrictX)
             {
                 if(transform.localPosition.x < 0)
                     fakeX = 0 - (ParentRT.rect.width / 2) + myWidth;
                 else
                     fakeX = (ParentRT.rect.width / 2) - myWidth;
 
                 Vector3 xpos = new Vector3 (fakeX, transform.localPosition.y, 0.0f);
                 transform.localPosition = xpos;
             }
 
             if(restrictY)
             {
                 if(transform.localPosition.y < 0)
                     fakeY = 0 - (ParentRT.rect.height / 2) + myHeight;
                 else
                     fakeY = (ParentRT.rect.height / 2) - myHeight;
                 
                 Vector3 ypos = new Vector3 (transform.localPosition.x, fakeY, 0.0f);
                 transform.localPosition = ypos;
             }
 
         }
     }
 }

Really you need to tick questions that have been answered correctly. It benefits you as well because some people won't help if someone gets a reputation for not marking correct answers.

Comment
Add comment · Show 4 · 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 LAFI · Feb 01, 2015 at 02:35 PM 0
Share

@$$anonymous$$mmpies Thanx a LOT you save my life ;)

avatar image LAFI · Feb 01, 2015 at 04:00 PM 0
Share

both codes works very well Thanks

avatar image Mmmpies · Feb 01, 2015 at 04:05 PM 0
Share

Hey - no problem @LAFI you might want to thumbs up @troien answer as well if you're able - glad $$anonymous$$e helped though.

avatar image jacksonkr · May 17, 2018 at 02:41 PM 0
Share

To make this a bit more dynamic I added the following lines into Start

 this.ParentRT = this.transform.parent.GetComponent<RectTransform>();
 this.$$anonymous$$yRect = this.GetComponent<RectTransform>();

This will make it so you don't have to drag the RectTransforms into the editor.

avatar image
13

Answer by troien · Feb 01, 2015 at 01:10 PM

This is a piece of code I made using the example Unity provides. (Forum post and asset store)

 using UnityEngine;
 using UnityEngine.EventSystems;
 
 public class DragableUI : UIBehaviour, IBeginDragHandler, IDragHandler
 {
     /// <summary>
     /// The RectTransform that we are able to drag around.
     /// if null: the transform this Component is attatched to is used.
     /// </summary>
     public RectTransform dragObject;
 
     /// <summary>
     /// The area in which we are able to move the dragObject around.
     /// if null: canvas is used
     /// </summary>
     public RectTransform dragArea;
 
     private Vector2 originalLocalPointerPosition;
     private Vector3 originalPanelLocalPosition;
     
     private RectTransform dragObjectInternal
     {
         get
         {
             if (dragObject == null)
                 return (transform as RectTransform);
             else
                 return dragObject;
         }
     }
 
     private RectTransform dragAreaInternal
     {
         get
         {
             if (dragArea == null)
             {
                 RectTransform canvas = transform as RectTransform;
                 while (canvas.parent != null && canvas.parent is RectTransform)
                 {
                     canvas = canvas.parent as RectTransform;
                 }
                 return canvas;
             }
             else
                 return dragArea;
         }
     }
 
     public void OnBeginDrag(PointerEventData data)
     {
         originalPanelLocalPosition = dragObjectInternal.localPosition;
         RectTransformUtility.ScreenPointToLocalPointInRectangle(dragAreaInternal, data.position, data.pressEventCamera, out originalLocalPointerPosition);
     }
 
     public void OnDrag(PointerEventData data)
     {
         Vector2 localPointerPosition;
         if (RectTransformUtility.ScreenPointToLocalPointInRectangle(dragAreaInternal, data.position, data.pressEventCamera, out localPointerPosition))
         {
             Vector3 offsetToOriginal = localPointerPosition - originalLocalPointerPosition;
             dragObjectInternal.localPosition = originalPanelLocalPosition + offsetToOriginal;
         }
 
         ClampToArea();
     }
 
     // Clamp panel to dragArea
     private void ClampToArea()
     {
         Vector3 pos = dragObjectInternal.localPosition;
 
         Vector3 minPosition = dragAreaInternal.rect.min - dragObjectInternal.rect.min;
         Vector3 maxPosition = dragAreaInternal.rect.max - dragObjectInternal.rect.max;
 
         pos.x = Mathf.Clamp(dragObjectInternal.localPosition.x, minPosition.x, maxPosition.x);
         pos.y = Mathf.Clamp(dragObjectInternal.localPosition.y, minPosition.y, maxPosition.y);
 
         dragObjectInternal.localPosition = pos;
     }
 }

The reason why I post this is because even though @Mmmpies his answer does work in some cases, this code works better when you change the pivot or when you change the Render Mode of the Canvas to 'Screen Space - Camera' or 'World Space'.

ps. I did make it in a way that it uses default values when you leave dragObject or dragArea empty/null, though it is better for performance when you set those values in the inspector ;)

Comment
Add comment · Show 6 · 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 LAFI · Feb 01, 2015 at 02:37 PM 1
Share

@troien Thank you for your answer you helped me more than you think ;) :)

avatar image luochuanyuewu · Jul 27, 2015 at 02:26 PM 0
Share

@troien Thank you,This helped me a lot.

avatar image mohansiriga · Jul 22, 2016 at 10:44 AM 0
Share

Thanks @troien. This is exactly what i am looking for. it helped me a lot.

avatar image Ozer_Jigme · Nov 11, 2017 at 05:24 PM 0
Share

Thanks so much for this. Anybody would know how to make it react to right mouse clicks?

avatar image RomanMalkov · Oct 26, 2018 at 11:10 AM 0
Share

@troien You best of the best!

Show more comments

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

10 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

Related Questions

Drag n Drop in a 3D orthographic environment 1 Answer

Bad piggies-like inventory? 0 Answers

How to drag and drop in 2D game 0 Answers

Showing random image from folder on my U.I. canvas by script 0 Answers

How to scale according to different mobile resolutions? 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