0
\$\begingroup\$

I have a world space canvas in front of the player and I want to shoot a ray towards an enemy (in the direction of the enemy) and create and object where Raycast hits the UI canvas.
I know that the physics engine doesn't interact with UI elements and event system is not the answer for me since it depends on pointer events and their position.
So how can I do this?
If possible, I would like to draw the ray or the line as gizmo to see if it's working.
My Current Code is this:

void OnDrawGizmos()
{
    foreach (AeroplaneAiControl item in GameObject.FindObjectsOfType<AeroplaneAiControl>())
    {
        Gizmos.color = Color.magenta;
        Gizmos.DrawLine(transform.position, item.transform.position);
        Vector3 Direction = transform.position - item.transform.position;
        RaycastHit rch;
        Ray r = new Ray(transform.position, Direction);
        Physics.Raycast(r, out rch);
        if (rch.collider != null)
        {
            Gizmos.color = Color.cyan;
            Gizmos.DrawLine(transform.position, rch.point);
            Gizmos.DrawSphere(rch.point, 0.1f);
        }
    }
}

it draws the magenta line but not the cyan line and no spheres.

\$\endgroup\$
  • \$\begingroup\$ Did putting a 3D box collider around the canvas not achieve your goal? \$\endgroup\$ – DMGregory Sep 20 '17 at 12:10
  • \$\begingroup\$ No I guess because canvas is in UI layer it gets ignored no matter what. If I change the layer does it effect the functionality of the UI elements? @DMGregory \$\endgroup\$ – Henjin Sep 20 '17 at 12:12
  • 1
    \$\begingroup\$ Try it and see! You don't need our permission to experiment in your own project. ;) \$\endgroup\$ – DMGregory Sep 20 '17 at 12:16
  • \$\begingroup\$ well it didn't work I'm gonna post my raycasting code to see if there is any thing wrong with that.@DMGregory \$\endgroup\$ – Henjin Sep 20 '17 at 12:17
  • \$\begingroup\$ would you please take a look at the code? @DMGregory \$\endgroup\$ – Henjin Sep 20 '17 at 12:29
1
\$\begingroup\$

The problem is with the ray casting code. By taking a look at the documentation page I realized that for getting the direction I have to subtract the player from target, and I was doing the opposite of this. So the results where not correct.

Vector3 Direction = transform.position - item.transform.position;

Should be changed to

Vector3 Direction = item.transform.position - transform.position;
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.