Finding the number of hex tiles inside of a hex shaped grid…
EDIT: There is a mathematical formula that is much better than the method I illustrate below. It is: 3n^2 - 3n + 1
A huge thanks to Sam Hughes for very patiently helping me out with this formula. He's the best mathematician I know...
Here's the JavaScript code to execute this formula (just change maxTiles to be however wide your hex grid is):
var maxTiles = 7; var n = Math.ceil((maxTiles - 2) / 2); var numberTiles = 3 * Math.pow(n, 2) - 3 * n + 1;
Below is the original post:
This is kind of like finding the area of a hex grid, except that for some reason none of the formulas I found for doing that would work. Also, finding the area of a triangle made of hex grids won't work with the normal triangle area formula either.
What I am illustrating here is how to find out how many hex tiles are inside of a hex shaped grid of hex tiles.
Here is a picture of the grid:

What you have to do is:
1. Take the half the width of the hex grid rounded down. So, if the hex grid is 7 wide, you take half of seven, 3.5, and round it down to 3. This can also be called "flooring" the number.
2. Take that number and use it to seed a floor loop, which counts down from that number, adding the new number to a grand total each time.
3. Multiply that grand total by 7 and add one for the middle tile (which never got counted).
Here is the code:
var triangleTotal = 0;
for(var spaces = Math.ceil((maxTiles-1)/2); spaces > 0; spaces--){
triangleTotal += spaces;
}
var triangles = triangleTotal * 6;
var numberTiles = triangles + 1;
return numberTiles;
You'll notice that I took the total minus 1 divided by 2 and "ceil"ed it, instead of taking the total divided by two and "floor"ing it. It doesn't matter which you do...
Here's a visualization proving this out:
I only took one math class in college, otherwise this would have probably been very obvious to me as it may seem to you. There is probably even a really fancy easy little formula for this, but I don't know it and couldn't find it...
Here's a page where you can test this formula out in action. Note that a hex is always going to be an odd number of hexes wide, so if you enter an even number and get a funny shaped hex, this formula isn't going to work...
JavaScript Haxagon Game Board with Hexagon tiles
I'm working on a JavaScript version of The Settlers of Catan. The first problem I decided to tackle was constructing (visually and array-structure wise) the game board using nothing but loops (didn't want to hard code it).
This ended up being much more difficult than I thought it would be.
I am going to split this up into two parts:
1. Setting up the game board visually
2. Setting up the array structure
Creating a Hexagonal game board with hexagonal spaces in JavaScript with for loops:
For this to work properly, you must have an even number of columns and rows. I chose seven since that is what makes up the Settlers of Catan game-board.
You have to split the building of the board into three stages:
1. The expanding stage
2. The apex or middle of the board
3. The contracting stage
I placed everything in one large for loop that counted off the "rows".
I figured out that while the rows are less than half the max rows divided by two (and rounded down) the board would be contracting. The number of tiles you would start with would be equal to the maximum number of tiles divided by two, rounded up, plus the current row number.
Once the number of rows equals exactly half the number of maximum tiles (rounded down) you are on the middle row. In this case the number of tiles is the max number of tiles, no math required.
Otherwise, you are in the contracting stage and the number of tiles you need is equal to the maximum number of tiles, minus the current row, minus half of the maximum rounded down.
Sound complicated? That's because it is. This took me about 30 minutes to get straight in my head after studying the game-board shape, tiles, and making several diagrams and sudo-coding and then writing the actual code and fixing bugs (and deciding if I had to round up or down at certain places).
Here is the actual code:
<html>
<head>
<style>
img{
margin-top: -18px;
}
#board{
padding: 50px 25px;
background-color: #000;
}
</style>
</head>
<body>
<div id="board">error loading</div>
</body>
<script>
function boardSetup(){
var max = 7;
var html = "";
for(var row = 0; row < max; row++){
if(row < Math.floor(max/2)){
//place spacer tiles
for(var space = 0; space < (Math.floor(max/2) - row); space++){
html += '<img src="spacerTile.png" />';
}
//place game tiles
for(var cols = 0; cols < (Math.ceil(max/2) + row); cols++){
html += '<img src="tile.png" />';
}
html += "<br />";
}else if(row == Math.floor(max/2)){
for(var cols = 0; cols < max; cols++){
html += '<img src="tile.png" />';
}
html += "<br />";
}else{
for(var space = 0; space < (row - Math.floor(max/2)); space++){
html += '<img src="spacerTile.png" />';
}
for(var cols = 0; cols < (max - (row - Math.floor(max/2))); cols++){
html += '<img src="tile.png" />';
}
html += "<br />";
}
}
document.getElementById("board").innerHTML = html;
}
boardSetup();
</script>
</html>
Here are the images that go with it:
Here is the tile:
Here is the spacer. This one is completely invisible: start->
<-end
Making the Ball Rotate
You asked for it, you got it. The ball now rotates.
I realized that I already am capturing how fast the ball is going along the "x" axis (left and right), and that I could rotate it simply by telling it to rotate the amount that it was moving on the x axis each time the frame updated.
All it took was this simple line of code:
_rotation += dx;
At first I did this:
_rotation += dx + dy;
So that when it would also take into account how much it was moving along the y axis (up and down). This worked really well and looked really cool because then when you pressed the "up" arrow to make it go up, it looked like it was "digging" through the air. But then I realized this was only conveniently working because I had it sloping down to the right. If it were sloping down to the left, the ball would not rotate because the dx would be negative and the dy would be positive and they would cancel eachother out. Also while it is sloping down to the right like it is now, they are both positive and actually make it look like it is rolling faster than it should be.
By the way, in case you haven't noticed, if you click on the flash movie, and then press the up, left, and right arrows, you can make the ball move.
One more thing. It is sort of jitteringly hovering above the ground right now. That's not good. It's not supposed to do that. I need to fix that...
The Ball Will Bounce…
Turns out, the whole problem was that I forgot to actually "rotate" the line. Apparently there is a slope, and then there is a slope. If you draw the line as a sloped line, flash doesn't consider it sloped. If you draw it flat, THEN rotate it to the slope you desire, flash considers it sloped. You then take that line and bounce a ball off of it. The example now WORKS! Also, note that rolling and bouncing are exactly the same, and this example rolls. Rolling is just bouncing so small that you can't see the bounce happen... kind of...
The Parts of a Triangle
Anyone remember Trigonometry? No? Me neither... Oh, wait, that's right, I never really took it. Well, I took Algebra and Geometry, but never a class specifically called Trigonometry. Is there such a thing? I'm sure there is. Anyways, I'm re-learning the parts of a triangle and how to find them.
Here is what I have figured out so far:

Why am I doing this? Well, I have to if I am ever going to get this game working.
Here is what I found out (after buying a $40 book to learn this. Excellent book by the way...):
In order to bounce a circle or bounce a ball off of a slope you have to bounce it off of not a slope. Yeah, let me say that again, you just basically don't bounce it off of a slope. What? Well, there is no such thing as a slope. There is flat, and then there is flat. To you it looks like a slope, but really it isn't. It's just a flat surface.
I know, I know, I'm not making sense here. Let me clarify. The only reason it looks like a slope to you, is that you are not on a level plane with it. A line is a line is a line. Tilt your head far enough and this: | will be flat and level. I'll venture to guess you only had to go about 90 degrees either way and that line became flat.
It's the same thing with flash:
- Take your angle
- Make the computer tilt it's head until you no longer have a sloped line (but rather a horizontal line)
- Do your calculation (make it bounce off of that line)
- Tell the computer to tilt it's head back

So, now I take the method I described a few days ago for finding the "slope" of the surface the ball is interacting with, and use the triangle that is formed by that interaction to apply this bounce method and I've got the main motion mechanics of my game working.
Should be easy. Hah! We'll see...
Lookup Tables for Math Equations
Well, I've begun creating little tutorials for myself.
The problem is that it sometimes can be months between flash game projects, and I often forget some of the things I learned last time around (although they are much easier to re-learn, but I usually just re-member).
So I started taking notes, but then I started just making little flash examples for myself, and then thought about it some, and just went ahead and started making a little tutorial.
I've never actually seen this technique used or suggested anywhere online (although I'm sure it's not original to me). So, I am posting it here (soon to be followed by many others).
What this does is allows you to take a complex equation, which will bring your flash game to it's knees, and predict different inputs and pre-calculate outputs. Then during the game if you didn't happen to predict an input, it will go ahead and calculate for that input, but then from that point forward consider that calculation as a "pre-calculated" calculation.
I've not actually used this technique in any game yet, and I know there will have to be some adjustments to it (you will probably have to round to whole numbers, because I don't think it will work with decimal inputs, or you will have to multiply everything by 100 to allow for decimals to the second place). So basically, if anyone uses this technique, let me know how it turns out please!
Tutorial Page
Source Code
Newton’s Laws
So... It turns out that what I am trying to do is one of the hardest things you can possibly try and do in two dimensional game programming. Great. While starting a new job and writing my first book.
I remembered that I had picked up "Beginning Math and Physics for Game Programmers" a while back when I was working on my tower defense game. I cracked it open expecting some sort of simple equational explanation that could be quickly and easily applied to my game and solve my problems.
Nope. It's not until chapter 11 that they start really talking about it. That's cumulitive of chapters 4, 8 and 9... and that doesn't even start addressing the collision part of it. That's just "If you have a ball with a known wieght on a known slope moving from a known point to a known point, THEN this..." So either it's a crap book, or it's just freakin hard.
What I did realize however is that if I figure this out I will know how they did Linerider (kind of)...
I’m a newb
Just browsing through some samples/tutorials here has made me realize just what a newb I am when it comes to all this flash game stuff. I think sometimes I struggle with stuff for days that would take someone else but a few hours. This can get very frustrating for me. I still have a lot to learn.
On the plus side, I really love coding, so it makes it all worth it. Even if it does make me feel like a complete idiot sometimes...
Oh, and I was recommended this book: "Foundation Actionscript Animation: Making Things Move" by Keith Peters by a flash game programmer whose game I liked enough to write him asking what the algorithm he used to handle his ball physics was. He didn't tell me the algorithm, but said he basically got it from that book.
Physics
It's all about how you search for what you search for (which you all already knew).
In my search for an algorithm for my marble game, I've been typing in asinine things like "rolling ball" or "game programming ball rolling" or "game programming 2d scrolling". Garbage like that.
Well, this morning I stumbled upon a repository of flash games, which led me to a little game called "ramps". After e-mailing the author to find out what his algorithm was, I noticed he used the word "Physics". Duh!
A single google search on the words "Game Physics" yielded a plethora of results. Hooray for me! Soon I will have my rolling routine in hand and ready to go!
This was immediately following a brain wave I had in the shower about an algorithm to find the angle of the slope that the ball might be resting on. It would probably have proven to be very taxing and slow, which would have made the game unplayable. We'll see how it compares to what other people have done though. I may just have figured it out myself, right before I found it online.
The method I thought up was this:
1. Take your circle (or ball) and add/subtract the radius (half the width) of it to the center x and center y coordinates in order to find the bottom left and bottom right corners.

2. Use a for loop (up to the height of the ball) to determine how close A is to the ground
3. Use a for loop (up to the height of the ball) to determine how close B is to the ground
4. Use the difference to determine the slope of the ground underneath A and B and how it should effect the direction of the ball.

I'm not exactly sure how I would use this information that I glean yet to move the ball. I do know that this would probably be hell on the processor, and that this is probably the wrong method. It's just the one I happened to come up with this morning, and I thought I'd share it.
I'll let you know as soon as I settle on a better one...
The one I have been using sucks. Basically what it does is use if/else statements to check and see if one side of the ball is hitting the ground and the other isn't. If one side is, it tells it to start moving towards that direction. This method does not take slope into account AT ALL (which is why it sucks).
Also, right now my collision detection happens after the ball has already moved. It needs to happen BEFORE. That way you will never have the ball inside of the wall, because the method will predict where the ball is going instead of tell me where it is (so you can act instead of react).





