- Home /
Move GUITxture by touch?
I have this code to move guitexture along with my touch position:
Touch touch1;
if(Input.touchCount > 0) {
touch1 = Input.touches[0];
if(touch1.phase == TouchPhase.Moved) {
touchGesture.pixelInset = new Rect(touch1.position.x,touch1.position.y,touchGesture.pixelInset.width,touchGesture.pixelInset.height);
}
}
The problem is that when I touch my screen the guitexture not repositioned along with my touch, but far of my touch position, I made sure that (touch1) xy values are the same as guitexture.pixelinset xy values on console, but strangely the gui texture not at the same position of touch.!! Here's more explanation, if you touch red circle to get the guitexture there:
You will get this result:
any help please!
Answer by robertbu · Apr 11, 2014 at 06:48 AM
GUITexture's transform.position is in Viewport coordinates. The easiest way to center a GUITexture on the finger/mouse would be to set the transform.position and live the pixelInset alone. Here is a bit of code for the mouse:
void Update() {
transform.position = Camera.main.ScreenToViewportPoint (Input.mousePosition);
}
Note if you have a reason, it can be done using the pixelInset, but you need more than you have here. First, the pixelInset values are relative to the position of the GUITexture. The default when you create the GUITexture is (0.5, 0.5, 0) which is the middle of the screen. So you need to set the x and y position of the GUITexture to (0,0) in the editor. In addition you will need to subtract 1/2 of the width and height to center the object on the cursor.
Your answer
![](https://koobas.hobune.stream/wayback/20220613142007im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Object is not following the touch position 0 Answers
Problem with multi touch[solved] 0 Answers
GUITexture placement 1 Answer
Cannot get GUIUtility.RotateAroundPivot working 1 Answer
Android Touch Input GUITexture 2 Answers