- Home /
detecting touch on gameObject
Hello, I have 2 gameObjects called (right , left) I need to execute some actions in case of touching one of them but it does not detect any touch input , take a look of the below code :)
public class player : MonoBehaviour {
public float speed = 3;
public GameObject left; //assigned via inspector
public GameObject right; //assigned via inspector
private Animator anim;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
Vector3 scale = transform.localScale;
if (Input.touchCount > 0) {
Touch t = Input.GetTouch(0);
if (t.phase == TouchPhase.Began)
{
if (left.GetComponent<SpriteRenderer>().bounds.Contains(t.position))
{
anim.SetInteger ("walk", 1);
transform.Translate (-speed * Time.deltaTime, 0, 0);
scale.x = -1;
}
else if (right.GetComponent<SpriteRenderer>().bounds.Contains(t.position))
{
anim.SetInteger ("walk" , 1);
transform.Translate(speed*Time.deltaTime,0,0);
scale.x = 1;
}
}
else if (t.phase == TouchPhase.Ended)
{
anim.SetInteger ("walk" , 0);
}
}
I just need some clarification. What exactly are the game object left and right? Are they colliders on the screen?
Also, you don't have to use Input.touchCount if your colliders are huge and you don't require precise coordinate of the figures, you can just use the normal On$$anonymous$$ouseDown stuff.
OnCollisionEnter doesn't even deal with touch or click input -.-
You could also use "On$$anonymous$$ouseDown" and it will work as a touch input.
@fighder take a look of this images http://imgur.com/HgvJPqI
Answer by fighder · May 09, 2015 at 02:42 PM
You should have a script component for each "left" and "right" gameObject.
Inside those scripts, use the OnMouseDown function and execute your code inside the function.
i.e.
void OnMouseDown(){
anim.SetInteger ("walk", 1);
transform.Translate (-speed * Time.deltaTime, 0, 0);
scale.x = -1;
}
to execute code when the user lifts their finger off the screen, use OnMouseUp instead.
the problem that I did not add a collider component no more no less thanks for your comment at all
Your answer
Follow this Question
Related Questions
Question about user input event handling in Unity game for iOS 2 Answers
Force touch to only work on a new touch - buttons 0 Answers
solution to detect multi- finger touch position 2 Answers
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
mouse input to touch input help please 0 Answers