Reputation: 612
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.
Upvotes: 3
Views: 11659
Reputation: 190
I know this is an old post but this took way longer than it should have so thought i'd share my solution in case it helps other trying to do the same thing.
var touchpoint = Instantiate(Resources.Load("prefabs/touchpoint"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
//set it parent to the main canvas
touchpoint.transform.parent = MainCanvas.transform;
//convert touch position to localposition reletive to canvas
Vector2 localPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(MainCanvasRect, new Vector3(t.position.x, t.position.y, 0), null, out localPos);
//set position on canvas
touchpoint.transform.localPosition = localPos;
Upvotes: 1
Reputation: 7100
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);
}
}
}
Upvotes: 3
Reputation: 49
use
gameobject.transform.position = camera.ScreenToWorldPoint(Input.mousePosition);
for Desktop. for mobile you want to replace InputmousePostion
with input.getTouch[i].position
.
Upvotes: 1