- Home /
Make image follow your cursor
Hello.
I've made a really simple inventory with PiDi's tutorial but I don't really know how would I nest my item icon (UI image) on specific position (let's say next to the cursor) when I'm dragging it around my inventory. Right now I'm setting the local position of my icon with this script:
if(draggingItem)
{
Vector3 mousePos = (Input.mousePosition - GameObject.FindGameObjectWithTag("Canvas").GetComponent<RectTransform>().localPosition);
dragItemIcon.GetComponent<RectTransform>().localPosition = new Vector3(mousePos.x + 15, mousePos.y - 15, mousePos.z);
}
The problem is that the icon is not moving as fast as the mouse and sometimes it prevents me from dropping the item to one of the slots (because I'm actually clicking at the icon image, not the slot).
It looks like this: http://i.imgur.com/zV0I1Js.gifv
I'd be very grateful for any bit of help!
Answer by DiegoSLTS · Jul 08, 2015 at 03:06 AM
Your code is OK, I don't think you can move the image to follow the cursor using something really different.
Maybe the problem with your code is that it's slow. I guess that code is being executed inside an Update function, so you're calling:
GameObject.FindGameObjectWithTag("Canvas").GetComponent<RectTransform>()
and:
dragItemIcon.GetComponent<RectTransform>()
every frame. GetComponent is not really slow, but you can save those references in a private variable instead of getting them each time. FindGameObjectWithTag IS slow, it goes through the objects on your hierarchy and checks the tag of each one until one has the "Canvas" tag. If you're always searching the same object on the scene just find it once in some Awake or Start method and use the reference in the future.
Your answer
Follow this Question
Related Questions
How to convert unity editor GUI functions to something that can be used in game? 0 Answers
How to scale triangle created by GL(using viewport position) with scale factor of Canvas? 0 Answers
How do I add something to the OnClick of a UI Button from an Editor-Script? 0 Answers
In-game text editor, native or NGUI 2 Answers
How to change the Width and Height in the script C#? (New Gui Unity 4.6 beta) 2 Answers