unity-game-enginetouchscreenmouse-position

How can I move an UI Image to a touch position?


I have an image on the scene. Now when I touch on my mobile device to a specific position, I want, that the image moves to this position.

How can I do it?

I wrote this:

transform.position = Input.mousePosition;

But this don't work. Ok, it's working, but the image is not anymore on the screen. It's somewhere on the right side.

I found this. But it's also not working:

gameObject.GetComponent<RectTransform>().localPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);

Here is the problem, that when I touch on the screen bottom left (mobile) the object is in the center of the screen.


Solution

  • You can move the UI Image by putting the following in a script attached to it:

    void Update() {
    
        for (var i = 0; i < Input.touchCount; i++) {
    
            if (Input.GetTouch(i).phase == TouchPhase.Began) {
    
                // assign new position to where finger was pressed
                transform.position = new Vector3 (Input.GetTouch(i).position.x Input.GetTouch(i).position.y, transform.position.z);
    
            }
    
        }    
    
    }