Worked in Unity 2D. I wrote code to move an object with the cursor. I created an "EventTrigger: on an object and gave it a drag function so that it would be activated when I pressed the mouse button on the object. I wrote a script with one method:
public void SetPos(Transform obj)
{
obj.position = Input.mousePosition;
}
I attached this script to the object that I want to move and in “EventTrigger” I specified this object, then this script and specified a link to the “Transform” component of the object to move. So when I launched
game, then when I touched it with the cursor and held it down, the object flew away 1000 units in x and y.
I used Image as the object. “Canvas” is configured according to the camera. I added a “2D Raycaster” component to the camera, and a “2D Box Collider” to the object.
Transform will always specify position in world space. Input.mousePosition is going to give you a point in the screen coordinate space. For example, if you have a 1080p resolution and you click in the upper-right corner, then Input.mousePosition is going to give you (1919,1079).
To convert a screen position to a world position you can use the camera function SceenToWorldPoint.
transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
If the object you are trying to move is on a Canvas, then you should move it using its RectTransform, not its Transform. When setting the position of a RectTransform you need to set the “anchoredPosition” using the screen coordinates.
1 Like