Monday, March 24, 2014

instantiate object at mouse position - change mouse position to world position.

If you are trying to instantiate a gameobject when player clicks on surface, you have to find the world point of the tabbed place. Then you can instantiate your object. 

You can get hit.point to find where the object is hit. If you are trying to make a shooting game. This will give you the world position. 

Or you can use mouse position and since mosue position is screen coordinates you change it into world position. 

Input.mousePosition is in screen coordinates (in pixels)

To get a position in world coordinates you need to use Camera.main.ScreenToWorldPoint(Input.mousePosition). 

Input.mousePosition is also a 2 dimensional position (because your screen is flat). To get a correct and meaningful world position you will also have to specify a z coordinate to describe how far in front of the camera the world point should be. So if you have a camera looking straight down onto a plane and the camera has a distance of 10 to the plane you would set the z coordinate to 10 to instantiate something on that plane.

here is an example code which gives the world point of Input.mousePosition. 

Vector3 myPos = Input.mousePosition;

myPos = Camera.main.ScreenToWorldPoint(myPos);

myPos.z = 10f;   //you have to modify z coordinate since it will always give you the camera's z position. 


here is an other code which I find on http://answers.unity3d.com/questions/32807/instantiate-object-at-mouse-position.html page. 


  1. Vector3 mousePos=new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f);
  2.  
  3. if(Input.GetMouseButtonDown(0)) {
  4. Vector3 wordPos;
  5. Ray ray=Camera.main.ScreenPointToRay(mousePos);
  6. RaycastHit hit;
  7. if(Physics.Raycast(ray,out hit,1000f)) {
  8. wordPos=hit.point;
  9. } else {
  10. wordPos=Camera.main.ScreenToWorldPoint(mousePos);
  11. }
  12. Instantiate(thePrefab,wordPos,Quaternion.identity);
  13. //or for tandom rotarion use Quaternion.LookRotation(Random.insideUnitSphere)
  14. }


hope this helps.

useful links:

+ http://forum.unity3d.com/threads/50321-2D-screen-coordinates-to-3d-world-coordinates


No comments:

Post a Comment