开发者

Per pixel collision detection in Javascript/Jquery/Gamequery

开发者 https://www.devze.com 2022-12-31 00:02 出处:网络
I am trying to program a web game in Jquery with the GameQuery plugin, problem is the GameQuery plugin has no support for per pixel collision detection only collision detection with bounding boxes. Is

I am trying to program a web game in Jquery with the GameQuery plugin, problem is the GameQuery plugin has no support for per pixel collision detection only collision detection with bounding boxes. Is it possible to implement per pixel collision detection in javascript/Jquery?

I have a world map with countries and a player which is moved using the arrow keys, I want to be开发者_开发技巧 able to tell which country the player is in at any time and the countries are irregular shapes.


Or attack it from a different angle...so to speak...

Vectors may be your key, cool stuff happening at http://www.raphaeljs.com

maybe some sort of combo/integration could work?


alright here is kind of a solution:

assign each country a different color in you map (do not assign special colors to borders, borders should be colored in either color of the countries).

load that image into a canvas

var img = new Image();
img.src = 'worldmap.png';
var map = document.getElementById('canvas').getContext('2d');
map.drawImage(img, 0, 0);

after that you can display your normal map above that map (it is only a reference, and can be hidden under other stuff - use divs and z-index for that).

to determine in which country the player is just get the pixel-data at his position

data = map.getImageData(x, y, 1, 1).data;
key = data.join("-"); // something like "255-0-0-255" for red
country = countries[key];

it should be an rgba-array, you may then look up what country is assigned to that color. so you will have to keep an array with the imploded rgba-values as key and the country names as value.

countries = {
"255-0-0-255"   : "Russia",
"255-0-255-255" : "China",
...
};

this does only work in browsers that have the canvas object. so if you are doing this on iphone or android you are lucky!


The images are just pngs with solid colours for the country and transparency for the rest.


It is not possible.

You have, however, a not very complicated alternative: use polygon-based collision.

Use an image to present the countries to the user, but use a polygon internally.

You may find a very complete explanation about how to implement this on this forum entry (you may have to scroll down a bit, until you see the images). The guy asking the question there wanted to do more or less the same as you want todo (mouse position instead of character position).

Regards!

0

精彩评论

暂无评论...
验证码 换一张
取 消