Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Drag and drop object to a x/y/z position

Discussion in 'Scripting' started by obianconero, Apr 1, 2014.

  1. obianconero

    obianconero

    Joined:
    Mar 20, 2014
    Posts:
    10
    hi, everyone :D

    I used this js code:

    Code (csharp):
    1.  
    2. function Update () {
    3.  
    4.     if (Input.GetMouseButton(0))
    5.     {
    6.         ray = Camera.main.ScreenPointToRay (Input.mousePosition);
    7.         if (Physics.Raycast(ray,hit))
    8.         {
    9.             transform.position.x = hit.point.x;
    10.             transform.position.y = hit.point.y;
    11.         }
    12.     }
    13.  
    14. }
    the problem is: when I drag the object, it just move around the screen.

    Q1: how to drag the object at the position that has been set.
    ____exp: my object in a Z position. when I drag it, the object move around X and Y position only (on image)


    $31.jpg

    Q2: is there the same question in this forum as I am? link, please


    thanks ;)
     

    Attached Files:

  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    Well the code you posted only changes the x and y position. This would move it around in only those directons.

    You need to also change the z position.

    There is a problem though, and is probably why who ever wrote the code you used doesn't change the z. Where in the z does it go?

    Your mouse doesn't move 3 dimensionally, it moves 2d. When you move your mouse around, where is it going in the z direction?

    This is why the Unity editor gives you the 3 axis out the sides of the object, and you can move it up and down said axes. And if you select to free move, it just moves on a plane that is in line with the current cameras viewing direction. This is the best you can really do...

    Of course your code you have isn't as robust as the Unity editor one. But that code can be written. You just are going to take the new mouse position and project it onto whatever it is you're moving on. If axis, you project it onto that axis. If plane, you project it onto that plane. The camera has most of these methods built into it... or a matrix you can use to do said calculation off.



    I'd love to help you beyond this... but you need to decide HOW the mouse interaction works. The code hinges on that.