'Unity Raycast2D snapping to origin
I am working on a game in which one of the major obstacles is lasers. The lasers use raycast to detect hits and, if it hits the player, the player is killed and a function from another script is called. However, the lasers always snap to the origin. I tried using the Ignore Raycast layer, but the raycast still goes to (0, 0) and doesn't output anything in the console. The only objects on the ignored layer are the Main Camera, Event System, and some containers for other objects. If anyone can give me some pointers as to what might be wrong, it would be greatly appreciated!
hit = Physics2D.Raycast(this.transform.position, this.transform.up, ~(IgnoreLayer));
point = hit.point;// + (Vector2.one*transform.forward*0.1f);
if (hit.collider != null)
{
Debug.Log("Target name: " + hit.collider.name);
if (hit.collider.tag == "Player" && firing)
{
pm.dead = true;
}
else
{
}
}
laser.SetPosition(0, thisPosition);
laser.SetPosition(1, point);
Solution 1:[1]
Well you are using hit.point without checking if it even hits anything .. unless it actually hits something the hit.point will be invalid and just have the default value (0,0).
hit = Physics2D.Raycast(this.transform.position, this.transform.up, ~(IgnoreLayer));
if (hit.collider != null)
{
point = hit.point;
laser.SetPosition(0, thisPosition);
laser.SetPosition(1, point);
Debug.Log("Target name: " + hit.collider.name);
if (hit.collider.CompareTag("Player") && firing)
{
pm.dead = true;
}
else
{
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | derHugo |
