I want to have a GUITexture follow the location of a touch screen drag
I prefer c# and I’m using unity 4.6 beta so I’m kind of used to the new GUI system.
Edit: Updated with ability to constrain location of touch sensitivity
/// <summary>
/// The texture we want to move
/// </summary>
public GUITexture theTexture;
/// <summary>
/// The camera you want to put the texture in front
/// </summary>
public Camera theCamera;
/// <summary>
/// The screen bounds this sprite should be controlled from
/// </summary>
public Rect controlScreenRect;
/// <summary>
/// Follow the touch with our texture
/// </summary>
public void TrackTouch()
{
//is there any touches
if (Input.touchCount > 0 )
{
//go through each touch
for (int i = 0; i < Input.touchCount; i++)
{
//Is this touch moving
if (Input.GetTouch(i).phase == TouchPhase.Moved)
{
//Is this touch in the bounds?
if (controlScreenRect.Contains(Input.GetTouch(i).position))
{
//Track the touch point
Vector2 touchPos = Input.GetTouch(i).position;
//move the texture
theTexture.transform.position = theCamera.ScreenToWorldPoint(new Vector3(touchPos.x, touchPos.y, theCamera.nearClipPlane));
}
}
}
}
}
Rect FollowButton = new Rect (Input.mousePosition.x - 5, Screen.height - Input.mousePosition.y - 25, 10, 10);
GUI.Box(FollowButton, “”);
This makes a small box 25 pixels above the mouse. The reason the -5 is there on the x position is because that is half the width of the box and that will make the box centered. The -25 is just to make it go above the mouse so it’s not directly on it. Adjust these to get different offsets. Input.mousePosition works perfectly on android also but it will appear at the center of multiply touches rather than the first or second. Shouldn’t be a problem depending on how your game works.