- Home /
Question by
motazmmnshob · Jan 06, 2021 at 01:51 PM ·
2draycasttouchraycasting
2d raycasting to touch position not working
void Update()
{
for ( int i = 0; i<Input.touchCount; i++)
{
if (Input.GetTouch(i).phase == TouchPhase.Began)
{
Touch touch = Input.GetTouch(i);
Vector3 touchposition = Camera.main.ScreenToWorldPoint(touch.position);
RaycastHit2D hit = Physics2D.Raycast(touchposition,touchposition);
Debug.DrawRay(touchposition, touchposition);
if (hit.collider)
{
Debug.Log(hit.transform.name);
}
}
}
}
Comment
Best Answer
Answer by motazmmnshob · Jan 06, 2021 at 07:38 PM
Finally I got it working :
void Update()
{
foreach (Touch touch in Input.touches)
{
//Detects Swipe while a finger touched the screen
if (touch.phase == TouchPhase.Began)
{
Ray touchposition = Camera.main.ScreenPointToRay(new Vector3(touch.position.x, touch.position.y, 0f));
RaycastHit2D hit = Physics2D.GetRayIntersection(touchposition);
if (hit.collider)
{
Debug.Log(hit.transform.name);
}
}
Answer by RageEye · Jan 06, 2021 at 03:35 PM
do it in foreach:
foreach (Touch touch in Input.touches)
{
//Detects Swipe while a finger touched the screen
if (touch.phase == TouchPhase.Began)
{
}
//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
}
//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
}
}
I am having a problem with the raycasting it self it is not starting from the touch position and it always start from the same place no matter where I touch on my phone(using unity remote5) and I tried doing it in foreach