Search Unity

Objetc in mouse position

Discussion in 'Scripting' started by Sputnicker, Feb 25, 2011.

  1. Sputnicker

    Sputnicker

    Joined:
    Mar 23, 2010
    Posts:
    26
    Hello, I need a code that make a object (ex: sphere) stay at mouse position in X and Y axis and at 0 position in Z axis.
    I need this to make my Gun in 2.5D sidescroller shooter, the gun is already facing the object, I just need to make it stay at crosshair position.

    Already tried ScreenToWorldPoint, but no sucess... ;/
     
  2. Cameron_SM

    Cameron_SM

    Joined:
    Jun 1, 2009
    Posts:
    915
    You were on the right track, ScreenToWorldPoint is what you need.

    Code (csharp):
    1. // totally untested made-up-on-the-spot code...
    2. Vector3 gunPosition = Input.mousePosition;
    3. Camera cam = Camera.mainCamera;
    4. gunPosition.z = -cam.position.z;
    5. gunPosition = cam.ScreenToWorldPoint(gunPosition);
    6. myGunObject.transform.position = gunPosition;
     
  3. Sputnicker

    Sputnicker

    Joined:
    Mar 23, 2010
    Posts:
    26
    Thanks Cameron, It worked almost perfectly, with some adjustments its now this way:

    Code (csharp):
    1. function Update () {
    2.     gunPosition = Input.mousePosition;
    3.     gunPosition.z = -Camera.mainCamera.transform.position.z;
    4.     gunPosition = Camera.mainCamera.ScreenToWorldPoint(gunPosition);
    5.     transform.position = gunPosition;
    6.     transform.position.z = 0;
    And the arm script is
    Code (csharp):
    1.  
    2. var fpc : GameObject;
    3. function Update () {
    4.     transform.LookAt(fpc.transform.position);
    5. }
    6.