Author Topic: Crosshair Not Working  (Read 1659 times)

huntsfromshadow

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 0
  • Posts: 1
    • View Profile
Crosshair Not Working
« on: February 19, 2014, 05:37:25 PM »
Hello,

Trying to work on a project that requires a corsshair in the 2D NGUI View moving over a 3d object,
and detecting it's over that object.

I'm trying to do it with raycasts, but having no luck.  If I move the crosshair over the objet and trigger the routine I don't get a hit, but if I move the crosshair further up and over I can get it to show a hit, but oviously on screen the crosshair is not over the object.

Any thoughts?  I'll admit Raycasts are not something I'm very familiar with so this could be just a stupid mistake.

Thanks

For reference the script is located on the crosshair UISprite Object, and the only other gameobject is a 3d cube as a test target.
UICamera is the NGUI 2D Camera inside UIRoot.

  1. bool isCrossHairOverTarget() {
  2.  
  3.     Vector3 pos = UICamera.mainCamera.WorldToViewportPoint(transform.localPosition);
  4.     Vector3 endpos = Camera.main.ViewportToWorldPoint(pos);
  5.  
  6.     Ray r = Camera.main.ViewportPointToRay(endpos);
  7.     RaycastHit rh = new RaycastHit();
  8.  
  9.     Debug.DrawRay (r.origin, r.direction * 10, Color.yellow, 5.0f);
  10.     if(Physics.Raycast(r, out rh)) {
  11.         return true;
  12.     }
  13.     else {
  14.         return false;
  15.     }
  16. }

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Crosshair Not Working
« Reply #1 on: February 20, 2014, 09:07:53 AM »
Quote
Vector3 pos = UICamera.mainCamera.WorldToViewportPoint(transform.localPosition);
You're calling a "World" function, while feeding it a "Local" position...

1. Convert transform.position to viewport point.
2. Camera.main.ViewportPointToRay the value from step 1.
3. Use the ray to raycast.