Search code examples
unity-game-engineraycasting

Top down 3D Raycast to Mouse Point


I am casting a ray from an empty transform at the tip of a gun. The cast is to head towards the mouse position on Right Click. There is a unexpected result of the hit point being half way from expected.

I have attempted to rework the Raycasting and check out the Unity documents and forums, perhaps i am missing so simple. I have included the code of my Fire Function. Note "Raycaster" is the empty gameobject it fires from.

public void Fire(Vector3 point)
{
    RaycastHit hit;
    if(Physics.Raycast(Raycaster.transform.position, point, out hit))
    {
        Debug.DrawLine(Raycaster.transform.position, point, Color.green); //expected
        Debug.DrawLine(Raycaster.transform.position, hit.point, Color.red); //actual

        if(hit.rigidbody != null)
        {
            hit.rigidbody.AddForce(-hit.normal * weapon.Damage);
        }

        GameObject Impact = Instantiate(ImpactParticle, hit.point, Quaternion.LookRotation(hit.normal));
        Destroy(Impact, 1f);
    }

}

The first Debug.Drawline in Green is what I expect, but the second Debug.Drawline is the actual. I must be the hit.point from the Raycast but it always is half way.

Issue example, Green is expected and red is actual


Solution

  • I think you use world position(point). Try convert your point argument to direction.

    Vector3 dir = point - Raycaster.transform.position;
    Physics.Raycast(Raycaster.transform.position, dir, out hit)