1

I am make a jquery game and I have a level as a background and instead of just having for each level lots of lines of code checking where it is, is there a way to check if two colors are touching. So the background and the character.

I would prefer to not use a plugin.

jquery for checking if it is touching one line:

if(level === 1) {
    if(c.css('left') === '90px') {
        c.css({'left': '115px', 'bottom': '94px'});
    }
}

http://jsfiddle.net/Hive7/KPyxN/2/

Hive7
  • 3,599
  • 2
  • 22
  • 38
  • "is there a way to check if two colors are touching" - no, not in the way it sounds like you want. – Matt Ball Aug 29 '13 at 13:30
  • so is there a way to do what I want without the long way? – Hive7 Aug 29 '13 at 13:31
  • Welcome to StackOverflow! We prefer questions to demonstrate a minimal amount of code, to better to reproduce the specific problem you're trying to solve. Read [the SO about page](http://stackoverflow.com/about) for more. – Blazemonger Aug 29 '13 at 13:34
  • @Blazemonger just saying I am not new – Hive7 Aug 29 '13 at 13:35
  • will pos a fiddle and code for you – Hive7 Aug 29 '13 at 13:35
  • Then you should see right away that your question is unanswerable in its current form. Without more specifics, it's impossible to even guide you to more information. – Blazemonger Aug 29 '13 at 13:37
  • sorry @Blazemonger have posted a fiddle – Hive7 Aug 29 '13 at 13:37
  • 1
    So you want to know if the blue box is over a specific color of your entire background image? I'm sorry, but JavaScript is unable to identify things like that. You need to rethink your entire approach. You might need to implement some kind of [collision detection](http://stackoverflow.com/questions/2440377/javascript-collision-detection). – Blazemonger Aug 29 '13 at 13:39

1 Answers1

2
 function collision($div1, $div2) {
      var x1 = $div1.offset().left;
      var y1 = $div1.offset().top;
      var h1 = $div1.outerHeight(true);
      var w1 = $div1.outerWidth(true);
      var b1 = y1 + h1;
      var r1 = x1 + w1;
      var x2 = $div2.offset().left;
      var y2 = $div2.offset().top;
      var h2 = $div2.outerHeight(true);
      var w2 = $div2.outerWidth(true);
      var b2 = y2 + h2;
      var r2 = x2 + w2;

      if (b1 < y2 || y1 > b2 || r1 < x2 || x1 > r2) return false;
      return true;
    }

JSFIDDLE DEMO

Vaibs_Cool
  • 6,126
  • 5
  • 28
  • 61
  • will try with a different approach with that. thanks – Hive7 Aug 29 '13 at 13:44
  • didn't work as I planned have a look at this http://jsfiddle.net/Hive7/KPyxN/3/ should alert tough I know this is because I am using images. Is there a way around it? – Hive7 Aug 29 '13 at 14:09