- Home /
Unity2D Raycast not working
I tried many times, searched on different sites ... Nothing works. The problem is in the operator if(hit.collider.gameObject == target). I want to make the turret shoot only when the enemy is in front of it. i changed configurations method Raycast() Code:
Vector2 up = transform.TransformDirection(Vector2.right) * 5;
Debug.DrawRay(transform.position, up, Color.green, 1);
if (!shoot)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, up, 0.1F);
if (hit != null)
if (hit.collider.gameObject == target)
{
Instantiate(Bullet, shootElem.position, transform.rotation);
shoot = true;
Invoke("reload", shootSpeed);
}
}
}
}
void reload()
{ shoot = false; }
Have you tried RaycastHit2D hit = Physics2D.GetRayIntersection(ray, $$anonymous$$athf.Infinity);
? I believe it gets the collider hit by the raycast, so you can check if the enemy is infront of the turret,
Answer by xxmariofer · Jan 05, 2021 at 11:12 AM
why are you using different vectors in the drawray and raycast? shouldnt be the same?
RaycastHit2D hit = Physics2D.Raycast(transform.position, up, 0.1F);
Umm, operator if(hit.collider.gameObject == target) work when enemy collider in begin ray
Your answer
Follow this Question
Related Questions
Why is this ray returning distance as zero? 1 Answer
Add collision to raycasted object? 2 Answers
2D Platform Player moving instantly from upper platform to lower, only when moving left 0 Answers
Player moves to the middle of the room when the level starts (2d point and click) 2 Answers
Ray Casting in 2D 1 Answer