• Create Account

Awesome job so far everyone! Please give us your feedback on how our article efforts are going. We still need more finished articles for our May contest theme: Remake the Classics

# HappyCoder

Member Since 28 Apr 2007
Online Last Active Today, 10:38 AM

### #5019480drawing triangular pyramid using dx9

Posted by on 09 January 2013 - 09:34 AM

Well if you an array of vertices each vertex can be found at a specific index
```{
{-1, -1, 0} // index 0
{-1, 1, 0} // index 1
{1, 1, 0} // index 2
{1, -1, 0} // index 3
}
```

When drawing triangles, vertices need to come in triples. The vertices I have listed above form a square. We need to break it up into triangles but a square has four points. There are two options at this point. One options is to repeat two of the vertices so I have 6.
```{
// first triangle
{-1, -1, 0}
{-1, 1, 0}
{1, 1, 0}
// second triangle
{-1, -1, 0} <-- repeats
{1, 1, 0} <--
{1, -1, 0}
}
```

Repeating vertices just ends up using more memory than needed. By using an index buffer we can reduce the number of repeats.
```{
{-1, -1, 0}
{-1, 1, 0}
{1, 1, 0}
{1, -1, 0}
}

// index buffer
{
0, 1 ,2, <-- first triangle
0, 2, 3 <-- second triangle
}
```

### #5018674Difficulty in Creating own Game Editor

Posted by on 07 January 2013 - 12:38 PM

When making your game editor try to reuse as much code that makes sense. The core of your game should be the core of your editor, do the design well enough and your editor could allow you to play sections of your level right in the editor. With a lot of code overlap you will have a lot less code you need to write. Now to address some of your questions.

• Having a easy to use interface is important. Try to keep things simple and flexible. If any part of your editor is difficult to use think of ways to improve its use
• Probably will be bigger but the media content to your game will far outweigh the size increase an editor will add

• I am not sure if I understand the question but your editor wont have to use the compiler. If you want to be able control game logic with your editor then I would use a scripting language, my personal preference is lua
• Are you talking about being able to add game logic and game flow, such as menus, using the editor? A good way to control transitioning from one piece of the game to the next is to break up the game into scenes. Each scene is edited&nbsp;separately&nbsp;and you can add transition points, for example. If the player passes through section X of your map, transition to scene Y. I also would not&nbsp;recommend&nbsp;trying to allow every aspect of your game, such as menus or in game huds, to be edited with the editor. A game editor should speed up the production of a game, not complicate it.
• There is no way to lock your resources entirely. The best you can do is make it hard enough that it wont be worth it to the average person. You could also package your resources in some custom file format, unencrypted. It could be as simple as a short header with some file information followed by the data from the image file. Somebody could still figure out your format, but most people wont.
• Don't try to do too much right away. You may have to sacrifice features you want to allow you to complete the project. Start simple, get things working, then expand your game with features later. You shouldn't, for example, be adding particle effects, cool animations, and cutscenes until you have your map, basic character movement, and object interaction done.

And a simple suggestion when you start adding different tools to your editor is to create a&nbsp;separate&nbsp;class for each tool. You should have a tool base class that all of the other tools extend. A simple example could look something like this.

```abstract class Tool
{
public MouseDown(Point position, ButtonState buttonState);
public MouseMove(Point position, ButtonState buttonState);
public KeyDown(KeyCode keyCode);
/// any other methods a tool should need
}

class TileTool extends Tool
{
/// here you have the code for drawing tiles and such
}

class GameObjectTool
{
/// here you have the code for adding, removing, and modifying objects in a scene
}
```

This makes it easy to change tools and will allow to add additional tools to your editor as needed

### #5018347Does using libraries impair compiler optimization?

Posted by on 06 January 2013 - 05:09 PM

I wouldn't worry about micro-optimizing by avoiding the use of external libraries. Even if it was slightly slower, you shouldn't worry about that when designing your program. When dealing with performance you want to choose efficient algorithms from the beginning, but don't worry too much about having the fastest algorithm possible. Just pick one that will have reasonable running time and, possibly more importantly, is simple to implement. If your code is designed well you should be able to easily change the algorithm later you find you need a faster one. When choosing what algorithm is faster, the most important factor is how well is scales meaning how will it handle 1, 10, 100, 1000, ect... number of items to proccess. This is known as an algorithm's complexity class.

Once you have your code working and if you find it isn't running as fast as you need it to. Then you profile the code. Find out where your program spends most of its time and decide how to speed that up. This may involve changing the algorithm you used. Change the way memory is used an the amount used to reduce cache misses. If you find there is a lot of time spent in a single piece of code, you may find ways to call that code less to reduce the amount of work done. Micro optimizing pieces of code to try to get the most per clock cycle or reduce the number of clock cycles will only make a noticeable difference if that code being optimized is being executed very frequently in the code.

So my advice to you. Don't worry about the speed impact of using a dynamic library. Write your code in a way that makes sense and is clean and easy to manage. Once you are done, then you optimize if needed. If you are worried about optimizing things too early you may find your project harder to manage and things may end up being more obscure. This means it takes longer for your project to be done and there will likely be more bugs and in the end the optimizations may have not made any significant difference to how fast the code runs anyway. To sum things up your time is more precious than CPU time.

### #5017663Javascript / HTML5 best practices

Posted by on 05 January 2013 - 12:14 AM

In my experience with javascript performance wasn't an issue. I made a simple 2D tile based puzzle game. (link) When I implemented the collision detection for it I initially did an O(n^2) algorithm for checking collisions against all of the objects in the scene and would come up with a faster method if needed. I ended up not needing it. The bottleneck in the game for me was drawing the graphics. I even tried to optimize it by having all of the tiles draw once onto an off-screen context and simply copy over that large image once every frame to reduce the amount of drawing calls but it didn't really change the speed much. It seemed that copying over pixels is what took the most time, but in the end The game still ran fine. I also used a port of box2d for an editor in a physics based game I worked on and it worked surprisingly well. (link) Basically what I am trying to say is don't worry about your game running too slow. Just program your game in a way that makes sense and focus on making your code beautiful. That brings me to the next thing I want to take about. Classes.

Javascript does not have classes built into the language, but you have prototypes and that lets you create classes yourself. Read up on javascript prototypes. Make sure you understand what they do and how they work. I will write out the basics here.

To create a 'class' you actually define a function.
```function Foo(bar)
{
this.bar = bar;
}
```

Then to create an instance of a class you use the 'new' operator on the function

```var foo = new Foo("string");
```

to add methods to the class you add functions to the prototype of a function

```Foo.prototype.getBar() = function() {
return this.bar;
}
```

Then you can call them on any instance of the class

```alert(foo.getBar());
```

One thing that is great about javascript is it has closures. When I started using javascript I didn't use them much, the more familiar I get with javascript the more I love to use closures. Basically what you need to know is this. Functions can be used as objects in javascript and with closures, any local variables in the same scope where the function was declared can be used in the function. For example

```var foo = "string";
var bar = function()
{
// foo can be used in this function,
// even if var is stored and called
// later after foo is out of scope
console.log(foo);
}

bar();
```

Any changes to variables in a closure are not reflected outside the closure (except for global variables) For example

```{
var foo = "original string";
var bar = function() {
// this only changes foo in this closure
foo = "new value";
}
bar();
// this will display "original string"
console.log(foo);
}
```

My advice to you is to get familiar with closures. They are great and, if used well, can make your code beautiful. One thing to remember is that the local variable 'this' does not go into closures. If you need to pass 'this' in you need to create a temporary local variable. For example.

```{
this.message = "this is foo";

bar = {};
bar.message = "this is bar";

var foo = this;
bar.functionCall = function() {
console.log(this.message); // this will print "this is bar"
console.log(foo.message); // this will print "this is foo"
}

bar.functionCall();
}
```

What is happening here is 'this' is the object that the function is stored in when it is called.

Anyway, Those are a few things I think are good to know when starting javascript. I hope it is useful to you.

### #5017203Good habits for game development

Posted by on 03 January 2013 - 12:29 PM

One thing that helps me get things done is having a deadline. Preferably a deadline that you cannot push back like for a contest. When you have a deadline it helps you keeps your project simple and cut out unnecessary features so the focus becomes finishing the game rather than trying to see how many awesome features can make it into the game. Even if you cannot find a contest or other hard deadline still try to set out a realistic timeline for yourself and follow it. If you find your initial estimates weren't accurate adjust them. But break up your project into smaller pieces and tackle one piece at a time.

### #5015111Mictlan

Posted by on 28 December 2012 - 11:30 AM

I love the topic of this game. I lived in Mexico for two years so I enjoy seeing elements of their culture show up.

### #5014256Questions about encapsulation, resource management, global variables* and the...

Posted by on 25 December 2012 - 04:06 PM

Why do the textures need to be in a manager?

Because most tile-based games use a small subset of textures, but those textures are drawn hundreds of times per level. If I load the same texture for each tile that needs it, the memory demands of this engine will be astronomical. By putting the resources in a manager, only one instance of a texture is loaded and it can then be accessed by any tile and/or sprite that needs it.

Each tile could simply have a pointer to the texture you want it to use. A pointer only takes up the size of an int.

### #4993547Detecting a radius based on coordinates?

Posted by on 24 October 2012 - 02:52 PM

So you are saying you need the smallest sphere that fully encloses an object from a given point inside the model?

All you need to do for that is loop through all of the points and find the point that has the furthest distance from the center. That distance is the radius of the sphere.

### #4989876For Beginners: The Importance Of Object Oriented Design

Posted by on 13 October 2012 - 02:01 PM

Enumerated Types
I am not sure what this is called, but I would like to add the concept of not using strings as enumerated types. For example

```void foo(string gender)
{
if (gender == "male")
{
// do stuff
}
else if (gender == "female")
{
// do other stuff
}
}
```

This is bad for a couple of reasons. First of all it allows gender to be any arbitrary string. Meaning "Male", "MALE", "m", and "darth vadar" are all valid string values, but may not be valid gender values. So as a programmer trying to figure out what valid values I can pass as a gender I may have to dig around in the source code how it is used. Also, passing around and comparing string values is slower than enumerated types.

This is how it should be done
```typedef enum _Gender
{
Unspecified,
Female,
Male
} Gender;

void foo(Gender gender)
{
if (gender == Male)
{
// Do Stuff
}
else if (gender == Female)
{
// Do Other Stuff
}
}
```

Now a programmer can know what valid values are just by looking at the enumerated type. The compiler can catch a typo if I accidentally typed one the enumerated types wrong and passing and comparing enumerated types is super fast as it is merely and integer.

Assertions

Assertions are great for catching bugs right when arise rather than when their effects have been propagated through your code. Whenever you write a function and you are making assumptions on the data you are going to operate on. Put this assumptions on as assertions. For example.

```public void foo(int index)
{
assert index >= 0;
// do stuff
}

public bool binarySearch(Array data, int value)
{
assert isSorted(data);
// do search
}
```

These assertions will take more processing time in a debug environment but once you release the final product they will be gone. Using assertions is very useful for tracking down bugs early rather than later. It is almost counter intuitive but making your program crash when something is wrong rather than silently ignoring it will result is code has less bugs as it will help you track down problems sooner. If you aren't familiar with assertions I would definitely look into it.

### #4988897Bullet misses the enemy

Posted by on 10 October 2012 - 05:04 PM

Try having the bullet go to where the enemy will be. This will mean you have to take into account the velocity of the bullet and the velocity of the player.

I also noticed you calculate the bullets new direction based on the difference between the enemies position and the towers position (enemy.pos - tower.pos). What if you did the difference between the bullets position and the enemies position. (bullet.pos - enemy.pos)

### #4983262Making Android Apps

Posted by on 24 September 2012 - 10:27 AM

2. What makes a game successful?
3. How much money do developers make from their apps?
4. Is it better to make a game free and put ads in it or is "freemium" better (or just straight upfront payment)?
5. What are good ways to advertise apps and gain recognition?

3. Unless your game goes to the top of the charts there isn't much money to be made in mobile game development.

4. Freemium done well is a good route to go. Free games are downloaded far more frequently than paid games so this gives your users a taste of your game, then with easily accessible in app purchases, it makes it more likely for users to spend money on your game.

5. The fastest way games spread is if people who get the game tell their friends about it meaning you can dump as much money you want into marking but unless people are excited enough about your game to tell their friends, it will be hard for the game to pick up momentum.

### #4962364Efficient ray-model intersect testing

Posted by on 23 July 2012 - 02:55 PM

spacial database or spacial index may be useful

You can add an index to the mesh for faster checks against the mesh and you can also add an index for objects in your scene. Implementing something such as this can be tricky. So my advice, be sure you need to add this. You may find, and I would expect, that your game runs fine without it. If you had hundreds or even thousands of objects, if you had very complicated meshes, or if you are doing hundreds of ray intersection tests per from then it may be necessary but if you are only doing a handful of tests on a handful of objects I wouldn't worry about that right way.

EDIT: If you do choose this route, I would recommend looking into Octrees. They are easy to understand and efficient.

A simpler thing you could do would be to transform the ray from world space to the objects local space for collision detection instead of the other way around by transforming the objects bounding box or, even worse, the mesh data.

### #4962355Collision Detection between non-axis aligned rectangular prisms

Posted by on 23 July 2012 - 02:28 PM

Collision detection can be generalized for any convex shape (convex meaning it has not indents.)
If there exist at least a single flat plane that can go between both objects without touching either of them then the objects don't collide. Or put in simpler terms two objects aren't touching if I can pass a flat piece of paper between them. This is known as the Hyperplane Separation Theorem (AKA Separating Axis Theorem)

The trick now is finding position and orientation of this plane. When dealing with objects that have only flat surfaces, like boxes, you can guarantee that if the objects don't touch, there will be a plane that separates them that is parallel to one of the flat surfaces of the two objects. Or in other words, the flat piece of paper that fits between the two non-touching objects can pass between the two objects and lie flat on one of the surfaces of one of the two objects.

What this means for our boxes is that we only have to check for 12 different planes to see if the two boxes collide because each cube has 6 faces and there are two cubes, but because a cube consists of 3 sets of parallel faces we can reduce the number of planes to test by half. This is because the plane separation theorem depends on the normal of the plane being tested. The same normal can be used to test two faces at the same time. So the algorithm works something like this.

some 'pseudo' pseudo code
```// I am assuming normal is a unit vector
// although the overlap algorithm will still
// work even if normal is not a unit vector
double scalarProjection(point, normal)
{
// http://en.wikipedia.org/wiki/Vector_projection
return point.dot(normal) / normal.dot(normal);
}
Range projectBox(box, normal)
{
Range result;

// iterate over each corner in the box
foreach (vertex in box.vertices)
{
double scalar = scalarProjection(vertex, normal);

if first vertex
{
result.max = scalar;
result.min = scalar;
}
else if (scalar > result.max)
result.max = scalar;
else if (scalar < result.min)
result.min = scalar;
}
}
bool doesCollide(boxa, boxb)
{
// create an array of vectors the represent the combined axis of the two boxes
Array<Vector> boxaxislist;

boxaxislist.append(boxa.axisList);
boxaxislist.append(boxb.axisList);

foreach (axis in boxaxislist)
{
Range boxaRange = projectBox(boxa, axis);
Range boxbRange = projectBox(boxb, axis);

if (!boxaRange.intersects(boxbRange))
{
// there was no overlap, we found a plane that separates the two boxes.
return false;
}
}

// no plane was found, the boxes must be overlapping
return true;
}
```

The axis list is simply an array of size 3 with the vectors in it.
Each vector is perpendicular to two of the faces of the box. You can think of this as
the x,y,z direction of the box. To know how to calculate the axis first think of a single
corner on a box. That corner will have the lines connecting it to three adjacent points.
Those three lines can be used as the three axis and can be calculated by simply subtracting
one endpoint from the other. You don't have to normalize the axis for this algorithm but keep
in mind if you later wish to use the axis in another algorithm it may require them to be normalized.
Just be aware of that

Here is a paper that describes what I just did but has some pictures.
Separating Axis Theorem for Oriented Bounding Boxes
If you need help understanding, google around some more about the seperating axis theorem and how to use it on boxes. If you still need help just ask what needs clearing up and if you do have anther question could post the way you are representing a box in 3 space?

### #4957830Am I "using" people?

Posted by on 10 July 2012 - 05:30 PM

I made a game once that allowed users to build levels and the result was very few people actually built levels and quality was generally low.

Users don't know what direction you want to take the flow of the levels as you progress though the game. They aren't going to work together to have a gradual difficulty curve. They aren't going to be worried about what order and how often you introduce new concepts into your game. In other words a collective group of people aren't going to be interested in ensuring your game has good design.

That being said I don't think you should rely on user made levels to make up the bulk of your levels. As tedious as it may be if you want a high quality game you will need to take the wheel in level design and do them all yourself or coordinate a group of people to build them.

To answer your original question I don't see anything wrong with using their levels in your game. I think most people would be happy to see their level released with the game. I am not a lawyer but you should be fine if you just state that the levels they make may become part of the game and you take ownership of the level when they submit them. You also might want to consider giving credit to the person who made the level.

### #4945202Most Optimized way to draw a circle DirectX

Posted by on 31 May 2012 - 10:59 PM

One thing you can do to greatly optimize this little piece of code is to create the vertices for a circle beforehand.

make the circle have a radius of 1 with the center at (0,0), then use matrix transformations to move and scale the circle.

```#define CircleResolution     100

static Vector2 gCircleData[CircleResolution];

void InitCircle()
{
for (int i = 0; i < CircleResolution; ++i)
{
gCircleData[i].x = cos(2 * PI * i / CircleResolution);
gCircleData[i].y = sin(2 * PI * i / CircleResolution);
}
}

// then to draw your cirlce
void DrawCircle( const Vector2 &Center,float Radius,Color color)
{
// save word matrix transformation
// set worldtransform = TranslateMatrix(Center) * ScaleMatrix(Radius) * currentWordTransform

d3dLine->Begin();

d3dLine->Draw(gCircleData, CircleResolution,color);

d3dLine->End();

// restore previous world transform

}
```

By doing it this way you avoid calculating sin/cos all the time which can be expensive. If you want to use lower resolution circles for smaller circles I would have a few premade circles at different resolutions and you choose from those few. Anyway, those are my two cents.

By doing it this way you

PARTNERS