- Home /
How to change the direction of the RayCast?
Hello, I'm making the 2D laser.
And It's working fine, but I need to rotate him, so its not creating the laser on up direction.
So I have this part of the code:
RaycastHit2D hit = Physics2D.Raycast (transform.position, transform.up);
So how can I change the code that the ray will be rotating with the parent object? And not will cast to up direction?
Maybe something with Translate?
Please help if you have any things in mind about this, thanks! :)
Answer by donutLaserDev · Mar 21, 2018 at 02:03 PM
Well, let's say, you want to raycast in the direction the object is facing. So, you could just pass transform.forward instead of transform.up. There are many other ways specify the direction of the ray but those depend on the actual situation.
Yes, but when I'm using forward the end point of laser is stucks in the 0,0,0 position.
I'm working in 2D maybe it's causing some problems?
$$anonymous$$aybe there is another method for this?
Here is all the needed line of my code i think
RaycastHit2D hit = Physics2D.Raycast (transform.position, transform.forward);
laserHit.position = hit.point;
lineRenderer.SetPosition (0, transform.position);
lineRenderer.SetPosition (1, laserHit.position);
Answer by Priyanka-Rajwanshi · Mar 23, 2018 at 12:28 PM
Hi @Rembo4Fight
You need to use transform.right. The end point of the laser is retuning (0,0,0) because your raycast is probably not hitting anything. Use the code snippet below.
RaycastHit2D hit = Physics2D.Raycast(transform.position, transform.right);
if (hit.transform != null)
{
lineRenderer.enabled = true;
laserHit.position = hit.point;
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, laserHit.position);
}
else
{
lineRenderer.enabled = false;
}
Your answer
Follow this Question
Related Questions
[Solved] How to move the camera in the forward axis 1 Answer
Help with Rotating code? 2 Answers
Move gameObject with mouse 1 Answer
Double reference to waypoints in FSM 0 Answers
Tower defense target update 0 Answers