# Question
Title: How can I make water appear darker with depth, like in Minecraft?
In Minecraft when you look at water the deeper you view the darker it gets. Does anyone know how to code something like that?

Minecraft with effect

similar game without effect

# Answer
There are essentially two different approaches for lighting water based on depth:

# Voxel-Lighting

Minecraft uses voxel-based lighting, wich works by propagating light to adjacent cubes, lowering the brightness depending on the block type. Dark oceans are a side effect of this system.

Water blocks sunlight and reduces the light by 3 levels per block (instead of the default 1 level), wich means the brightness in an ocean for each distance from the surface is:

```
0 (surface): 15 (direct sunlight)
1:           12
2:            9
3:            6
4:            3
5 and below:  0 (darkness)

```

Source: Minecraft Wiki - Light

# Distance-Based Shadowing

In games with a traditional lighting model, this effect can be created by measuring the amount of water that is between the light source and the ocean floor. The light is then faded based on this distance. There are a few methods for doing this:

## Direct Calculation

If you have a flat surface, you can easily calculate the distance the light travels in the water if you pass the surface normal away from body of water and the dot product of this normal and a surface position into the geometry shader.

The effective water distance is

where is the position of the vertex and is the angle between the light direction beneath the surface and the water's surface normal towards the body of water.

At sunset, only reaches a bit less than 50° because the light is refracted when entering the water.
Here's a blog post with a good explanation: The Digital Camera: Total Internal Reflection
Another post with more details: The Digital Camera: Snell’s Law of Refraction

If you're using a heightmap on a surface parallel to the water, becomes . The right factor equals 1 if the sun is directly above the water surface.
With a point light, you have to calculate for each vertex based on the relative position to the light source.

With a fixed water level or a fixed light direction, parts of the equation are constant and shouldn't be calculated in the shader for performance reasons.

### Pros:

* Fast and accurate

### Cons:

* Only works for flat water surfaces or only for light from directly above, as only one surface is normally taken into account. (The combination of a rough surface and tilted light could work to some extend with parallax mapping.)
* No caustics

## Shadow Mapping

If you render the water surface to a separate depth map (as seen from the light source), you can use that depth texture to calculate the distance the light travels in the water before hitting the surface.
To do this, you project each vertex into the light source's view projection in the vertex shader and do the texture lookup in the pixel shader.

If the surface is relatively flat, you should use a refracted light origin for better results.

### Pros:

* Works with relatively complex water geometry, as long as it doesn't occlude itself.\*
* Can be reused for almost any kind of partially transparent volume.

### Cons:

* Slower than the direct calculation.
* Needs additional VRAM for the depth map.
* Not 100% accurate.

\*You can determine the amount of water in front of the nearest solid surface by counting the depth from the light's POV as follows:

1. Render the solid geometry in your scene as normal. For each fragment, you add the depth value to the result texture.
2. Render the water's front-faces without updating the depth buffer and subtract the fragments' depths from the result.
3. Render the back-faces in the same way, but add the fragment depth to the result.

The result texture now contains the amount of water in front of the light in light-view-space, so the value must be transformed back before you use it. This method works to calculate the directional light (minus refraction), but will lead to incorrect ambient light if the surfaces are very irregular and there's a large amount of air between to bodies of water affecting the same fragments.
The pros and cons are the same as for normal shadow mapping, except that you need one more buffer while calculating depth and the performance is worse because you have to draw more geometry.

## Ray-Tracing

Ray tracing is by far the most accurate but also the most expensive solution for rendering transparent volumes. There are two ways of doing this: 1. Tracing from the ocean floor towards the surface and 2. Tracing from the light source towards the water. Multiple rays are needed for each point on the floor to calculate the brightness.

### Pros:

* Works correctly with every geometry.
* Correct caustics!

### Cons:

* Slow!

# Additional effects

There are a few more things to take into account when rendering water:

## Fog

Light in water is scattered again while travelling to the observer, so you should blend it towards a solid color.

**If the observer is submerged**, you can just render fog based on the final result of the depth buffer. The fog color, but not its density should change with the observer's distance from the surface! (Minecraft only uses this part of the effect.)

**If the observer looks at the water from above**, you need to calculate the fog based on the depth difference between the surface and the geometry under water. The fog colour should get slightly darker with larger depth differences, but should only change to the point where the fog is fully opaque.

The fog colour should also depend on the view direction for each pixel, so it's slightly darker when looking down in both cases.

## Faking Caustics

If you use a seamless tiling 3D-Texture instead of a decal for fake caustics, you can avoid stretching on vertical surfaces. The strength of scattered light near the surface varies in three dimensions, so using a 2D-Texture usually produces stretching somewhere in the scene. You can model changing light angles by projecting the vertex positions of the floor into a different coordinate system.

Another possibility is to calculate the light density based on the surface position in the light's coordinate system, although that would most likely cost some performance.

The caustics should fade faster than the diffuse light with increasing depth.

## Colour Gradient

Colours are scattered differently, so the light colour should change with increasing depth. This also prevents abrupt edges where, for example, a beach intersects the water surface.

## Angle of Incidence

Because of refraction, the light hits the ocean floor much steeper than it normally would. The Wikipedia article about Snell's law has formulae for angles and vectors.
> 51 votes

# Answer
I believe that the sky lighting effect in Minecraft is straight down - things get shaded by what is above them no matter where the sun is. Then local lighting from torches, etc. is applied with a dropoff effect - the farther away from the light source, the less light a cube gets.

If done this way, each layer of water would cumulatively shadow the layer below it, so each becomes progressively darker. Tree foliage provides shade like this, however it is not cumulative. You get the same shade under a tree whether it's 1 or 100 foliage cubes.

One clue that this is the method being used is that water doesn't get darker when farther away from the viewer - only as you go down. Yes, the fog effect does kick in at distance, but not the water dark effect.

So the basic formula for calculating lighting would be something like this in pseudo-code...

```
light_on_cube = 1.0
for each cube above target cube, from lowest to highest {
   if cube being examined is tree foliage
      light_on_cube = 0.5
   else if cube being examined is water
      light_on_cube = light_on_cube - 0.1
   else if cube being examined is solid
      light_on_cube = 0
}

```

This isn't perfect for calculating lighting under overhangs or in caves, as it would be pitch dark under an overhang using this method. But one could add in both local light sources (torches, fires, etc.) as well as treating sun lit blocks as light sources. Something like this might do it...

1. Calculate light from sun from directly above (via above pseudo-code) for each cube.
2. If a cube has a light source next to it, consider it fully lit (1.0)
3. If a cube is receiving no sun from directly above, give it some light based on how far away it is from a fully lit cube. Closer means more light, farther away means less (until zero).

The idea here is that if a cube is lit by the sun or a torch, the cube next to it is going to also be lit in some way. And the farther away you are from that lit cube, the less light there will be. It's sort of a kludge way to estimate diffuse lighting but I think (?) it would work.
> 6 votes

# Answer
Perhaps I'm misunderstanding the question, but why can't you just change the colour of the blocks depending on their depth?

If you have the depth *d* (in blocks, starting at 0) then a reasonable equation for brightness would be:

*L* = (1-*m*) *e*<sup>-*kd*</sup>\+ *m*

Code: `L = (1.0 - m) * exp(-k * d) + m;`

*k* controls how fast it gets darker (higher = faster). A reasonable value would be 0.5.
*m* is the minimum brightness you want.
*L* varies from 0 to 1.

If you don't know how to change the colour of the blocks in whatever graphics API you are using then please ask that as a separate question (stating what API you use, and whether or not you are using shaders).
> 3 votes

---
Tags: effects
---


# Question
Title: What are some good game development programs for kids?
I know a very bright little boy who excels in math, but at home he's glued to his Nintendo DS.

When I asked him what he wanted to do when he grew up he said "Make video games!"

I remember a few years ago there was mention of a MIT software called Scratch and I thought maybe this kid can do want he wants to do.

Has anyone used any of the "game development" for kids softwares out there? Can you recommend any?

# Answer
> 9 votes
Not looked at it myself, but I thought I'd mention Kodu. What works for you will depend a lot on age and how keen they are.

Way back when I was a kid we had the Shoot'Em-Up Construction Kit. :)

# Answer
> 9 votes
Yoyo Games' Game Maker is a pretty common tool.

If we're talking bright, BRIGHT kids, who have an attention span and would be committed to learning something, you may also want to try Python. This one is definitely a good games-oriented HTML book for Python.

Chances are, Game Maker will be much better suited: You can get an obvious end product.

I also haven't used it or heard about it, but Ruby for Kids - Make Games in Minutes! looks promising.

(I think I may not be a good example, but I started off with Flash aged 11. :P)

# Answer
> 6 votes
There's also Alice from Carnegie Mellon. It's centered around teaching programming concepts through a visual interface to create 3d animations and games.

# Answer
> 6 votes
I've used Scratch and I'd say it isn't quite so much for teaching game programming as much as teaching kids the concept of programming. It has a drag and drop interface, event-based model, fairly easy to learn (\< 1hr for an experienced programmer). If your kid in question wants to make stuff move on screen and do it in a way that is lower level than "select a character to be your avatar", this might be useful.

I think it works well for experimenting as you can make it do a lot of different things with enough tinkering.

# Answer
> 4 votes
I would definitly recommend YoYo GameMaker mentioned above.

I used it 6 year ago (when I was still in high-school) to teach programming concepts for elementary school kids. This experiment worked great! Kids picked it up really fast and loved it from the day one. Many of them are still involved in scripting and hacking, so I think this time was well spent.

Main advantages is would mention:

* Really easy to get going (we drew simple stick figure in Paint and scanned some pencil background world from paper)
* No scripting abstraction
* Explains really well object oriented thinking and shows that to make things work, you really have to define everything (key events, gravity, collisions, action etc.). There is no magic in games, you can describe the world the way you want and everything is changeable.

# Answer
> 3 votes
RPG Maker was great when I was a kid. But they have come a long way since then. They have a lot of features, and even there own scripting language/environment. It is all pretty easy too, and you can have something working really quickly. Also moves a lot of the tricky stuff in game development out the way, so the kids can be more creative.

You are definitely limited to what you can do by the engine, but it is a great place to start learning the concepts.

# Answer
> 3 votes
Wario Ware D.I.Y. is a game that will let your kid make simple games on his DS. I understand that it is a good gateway to more complex systems like Game Maker.

# Answer
> 2 votes
Klik n' Play. Not for sale anymore, but you can find copies online easily.

# Answer
> 1 votes
I had looked at Scratch. It was a solid product to create animations etc. I am working on something to create and share games (Flash based).

# Answer
> 1 votes
I have used Kodu with nearly 1000 students from age 8 to 17. Great for making simple to more complex games.

Web based game creation tools like Sploder and Atmosphir are also popular with kids.

# Answer
> 0 votes
12000 kids already happily used this: http://www.youtube.com/watch?v=5-X-Ebh1kYA&feature=channel\_video\_title

---
Tags: education
---


# Question
Title: How do I create a blob shadow under a character?
I have a webgl based 2.5D platformer game, and I would like to add a simple blob shadow under the character to help the player with the platforming.

How is this normally done?
As you can see below, I do not need to worry about sloped terrain if that matters.

# Answer
**The Basics**

Create a plane. Give it a shadow decal texture. Attach it to your character per the scene graph. Cast a ray from the underside of your character, check where (if anywhere) it intersects with your platforms, and push your shadow plane down accordingly to that vertical level (usually positive y-axis) where the platform top is. This will work, but if your character is near a plaform edge, his shadow will go off into empty space.

**Beyond the Basics**

So what about when your character is eg. standing on the edge of the platform, or if he is directly over a "step" between two platforms? In that case you need a way to split that shadow plane over one or more platforms. There's a question that needs to be answered first, here: Will your platforms ever be situated differently along the z axis, as well as x and y (as in your screenshot) i.e. will your world be true 3D rather than pseudo-3D? This fundamentally affects the logic you can use for shadow clipping (and everything else, too).

*Geometric clipping*

Create your full plane mesh with blob shadow decal on it. If your shadow is over a breach or edge, you'll need a single mesh for each platform that the shadow will fall onto -- you'll need to do multiple raycasts, one from each corner of your shadow plane, to determine this. For each platform the shadow falls over, clip that platform's shadow plane, or clip the texture on that plane -- whichever is easiest in the 3D API you're working in -- so that it looks the shadow doesn't "lie into empty space" off the edge of that platform. The pro here is its more accurate to do things this way; the cons here are that (a) it could get a little messy if the shadow could be split over platforms in both x and y rather than just x; (b) you won't be able to have a silhouette shadow (but that wasn't one of your requirements, anyway :)

If your game logic is 2D, this can be greatly simplified to line math, i.e. checking range overlaps.

The pro here is that you don't need to fiddle with mesh vertices. The con is that you are creating many individual plane meshes which may impact performance. You can merge them into one mesh though, by creating a single plane mesh matching that cellular outline.

*Grid-based clipping*

Considering the potential splitting scenario, this can make things easier. Pick a resolution for your grid. Cast a ray for each cell in the grid, and create a miniature shadow plane at each location, in this way building up the character's entire shadow. Another benefit to this is that you could (with a bit of further effort to determine your characters silhouette from below) have a pretty accurate silhouette shadow rather than just a blob shadow. But that's up to you. Assuming your character doesn't move along the z axis, only x and y, you won't even need a grid, you'd only need strips of your original blob decal. I'm sure this will make sense if you give it some thought -- subdivision in this case, is only required along the x-axis.

The pros here are this approach lends itself to both splitting your shadow across platforms in numerous dimensions, and that you can have proper silhouette shadows. The con is that you are "rasterising" your shadow, resolution is a trade-off between good looks and performance. But considering you were willing to go for a blob shadow, if I were you I might opt for this approach.

---

Considering everything appears to be arranged orthogonally along your world axes, both these approaches will work well. If you were to implement ramps etc., you should still be able to tilt your shadow planes, but if this is likely to be the case, I would opt for the geometric approach as it will be easier to maintain your sanity under those circumstances. However if using platforms placed arbitrarily in all 3 dimensions, and provided these all lie flat (0 degrees to horizon) I would definitely opt for the grid-based approach.
> 14 votes

---
Tags: webgl, shadows
---


# Question
Title: What can I use to generate 2d vector graphics as a list of coordinates?
I am working on a game that uses simple 2d vector graphics. I want a tool that will let me visually draw things like arbitrary polygons by placing points.

A perfect tool would present a grid that I could scale larger or smaller (ie: the window is 10 units across or the window is 20 units across). It would let me draw a polygon on this grid, and will tell me, simply, the coordinates of each point.

It would be great if this tool could then export a file format that was something like

```
0, 5
3, -2
0, 0
-3, -2

```

For bonus points, it would be great to be able to assign other attributes to each point. In the end, this will get passed to OpenGL, so things like color and opacity could possibly be used.

# Answer
Well, Flash, Illustrator and so on allow you to draw vectors while snapping to a grid. You could then export as SVG and do some processing on the SVG data, but be warned, I've heard it said that the SVG specification is nightmare.

Why not write your own? Seems really straightforward to do, from what you've said. Set up your onscreen grid according to the scaling the user has specified. Do some simple math, on mouse release, to see what the closest point on the on-screen grid is, and snap to that. I would write this in something like Adobe AIR (Flash for desktop) since Flash supports easy-to-use vector drawing in code. While normal Flash can't access the file system, AIR can, so you can just write your CSV-like file to disk. You could write each vertex as something like

```
[x, y, (metadata1, metadata2, ...)]

```

...to elaborate on your example.

You could even use a bit of Flex for the UI part of it, if you wanted to go that far. Sounds like a good FOSS project in fact -- although I don't doubt there are similar things out there, somewhere.
> 2 votes

---
Tags: tools, vector
---


title: Collision Detection with Isometric Map

text:
# Question
Title: Collision Detection with Isometric Map
I'm using the "Zig-Zag" approach to drawing my isometric map (as seen here https://stackoverflow.com/questions/892811/drawing-isometric-game-worlds). Now I need to do collision detection on the irregularly shaped map.

All I need to know is how to figure out if point (x, y) is colliding with the zig-zag isometric map.

# Answer
> 5 votes
Hmm. You may be mixing up your game (control) logic with your rendering (view) logic.

There are a few ways:

1. Grid-placement checks using the grid representing your world in your game logic. In the link you posted, this would be the abstract 2D (or 3D) grid you store in memory as array, that represents the city blocks. This would help in eg. a Sim City type game where you only need to know, "Can I put this here?" Useful for placement, but not so much for analog movement -- good for Chess, but not for PacMan.
2. Logical grid checks as axis-aligned boxes PLUS circular collision checks. Here you can use your logical grid as a set of boxes which you can very easily check against one another; but you can also check them against circles representing mobile entities in your game eg. the player, cars on the streets, or whatever. This is simple to implement and very fast because no trig is required really, the only thing you use is overlap checks on the x and y axis (bounding box checks) and pythagoras for radius checks, and point-in-square checks.
3. You may want pixel-perfect collision detection. If you do, do a search on it, you will find stuff on here, on gamedev.net forums, on gpwiki.org, all over in fact. It involves checking which pixels of one sprite overlap which pixels of another sprite, in a given rectangular region that represents the overlapping area of the 2 square bitmaps which constitute those sprites. Consider this only if you need a high degree of accuracy, for example in an action game with large, relatively slow moving sprites this might be useful. If your sprites are small and fast moving, check out option 2 -- it will be good enough!
4. Use a physics engine like Box2D for collisions if you need really fast collision detection for a great many objects and once, i.e. most of your objects are not static.

If you use approach 1 or 2 or 4, then how you end up rendering after doing the logic I've outlined, is your choice entirely. It could be isometric, it could be top down, side on, full 3D, whatever. But generally there is a distinct difference between your *actual world* (which is just data) and how it is *represented* (which is usually just pixels). So don't let the fact that your world is viewed isometrically, confuse you -- it's still just a plain old grid. Do the collision checks on that grid, then worry about whether its isometric or not.

---
Tags: isometric
---


# Question
Title: How can I handle a touch event in cocos2d for Android?
How can I handle a touch event in cocos2d for Android? And how to move a sprite using `ccTouchesMoved`?

# Answer
> 1 votes
You need to enable touches by adding `this.setIsTouchEnabled(true);` to the constructor of your `CCLayer`. Then override `ccTouchesMoved`, like this:

```
@Override
public boolean ccTouchesMoved(MotionEvent e)
{
    // convert event location to CCPoint
    CCPoint p = CCDirector.sharedDirector().convertToGL(e.getX(), e.getY());

    // update the position of your sprite
    yourSprite.setPosition(p.x, p.y);

    return true;
}

```

# Answer
> -2 votes
http://www.raywenderlich.com/2343/how-to-drag-and-drop-sprites-with-cocos2d

---
Tags: android, cocos2d
---


title: Level design community help?

text:
# Question
Title: Level design community help?
I'm developing a 2D physics platformer game, with commercial purposes. Almost everything is finished:

* An original game concept
* The whole 2D self-written game engine
* A level interpreter to read xml levels
* A level editor with an advanced GUI to generate levels in xml
* An advanced level object system
* Profile manager (load & save game progress)
* etc ...

But, my problems are of course inspiration for levels...

Is it possible to publish my game concept and ask community for level designs? And still keep my game concept save from being copied by others. Do I have copyrights on a game concept for a game which isn't officially released?

And if I should ask community, should I do an action like, for everyone who submits an approved level design (not the xml, but only a sketch), they receive one cent per sold copy of the game?

What do you think? Tips, pitfalls?

Thank you in advance!

---

For the interested people, here is a screenshot from the level-editor:

Fullscreen image

# Answer
> 8 votes
* Is it possible to publish my game concept and ask community for level designs? **Yes.**
* And still keep my game concept save from being copied by others. **No, once you release your game, anyone can copy your concept.**
* Do I have copyrights on a game concept for a game which isn't officially released? **As eBusiness said, you can't copyright a concept, just the specific elements of your game (mostly, art, music, and code)**
* And if I should ask community, should I do an action like, for everyone who submits an approved level design (not the xml, but only a sketch), they receive one cent per sold copy of the game? **No, because if 100 people submit level sketches and you want to sell the game for $10, then you'd be sending all your income to the level designers.**

Unless you already have a community of people waiting to play your game, you're going to have a hard time getting people to design levels for you. And if your concept is truly original, then people are going to have a hard time designing good levels, because they don't know how your game works.

The best solution (or at least, the one that's been done many, many times before with decent success) is to release your game with a set of levels made by you (or possibly a friend, or a level designer that you hire, if you can afford one), and then release the tools used to make those levels. If people like your game, then they'll build levels for it, and if you encourage this, you'll have all sorts of people making content for your game with very little effort on your part. Done properly, this can extend the life of your game and encourage new people to buy it.

The trick to all of this is to have a good set of levels to start with, which will encourage people to buy the game. One possible idea is to give the game (and level editor) away for free, but make it so that you have to buy the game to play more levels.

# Answer
> 7 votes
Basically, you lack the only interesting thing which people actually play platformers for. All these technical stuff you've listed can be done rather quickly compared to the interesting game levels. Levels need a lot of thought, work and polish, also they tend to spawn features when some idea cannot be expressed by existing components. So if you don't have the levels, you don't have the game.

Summing up, you're basically going to publish a specialized game engine and ask people to make your game for you in return for a small fee while forbidding them to use this engine for anything but your own idea. Capitalism, ho! I've never seen it's done, considering how hard it would be to make a consistent game out of levels made by many different people. Just remember how nicely levels were themed in "World of Goo" versus list of abrupt challenges in "N".

If you don't mind these things, I guess it could work in theory, lets consider criteria for the best case:

* Community around your soon-to-be-game is large, so percent of creative people with nothing to do is high.
* Your concept and engine are heavenly good and/or money share is really tempting and/or it's otherwise attractive, so said people will want to become involved. Chances are, if you have troubles using your concept after the first level, it would be difficult for others to use it as well.
* It's would be frustrating for a community member to create a level only to find out that it won't be inserted into a game. You'll need to make this custom levels playable one way or another, or invent some other form of compensation for wasted time.
* You will spend a lot of time by helping lots of people with your toolset.
* You will spend a lot of time by sending feedback and doing overall community management, since you will receive lots of low and mediocre quality levels.

**All points considered, it might be best to employ a "level-driven development" (think of possible cool applications of game mechanics, then build levels around them) or find yourself a level designer to do it for you.** Also if your concept is good, it will be stolen regardless of what you do. Don't worry about it, real value lies not in a concept but in what you do with it.

# Answer
> 5 votes
Let's take the basic legal first. Your copyright applies no matter if you have released the game or not. You do not have copyright for a concept, only for the very game you made. Except for extreme plagiarism you do not have means for stopping other people from making a similar game.

Given that you basically have no community, and is unlikely to get one unless you have a good game, it would be hard to ask them. The better a game you have already made, the easier it will be to persuade other people to build upon it.

For now, if you can't make levels on your own, I think you'll have to pay someone, and for a physics game it's probably a pretty big job, good or bad levels tend to really make or break those.

# Answer
> 4 votes
There are multiple questions here, but I'll only answer a couple.

Do you have copyrights? Yes. In most countries, you have copyright over anything you create ever as soon as you create it. Of course, this only applies to the code and assets; the game concept is not protected by copyright.

Is your game concept safe? It doesn't matter. The true success of a game is in the implementation, not the idea. The only games that get cloned exactly are those which are *already successful.* Any decent game designer will have a hundred unmade ideas of their own, and no one will be able to implement your concept better than you.

---
Tags: level-design, publishing
---


# Question
Title: How should I approach architecting a data-driven shoot-em-up?
I'm venturing into Mobile/Tablet based development coming from the world of Web Applications.

I want to write a game similar to 1942/43 video game from the 80's:

...similar in the sense that I have a plane/spaceship that flies vertically "up" the screen and stuff comes down to attack it (otherwise nothing that would violate copyright).

I'm familiar with collision detection, sprites, object pooling, etc. but what I'm spinning my wheels on is how to layout all the code for this game. e.g. it doesn't fit my normal MVC pattern, I don't have a DB, and the user input will likely be limited to touch based movement around the screen with "auto-fire" on all the time.

What I'm blanking out on is how to do all the "levels" and sequence "waves" of attackers within a level.

Should I just have a "level" file for each level, that queue's up attack waves? if so, based on time? based on some event? based on a position passed by the player?

e.g.

```
<level id="1">
  <event timeoffset="500" type="attack" name="vConfiguration" position="50"/>
  <event timeoffset="1250" type="attack" name="jConfiguration" position="75"/>
  <event timeoffset="1300" type="bonus" name="quadGunUpgrade" position="10"/>
  ...
</level>

```

Part of me thinks this would be really easy to setup levels this way, then read in the file to queue up the events for the attacks/bonus/? to occur (where each named "attack" is a bit of configured code to position "N" enemies and start their flight sequences)

The other part of me thinks - whoa! before you even dream of implementing this - determine how others would approach it - no need to re-invent the wheel or create a monster.

# Answer
That is, in fact, how many old arcade games were created. Not the XML part of course, but the game is actually a playback engine that eats timed events that are simply a static data listing like what you have above.

All of the triggers you mention would be valid: time is the most common because it puts pressure on the player; events like "destroyed the wall" are used a lot; and position triggers, too. Other events like "specific enemy killed" can be used to build boss sequences, etc...

All just from reading data from a table and playing them back in the engine. It makes for compact code and fits in tiny memory spaces.

You're on a proven track with this design.
> 4 votes

---
Tags: design-patterns, level-design
---


title: How can I draw the depth value in GLSL?

text:
# Question
Title: How can I draw the depth value in GLSL?
I want to draw the depth buffer in the fragment shader, I do this:

**Vertex shader:**

```
varying vec4 position_;

gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
position_ = gl_ModelViewProjectionMatrix * gl_Vertex;

```

**Fragment shader:**

```
float depth = ((position_.z / position_.w) + 1.0) * 0.5;

gl_FragColor = vec4(depth, depth, depth, 1.0);

```

But all I print is white, what am I doing wrong?

# Answer
> 4 votes
position\_.z shouldn't be larger than 1 or lower than 0. You should try to use linear depth for the display, which after applying the projection matrix is (usually) stored in the w coordinate instead. Take that, divide by an appropriate number (depending on the scale of your game) to bring the numbers between 0 and 1 for your interesting depth and watch.

gl\_fragcoord is not relevant to this discussion; gl\_fragdepth is an output variable to modify the post-projection depth in the pixel shader. You're not trying to do that, so don't use that either.

# Answer
> 2 votes
A cheesy way might be to set up some linear fog. Make the fog colour black, draw all your geometry white, and voila.

# Answer
> -1 votes
Maybe you can try one of these two variables. gl\_fragcoord or gl\_fragdepth

I didn't read those manuals, but I think, it could be helpful.

---
Tags: opengl, shaders, glsl
---


# Question
Title: Would studying psychology give an advantage to a game designer?
I've recently read The Art of Game Design and am currently reading Why Reality is Broken and am wanting to learn more about the psychology behind game design. I'm a computer science student but I'm intrigued by the subject and have thought about minoring in psychology.

For the veteran game design people out there, would academically studying psychology give a huge advantage to a game designer? There is one class in particular called Sensation and Perception that gets into what goes on in the nervous system when we are stimulated through our five senses and how these stimulations creates certain perceptions.

So, basically is this over doing it for someone who wants to create games/become a game designer?

What originally caught my interest in this subject was reading about how zynga hired a psychologist to help design the mechanics for farmville.

# Answer
> 20 votes
I have a psychology degree, and have been working as a programmer in the mainstream video game industry for the last thirteen years.

For me, having the psychology degree (rather than a computer science degree) was a major hurdle to getting hired as a programmer, and if I had it to do over again, I'd almost definitely get the computer science degree instead of the psychology one.

But you're not talking about getting hired as a programmer; you're talking about a job in design. And specifically which degree you get is less important for design jobs than it is for programming jobs, so I think you wouldn't have any trouble at all justifying why you wanted the psychology degree.

In fact, I think one could make a very strong argument for why psychology would be an ideal degree for a game designer. Alternate strong contenders might be history, literature, philosophy, filmmaking, and similar broad disciplines which cross across a lot of areas of knowledge. As a game designer, you really want a wide breadth of knowledge, rather than a lot of depth in a single area. Check Tom Sloper's site for more details about further useful areas of study.

I will mention, though, that I've personally found that working in the game industry can be doubly stressful when you have a background in psychology. I've trained rats in skinner boxes, and I've been through the process of vetting human studies for ethics violations. And sometimes, the things you get asked to do to your players start feeling more like the players are rats in skinner boxes, rather than humans in ethically designed tests. And that can be a bit distressing, sometimes.

Or at least, that's been my experience. None of my colleagues have ever seemed to notice or be bothered. And so I assume that it's just my psychology background which has made me hyper-sensitive to this sort of thing. So I thought I'd mention it.

# Answer
> 4 votes
I'm not strong on psychology, although the subject interests me greatly. In my opinion, either path you choose, I can't see it giving a disadvantage. Knowing how a person thinks will definitely be important when it comes to creating emotional attachment to characters, scaring the player, etc.

Although, these skills can also be gained just by playing and analyzing games that currently do what you're after. If you're going after something disturbing and scary, play and analyze Silent Hill games, for example.

Knowing the reasoning behind people's decisions could aid you in implementing mechanics to create positive perceptions of your games (or whatever perception you're trying to put across), but I would be cautious of the course itself as a lot of material will most likely be fairly irrelevant to games. As you say, Sense and Perception sounds like a good step. If you can, find out more about it, talk to the professors, etc. Be up front about your intentions about what you want to do with the knowledge you're provided and they should be able to tell you directly whether it could help you out.

Personally, I would find out more about the course, make sure the subject matter is stuff that you're really interested in. On top of that, keep playing a wide variety of games, even if you don't like them. Analyze the best games you've ever played and ask yourself what makes them so great. I believe understanding that is the key to understanding how to make great games.

Good luck mate.

---
Tags: game-design
---


# Question
Title: What resources are available for iPhone development using AS3?
I've just realeased my first game developed for the iPhone using AS3 and the iPhone Packager http://itunes.apple.com/us/app/snapshot-paintball/id407362440?mt=8&uo=4

I want to take the game to the next level but I am not using the native iPhone SDK so I need some other ideas, I am fresh to iPhone development and it's hard to find good resources, any AS3 developers out there willing to share some links? Highscore frameworks and best practices, connecting to Facebook, ui classes/gestures. Thanks.

# Answer
It's not free, but this seems to be THE gesture library for actionscript. http://gestureworks.com/features/
> 1 votes

---
Tags: iphone, actionscript-3
---


# Question
Title: Where can I find examples of demoscene-like pixel art effects?
I will keep this simple. The question pretty much sums up what I am looking for. Where are some locations for 2D effects. Specifically ones like those used in old Amiga demos. They do not need to have source code. I am just looking for inspiration to code and replicate some of the effects.

It would be nice to have a list of links to images and examples as opposed to downloading old demos and running them through an emulator.

# Answer
> 6 votes
* The Art of Demomaking from the old flipcode archives might be a good start. The whole site has a lot of stuff, but is mostly PC centric although pre 3D hardware.
* These'll blow your mind nicely: Old School Color Cycling with HTML5
* Hornet archives have the biggest collection of oldschool sources and docs in the internets (mostly from PC though). You can access it through the `ftp` protocol if you want.
* Pouet, among other goodies, has a metric ton of links to youtube vids, so you don't have to use any emulator
* AmigaDemos.org would be similar to Pouet.

---
Tags: graphic-effects, special-effects
---


# Question
Title: How would you recommend I get started with ActionScript 3?
I wanted to make Flash games so I bought the book "Flash Games Development with AS3." I did the 'hello, world' program by trace and addChild (or something like that). But the problem was, instead of understanding what I was writing, I was just copying and pasting those lines of code. I felt it wouldn't work that way, and as the book had asked the learners to know at least some Java/Javascript, C#/C++, I didn't go any further.

Now, I want to start again (and yes, I still don't know Java or C programming). What would you recommend for me?

Thanks :)

# Answer
I used this book: Foundation ActionScript 3.0 Animation: Making Things Move! It pretty much discusses the basics, not only about actionscript but also about flash itself. Which is pretty essential if you wan't to build graphics heavy applications (games!)

The book doesn't *really* discuss games, but does teach you the fundamentals of making games. You will create a sphere that you will be able to controll with your keyboard using some easy physics for example.

---

I understand the copy pasting without understanding, I had the same problem when I got my first semester in actionscript (failed miserably, then passed with a 9/10 next year). I will give you a very brief and basic explanation of all the things I found confusing.

## **Variables**

Everything with a \[var\] notation in front of it is a variable. A variable is simple a holder for a certain value. A real world example of a variable is your bank balance - it holds your balance! Every variable has a type, just to name some:

* Number: holds a number
* String: holds a piece of text
* Sprite: A graphic

So your bank balance could be a variable with the type number.

Note: You will see "int" and "number" both being used as numeric values. The difference is that int can't hold floating point values and is therefore calculated faster. Number can hold floating values but is slower.

In code: (everything with "//" in front of it is a comment and is not executable code)

```
    //var: we tell actionscript that we're making a variable
    //balance: the name to refer to this variable is named ballance
    //:Number: We tell actionscript that the variable is the type number
    //=100: We assign the value 100 to the variable
    var balance:Number = 100;

    //we can also change the variable's value later on like this:
    balance = 200;

    //or creating a new variable and add them up
    var paycheck:Number = 100;

    balance += paycheck; //200 + 100 = 300!

```

Now we know that balance is 300, but how would we check in flash? We can use the trace() command for this. Trace doesn't actually add anything for your application, it is mainly for debugging purposes. trace will display a value to an external panel in flash. So if we would want to check the value for the balance we would do the following:

```
trace(balance);

```

Try tracing before and after you added the paycheck, you will see that the value has changed!

---

Now using sprites is ofcourse a little different, since it doesn't hold any numbers, but a graphic. Flash uses a canvas called the stage. If we want to display something we need to add it to the stage. Just as you would add your paint to the canvas to make a painting. Adding things to the stage is done by using addchild(objectToBeAddedHere).

However, just making an empty sprite will display nothing, since it doesn't contain any graphics yet. Using a brush without paint on it wouldn't create anything right? Creating simple graphics with flash is done as following:

```
//we want to create a variable called example sprite with the type Sprite.
    //what should it hold? A new Sprite!
    var examplesprite:Sprite = new Sprite();

    //we have created a new sprite, but by default a sprite is empty. Let's create some graphics
    //to create create grahpics, the sprite has a graphics property. You can access properties by using a point (.)
    //examplesprite.graphics -> we have now accessed the graphics, let's call a function within those graphics!
    //we will talk about functions later on, don't worry. Let's call the function beginfill to give the sprite a colour.
    examplesprite.graphics.beginFill(0x000000); //0x000000 = black;

    //we have given it some colour, but what exactle have we given colour? exactly, nothing!
    //lets create a circle shape using the graphics property again.
    examplesprite.graphics.drawCircle(0, 0, 10); //x, y, radius

    examplesprite.graphics.endFill(); //We are done filling our shape, so we need to use endFill now

    //the sprite is complete! but how do we show it on the stage? using addchild!
    addChild(examplesprite);

```

You have now created a circle shaped sprite with 10 pixel radius at the location's given in drawCircle (0,0). Flash's coordinate system begins in the topleft corner, so x and y 0 is 0 pixels from the top left. x = 10 woul move the sprite 10 pixels to the right. y = 10 would move the sprite 10 pixels below.

Try it:

```
    var examplesprite:Sprite = new Sprite();
    examplesprite.graphics.beginFill(0x000000); //0x000000 = black;
    examplesprite.graphics.drawCircle(0, 0, 10); //x, y, radius
    examplesprite.graphics.endFill();

    addChild(examplesprite);
    examplesprite.x = 10;
    examplesprite.y = 10;

```

## Functions

These are the basics for variables. let's move on to functions A function is sequence of code to be executed. drawCircle(x, y, radius) is a function that holds a sequence of code to draw a circle.

A function can have parameter variables that you need to input. The drawCircle has x, y and radius as parameters. You can pass it values, but also variables of the given type into the parameter. x, y and radius are all of the type number.

Let's move the drawing of a circle into a function now.

```
    //we're not using a variable but a function now, so note function in front. drawCircle is the name to refer to the function
    //X, Y and Radius are the parameters, all with the type number. colour holds a colour, which is of the type uint in this case;
    function drawCircle(X:Number, Y:Number, Radius:Number, colour:uint) {

        //let this function create a new sprite!
        var circle:Sprite = new Sprite();
        circle.graphics.beginFill(colour);
        circle.graphics.drawCircle(X, Y, Radius);
        circle.graphics.endFill();

        addchild(circle);
    }

    //to use the function, you call it like this:
    drawCircle(10, 10, 20, 0x000000);

```

.

```
//we could also pass it variables if we wanted:
        var x:Number = 10;
        var y:Number = 10;
        var radius:Number = 20;
        var colour:uint = 0x000000;

        drawCircle(x, y, radius, colour);

        //important! we cannot acces the circle variable outside of the function, if you want to acces the circle
        //outside of the function you should make the variable before the function.

        var circle:Sprite;

        function drawCircle(X:Number, Y:Number, Radius:Number, colour:uint) {
            circle = new Sprite();
            //blablabla
        }

        //the circle is outside of the function, we can acces it, hurray.
        circle.x = 10;

```

## Events

Last but not least events! Events are as you might have figgured, events that happen during your application. There are events for when you click your mouse, when you press your keyboard, etc etc. You can react to these event with a function. It works likes this:

```
 //we want to "listen" to an event of the type MouseEvent, and the mousevent action is CLICK.
    //so we will wait for when the mouse is clicked, and attach a function to be executed when that happens
    stage.addEventListener(MouseEvent.CLICK, functionWeWantToCall);

    //the parameter is the type of event we use, in this case MouseEvent
    function functionWeWantToCall(e:MouseEvent) {

        //do something
    }

    //the eventlistener is attached to the stage right now, so it happend when the stage is pressed.
    //you could also attach it to a created sprite for example;
    var circle:Sprite = new Sprite();
    circle.graphics.beginFill(colour);
    circle.graphics.drawCircle(X, Y, Radius);
    circle.graphics.endFill();

    addchild(circle);

    circle.addEventListener(MouseEvent.CLICK, clickCircle);

    function clickCircle(e:MouseEvent) {

        //we change the scale of the sprite when the sprite is clicked
        //we can detect the target of the click by using e.target property
        e.target.scaleX += 1; //increase the scale on the X axis by 1;
        e.target.scaleY += 1;
    }

```

There are events for bassicly everything, shouldn't be too hard to find online. The Event.ENTER\_FRAME is very important for games. The function attached to the event is called every time a new frame starts (30 times a second default in flash). So if you add 1 to the x position of a sprite each time that function is called, the sprite will move :)

Using keyboard events, you can add or subtract values from the x and y of a sprite. You can essientally controll it usin your keyboard!

Sorry for the lengthy write-up. I remember how frustrating it was for me. Good luck!
> 4 votes

# Answer
You probably want something like this. Colin Moock was regarded at one time as the definitive AS3 expert. http://www.amazon.com/Essential-ActionScript-3-0-Colin-Moock/dp/0596526946

You may also want to check out http://www.bit-101.com/blog/ as Bit-101 is a seasoned Flash veteran.

Beyond that, there are some more general resources about ECMAScript worth exploring, such as http://jibbering.com/faq/notes/closures/ which will help you understand the language.

Apart from learning ECMAScript / AS3 you will also need to learn about game development. This site already offers many suggestions about books and websites to read that are related to the various topics in this field.
> 3 votes

---
Tags: actionscript-3
---


# Question
Title: What is causing these texture edge artifacts on some video cards?
I have a 2d heightfield converted into a very simple mesh and textured with tiles from a texture atlas. The tiles texture is drawn with:

```
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);

```

On my integrated Intel card, it draws as I intend (top picture). On a friend's ATI card, it has very visible edges (bottom picture).

What causes this, and how can I avoid it?

Extra info:

* glColor4f(1,1,1,1) has been called before drawing the mesh
* the texture atlas is a simple vertical strip, so the right-side of each tile has `x=1.0f`
* the vertices are being shared so there isn't really a 'hole' between my rows
* the resolution on both systems is the same
* the vertices and texture coordinates are all passed as GL\_FLOAT
* the tiles atlas is mipmapped

# Answer
At a guess you should be using GL\_CLAMP\_TO\_EDGE instead of GL\_CLAMP. I don't have an Intel to verify on but I suspect that the ATI is actually the one doing the right thing (OpenGL on Intel can suck badly - their drivers are notorious).
> 2 votes

# Answer
Try using `GL_CLAMP_TO_EDGE`. The GL spec says, that `GL_CLAMP` clamps to \[0,1\], so you get problems at the edge where the border color gets in, whereas `GL_CLAMP_TO_EDGE` clamps to `[0.5/size, 1-0.5/size]`, which is what you want, as GL returns exact texel values at the texel center.

I think the ATI is right, as it uses the border color for values out of the valid texture range. which would either dim the edge region (when filtering linear) or make one side completely black (the default border color) when using nearest neighbour filtering. Or maybe on the Intel you just don't get exact 1.0, so in nearest filtering you still get the last valid texel. In either case, you are on the safe side with using `GL_CLAMP_TO_EDGE`.
> 5 votes

---
Tags: opengl
---


# Question
Title: XNA 4.0: 2D Camera Y and X are going in wrong direction
I asked this question on stackoverflow but assumed this might be a better area to ask it as well for a more informed answer.

My problem is that I am trying to create a camera class and have it so that my camera follows the proper RHS, however the Y axis seems to be inverted since on the screen the 0 starts at the top.

Here is my Camera2D Class:

```
    class Camera2D
    {
        private Vector2 _position;
        private float _zoom;
        private float _rotation;
        private float _cameraSpeed;
        private Viewport _viewport;
        private Matrix _viewMatrix;
        private Matrix _viewMatrixIverse;

        public static float MinZoom = float.Epsilon;
        public static float MaxZoom = float.MaxValue;

        public Camera2D(Viewport viewport)
        {
            _viewMatrix = Matrix.Identity;
            _viewport = viewport;
            _cameraSpeed = 4.0f;
            _zoom = 1.0f;
            _rotation = 0.0f;
            _position = Vector2.Zero;
        }

        public void Move(Vector2 amount)
        {
            _position += amount;
        }

        public void Zoom(float amount)
        {
            _zoom += amount;
            _zoom = MathHelper.Clamp(_zoom, MaxZoom, MinZoom);
            UpdateViewTransform();
        }

        public Vector2 Position
        {
            get { return _position; }
            set { _position = value; UpdateViewTransform(); }
        }

        public Matrix ViewMatrix
        {
            get { return _viewMatrix; }
        }

        private void UpdateViewTransform()
        {
             Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0)) *
                           Matrix.CreateScale(new Vector3(1f, 1f, 1f));

             _viewMatrix = Matrix.CreateRotationZ(_rotation) *
                          Matrix.CreateScale(new Vector3(_zoom, _zoom, 1.0f)) *
                          Matrix.CreateTranslation(_position.X, _position.Y, 0.0f);

             _viewMatrix = proj * _viewMatrix;

        }

    }

```

I test it using SpriteBatch in the following way:

```
protected override void Draw(GameTime gameTime)
{
    GraphicsDevice.Clear(Color.CornflowerBlue);
    Vector2 position = new Vector2(0, 0);
    // TODO: Add your drawing code here
    spriteBatch.Begin(SpriteSortMode.Immediate,
        BlendState.AlphaBlend,
        null,
        null,
        null,
        null,
        camera.ViewMatrix);

    Texture2D circle = CreateCircle(100);
    spriteBatch.Draw(circle, position, Color.Red);
    spriteBatch.End();

    base.Draw(gameTime);
}

```

# Answer
So after just thinking **logically**, I was able to deduce the proper transformation. I'll outline the steps here incase anyone wants the real breakdown:

It is important to understand what is a *Camera Transformation or View Transformation*. A View Transformation is normally what is needed to go from Coordinates **relative** to your Camera to World-Space coordinates. The inverse of the View Transformation would then make a world coordinate relative to your Camera!

*Creating a View Matrix*

1. Apply the camera's rotation. We are doing it in the Z axis only because this is for a 2D camera.
2. Apply the transformation of the Camera. This make sense since we want the World coordinate which is the sum of the camera coordinate and the object relative to the camera.
    1. You might notice that I multiplied the Y Component by -1. This is so that increasing the Camera's Y Position correlates to moving up since the screen's Y value points downward.
3. Apply the camera's zoom

Now the inverse of the matrix will do World Coordinate -\> View Cordinates.

I also chose to center my camera in the center of the screen, so I included a pre-appended translation.

```
Matrix proj = Matrix.CreateTranslation(new Vector3(_viewport.Width * 0.5f, _viewport.Height * 0.5f, 0));

        _viewMatrix = Matrix.CreateRotationZ(moveComponent.Rotation) *
                    Matrix.CreateTranslation(moveComponent.Position.X, -1 * moveComponent.Position.Y, 0.0f) *
                     Matrix.CreateScale(new Vector3(zoomComponent.Zoom, zoomComponent.Zoom, 1.0f));

        _viewMatrix = proj * Matrix.Invert(_viewMatrix);

```
> 0 votes

# Answer
This is the mistake: Matrix.CreateTranslation(\_position.X, \_position.Y, 0.0f)

Make it like this: Matrix.CreateTranslation(-\_position.X, -\_position.Y, 0.0f)

Explanation: The matrix specifies how the world should be transformed, not how the camera is transformed. Thats why you need to insert the **negative** values.
> 4 votes

# Answer
All of my Camera classes start with this as a base:

```

public class Camera {

    private Vector2 position = Vector2.Zero;

    public float Left {
        get { return position.X; }
        set { position.X = value; }
    }

    public float Top {
        get { return position.Y; }
        set { position.Y = value; }
    }

    public Matrix TransformMatrix {
        get {
            return Matrix.CreateTranslation( new Vector3( -position, 0f ) );
        }
    }

    public Camera( ) { }

} // Camera

```

I use the same method that Felheart has highlighted by inserting the negative values (`-position`) into the `Matrix.CreateTranslation` function call and have never had a problem with the camera moving in the wrong direction. My camera is used just like yours:

```

spriteBatch.Begin(
    SpriteSortMode.Deferred,
    BlendState.Additive,
    SamplerState.AnisotropicClamp,
    null,
    null,
    null,
    camera.TransformMatrix );

spriteBatch.Draw(
    someTexture,
    x,
    y,
    width,
    height,
    color );

spriteBatch.End();

```
> 0 votes

---
Tags: xna, c#, xna-4.0, camera, matrix
---


title: How to create a reasonable AI?

text:
# Question
Title: How to create a reasonable AI?
I'm creating a logic game based on Fox and Hounds game. The player plays the fox and AI plays the hounds. (as far as I can see) I managed to make the AI perfect, so it never loses. Leaving it as such would not be much fun for human players.

Now, I have to dumb-down the AI so human can win, but I'm not sure how. The current AI logic is based on pattern-matching - if I introduce random moves which make the board go out of pattern space the AI would most probably play dumb until the end of the game.

Any ideas how to dumb down the AI in such way that is does not go from "genius" to "completely dumb" in a single move?

# Answer
> 7 votes
Many implementations may lead to a random weighted chance for moves -- say, a chance to make an optimal move and a chance to make a suboptimal move. Determining how suboptimal a move is could be a very tricky problem, but will also lead your AI to making much more seemingly-intelligent decisions.

Important note: No matter the difficulty setting, it would probably be a bad idea to have the AI pass up a chance to immediately win the game. If there is a possibility to make a move that would finish the game that turn, it should always be taken. If not, it will absolutely destroy the player's impression of how the AI is acting.

# Answer
> 10 votes
Since this appears to be a 'solved' game, the only answer is that the computer must make intentionally bad moves.

A quick solution may be to calculate the best move, then also calculate another legal move that may not be so good. The difficulty rating of the AI would be measured in the percent chance it picks the other not so good move, over the perfect move.

* Difficult - 90% good moves
* Hard - 70% good moves
* Normal - 50% good moves
* Simple - 20% good moves
* Was Dropped As A Child - \<5% good moves
* Hotdog - All Random

---
Tags: ai
---


# Question
Title: How do I add a text area to my 3D android world
i am learning 3d game development on android , i was wondering is it possible to add text areas or any thing that allows a user to enter a text in a 3d world ? and how ?

# Answer
Your problem have a two part answer :

1 : First you have the problem of letting the user input some text. This can be easily done using the virtual keyboard available in Android. Something like this should do the trick.

```
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);

```

Of course if you want something with your own look and feel you can create your own input service (look here for more info http://developer.android.com/resources/articles/creating-input-method.html)

2 : Then, you need to give the user some kind of feedback, meaning write the text the user is typing in 3D. To do this, the basic idea is to create one quad per character, and map it to a texture containing your font, and place the quads in 3D where you wan't them to be.
> 2 votes

# Answer
On android, there are many ways to read strings input:

* As gameloft, develop your own widget and code your own Virtual Keyboard; that is probably the better to way for an immersive experience
* Or use the Android Libraries to do it.

About the second solution:

* in your Layout, there is probably a GLSurfaceView but you can add others views. So you can use an EditText to read input. Just show or hide it when you need it.
* otherwise you don't want use Android View because you have your own GUI. Use only the Virtual Keyboard when needed.

You can read my old tutorial with code and the phil hassey blogs about porting its game from IOS to Android.

we're talking about JNI (Java bridge with C) because our engines are C/C++ code...
> 1 votes

---
Tags: 3d, android
---


# Question
Title: Are there any open source Source engine VTX/VVD viewers?
I've been playing with loading and displaying Source Engine models (TF2, specifically) and have had mild success, but there are some aspects of it that are eluding me still. I've been primarily looking at http://developer.valvesoftware.com/wiki/MDL and online forks of the SDK headers like http://hlssmod.net/he\_code/public/studio.h to understand the formats, but I've found the headers to be helpful, but lacking some crucial implementation details. The Developer Community pages do talk implementation, but much of it is speculation and I've already identified several points where it is wrong, so I'm struggling to locate some better resources.

I've got the whole .VVD file parsing now (as in: I can get the correct verts for a given LOD, verified by rendering a pointcloud.) The specific issue I'm looking at now is in the .dx90.VTX file. Drilling down into the Mesh Strip Groups, it seems like I can render the first strip group just fine (I have the Heavy's chest, arms, and legs rendering) but subsequent meshes are a mess of random triangles. It feels to me as if there should be a per-mesh offset into the .VVDs vertexes somewhere within the .VTXs structure, but I can't locate one. Maybe there's something in the .MDL, which I haven't started looking into yet, but it feels very odd to me to have such closely related data in separate files.

I know that's probably all gibberish to anyone that's not intimately familiar with the Source model formats. Really what I could use more than anything else is some reference code from another app that is loading these files. Are there any open-source exporters/viewers out there?

# Answer
> 2 votes
You could use the source code for DuctTape as a reference. Be aware it's GPL licensed.

---
Tags: models, loading, file-format, source-engine
---


# Question
Title: Appropriate level representation / data stucture for a 2D platfrom game?
I'm about to program a copy of Mario in Java. I'm thinking on 2 representations/data structures for the levels but I'm not sure which one should I choose:

* A 2D integer array.
* A quadtree to divide the level in pieces.

What are its advantages and disadvantages?

# Answer
The point of a quadtree is to efficiently cull large chunks of the data so that you only spend time on the data in the immediate vicinity. However a 2D array already gives you location-specific random access, so for a 2D game that may make a quadtree redundant. In a 3D game you can't use an array to locate everything and that's where quadtrees (or better yet octrees) are handy.

Now, I'm talking here about the underlying data representation for the level. Depending on how your graphic architecture is setup (eg. doing 2D graphics with planes in a 3D engine) you may want to use quadtrees in the scene graph in order to efficiently cull graphical content.

And then don't forget various enemies and other interactive objects in your level. Perhaps you use a 2D array to manage the tiles of the level, but use quadtrees to organize all the interactive elements (eg. for a physics engine).

---

Think of it this way: pick a point at random in your level, and then think about how much work it'll take to figure out everything within a 1000 pixel radius of that point. If you can do that quickly because everything is organized by location in a 2D array, then you don't need a quadtree. If however you would have to loop through everything and check each object's distance individually, then you could make the search much more efficient by using a quadtree.
> 9 votes

---
Tags: 2d, java, data-structure, platformer
---


# Question
Title: What is a reasonable OpenGL version baseline for a mid-range 3D game?
I decided recently write a 3D game in my spare time, as I was tired of my daily "corporate programming". If I expect to be done in 6 months/1 year, which version of OpenGL should I use as baseline? In other words, which version of OpenGL should I require my potential users to have?

I did some OpenGL has a student, but that was in the days of the *first edition* of the red book. Things have changed a lot since then.

# Answer
First you can always assume GL2, I think, as you won't find much pre-2.0 hardware around. Next, it is mostly a question of the major version, as these are mainly dependent on the hardware, whereas minor versions often are more of a driver question. For example a hardware supporting GL 3.1 is likely to support GL 3.2 (and 3.3), too.

Next, it depends on the features you need. For example these are IMHO the major features of the newer versions (forgive me for forgetting your favourite feature):

OpenGL 3:

* geometry shaders
* texture buffers
* instanced rendering
* integer textures and attributes
* integer operations in shaders
* transform feedback
* FBOs
* floating point textures

The first six of these are real hardware features of GL3/DX10 hardware, whereas the last two (important ones, I think) are core since 3.0, but are supported on most newer GL2 hardware by extensions (since GeForce 6, I think)

OpenGL 4:

* tessellation shaders
* double precision attributes and shader operations (and textures?)
* improvements of shader managment
* image load/store operations

In my opinion GL3 brings some really nice features, but there is nothing that prevents you from writing modern and future ready GL applications (without fixed-function) with only OpenGL 2.0/2.1, that may later be easily improved by new features of newer hardware. But maybe nowadays GL3 might also be a valid requirement, although I still sit on 2.1 hardware. But honestly, it just depends on the hardware features you need and GL 2.0/2.1 might suffice for a solid "baseline". But as you say you last time used the old and deprecated way of OpenGL you might first need to make yourself acquainted with the new and modern shader-only approach, as this is the way to do hardware accelerated real-time graphics today (and tomorrow).

Finally, if you're more familiar with DirectX (and as that seems the one people classify hardware by, nowadays), the relations GL2 ~ DX9, GL3 ~ DX10 and GL4 ~ DX11 may also guide you.
> 8 votes

# Answer
> If I expect to be done in 6 months/1 year, which version of OpenGL should I use as baseline?

None. If you expect to be done in 6 months to a year, unless your game has negligible graphics (SpaceChem, Tetris, etc) directly using OpenGL is going to slow you down. If you want to make a game quickly, then you should be using something higher level than OpenGL. Ogre3D, Irrilicht, etc, there are any number of engines that don't require direct usage of OpenGL.

Taking the time factor out of it, you can think of the populations for each version like this:

2.1: People who have bought a graphics card in the last 8 years. This also covers more recent Intel hardware (though don't expect these to work well without fiddling with it).

3.3: People who have bought a graphics card in the last 5 years. Or an integrated graphics chipset (from AMD) in the last 5 years.

4.2: People who have bought a graphics card in the last 2 years. This also covers more recent AMD integrated chipsets, as well as on-die CPUs that AMD is starting to make.
> 5 votes

---
Tags: opengl
---


# Question
Title: How to get object to lose less velocity as its speed increases
I'm developing a game in Flash and I need a little help. It can be considered a math problem.

My object is flying with speed `X` and my object can collide with stones. When it collides with a stone, I need my object to break the stone and continue, but with less velocity. It's easy to hard-code it and write something like: `myVelocity -= 10;`, but my main problem is that I want it to lose *less* velocity the higher the initial velocity is.

For example: If the velocity is 300 I want it to lose 10 and if it was 200 I want it to lose 20.

Can this be done with some kind of formula?

# Answer
> 6 votes
I would invert the speed and multiply by something you like:

```
float velocity = 300.0f;
float collisionEffect = 3000.0f / velocity;
if (collisionEffect > velocity)
{
    // Choose which one you like: with or without restitution

    // No restitution
    collisionEffect = velocity;

    // Restitution
    collisionEffect = velocity + (collisionEffect - velocity) * 0.3f;
}
velocity -= collisionEffect;

```

This example gives these effects:

```
400 loses 7.5
300 loses 10
200 loses 15
100 loses 30
 50 loses 50  // Using no restitution
 50 loses 53  // Using restitution
 20 loses 20  // Using no restitution
 20 loses 59  // Using restitution

```

# Answer
> 29 votes
those system you and others describe will not will not generate real looking physics. the main formula is to decrease 0.5\*m\*v^2 (kinematic energy) by a **constant** value whenever object hits somewhere.

so if an object with weight 2Kg hits some block, which needs 16j energy before it breaks: object movement speed will change according to this table :

```
4  m/s -> the block will not break
5  m/s -> 3   m/s
6  m/s -> 4.4 m/s
7  m/s -> 5.7 m/s
8  m/s -> 6.9 m/s
9  m/s -> 8   m/s
10 m/s -> 9.1 m/s

```

# Answer
> 2 votes
You've not really given enough information to tell what sort of range you want, i.e. whether it is capped, whether you want geometric progression, etc.

First thing you want to do is derive a number proportional to the amount of speed you want to lose (it doesn't have to be the same, but it should decrease as the speed increases to make it proportional to your loss). The standard way to do that is to take the *reciprocal*:

```
temp = 1 / currentVelocity;

```

Now, for 100 you will have 0.01, for 200 you'll have 0.005, for 300 you'll have 0.0033 and so on.

Now you just need to adjust that number to whatever you really want, by multiplying it. So

```
k = 3000;
newVelocity = temp * k;

```

will give you your 20 for 300, but it will give you 15 for 200 rather than 10. This may be fine for you, in that case you don't need to read further. You can adjust k as you like but you may not get numbers the way you like them unless you do a little more, such as implement geometric progression, or change the base for increase. I'm not going to go into geometric progressions here, but if you want to change the base, you do it as follows:

```
base = 100;
temp = 1 / (currentVelocity - base);
if (temp < 0) temp = 0; //adjust temp so never less than zero, cannot gain force!

k = 2000;
velocityLoss= temp * k;
if (velocityLoss > currentVelocity) //(1) or make currentVelocity an unsigned int
    velocityLoss = currentVelocity; //(2)

```

This will provide you with the range you originally asked for in your question, 300 -\> loss of 10, 200 -\> loss of 20. FYI 100 -\>loss of 40, and 50 -\> loss of 80(!) which means you'd need to restrict your subtraction -- which is what I've done in lines (1) and (2).

There are other ways of approaching this whole problem, of course, which I'm sure those more mathematically adept than I, will post here.

# Answer
> 0 votes
I think, you can use just simple division by velocity. For example: lost = 3 000 / myVelocity. When velocity is 300, you will lose 10, when it's 200, you will lose 15. It's up to you to choose correct constants.

If you want, you can use more complex formula, like: constant / (constant2 * velocity^2 + constant3 * velocity). Again - just choose constants, which will suit you.

---
Tags: mathematics, physics
---


# Question
Title: Can world depth be achieved in a side scroller?
I tend to build games with strong stories, which usually involves quite an indepth world environment. Typically I develope typical 2.5 over head view JRPG style (think Zelda, Final Fantasy 3, etc) because I have it stuck in my head that you can only achieve world depth using this style.

This question is limited to the 2D environment. Can this be achieved in a 2D side scroller? Can a user experience the world when only seeing it from the side? Can he/she explore villages in this manner? Any examples would be great.

The closest thing that comes to my mind at the moment is Castle Crashers.

# Answer
Yes. There were a few games, many years ago, that used a 2D side scroller viewpoint, which were very immersive and highly explorable:

1. Colorado / Starblade (same engine, action / adventure)
2. Drakkhen (action / adventure)
3. Sapiens (action / adventure)
4. Stronghold (a strategy RPG)

You can find videos for all of these on youtube.

These all allowed movement "in" and "out" ("north" and "south") of the screen as well as left and right ("east"/"west"), between screens -- enabling a non-linear world.

The main limitation for the sidescroller is the restriction in vertical space. This was overcome in games like Golden Axe and D&D: Shadows Over Mystara by giving the characters some vertical movement room without changing the perspective too much -- this makes combat more interesting, and you can evade enemies and go past them into other locations.

Sapiens was a particularly innovative approach to game design considering how old it is. One aspect was that you could see your x, y position on a map, although each location was a side-scroller view. Stronghold does much the same.

Stronghold is a particularly interesting/unique game in that it used a primitive vector based approach to show vistas of the world behind the current location, however the perspective is much the same as a platform game.

Finally, I'd say that in some ways, there's even more potential to achieve greater world depth in sidescrollers than in top-down or isometric views because, like FPSes, this is a natural view for a human being to see other creatures, and their world from -- eyes level to the horizon. So it can actually be quite evocative as a result.
> 5 votes

---
Tags: game-design, level-design, side-scroller
---


# Question
Title: Recording the gameplay in the game itself?
I'm presently working on a 3D car racing game for the iOS platform. I had to implement a replay system and then record that replay in a video file to upload it to YouTube.

I'm only having issues with the recording part, the rest is done. What I'm doing is using the `glReadPixels()` command of OpenGL ES 1.1 to capture the framebuffer content and creating a video from these frames during runtime (using AVFoundation framework).

The problem I'm facing is that I have to call `glReadPixels()` in each update which is very slow . It decreases the FPS from around 30 to only 2-3... Is there any alternative to the `glReadPixels()` command? Or did anyone create a replay system and recorded to video?

# Answer
Since you have the replay system in place, I'd suggest you only store the replay-data during gameplay and then render a video from that replay offline. Eg. after the game has finished and the user chooses to post the replay as video, then you would render the video from the replay-data (by playing the replay and using `glReadPixels`).
> 8 votes

# Answer
I think the simplest way is to record user and AI actions and state during gameplay, not actual frames. After gameplay has finished, either the player completing the race or quitting back to the main menu they are given the option to look at a replay (or save one) and only then are those actions used to recreate the frames by playing back the actions and state through the game engine. This has the additional benefit of not (essentially) having to draw each full frame multiple additional times during gameplay.
> 0 votes

---
Tags: iphone, opengl-es, ios, ipad, video
---


# Question
Title: Did Street Fighter II Employ Machine Learning?
As a kid hanging out in my local arcade, me and my friends used to swear up and down that our computerized sf2 opponents would learn our strategies.

I wonder if anyone here might know whether that was the case. It feels as if it couldn't have been as simple as a finite state machine, because the opponent's tactics were definitely different depending on how early in the session you'd encounter them. And as each fight went on, it was as if old tactics would stop working. Brilliant games :)

anyways, I know it's a relatively open ended question. I had so many great memories playing that game, and it would be interesting to know whether the AI was that sophisticated, or otherwise what techniques it may have used so I can potentially use similar techniques in my own game designs.

# Answer
> 10 votes
As someone who, more than once, beat the (SNES version of the) game on the hardest difficulty level with one repeated move (M. Bison's Psycho Crusher), I feel I can safely say it did not learn from strategies.

Though, this question does remind me of something I read in Ernest Adams' *Fundamentals of Game Design*:

> Most current video games do not, in fact, contain much real AI. The point of video games is to entertain, not to simulate intelligence in depth, so they usually contain just enough AI to make the player feel as if the software is reasonably smart. The players—who are already immersed in the make-believe world anyway—are often happy to give the game credit for intelligence that it doesn't really possess.

Source

# Answer
> 1 votes
I played the game a lot on the Snes, and a little in the Arcade, and I know that era of videogames well cause I was a kid and I loved em... And I'm pretty sure the AI was absolutely unadaptative. I, myself, didn't see any kind of learning at all, but maybe someone from Capcom could prove me wrong...?

---
Tags: ai
---


title: XNA Webcam video

text:
# Question
Title: XNA Webcam video
How can I embed a video in a XNA application? I'm developing a card game with XNA C# and I need to send webcam video between four machines. Could anyone give me some tips about that?

# Answer
> -1 votes
I believe the general solution to this is to capture the webcam images and apply it to a Texture2D. This is known as rendering to a texture. You can find more information here: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Render\_to\_texture.php

Be warned that that tutorial is made for XNA 3.1 so it might need a bit of work porting it to XNA 4.0 code.

I've found a few webcam components/image capture facilities that are written in C# so they can be used along with the XNA framework:

https://stackoverflow.com/questions/1789684/webcam-calling-in-xna \- This SO question provides a few answers and even some techniques to apply the webcam stream to an image (although it's a very dirty way in my opinion).

http://forums.create.msdn.com/forums/p/1467/9530.aspx#9530 \- This forum post provides an XNA specific Webcam component that allows you to capture the images to a texture. I believe this to be fairly buggy, but the code should provide you with a good starting point.

Hope that helps!

---
Tags: xna, c#, video
---


# Question
Title: How do I make objects move along a path?
I'm trying to get something like the below image. As you can see, there's a highway and inside of it, there'll be some objects moving (millisecond). I guess the street behavior is like a pipeline. When the highway loads an object, it appears at the beginning and it'll be moving through the highway until it arrives in the other extreme of the highway.

My main problem is, how can I move several objects only inside of the highway?

# Answer
That depends: how do you *want* them to move?

### The unnatural option

Define a preset path with a series of vertices and have the balloons follow the path strictly.

### A more natural option

Make the balloons boids and implement crowd path following behaviour, which will have them follow the path (and not get too far from it) whilst avoiding collision with each other. Both those pages contain Java applet examples.

The author of those pages notes he cannot distribute the source code of the examples, however OpenSteer offers C++ implementations of those algorithms.

(I'm not aware of any C# boids libraries, or any decent tutorials - the best I've done is just follow code examples)
> 18 votes

# Answer
You need a list of points and a list of balloons

```
class Path
{
   List<Vector2> Points;
   float[] Lengths;
   Vector2[] Directions;

   void Build()
   {
       Lengths = new float[Points.Count-1];
       Directions = new float[Points.Count-1];
       for (int i=0; i<Points.Count-1;i++)
       {
            Directions[i] = Points[i+1] - Points[i];
            Lengths[i] = Directions[i].Length();
            Directions[i].Normalize();
       }
   }
}

class Balloon
{
     Vector2 Position;
     float StagePos;
     int StageIndex;
     Path Path;
     float Speed;

     void Update(float Seconds)
     {
         if (StageIndex!=Path.Points.Count-1)
         {
             StagePos += Speed * Seconds;
             while (StagePos>Path.Lengths[StageIndex])
             {
                 StagePos -= Path.Lengths[StageIndex];
                 StageIndex++;
                 if (StageIndex == Path.Points.Count-1)
                 {
                     Position = Path.Points[StageIndex];
                     return;
                 }
             }
             Position = Path.Points[StageIndex] + Directions[StageIndex] * StagePos;
         }
     }
}

```
> 5 votes

# Answer
If you have a road made up of tiles with a single path ("pipeline" as you called it), then you don't need boids, avoidance, AI, or really anything super special. Just have each balloon move in the natural direction of the road tile. For example, given a starting tile with only one non-sand tile to touch, you can figure out which direction to move -- it is the direction that is "not here, not where I was, and not sand". Since your road has only two possible directions of flow, once the initial direction and tile are established, the algorithm will solve the problem.

The balloons will appear to follow each other simply because there isn't anywhere else to go. If they all move at a constant speed, then no collisions are possible. Even if they don't move at a constant speed, the "not here, not where I was, and not sand" can be have "and make sure there is enough space for me" appended.

You could generalize a little and use the tile's image as a method of extracting direction. For example, an L shaped road stripe means either "if you're going south, then turn east" or "if you're going west, turn north".

This system breaks down when you decision making to do, i.e. more than a single path that can be taken, but from your screenshot and description of the problem, that doesn't seem to be an issue. If it is a requirement for your application, then definitely invest in a more AI-centric approach.
> 3 votes

---
Tags: xna, c#, xna-4.0, windows-phone-7, tower-defense
---


# Question
Title: Pickup another book or submerge into XNA
Completely read Head First C#.

Should I read something else or get personal with XNA from here on? Got links?

Edit: Hobby. Interested in 2D and 2.5D gamedev for personal fun, nothing serious. Multiplayer(in 2D/2.5D games) is also a very interesting topic for me. Basically not sure where to go now from here.

# Answer
> 7 votes
Well, start programming!

You can google for some basic tutorials to get you started, but if you don't know with what game to start, this answer is a great starting point: What are good games to "earn your wings" with?

As for books, I would suggest you start from something like XNA 4.0 Game Development by Example: Beginner's Guide and then move to Building XNA 2.0 Games: A Practical Guide for Independent Game Development

Personally, I would get my hands dirty and then move on reading a book for more advanced topics.

# Answer
> 1 votes
I hate to link to an existing answer, but the one I posted here might be useful: Wise approach to becoming good at C# XNA

> Start by making something simple. Maybe a static sprite that moves across the screen when you press certain buttons. Add some objects to play with collision. Then when you feel comfortable with that work on sprite animations, and a simple camera. It really isn't hard.
>
> If you want a jump start, look at something like Flat Red Ball. It is simple 2.5D game engine that might help. If you want to make your own, look at this tile engine series. It will show you stuff like how to make a camera, animations, collision, and the rest. There is also this 2d tutorial series. I don't have a nice playlist for it so you will have to search youtube for the different parts. For even more resources, check out the ever-growing list of samples on the App Hub site.
>
> If you really want to take classes, I can vouch for http://LearnVisualStudio.net. I know a few people who have taken them, and have seen the content. It is presented nicely and easy to follow.
>
> When in doubt, come back here and ask questions. The people here are very responsive and helpful. If you need help on general C#/programming concepts try http://stackoverflow.com. It is another wonderful resource.

# Answer
> 0 votes
I started XNA as an existing professional C# developer so it's a bit different but I found the samples in the educational catalog at create.msdn.com really useful.

They've got samples of most of the things you'll probably want to do. If videos are more your thing, they've got lots of those too.

# Answer
> 0 votes
I was at a similar position to you a few months back except I've done game development before so was looking to refresh things.

i found the following site very useful for getting me up and running again with simple 2D sprite displaying.

http://www.xnadevelopment.com/tutorials.shtml

---
Tags: xna, c#, 2d, software-engineering, 2.5d
---


# Question
Title: Is there a tool to help quickly define animation frames from non-uniform size sprite sheets?
Many of the sprite sheets online have non-uniform sized rectangles as the animation frames and often use a portion of the image for credits, etc., this makes it hard for a game engine to correctly clip the sheets.

Is there any tool that can help you quickly define frames in a sheet, export animation data which the game engine would use?

# Answer
> 7 votes
*\[Moved from question body\]* Here's a list of what I've found by googling:

* **Sprite Vortex** : It can auto-detect frames. There has been some crashes and is still buggy, otherwise it's a very good option. When you are exporting, make sure you click the root item instead of individual animation in the tree view to export all animation definitions.
* **darkFunction Editor** (http://darkfunction.com/): By double-clicking a sprite, it will automatically make a frame. Still some manual work but works great so far.
* **Spritimator**: Saw this used by a tutorial, but the author's webpage seems down at the moment.

# Answer
> 2 votes
Usually such sprite sheets come with an additional file with coordinates for the packed frames (some might even be rotated). Extracting frames without these coordinates can really be a cumbersome task. Automating it would also be very hard to do, since a single sprite doesn't necessarily have a contiguous shape.

If the coordinates file is missing, I'd probably use the Photoshop Slice tool to mark individual frames and then you can export all slices at once by using "Save for Web & Devices".

---
Tags: animation, spritesheet
---


# Question
Title: What is a good book on physics for game development?
I'm looking for a good beginners' book on the subject of physics in game development. Something that focuses on 2D games would be preferable.

# Answer
I am going to make a recommendation based on what I have read and how I started. Now I am assuming that when you say *beginner* you mean a *beginner* in physics engines and not programming. I won't write details as you can get that from the Amazon reviews.

Game Physics Engine Development

This book was a very good introductory book for me. Although like every book, it has shortcomings (some code does not work as expected but that's fine, forces you to think even more!)

Real-Time Collision Detection

Absolutely wonderful book/reference but a little more advanced. You can start with this book if you like. It depends on what your *beginner* level really is.

Game Physics

This is not for beginners, but it is something to keep in mind. All of Eberly's book's are math heavy but once you understand the full subject, his books, in my opinion become indispensable simply because there are a rare few people knowledgeable enough to delve into that much detail.

It is not going to be an easy ride. Physics is one of the tougher topics in game development. Good luck!
> 23 votes

# Answer
Okay, so I found a couple books all with more that 2d physics but, the physics of 2d as well so I don't think it would hurt anything to have more than you need to just in case.

Physics for Game Programmers(java examples) which looks to be the best balance of the bunch. amounts to something like physics 101 and has java code examples

Game Physics (c++ examples) This seems to be even more geared towards some hardcore 3d development than anything else and uses OpenGL (bonus)

Physics for Game Developers (c++ windows api) This book while apparently a bit more easily accessible is the most error prone of the bunch. But its like $5 so with that in mind I don't think you would be too much of a bad investment.
> 4 votes

# Answer
http://www.amazon.com/Mathematics-Physics-Programmers-Charles-Development/dp/1584503300 The Game Development program at my college uses this book for the first year of math/physics. There are a great deal of books on the subject, but this one is quite good IMHO.
> 1 votes

---
Tags: 2d, physics, books
---


title: HTML5 collision with images

text:
# Question
Title: HTML5 collision with images
Can anyone please help me out with a small test game I'm creating. I'm basically creating this game to learn a few things about HTML5 and so far it's all been good. I've been able to create a canvas with a air balloon that can fly and drops to the bottom when it's not. Now I want the air balloon to be able to stop on another image, which I've called "level1". If someone could perhaps have a look at it, view the source and suggest how I would do this, I would appreciate it.

Or perhaps using images isn't the most efficient way to create a level. If it isn't then please say. Thanks again. :)

Here's the game.

# Answer
If your "level1" sprite is fairly simple, you can emulate this by create a number of bounding boxes around/over it, check when the balloon penetrates these bounding boxes, and push it back to a safe distance.

Else look into "pixel-perfect collision detection".
> 2 votes

# Answer
I think you need to combine two methods here. First check the bounding boxes of the platforms and the balloon. If the bounding boxes overlap, you have to do more accurate checking.

For the second step you have at least two options. You can check the bitmap of the ship (ctx.getImageData etc) against the platform. I guess here you could use the alpha value of each pixel. This is probably better option if you have organic looking levels/platforms.

Other option for the second step is to define simple geometric shapes representing the balloon and level. A circle for top, a triangle for ropes and a box for the basket and level. There are several tutorials online how to check collision between these basic shapes.
> 1 votes

---
Tags: collision-detection, javascript, html5
---


# Question
Title: Can I get around a Pokemon copyright with new art and minor changes?
If I develop a game that is essentially pretty much Pokemon (you're a trainer, you catch "monsters" and put them to fight and level up etc), and I do the next things:

* I'm a trainer with a 6-"Monsters" party.
* Mechanics like the PC, Gym Leaders and "tall grass" will be used.
* I will throw an "ball" to catch the weakened "monster".
* I will use common item names, like "potion", "high potion".
* The battles are almost the same as Pokemon in terms of mechanics (four moves, elements, critical, evasion etc)
* I will NOT use Pokemon names nor graphics... artwork is mine.
* Some of the attack names will match Pokemon attack names. I think it is okay, like "ember". Come on.

With all these points, I shouldn't run into copyright issues or anything right? Even if the game feels a lot like Pokemon itself?

# Answer
First, I am not a lawyer, this is not legal advice, if you follow my advice and get sued then it's your fault not mine.

That said, you've talked about "copyright issues". I'm going to break this down into two questions:

1) If I get sued for copyright infringement, will I win?

Probably! Game mechanics can't be copyrighted, so you're safe there. If "potion" isn't officially in the public domain then it's only one court case away from being so. "Ember" should be reasonably easy to defend - I know that ability name is used elsewhere. The "ball" is probably the sketchiest thing you've got, and if you just change the ball you're probably gold.

2) Will I get sued?

Maybe.

Unless you have a nice big legal war chest to rely on, getting sued is almost as bad as losing. You can't hope to match Nintendo's legal funds. It will not happen. You'll go to court, and you'll probably blow thousands of dollars *just on prep work*. And then even, if you win, there's no way you're getting that money back without a second court case - more money, and you're not even guaranteed to win that one.

So, as I see it, you have two realistic approaches ahead of you.

First, you can change things up enough so it's not as sketchy. Give your game a feeling of its own, not one copied from Pokemon. Don't use "gym trainer" and "tall grass", invent stuff. Instead of four abilities, use six. Give your PC a seven-monster party, and do something new with the monsters. Throw out two thirds of the Pokemon elements and make your own. (You're probably safe with "fire", but if you have "psychic", "bug", "rock", and "ghost", people will look at you a bit odd.) "Inspired by Pokemon" is safe. "Exact copy of Pokemon" isn't safe.

Alternatively: get legal counsel, get legal insurance, *and* form an official company to get at least a slight hint of the corporate veil going on. It'll cost you money, but it'll be a lot cheaper than being sued into oblivion by Nintendo, who will probably cheerfully drop the suit the instant you sign over all your intellectual property to them, and not a moment before.

Again, not a lawyer, not legal advice, get a lawyer.
> 15 votes

# Answer
Why bother?

It's pointless to clone a game widespread such as that one: doing so you automatically give away any chance of success for your game!

You risk getting sued to build something that will be worthless anyway? Why, lol, that's nonsense!

You'd better focus on actually creating something original instead.
> 11 votes

# Answer
Others have addressed the legal issues: copyrights cover code and artwork, not concepts; trademarks cover things like the Pokemon names; and patents can probably cover game mechanics, but that's unlikely to get you in trouble.

The issue I'm concerned with is the ethical one. This would be plagiarism. Ask yourself why you want to do this. Is it to learn to develop games? Then you should probably start with a smaller concept. Is it to make money? Then you are exploiting the creative work of Game Freak, essentially stealing their concepts for your own gain. Is it to demonstrate your own skills? Then you should do something original that will earn more recognition, instead of having people see you as a copier. Is it because you enjoy Pokemon and want to make a fun game? Recognize that your Pokemon clone will probably be much poorer than Pokemon, and that you've got a much better chance of success with an original idea.

In a comment, you ask "What's wrong" with cloning a complex game. It's unethical, and the reason you're asking about copyright is that you recognize that fact. If it's for personal education, go ahead, but there's little point in releasing such a thing.
> 7 votes

# Answer
Just a thought: couldn't this question itself potentially be evidence in a copyright-related trial? If I represented Nintendo, I know I would present evidence that portrayed you as negatively as possible. Asking how much you can get away with seems inherently sketchy to me. It suggests you intend to ride Pokemon's design coattails for easy profit, which isn't a good idea.
> 6 votes

# Answer
This is probably close enough that you should consult a lawyer, not ask on a forum like this. Copyright only covers tangible works for the most part, but that doesn't mean this isn't a trademark or other IP issue. Really if you are having doubts, that usually means you have crossed a line already.
> 4 votes

---
Tags: legal, copyright
---


# Question
Title: Can i tell if a Vertex Tree is a solid shape?
if a Vertex looks like this:

```
struct vertex {
    vec3 point;
    vertex [] connected;
};

```

Can I tell if this makes a solid shape with no holes? (e.g a sphere or a cube, NOT a sphere with a side missing for example)

(if i can see the back of a face from outside of the shape then it is not solid)

# Answer
> 7 votes
This is quite a tricky question.

My idea to test if an object has no hole is to check all edges and make sure they all belong to 2 different triangles. If an edge only belong to one triangle, it means it's a border of the whole surface, meaning there's a hole.

This could be harder if you have different vertex at the same position (for example to have different texture coordinates per face).

---
Tags: c++, 3d, mathematics, 3d-meshes
---