Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Multiple moveable gameobjects by mousedrag, need to block each other but not move when they hit

Discussion in 'Physics' started by nifi1, Nov 14, 2023.

  1. nifi1

    nifi1

    Joined:
    Mar 8, 2019
    Posts:
    1
    Fairly new to Unity - I'm trying to create a base game mechanic - I have multiple gameobjects that I move along either an X or Y axis on a grid. I want each gameobject to be draggable but I want each gameobject to block the one that is being dragged. At the moment on each collision one or two object float off in to the distance on collision. Any pointers as to what I am doing wrong. (I have tried multiple options on the on collision function)

    Code (CSharp):
    1. void OnMouseDrag()
    2.     {
    3.         float currentMouseX = Input.mousePosition.x;
    4.         float deltaMouseX = currentMouseX - initialMouseX;
    5.  
    6.         if (isDragging && canMove)
    7.         {
    8.             Vector3 localPosition = transform.localPosition;
    9.  localPosition.x += deltaMouseX * moveSpeed * Time.deltaTime;
    10.          
    11.             if (localPosition.x <= 2 && localPosition.x >= -2)
    12.             {
    13.                 transform.localPosition = localPosition;
    14.             }
    15.             initialMouseX = currentMouseX;
    16.         }
    17.  
    18.     }
    19.  
    20.     void OnMouseDown()
    21.     {
    22.  isDragging = true;
    23.  
    24.         screenPoint = Camera.main.WorldToScreenPoint(transform.position);
    25.         offset = transform.position - Camera.main.ScreenToWorldPoint(
    26.             new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    27.  
    28.             initialMouseX = Input.mousePosition.x;  
    29.     }
    30.  
    31.     private void OnMouseUp()
    32.     {
    33.         isDragging = false;
    34.         SnaptoGrid();
    35.     }
    36.  
    37.     void SnaptoGrid()
    38.     {
    39.         //float gridSize = 1.0f;
    40.         float nearestX = Mathf.Round(transform.localPosition.x / gridSize) * gridSize;
    41.         transform.localPosition = new Vector3(nearestX, transform.localPosition.y, transform.localPosition.z);
    42.     }
    43.  
    44.  
    45.     void OnCollisionEnter(Collision collision)
    46.     {
    47.         // Optional: Check for a specific object by tag
    48.         if (collision.gameObject.CompareTag("car"))
    49.         {
    50.             Debug.Log("Hit gameobject");
    51.         }
    52.     }