I am trying to check in Unity if a point(x location of touch,y location of touch) is inside a game object created(Rectangle shaped), if yes, start and spin it around.
I am pretty new to Unity but I tried doing it myself, here is what
Rigidbody rb;
float x, y;
MeshCollider col;
Vector3 v;
bool bo = true;
// Use this for initialization
void Start()
{
rb = GetComponent<Rigidbody>();
col = rb.GetComponent<MeshCollider>();
}
void Update()
{
if (bo != true)
rb.transform.Rotate(Vector3.back, Time.deltaTime * 200, Space.World);
if (Input.touchCount == 1)
{
x = Input.GetTouch(0).position.x;
y = Input.GetTouch(0).position.y;
Debug.Log(x + "DOTS " + y);
v = new Vector3(x, y, 0);
if (col.bounds.Contains(v))
bo = false;
}
}
My console is not showing anything, also if I type Debug.Log("HELLO");
and I can't pretty much check myself so that is pretty much my code, appreciate any help.
I think you don't get Log due to you are testing on PC, not on mobile device.
In order to check if the touch point is in bounds of gameObject fire a ray from camera:
#if UNITY_EDITOR
if(Input.GetMouseButtonUp(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
#else
if(Input.touches.Length == 1 && Input.touches[0].phase == TouchPhase.Ended)
{
Ray ray = Camera.main.ScreenPointToRay(Input.touches[0].position);
#endif
int layerMask = (1 << YOUR_TARGET_LAYER_ID);
RaycastHit[] hits = Physics.RaycastAll(ray, 100f, layerMask);
foreach(RaycastHit hit in hits)
{
if(hit.collider == col)
{
Debug.Log("Bingo!!");
break;
}
}
}
Note that I used precompiler directives to make possible this code work on mobile device and on PC.
YOUR_TARGET_LAYER_ID is a layer id of the target you want to only be resposive to ray cast. This will ensure that if some other object is covering the target, it will be ignored.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments