collision detection in javascript game?
My Map ar开发者_运维问答ray ;;
map[0] = [0,0,0,0,0,0] map[1] = [0,1,0,1,0,1] map[2] = [0,0,0,0,0,0] map[3] = [1,0,1,0,1,0] map[4] = [0,0,0,0,0,0] map[5] = [0,1,0,1,0,1]
1= Hurdle 0 = Nothing
i've to detect collision detection b/w player and hurdles in map.
player.x & player.y is the reference from left top . Each hurdle is 40px of width and length .
i need a roughly concept not codes
You have to normalize player position to the collision map unit as player position is in px
units and your collision map is in array index
units and then test if the field the player tries to enter is not a hurdle.
function normalizePosition(entity){
return {
x: Math.ceil(entity.pos.x / TILE_WIDTH),
y: Math.ceil(entity.pos.y / TILE_HEIGHT)
}
}
Normalize position will give you entity coordinates on the collision map and next you have to test the actual collision to see what kind of tile is the entity entering
function mapCollision(entity, map){
var mapCoords = normalizePosition(entity),
tileType = map[mapCoords.y][mapCoords.x];
return tileType;
}
It will return the code of tile type on the map for player normalized position in case you wanted to have there different things then just blocks like some kind of slowing down traps or whatever other bear pits. You could then handle different cases where zero would default to accepts player entering the tile.
Hope I didn't tell to much :)
Good luck with your game and if you'll remember I'd be happy if you'd share the effects with me when its done :)
Tom
Update
I made a simple example for better interpretation purpose: http://fiddle.jshell.net/qFCyn/1/
Use this:
var BLOCK_SIZE = 40; // 40px * 40px blocks
var hurdle = map[player.y/BLOCK_SIZE][player.x/BLOCK_SIZE]
if(hurdle) {
// stuff
} else {
// other stuff
}
精彩评论