Author Topic: Positioning Widget Based on World Object Position  (Read 2581 times)

DarksBlood

  • Guest
Positioning Widget Based on World Object Position
« on: February 25, 2013, 09:32:16 PM »
Hello everyone, I have something I hope I could get some help understanding.
So here how my set up works. I have A capsule which has a long cube as a child and on the cube is an empty game object at the very end of it. I'll refer to the capsule as the turret, the long cube as a barrel and empty as a Spawn Location. the barrel has the main camera attached to it as child as well. I managed to manually position a sprite on a 3d UI to represent where a projectile will land from the "Spawn Location"; 
However I want to do this with script and I have been really puzzled by this for a while now.

I've search and most people have suggested casting a ray and then using ray cast and worldtoscreenpoint.
Can I please get any suggestions on this please?
  1. void Start ()
  2.         {
  3.                         RaycastHit Hit = new RaycastHit ();
  4.                         Ray ray = CameraToUse.ScreenPointToRay (transform.position);
  5.                         Debug.DrawRay (transform.position,Vector3.forward,Color.red);
  6.                         if(Physics.Raycast (ray,out Hit))
  7.                         {
  8.                                 Vector3 Pos = CameraToUse.WorldToScreenPoint (Hit.point);
  9.                                 Vector3 CrossPos = new Vector3(Pos.x,Pos.y,Cross.position.z);
  10.                                 Cross.localPosition = CrossPos; // Set the parent of the spirte to the location
  11.                                 print ("Pos " + Pos);
  12.                         }
  13.                
  14.         }
  15.  
  16.  

ArenMook

  • Administrator
  • Hero Member
  • *****
  • Thank You
  • -Given: 337
  • -Receive: 1171
  • Posts: 22,128
  • Toronto, Canada
    • View Profile
Re: Positioning Widget Based on World Object Position
« Reply #1 on: February 26, 2013, 07:23:40 AM »
Check the health bars sticky. It has the code you need to convert from world space to screen space.