Search Unity

2D Gear Box Movement

Discussion in 'Scripting' started by fazraz, Feb 14, 2018.

  1. fazraz

    fazraz

    Joined:
    Feb 27, 2015
    Posts:
    14
    Hi all,

    I'm looking to create a very simple 2D gear stick which is draggable into the correct gear positions (1, 2, 3, 4 and 5). Here is an image of what I mean:

    Gear 1 - https://imgur.com/GmcIvf1
    Gear 2 - https://imgur.com/Fj3KD4W
    Gear 3 - https://imgur.com/q5zlhbf

    etc.

    I have a script which allows the red 'gear stick' to be draggable, however I don't know how to keep it within the bounds of the gear guide (the grey lines).

    Would be very grateful if someone could point me in the right direction.

    Many thanks,
    Farid
     
  2. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    If you can drag it, then you have to restrict the movement to form the shape of the gearbox. So if it's in position one, it can only go down until a junction or the position 2. That's the only way I can think of.
     
  3. fazraz

    fazraz

    Joined:
    Feb 27, 2015
    Posts:
    14
    I don't feel like this gives me enough information to do it :(
     
  4. fire7side

    fire7side

    Joined:
    Oct 15, 2012
    Posts:
    1,819
    You didn't give any code, which makes anything more virtually impossible.
     
  5. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    This would be a more complicated case of dragging along a line, so I'd do it in stages:
    Step 1: Drag a slider along a line. I think you'd just need to project the mouse position onto the line and then clamp it between the two endpoints.
    Step 2: Have multiple lines, and have zones (a small square) in which you can swap between them. Probably something like, while inside the zone, determine which axis the user's attempted movement is closer to (or which projected position is closer to the mouse position) and switch which one is the "active" line accordingly.
    Step 3: That's only going to cover straight line movement with sharp corners, so if you want curved movement you'll need to handle that differently.
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    I thought about this and tried to make a mock design. At the "intersections" and ends, I created small box collider2ds with pointer drag and enter methods. I had an list of allowed connections, so if you began dragging from any intersection you were allowed to go to any one that was next in the path.
    It's not perfect, because the gear/knob doesn't actually move when you move, but it was a simple example. I added a swift 'movement' after any valid pointer enter (while dragging) to simulate the knob moving along into position.