- Home /
2D moblie game raycast problem
Hey guys, I am trying to shoot a raycast2D at the position of my finger, when I touch the screen on my android tablet. I then want it to destroy the gameobject if it is tagged bad guy and add to the players score, however it doesn't work.
my code
void Update(){
if(Input.touchCount >0){
foreach (Touch touch in Input.touches){
Vector2 dir = Vector2.zero;
Vector3 touchworldpos =Camera.main.ScreenToWorldPoint(touch.position);
Vector2 touchpos2d = new Vector2(touch.position.x,touch.position.y);
Debug.Log(touchpos2d);
RaycastHit2D hit = Physics2D.Raycast(touchpos2d,dir);
Debug.DrawRay(touchpos2d,dir,Color.blue);
if(hit!=null&&hit.collider!=null){
if(hit.collider.tag ==" bad guy"){
Destroy (hit.collider.gameObject);
die.Play();
Addscore.AddScore();
player.transform.localScale+=new Vector3(0.1f,0.1f);
}
}
}
}
}
Answer by maccabbe · Dec 23, 2015 at 07:31 PM
Screen space != world space. Stop using touchpos2d which is in screen space. Replace it with touchworldpos which is in world space but strangely not used after it is assigned.
There's no point to doing a Physics2D.Raycast with a ray that has a length of 0. That's a point and you should use Physics2D.OverlapPoint or Physics2D.OverlapPointAll for points.
Physics2D.Raycast/Physics2D.OverlapPoint only return the first collider hit. You probably want to use Physics2D.RaycastAll/Physics2D.OverlapPointAll instead.