Search Unity

How to move puzzle pieces with mouse?C# -beginner-

Discussion in 'Scripting' started by Farawe, Mar 26, 2020.

  1. Farawe

    Farawe

    Joined:
    Aug 15, 2019
    Posts:
    2
    So i made something like this in unity UI (took image from google photos, not mine)

    Puzzle.png

    with pieces, a key, a background table.

    I want the player to move the pieces using the mouse. Pieces can move either horizontally or vertically.
    I made an UI panel and put them there, every piece is a UI image.

    What i tried: - moving them with functions like onDrag, attaching them rigidbodies, triggers. The rigidbodies didn t work smoothly, when I moved the piece with a greater speed, the collisions weren t detected and the piece would go over another.(I used rigidbody.move())

    - moving the pieces by getting the mouse input and then (piece).transform=Input from mouse. This time the triggers attached to the pieces were with: is trigger ON. I made a different script for: when smth enters the collider of the piece, the piece that entered would go back to the original position. This methord worked better but it s not smooth at all. The player would need to move the piece slowly so it wouldn t hit a collider.

    What functions or method can be used to move the pieces smoothly, without going over other pieces / the border of the table?
     
  2. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,338
    You don't want to do this with built-in physics or collision, that'll just be chaos.

    Instead, have a data representation of your pieces and their positioning, and when you move a piece, check if the position you're trying to move it to is filled, and prevent the movement if that's the case.

    The most straight-forwards way of doing that is to have a 2D bool array representing if a square is open or not, and calculate the positions in that array from your piece positions.
     
  3. Farawe

    Farawe

    Joined:
    Aug 15, 2019
    Posts:
    2
    thank you!:)