Code Monkey home page Code Monkey logo

von-grid's Introduction

NOTE: This repo is no longer maintained

Feel free to fork and do whatever. There is a dev branch that has an incomplete rewrite, but everything here is so old that even I don't get what I was thinking. Enjoy!

3D hex tile system

screenshot

I never found a good (and free!) library for creating perfect hexagons and arranging them in a grid. But I did find Amit's wonderful explanation, and finally had the time to throw something together.

You can use the Board class with different graph types (hex and square), or you can make your own if you implement the interface.

Please use this to make awesome hex-based web games. Or port the code and make awesome hex games there. Just make awesome hex games, ok?

Features

  • Simple API for attaching objects to the grid through Board.js
  • A pathfinding* with or without weighted nodes, and a walkable flag
  • Make maps with the editor (autosaves to localstorage, and save/load as .json files)
  • Varied height
  • Sparse maps
  • Mouse interaction with the grid's cells (over, out, down, up, click, wheel)
  • Programmatic geometry, allow you to precisely adjust every aspect of the hexagon
  • Square grid that can be used interchangeably
  • Include only the hex grid by downloading dist/hex-grid.js, or all grid types with von-grid.js, etc

Roadmap

  • Improved editor
  • Improved API
  • Abstract grid

Usage

Basic board

screenshot

var scene = new vg.Scene({ // I made a very handy util for creating three.js scenes quickly
	cameraPosition: {x:0, y:150, z:150}
}, true); // 'true' or a config object adds orbit controls

var grid = new vg.HexGrid();

grid.generate({
	size: 4
});

var board = new vg.Board(grid);

board.generateTilemap();

scene.add(board.group);
scene.focusOn(board.group);

update();

function update() {
	scene.render();
	requestAnimationFrame(update);
}

Examples

For the simple examples you can drop them into Chrome, but for ones that require images or models, you'll have to run gulp serve-examples. A browser tab will be opened to the examples directory for you.

Editor

screenshot

von-grid's People

Contributors

chabloz avatar generateui avatar harlantwood avatar vonwolfehaus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

von-grid's Issues

Best way to implement other hexgrid forms

Hi,
I have implemented a custom hexgrid form. For doing this, I have implemented a new "generate" function in HexGrid.js. Is there another way to perform it without changing the core code. Thank you

multi-level grid cells

I was wondering how to go about adding a z-coordinate to the grid. i'm imagining something like:
untitled

Where the 3 middle cells at the top are directly above the 3 in the middle below. it would be cool for creating bridges or ledges

Update lib paths

Need to rename hex-grid.min.js to von-grid.min.js in some examples...
After renaming I have blank screen and 'THREE.WebGLRenderer 73 three.min.js:578' in console in both Win and Debian Chrome and Edge.
In pathfinding - "Cannot read property 'gridPos' of undefined HexGrid.js:161".
In editor - "Cannot read property 'depth' of undefined main.js:161"

removeAllTiles function doesn't remove all tiles

Hi,

I found an issue when removing all the tiles, where only some of the tiles are been removed. I believe this is due to the element being shifted down by one. The index variable t is not shifting after each removal.

for (var e = this.tileGroup.children, t = 0; t < e.length; t++)
  this.tileGroup.remove(e[t]);

However, was able to fix with the following code,

var e = this.tileGroup.children
while(e.length>0)
  e.pop();

Some bugs in SquareGrid

  1. No _geoCache in vg.SquareGrid. Solved by adding "this._geoCache = [];" to SquareGrid constructor.
  2. Null x property on line 102 then.
    Probably solved by changing method:
    cellToPixel: function(c, pos) {
    this._vec3.x = c.q + (this.cellSize/2);
    this._vec3.y = c.h + (c.depth/2);
    this._vec3.z = c.s - (this.cellSize/2);
    return this._vec3;
    },
  3. Then got "Uncaught TypeError: Cannot read property 'center' of undefined" on line 135 of three.js

grid navigation

Hi, I just come across this great looking bit of code, and apologies if this is not the correct place to ask this question, however:

I would like to have a player "roll a dice" to determine straight line movement around the board. If a player is starting in the centre of the board 0,0,0 and rolls dice for direction (D6) (1 is top-right, 2 is right, 3 is bottom right etc) and distance (D6) what is the best method for calculating the destination tile? the dice bit i can figure out it's calculating straight lines to the dest tile I havent got my head around yet...

I was also wondering if there is a method to display each tiles coords on the board to help me figure out some of the maths of wrapping off the end of the board back onto the other side??

and finally... :-) whats the difference between cell and tile in your code?

Remove existing tiles

In examples/js/EditorPlane.js at line 143 the mouse click event not working correctly. For removing the tile i moved this code into MouseCaster.UP switch branch and added an if/else to look if the tile exists

Editor dosnt work correctly on localhost

I dont know what happend with mouse hovering on the EditorPlane, but i can hovering on the plane. Hover mesh are locked on the x-axis, or z, i don't know why mouse position on local server dont work correctly, help pls.

PS. i try download editor from branch gh-pages, and the same problem.

incomplete hex overlay

I can see that the hex overlay is always missing a line on it's right side.

generateOverlay: function(size, overlayObj, overlayMat) {
        var x, y, z;
        for (x = -size; x < size+1; x++) {
            for (y = -size; y < size+1; y++) {
                z = -x-y;
                if (Math.abs(x) <= size && Math.abs(y) <= size && Math.abs(z) <= size) {
                    this._cel.set(x, y, z); // define the cell
                    var line = new THREE.Line(this.cellGeo, overlayMat);
                    line.position.copy(this.cellToPixel(this._cel));
                    line.rotation.x = 90 * vg.DEG_TO_RAD;
                    overlayObj.add(line);
                }
            }
        }
    },

So I tried drawing the hex overlay using the pointsGeometry() instead and it worked

generateTileOverlay: function(size, overlayObj, overlayMat) {
        this.cellShape.autoClose = true;
        var geo = this.cellShape.createPointsGeometry();
        var x, y, z;
        for (x = -size; x < size+1; x++) {
            for (y = -size; y < size+1; y++) {
                z = -x-y;
                if (Math.abs(x) <= size && Math.abs(y) <= size && Math.abs(z) <= size) {
                    this._cel.set(x, y, z); // define the cell
                    var line = new THREE.Line(geo, overlayMat);
                    line.position.copy(this.cellToPixel(this._cel));
                    line.rotation.x = 90 * 0.0174532925;
                    overlayObj.add(line);
                }
            }
        }
    },

Callbacks for loading

I think hex-grid is great! I am trying to add websocket networking with it. I am more of a C programmer than a Javascript developer. I would like to wrap the whole grid in a network system. I moved the code in map-maker-html into it own JS file. I also added controls at the top to select a file to load.

Your JS code is much better than mine. Given some suggestions I am sure I could add the necessary code.

Freshening dependencies?

First of all, thanks for von-grid :) I'm planning to use it to make an awesome hex games :)

It seems that von-grid hasn't been updated in a while. npm install produces a list of deprecation warnings, and an error:

npm WARN deprecated [email protected]: This module relies on Node.js's internals and will break at some point. Do not use it, and update to [email protected].
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated [email protected]: Deprecated, use jstransformer
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: Please update to at least constantinople 3.1.1
npm WARN deprecated [email protected]: please upgrade to graceful-fs 4 for compatibility with current and future versions of Node.js
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated [email protected]: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: CircularJSON is in maintenance only, flatted is its successor.
npm WARN deprecated [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
npm WARN deprecated [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated [email protected]: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
npm WARN deprecated [email protected]: gulp-util is deprecated - replace it, following the guidelines at https://medium.com/gulpjs/gulp-util-ca3b1f9f9ac5
npm WARN deprecated [email protected]: Jade has been renamed to pug, please install the latest version of pug instead of jade
npm ERR! code ENOENT
npm ERR! syscall chmod
npm ERR! path /home/duncan/code/von-grid/node_modules/riot/node_modules/.bin/riot
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, chmod '/home/duncan/code/von-grid/node_modules/riot/node_modules/.bin/riot'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent 

Using von-grid against recent versions of threejs also produces errors because threejs no longer exports the Geometry type (see https://discourse.threejs.org/t/three-geometry-will-be-removed-from-core-with-r125/22401).

I was thinking of raising a separate issue for each of the above (this issue being more for discussion of the approach). Then, hopefully, I can raise some pull requests to address at least some of the above, albeit slowly and haltingly; I'm only a dilettante JavaScript developer, and the last game I wrote ran on an Amstrad CPC. It'd still be faster than writing my own von-grid from scratch though ;)

Does that sounds like a reasonable approach? Asking because I'm not sure of the status of von-grid, and whether you may already be working on any or all of the above.

Problem when click on tiles on MOBILE

Hello,
I like very much this hex grid, but i found an issue i can reproduce but can't understand why this happen,

on browser on PC when you click a tiles, the tiles toggle, but on mobile browser ( or developper console in responsive mode ) when you click on a tiles its the previous one which is select !!

so first click => tiles = null;
second tiles => tiles = previous tiles

every times !

this is for any examples in the source code ! BUT in the git hub try out demo this not happen at all !

thx if soemone has a solution, i search by my side and post here if i have a solution :)

Setting camera / focus in the middle of hexgrid

Hi there

Thank you for hex-grid, it's awesome. ๐Ÿ‘

I created a square hex-grid and want the camera to look and "attach" to the middle.
Currently my 0,0,0 coordinate is on the bottom left, and I would like that it stays that, because I am generating the map with a script + additional data.

The selected tile is the 0,0,0 coordinate, the red mark is where i want the middle to be and should be the middle.

image

Thanks for pointing me in a direction, that I can help myself :)

Port to modules

Hey there, awesome library @vonWolfehaus! Thank you for implementing the hex logic and Three.JS is a great choice.

In case anyone coming across this repo wants to use it as a standard module like I am trying to, I ported it over to modules and away from a global variable to make it dead-simple to use in projects with module loading already setup (I'm using it in a create-react-app app, so it needed to be in modules): https://github.com/breeze4/von-grid

The diff: master...breeze4:master

Basically I ran a code formatter over it, turned all the vg.WhateverObject into importing WhateverObject, moved the constants into a separate file and export the things an end-user would need.

I haven't fully used the entire thing, so there might be some problems, but so far it works really well. I'll probably find problems with it as I keep using it and will try to fix issues as I find them.

Hopefully someone else finds this useful.

Environment ?

Dude what's your setup and environment like ?

Tried to get this running but had tons of gulp errors, which I think I've resolved, but now am getting errors when trying to run your app.js.

\bin\runnerw.exe" "\nodejs\node.exe" app.js
\vongrid\editor\app.js:5
window.define=i,window.define.amd=!1,window.require=e}()
^

ReferenceError: window is not defined
    at \vongrid\editor\app.js:5:1
    at Object.<anonymous> (\vongrid\editor\app.js:5:55)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

Process finished with exit code 1

Looks like some interesting code and am eager to try it out...

Thanks in advance for your time, effort and talent with regards to any help offered.

loadJSON malfunction

loadJSON loads the file asynchronously, so when the latter code runs the generateTilemap function, it will find empty cells (as the .json file might not be loaded by this time). See the below code:

var grid = new vg.HexGrid({
    rings: 0,
    cellSize: 10,
    url: 'js/maps/middle1.json'
});

var board = new vg.Board(grid);
board.generateTilemap(); //<<nothing guarantees that the json file has been loading, filling up the HexGrid.cells array.

individual vertex height

Is it possible now to change the height of a cell at individual vertices? sort of like the bottom one here:
untitled (1)
I'm trying to make a smooth incline

square-ish board

Could you add a sibling function to HexGrid.grid.generate() that helps one generate square-ish boards. Currently grid.generate() builds a hex-shaped board, but it would be awesome to be able to request .generate() to prepare a square and rectangular boards W hexes wide and H hexes high.

I tried to figure this out in hex cube coordiantes to do this myself and submit a PR, but I'm too unsmart in hex grid coords.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.