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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Drag and place objects, Logical problem

Discussion in 'Scripting' started by Vaspix, Feb 6, 2020.

  1. Vaspix

    Vaspix

    Joined:
    Jun 8, 2019
    Posts:
    54
    Hello,
    I'm making a 2D game where you can drag and place certain objects (when clicking on them and holding, they follow cursor until mouseButton is up)
    This code piece makes SelectedObject follow mouse Position, it also snaps objects on grid (also if they have odd-numbered scale it increases position on appropriate axis on 0.5f cause otherwise it won't snap properly)

    Code (CSharp):
    1.  
    2.                     // Even
    3.                     if (SelectedObj.transform.localScale.x % 2 == 0)
    4.                         HorEven = 0f;
    5.                     else
    6.                         HorEven = 0.5f;
    7.  
    8.                     if (SelectedObj.transform.localScale.y % 2 == 0)
    9.                         VerEven = 0f;
    10.                     else
    11.                         VerEven = 0.5f;
    12.  
    13.                     // Move Obj
    14.                     SelectedObj.transform.position = new Vector3
    15.                         (Mathf.RoundToInt(mousePos.x + HorEven) - HorEven,
    16.                          Mathf.RoundToInt(mousePos.y + VerEven) - VerEven);
    So my problem is, I'm changing Position of object, so I can't for instance take a corner of a big object to move on 1 unit, cause its center will be set to mousePos immediately
    I was trying to figure out how I can make object follow mousePos not by its center, but by the part where mousePos takes the object.

    Do you have any idea how to implement this? Thank you! (If something is not clear I'll try to explain better) :)
     
  2. PaulR

    PaulR

    Joined:
    Nov 14, 2012
    Posts:
    43
    You need to save the X and Y offset from the object position to the mouse when the mouse button is first pressed.

    Then on each frame as you update the object position, add this X and Y offset to the mouse position.
     
    Vaspix likes this.
  3. welby

    welby

    Joined:
    Mar 22, 2011
    Posts:
    549
    yeah,.I did something like this a while ago.

    You make a phantom object that snaps to your mouse,.but the actual Unit Object is temporarily SetParented to it until you release, thereby keeping its relative position. That may do it, too.
     
    Vaspix likes this.