collision detection in javascript game?

和自甴很熟 提交于 2019-12-01 13:39:05

问题


My Map array ;;

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


回答1:


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/




回答2:


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
}


来源:https://stackoverflow.com/questions/4871669/collision-detection-in-javascript-game

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!