Mapbox driving basic game
by jscastro76
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css">
<script src="https://unpkg.com/threebox-plugin/dist/threebox.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/threebox-plugin/dist/threebox.css">
<div id='map' class='map'>
<div class="mapboxgl-ctrl helpDiv">
<div id="help" class="help">
Press "W", "A", "S", "D" keys to drive the truck
</div>
</div>
</div>
CSS
body, html {
width: 100%;
height: 100%;
margin: 0;
}
#map {
width: 100%;
height: 100%;
}
.helpDiv {
width: auto;
left: 50%;
top: 0px;
z-index: 2;
position: absolute;
}
.help {
background: rgba(0, 0, 0, 0.5);
color: #fff;
position: relative;
text-align: center;
top: 10px;
left: -50%;
padding: 5px 10px;
margin: 0;
font-size: 11px;
line-height: 18px;
border-radius: 3px;
z-index: 1;
display: block;
}
JavaScript
mapboxgl.accessToken = "COPY YOUT MAPBOX TOKEN HERE";
let minZoom = 12;
let mapConfig = {
map: {
center: [-122.4301905, 37.7298202],
zoom: 20,
pitch: 60,
bearing: 38
},
truck: {
origin: [-122.4301905, 37.7298202, 0],
type: 'mtl',
model: 'https://unpkg.com/threebox-plugin/examples/models/Truck',
rotation: {
x: 90,
y: 0,
z: 0
},
scale: 3,
startRotation: {
x: 0,
y: 0,
z: -38
},
date: new Date(2020, 6, 19, 23)
},
names: {
compositeSource: "composite",
compositeSourceLayer: "building",
compositeLayer: "3d-buildings"
}
}
let map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/satellite-streets-v11',
zoom: mapConfig.map.zoom,
center: mapConfig.map.center,
pitch: mapConfig.map.pitch,
bearing: mapConfig.map.bearing,
antialias: true // create the gl context with MSAA antialiasing, so custom layers are antialiased
});
window.tb = new Threebox(
map,
map.getCanvas().getContext('webgl'), {
realSunlight: true,
enableSelectingObjects: true,
enableDraggingObjects: true,
enableRotatingObjects: true,
enableTooltips: true
}
);
tb.setSunlight(new Date(2020, 6, 19, 23), map.getCenter());
// parameters to ensure the model is georeferenced correctly on the map
let truck;
function createCustomLayer(layerName) {
let model;
//create the layer
let customLayer3D = {
id: layerName,
type: 'custom',
renderingMode: '3d',
onAdd: function(map, gl) {
let options = {
type: mapConfig.truck.type, //model type
obj: mapConfig.truck.model + '.obj', //model .obj url
mtl: mapConfig.truck.model + '.mtl', //model .mtl url
units: 'meters', // in meters
scale: mapConfig.truck.scale, //x3 times is real size for this model
...