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. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Resolved Drag and drop not starting at centre of UI element

Discussion in 'Scripting' started by ArthurHaleta, Sep 26, 2022.

  1. ArthurHaleta

    ArthurHaleta

    Joined:
    Dec 24, 2021
    Posts:
    46
    I am making a card system where you have a horizontal layout group of your cards at bottom of screen. Hover to disable layout group and move card up, and vice versa. On drag it should, well, drag, but there are two problems: 1, the card doesn't start at the centre of the mouse, and 2, it moves in a much smaller magnitude to the mouse. Here is the entire script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. using UnityEngine.UI;
    6.  
    7. public class card : MonoBehaviour
    8. {
    9.     private HorizontalLayoutGroup lt;
    10.  
    11.     private float inity;
    12.  
    13.     private float hoverUp = 120;
    14.     private float hoverTime = 0.25f;
    15.  
    16.     private void Awake()
    17.     {
    18.         lt = transform.parent.GetComponent<HorizontalLayoutGroup>();
    19.     }
    20.  
    21.     public void hoverin()
    22.     {
    23.         inity = transform.position.y;
    24.  
    25.         lt.enabled = false;
    26.  
    27.         LeanTween.moveY(gameObject, inity + hoverUp, hoverTime).setEase(LeanTweenType.easeOutSine);
    28.     }
    29.  
    30.     public void hoverout()
    31.     {
    32.         lt.enabled = true;
    33.  
    34.         LeanTween.moveY(gameObject, inity, hoverTime).setEase(LeanTweenType.easeOutSine);
    35.     }
    36.  
    37.     public void drag()
    38.     {
    39.         lt.enabled = false;
    40.  
    41.         transform.position = getMousePos();
    42.     }
    43.  
    44.     public void drop()
    45.     {
    46.         lt.enabled = true;
    47.     }
    48.  
    49.     private Vector3 getMousePos()
    50.     {
    51.         Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) * 100;
    52.         mousePos.z = 0;
    53.  
    54.         return mousePos;
    55.     }
    56. }
    I think it could be the layout group and the other functions interacting with the gameObject while dragging but i'm unsure. Thanks!
     
  2. ArthurHaleta

    ArthurHaleta

    Joined:
    Dec 24, 2021
    Posts:
    46
    I just added the mouse position offset to the mouse position/ new transform position, so it's fine now.
     
unityunity