user16642652
user16642652

Reputation:

How to find direction and calculate end point of a raycast Unity2D

I am trying to make a gun in Unity that shoots a Raycast with a Line. (in 2d) I am using the player position as the origin and the mouse position as the direction. This works perfectly when there is a collision detection, but when there is not a collision, I have to find the direction and calculate the end point manually, because I still want the line to render if the player misses their shot. Here is my code to find this end point:

        //finding the position of Mouse in worldspace
    Vector3 mousePos = CameraController.mouseToWorld(Input.mousePosition);
    mousePos.z = 0;

    //Calculating whether or not the raycast is a hit
    RaycastHit2D Ray = Physics2D.Raycast(Player.transform.position,mousePos,distance);
    if(Ray.collider != null)
    {
        PassTheHit(Ray, Ray.collider.gameObject.name);

        point = Ray.point;
    }
    else
    {
        //Calculating the farthest point on the line. this does not work.
        point = (transform.position - mousePos).normalized;
        point *= -1 * (distance / 2);
        point.z = 0f;
    }

Particularly note the else{} statement. The calculation to find the point does not work. It is waaaay too long and does not shoot in the right direction.

Any help is greatly appreciated.

Upvotes: 0

Views: 1690

Answers (1)

derHugo
derHugo

Reputation: 90639

Either way you are using your Physics2D.Raycast wrong. It expects a

  • Start position
  • and a direction

you are passing in a second position.

What you rather want to do is using the direction

Vector2 mousePos = CameraController.mouseToWorld(Input.mousePosition);

Vector2 direction = ((Vector2)(mousePos - transform.position)).normalized;

which then you can use for both things

RaycastHit2D Ray = Physics2D.Raycast(Player.transform.position, /*here*/ direction, distance);
if(Ray.collider != null)
{
    PassTheHit(Ray, Ray.collider.gameObject.name);

    point = Ray.point;
}
else
{
    point = transform.position + /*and here*/ direction * distance;
}

Sidenote: Avoid to give a RaycastHit2D the name Ray as there is a type that is called Ray so it is misleading ;)

Upvotes: 2

Related Questions