I'm building simple match 3 game.
I have the parts where I move the gems with the mouse only in the straight X or straight Y, up and down and both sides, no 45 degrees movements on grid.
I'm looking for simple collision detection algorithm for the situation when for example:

a gem is moved up or down or left or right and there is another gem. How can it detect it touched a gem and which gem it is?

  • 2
    \$\begingroup\$ It sounds more like you are looking for an algorithm to detect a valid move rather than collision. \$\endgroup\$ – UnderscoreZero Jul 22 '13 at 20:08
  • 2
    \$\begingroup\$ You don't even need collision detection per se. Since your gems are arranged in a grid, just check the grid location where you want to move to and see if it's occupied. \$\endgroup\$ – MichaelHouse Jul 22 '13 at 20:22
  • \$\begingroup\$ Thanks , any idea on how to make it generic? \$\endgroup\$ – user3689 Jul 23 '13 at 7:01

You could have all your gems contain their position (you probably do) and attach a method to the setter of that position so that it checks its surroundings for the gems around it.

In C# it would probably look something like this

private Vector2 mPos = something; // position of the gem
public Vector2 Position {
  get { return mPos; }
  set { mPos = value; GemMoved(mPos); }

public void GemMoved(Vector2 pPos) 
   var sameneighbours = map.FindNeighbours(this.Position, this.Color);

Another approach would simply to be check the board through for connected areas once a move is made. It's quite fast to check connected areas every time something happens unless your map is massive. By doing something like

bool[,] boardMarked = new bool[width, height];
for(int x = 0; x < width; x++)
  for(int y = 0; y < height; y++) {
    if(!boardMarked[x,y]) {
      int count = FindAndMarkConnected(x,y);
      if(count >= 3) EliminateAreAndGivePoints(x,y);
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.