这个开源游戏项目是克隆目前最火手游Pokémon Go,使用Mapbox作为地图, Pokéapi作为Pokémon数据和精灵,使用Pusher处理发送位置定位给所有玩家。
使用Mapbox作为地图是因为它有一个很完美的Javascript库包组件,使用Mapbox GL能很容易通过图片和一些坐标将精灵加入地图:
var marker = new mapboxgl.Marker(createSprite(data)) .setLngLat(data.coordinates) .addTo(map);
|
这将创建了图片叠加到地图上,然后加入一个事件处理器以便触发情态窗口开始战斗。
const modal = document.getElementById('modal'); document.querySelector('body').addEventListener('click', show);
function show(event) { if(event.target.classList.contains('pokemon')) { currentSprite = event.target; currentSprite.dataset.currenthp = currentSprite.dataset.hp;
modal.querySelector('.modal-image').src = event.target.src; modal.querySelector('.modal-name').innerHTML = event.target.dataset.name; modal.querySelector('.modal-current-hp').style.width = '100%'; modal.querySelector('.modal-current-hp').style.backgroundColor = '#39e239'; modal.querySelector('.modal-attack').innerText = 'ATTACK!!!'; modal.querySelector('.types').innerText = currentSprite.dataset.types; modal.classList.remove('hide'); } }
|
关于位置定位,需要所有玩家在同样位置看到相同的Pokemon,这时Pusher就非常适合,能够使用它发送同样事件给所有玩家。
最后是Pokemon数据,pokeapi非常简单令人惊奇,是所有Pokemon数据的RESTful API。下面是调用代码:
fetch(`http://pokeapi.co/api/v2/pokemon/${pokemonId}/`) .then(res => { return res.json(); }) .then(pokemon => { const data = { id: pokemonId, name: pokemon.name, sprite: `https://pokeapi.co/media/sprites/pokemon/${pokemonId}.png`, coordinates: [lng, lat], expires: parseInt((new Date()).getTime() + duration, 10), hp: pokemon.stats.find(stat => stat.stat.name === 'hp').base_stat, types: pokemon.types.map(type => type.type.name[0] + type.type.name.substring(1)) }
pusher.trigger(bounds, 'encounter', data); });
|
更详细说明见:Building A Pokémon GO Clone Using Web Technologies And Pusher
项目地址:
AverageMarcus/Pushermon-Go: A Pokémon Go clone