Realism with Randomness and Math

One thing I like about game development is the occasional challenge that comes along that requires you to clean out the cob webs in the ol’ noggin and reach back for a few knowledge nuggets that you somehow managed to hold on to from your high school trigonometry class. Take for instance this little problem in recreating Mancala. While it would be simple to neatly order the stones in each of the bowls it would hardly lend itself to any bit of realism. What we need is randomness to create the effect they were tossed in the bowl. So, how can we do that? Observe.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Random radius.
var new_r:int = (_bowlShp.width/2) - s.width;
new_r = Math.random() * new_r;

// Random angle.
var new_ang:int = Math.random() * (Math.PI * 2);

// Find the new x and y positions.
var new_x:int = Math.cos(new_ang) * new_r;
var new_y:int = Math.sin(new_ang) * new_r;

// Move the stone.
s.x = new_x;
s.y = new_y;

// Random rotation.
s.rotation = Math.random()*360;

Lines 2 and 3 take the radius of the bowl and subtracts the width of the stone. It then finds a random number between 0 and this shortened radius. Line 6 chooses a random angle. Lines 9 and 10 is where the fun comes in. Using our random values and a bit of right triangle trig, new x and y coordinates are chosen for the stone. We finish it off by moving the stone to the new location and giving it a little spin.

Essentially you can think of this whole process as first placing the stone in the center of the bowl, move it out a random distance from the center without falling outside of the bowl, and swing it around from the center at a random angle.

Mancala game stones in bowls

Category: Labs
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
3 Responses
  1. Marc says:

    Well, now I know how you put Therese and Fulton to sleep at night.

  2. Sharon says:

    I love math. Fabulous dear!

  3. Aunt Mary says:

    Don’t worry, Sharon. Marc’s just jealous because he only knows babesonometry (Marc + Misty= Babes loves babes). As for me…I haven’t the faintest clue about math. :)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>