Hey.
I’ve been trying to figure out how to make a control for my game.
I got the idea to take a sprite and if the finger is on this sprite
it should act like Input.GetKey.
(A sprite also doesn’t change the position as the GUI, what i mean with it is that it doesn’t change its position and is easier to build it)
Can anyone help me.
1 Answer
1void Update()
{
if (Input.touchCount == 1)
{
Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
Vector2 touchPos = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos))
{
//your code
}
}
}
Edit :
Here’s something I wrote. It would come in handy if you need to control all touch inputs from 1 script :
private GameObject beganObj;
private GameObject currentObj;
void Update ()
{
if(Input.touchCount > 0)
{
for(int i = 0; i < Input.touchCount; i++)
{
Touch currentTouch = Input.GetTouch(i);
if(currentTouch.phase == TouchPhase.Began)
{
Vector2 v2 = new Vector2(Camera.main.ScreenToWorldPoint(currentTouch.position).x, Camera.main.ScreenToWorldPoint(currentTouch.position).y);
Collider2D c2d = Physics2D.OverlapPoint(v2);
if(c2d != null)
{
beganObj = c2d.gameObject;
}
}
if (currentTouch.phase == TouchPhase.Moved)
{
Vector2 v2 = new Vector2(Camera.main.ScreenToWorldPoint(currentTouch.position).x, Camera.main.ScreenToWorldPoint(currentTouch.position).y);
Collider2D c2d = Physics2D.OverlapPoint(v2);
if (c2d != null)
{
currentObj = c2d.gameObject;
}
}
}
}
}
JS :
function Update()
{
if (Input.touchCount == 1)
{
wp : Vector3 = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
touchPos : Vector2 = new Vector2(wp.x, wp.y);
if (collider2D == Physics2D.OverlapPoint(touchPos))
{
//your code
}
}
}
I think this will do it in javascript. Attach this to sprite you want to use as button and make sure you have a 2D collider in your sprite object.
Another way to do this with guiTextures :
function Update()
{
if(Input.touches.Length > 0)
{
for(int i = 0; i < Input.touchCount; i++)
{
if(this.guiTexture.HitTest(Input.GetTouch(i).position)
{
if(Input.GetTouch(i).phase == TouchPhase.Began)
{
// Write what you want to do when guiTexture is touched.
}
}
}
}
}
Attach this script to your gameObject that’s holding guiTexture. I haven’t been using javascript for a while now, so I apologize in advance if there are any mistakes. Good luck.
I am not very familiar with C# (I prefer JavaScript), and i want to add a second button so how could i add the button with a new variable
– lixpoxxI have edited my question. See if that helps.
– Rioneerhow to control the movement speed of the object from the script mentioned above ??
– ShrishGour