A
A
Anton Vertov2018-05-23 17:42:44
Game development
Anton Vertov, 2018-05-23 17:42:44

IDragHandler Flies to Narnia. Why?

Good day. I am using Unity3D.
I created a 2D Scene where I want to hold the object and move it by pressing the left mouse button / touching the finger on the phone.
Created an object (image). I throw a script like this on it:

using UnityEngine;
using UnityEngine.EventSystems;

public class EventHandle : MonoBehaviour, IDragHandler
{
    public void OnDrag(PointerEventData eventData)
    {
        this.transform.position = eventData.position;
    }
}

I'm starting a project. When you click and drag this object, it completely disappears from the scene and flies away to no one knows where. I look at the positions in X and Y, and they instantly gain ~ 8000 and ~ 10000, respectively, and I barely move the mouse.
In general, I want the object to cling and walk in the center of the cursor when pressed and held, I don’t understand why such a problem occurs. Please tell me how to solve this problem correctly. Thank you very much!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel, 2018-05-23
@1Frosty

The fact is that the touch occurs in a different coordinate system.
To convert the touch to "world" coordinates, you need to use the Camera.main.ScreenToWorldPoint() method

public void OnDrag(PointerEventData eventData)
{
   transform.position = Camera.main.ScreenToWorldPoint(eventData.position);
}

G
GreatRash, 2018-05-23
@GreatRash

The Internet advises to try:

public void OnDrag(PointerEventData eventData)
{
    transform.position += (Vector3)eventData.delta;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question