- Home /
Unity 2D Top-Down Raycast length/distance and direction problem
I'm trying to build a top down 2D game and now I want to add a laser shooting to the game. I watched Unity raycasting video and also searched over 20+ post about raycasting, but still can't figured a way to shoot the ray properly.
Problem 1:
I can't make the ray shoot along the x-axis, it always shoot towards the z-axis, meaning that you can't see anything when it shoots because it shoot into the screen.
So, I rotate my laser tip by 90 degree on y-axis, making its z-axis facing toward the right size(aka the front side) so it shoots to its front. I don't know if it is a proper way to solve it, if there's a better way like a setting or just scripting. I would like to know! thx!
Here is what I've got so far(adjust the Scene View to see from the back side of the game, so you can see the all the ray):
The left circle is the one i apply my rotation fix, the other one is where i haven't apply the fix and so it's shooting into the screen.
Problem 2:
As you can see from above screenshot, the laser isn't shooting far enough, and in my code I have already set the distance to Mathf.Infinity. No matter what value I set, it always shoot at the same distance. I've tried 1f, 100f, and 100000f and none of them work.
and here is my code for the raycasting part (was doing IEnumeratot because the tutorial was doing it this way, and I don't think it's what causing the problems):
IEnumerator fireLaser()
{
line.enabled = true;
while (Input.GetKey("r"))
{
//Debug.DrawLine(transform.position, player.transform.position);
//Physics2D.Linecast(transform.position, player.transform.position);
Debug.DrawRay(transform.position, player.transform.position);
Ray2D ray = new Ray2D(transform.position, transform.right);
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right, Mathf.Infinity);
yield return null;
}
line.enabled = false;
}
for the "Line Renderer" component settings, I've unchecked the "use world space" box, or else the laser will have one end that stick to the center of the screen...
Problem 2.5:
From above code. I found that I can change "transform.right" to "transform.up" or "transform.toward", and it has no impact to what i see from game. Is that normal? should it shoot to different direction when I change it?
That's all the questions I need to ask, I hope someone could give me some help. THANK YOU!
this it the LaserTip setting, just in case
Your answer
Follow this Question
Related Questions
Trying to make a topdown 2d laser 2 Answers
RaycastHit2D to hit an enemy when player rotates. (Using keyboard input only) 2 Answers
Detect tag with 2d raycasting 1 Answer
LineRenderer (Laser Beam) is not following the ray it's going on the wrong direction when reflecting 1 Answer
Is there a better way to find where to start my raycast? 2 Answers