DCYılmaz
DCYılmaz

Reputation: 99

An object is not dragged to the correct position after scaling the canvas in Unity

I resize 1920x1080 according to the screen size to get more performance on Android. With this code:

Screen.SetResolution(Screen.currentResolution.width / 2, Screen.currentResolution.height / 2, true);

But since the canvas stays at 1920x1080 resolution, I need to resize it as well. When I try to resize the canvas, the drag operation in onDrag does not work correctly or the places of the objects are shifted.

If I select "UI Scale Mode:Constant Pixel Size" on Canvas, there is no problem. But the canvas stays at 1920x1080. If I choose "Scale With Screen Size aaxbb" and "Match:0.5", the objects are not dragged to the correct position as in the videos and they appear in different places when the game starts. My onDrag Code:

public void OnDrag(PointerEventData eventData)
    {
        rectTransform.SetAsLastSibling();
        rectTransform.anchoredPosition += eventData.delta;
    }
    public void OnEndDrag(PointerEventData eventData)
    {
        pointerEventData = new PointerEventData(eventSystem);
        pointerEventData.position = Input.mousePosition;
    }

unity drag problem

Can experienced friends help? How do you solve this?

Upvotes: 1

Views: 211

Answers (1)

Bluze Ocean
Bluze Ocean

Reputation: 59

There is a Screen Space and there is a World Space. Since you didn't mention which one you are working in, I'll assume you are working in the world space because the picture shows some 3D objects.

When working with drag object in the world space, you need to make a transition, and would look something like this:

pointerEventData.position = Camera.main.ScreenToWorldPoint( CaInput.mousePosition);

Upvotes: 0

Related Questions