Search Unity

Drag and Drop only on x and z axis?

Discussion in 'Scripting' started by Asta_D, Dec 10, 2015.

  1. Asta_D

    Asta_D

    Joined:
    Oct 16, 2013
    Posts:
    15
    Hello

    I used this script to do a drag&drop and it is working onx,y,z.
    Code (CSharp):
    1. public class Dragit : MonoBehaviour {
    2.     Vector3 dist;
    3.     float posX;
    4.     float posY;
    5.  
    6.     void OnMouseDown(){
    7.         dist = Camera.main.WorldToScreenPoint(transform.position);
    8.         posX = Input.mousePosition.x - dist.x;
    9.         posY = Input.mousePosition.y - dist.y;
    10.  
    11.     }
    12.  
    13.     void OnMouseDrag(){
    14.         Vector3 curPos =
    15.             new Vector3(Input.mousePosition.x - posX,
    16.                 Input.mousePosition.y - posY, dist.z);
    17.  
    18.         Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
    19.         transform.position = worldPos;
    20.     }
    21. }
    But i would like to move the gameobject only on the x and z axis and i don't get it. Could anybody helo me with that?

    Greetings from Germany
    Asta
     
  2. Browdaddy96

    Browdaddy96

    Joined:
    Aug 27, 2015
    Posts:
    82
    Might I recommend using a Vector3 instead of 2 floats? Here is my solution:

    Code (CSharp):
    1. Vector3 dist;
    2.  
    3. void OnMouseDown(Vector3 _pos)
    4. {
    5.       dist = Camera.main.WorldToScreenPoint(transform.position);
    6.       Vector3 pos = new Vector3 (_pos.x - dist.x, transform.position.y, _pos.x - dist.x);
    7. }
    your OnMouseDrag method looks good.

    Sorry if this does not work I am in school and can't test it on unity.

    Greetings from New York America
     
  3. martinmr

    martinmr

    Joined:
    Mar 25, 2015
    Posts:
    325
    last shouldn't it be "_pos.y - dist.y" at the z Value of the vector3 ?

    Code (CSharp):
    1.  Vector3 pos = new Vector3 (_pos.x - dist.x, transform.position.y, _pos.y - dist.y);
    so you can move x and z with 2 axis ?
     
  4. Browdaddy96

    Browdaddy96

    Joined:
    Aug 27, 2015
    Posts:
    82
    I believe I just had a brain fart.