Question by
tickettoekumen · Aug 12, 2021 at 12:10 AM ·
mobiletouchdetectioninherit
Inaccurate touch detection from the base class
Hey, I'm trying to get an info if a touch to the mobile screen is colliding with the specific game object. If I attach this script to the object itself, everything works fine.
But, I want to make it a part of the base class, so I don't have to write this for every object in the game. However, when I make this script inherited, touch shows that game object is everything except the game object.
What can be the reason and how to fix it?
public abstract class ArchMage : MonoBehaviour
{
[SerializeField]
private GameObject mageObject;
private Collider2D collMage;
// Start is called before the first frame update
void Start()
{
collMage = mageObject.GetComponent<Collider2D>();
}
// Update is called once per frame
protected virtual void Update()
{
CheckIfTouched();
}
void CheckIfTouched()
{
if (Input.touchCount > 0)
{
Touch touch = Input.GetTouch(0);
Vector2 touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
//TESTING. Draw line to touch from the center
Debug.DrawLine(Vector2.zero, touchPosition, Color.red);
if (touch.phase == TouchPhase.Began)
{
Collider2D touchedCollider = Physics2D.OverlapPoint(touchPosition);
if (touchedCollider == collMage)
{
Debug.Log("HIT");
}
}
}
}
}
Comment