Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Takes the collision data defined in the collision editor of Tiled and applies it to
- * and exisiting tilemap for use with P2 physics bodies.
- *
- * Tilemap json data MUST be loaded in the Preload state/function using game.load.json() before this function is called
- * map must only have ONE tileset
- * each tile can only have ONE polyline set for it's collision
- * the polyline MUST be a complete shape (the last point is indentical to the first)
- *
- * @param {Phaser.Tilemap} map - this is the map which you want polylines added to
- * @param {string} key - this is the key for the raw json tilemap data loaded in the preload state
- * @param {bool} [roundValues=true] - Will round the x,y coordinates for the polylines to nearest integer
- */
- addPolylineCollision: function (map, key, roundValues) {
- if (roundValues === undefined) { roundValues = true; }
- // json with the collision data that was omitted by phaser
- let data = this.game.cache.getJSON(key);
- //console.log(data);
- let collisionData = data.tilesets[0].tiles;
- // array of the collision polygons that will get added to the tilemap
- var polygons = [];
- // tiles in the Collision Layer that will help define the polygons
- let mapData = map.layers[map.getLayer('Collision Layer')].data;
- for (let row in mapData) {
- for (let col in mapData[row]) {
- var wall = collisionData[mapData[row][col].index - 1];
- if (wall !== undefined) {
- for (let i in wall.objectgroup.objects) {
- let poly = {
- height: 0,
- name: "",
- polyline: [],
- properties: undefined,
- type: "",
- visible: true,
- width: 0,
- x: mapData[row][col].x * map.tileWidth,
- y: mapData[row][col].y * map.tileHeight
- };
- for (let j in wall.objectgroup.objects[i].polyline) {
- var coords = [wall.objectgroup.objects[i].polyline[j].x,
- wall.objectgroup.objects[i].polyline[j].y];
- if (roundValues) {
- coords[0] = Math.round(coords[0]);
- coords[1] = Math.round(coords[1]);
- }
- poly.polyline.push(coords);
- }
- polygons.push(poly);
- }
- }
- }
- }
- console.log(polygons);
- map.collision['Collision Layer'] = polygons;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement