- Home /
detecting touch android just once in update
i'm making a whac a mole game and i want the moles to detect a hit only once in a lifetime of 1 second,and if not hit to reduce the number of lives the player has.unfortunately the script is called too many times the first time itself and the user dies even before three moles show up .the deadcount reaches zero in the first mole itself.here's the code
using UnityEngine;
using System.Collections;
public class MoleHit : MonoBehaviour {
// Use this for initialization
public Vector2 touchpos;
public static bool hitFound=false;
public Sprite cracked;
public Sprite intact;
private SpriteRenderer sp;
void Start () {
sp = gameObject.GetComponent<SpriteRenderer> ();
sp.sprite = intact;
}
void FixedUpdate()
{
if(Input.touchCount==1) {
if (Input.GetTouch (0).phase == TouchPhase.Began) {
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.GetTouch (0).position);
touchpos = new Vector2 (pos.x, pos.y);
}
if (collider2D.OverlapPoint (touchpos)) {
sp.sprite = cracked;
hitFound = true;
audio.Play ();
}
}
Debug.Log (hitFound);
Scorer ();
}
void Scorer()
{
if (hitFound) {
ScoreCounter.countScore++;
hitFound=false;
}
else {
ScoreCounter.deadCount--;
}
}
}
Answer by pstreef · Jun 16, 2014 at 08:28 PM
I would add a timer and use regular update. AFAIK using fixed update is not recommended when using input.
It would something like this: (untested!)
using UnityEngine;
using System.Collections;
public class MoleHit : MonoBehaviour {
// Use this for initialization
public Vector2 touchpos;
public static bool hitFound=false;
public Sprite cracked;
public Sprite intact;
private SpriteRenderer sp;
public float TimeoutTime = 1.0f;
private float timeCounter;
private bool hitSet;
void Start () {
sp = gameObject.GetComponent<SpriteRenderer> ();
sp.sprite = intact;
touchpos = new Vector2(0.0f,0.0f);
timeCounter = 0.0f;
hitSet = false;
}
void Update()
{
timeCounter += Time.DeltaTime;
if(Input.touchCount==1 && !hitSet)
{
hitSet = true;
if (Input.GetTouch (0).phase == TouchPhase.Began)
{
Vector3 pos = Camera.main.ScreenToWorldPoint (Input.GetTouch (0).position);
touchpos = new Vector2 (pos.x, pos.y);
}
}
if(timeCounter > TimeoutTime)
{
timeCounter = 0.0f;
hitSet = false;
if (collider2D.OverlapPoint (touchpos))
{
sp.sprite = cracked;
hitFound = true;
audio.Play ();
}
Debug.Log (hitFound);
Scorer ();
}
}
void Scorer()
{
if (hitFound) {
ScoreCounter.countScore++;
hitFound=false;
}
else {
ScoreCounter.deadCount--;
}
}
}
Your answer

Follow this Question
Related Questions
touch buttons function OnGUI issue 1 Answer
How to touch, move and rotate 3D objects in XZ? 1 Answer
If you help me, i make you 3d object 1 Answer
multi-touch woe, index out of bounds? 1 Answer
How to make a android touch menu? 0 Answers