# Question
Title: Good way to play a sound when something happens? How does this sound?
So I was thinking about how monolithic my classes get a lot of the time. For example, in the `Character` class's `Jump` method, one may have a reference to a sound effect object and play that. By itself that is fine but when physics, animation, collision, etc. are taken into account, the Jump method gets huge and the `Character` class has a lot of dependencies to many different things. Still, this may be fine. However, what if we no longer want a sound to play when the character jumps? Now, we have to find that specific line of code in the jumbled mess of the `Jump` code and comment it out or whatever.

So.. I was thinking..

What if, instead, there was some sort of `AudioSystem` class and all it did was subscribe to random events it's interested in in other classes. For example, the `Character` class may have a `Jumped` event (static too, I suppose) that is raised within the `Character` class in the method. Then, the `Character` class would know nothing about the little sound effect that is played when the character jumps. The `AudioSystem` would just be a huge class that the programmer could retreat to to hook up sound effects with certain events that happen in the game through the use of static events. Then, if it got too big it could be separated in to subclasses like `EffectsAudioSystem`, `BackgroundAudioSystem`, `AmbientAudioSystem`, et cetera.

Then, in the options for the game, one could have a checkbox to enable or disable these sorts of sounds and all that would need to be done is just to disable that one system with a simple and single Boolean flag. This idea of systems could also be extended in to things like physics, animations, etc. to the point where most of the game responses resulting from player actions are hooked up through these elaborate and decoupled systems.

Okay, so my question may be a little vague, but how does this sort of thing sound? I haven't really ever heard of much kind of talk about this sort of system. This is all up in my head right now without any coding done so far so perhaps it's one of those "good in theory but not in practice" kind of deals. Would this kind of system work with a larger game or would it eventually break down and become even more of a spaghetti mess than the original system?

# Answer
> 2 votes
Messages are a hell to debug and maintain. It sounds good in theory, but once put in practice it gets messy with lots of duplicated data sending around. The jump-sound-effect will need a lot more data at the end, for instance the position, velocity, material the character is on, you name it, the list will be long at the end.

So either you will need to collect this data and send it to the AudioManager via a very specific event/message with the data copied in it or you will send a reference to the character in the message, so the AudioManager can access the data, both ways end up messy, and now the audio-manager has to choose a sound for the material-underground etc.

So at the end the specific event (which is a very specific class for only this message) will couple those classes very deep again. Not much won and at the end you will have a messy big list of very specific events/classes which only serve the purpose of sending data around, which exists already, and may be out of date and will suffer from all other problems of duplicated data.

So there will be a huge list of unnecessary classes to maintain which introduce a deep coupling between the character and the AudioManager, except now it is scattered all over the source-code. Not only in the Character- and AudioManager-classes.

Still a good idea to decouple your code, but Messages are really just another way of deep couplings. Some code just has to be coupled, use the most direct way to couple them, don't over-engineer.

# Answer
> 2 votes
I don't think a message passing system is over engineering at all. In fact it can make it dramatically easier to get things done in the polish phase. **You're doing it right!**

What you described is exactly what I threw together for our Global Game Jam game last year. I was responsible for creating and editing the SFX, and integrating music that myself and another composer wrote into the game in a way that didn't suck.

What's great about this approach from an audio perspective is that it allows you to do so many more interesting things with your sound. If you think a sound effect in a game is merely a sound file, volume, and panning, then you're doing it wrong.

## Example

For our game you were a dinosaur flying a spaceship running into planets to score points. We were working in Flash, so a data driven infrastructure wasn't needed. The AudioManager was a class consisting of a bunch of static methods whose sole purpose was to control what sounds happened in response to a game event.

If I were to write it in C++, then it would have taken a bit more time to abstract all the possible behaviors sounds could have. The requirements for a message notifying the system an action had taken place wouldn't be too complicated. It would just need the message type, the object of origin or object being affected, access to some kind of game state context, and not much else. The protocol could grow as the game's needs grow. Naturally, if you do all of this in implementation in code (like our shoddy GGJ code), you have a worse monolithic class problem. But that's easily mitigated by making a data-driven system.

Anyway, here's how our game audio system reacted to various messages:

* **Player collides with planet:** This would trigger a planet explosion sound, basic enough. then immediately after it would query the running combo counter. If it was high enough it would schedule a sound effect to be played half a second or so later of the dinosaur doing a victory roar. Also in the background a random planet population value was calculated (something like 600 to 3000--I have no idea why that range was chosen, it was some abandoned gameplay mechanic and still lying around for me to use to make the audio interesting), and so I used that to scale the volume of the distant sound of screams (planetary citizens meeting an untimely fate).
* **Player holds spacebar for acceleration:** Upon receiving this a little "whoosh" thruster sound was played, but also simultaneously a low looped engine roar ramped up over 1.5 seconds. The particle system also used this to fire an emitter IIRC
* **Player lets go of spacebar for deceleration:** Now that the player had let go of the spacebar, the audio system knew it had to ramp the engine loop back down. If I had more time I would have liked to layer another sound over it that was a sort of whining pitching down type of sound.
* **Player collides with evil space mine:** Space mines are bad, so not only is there a metallic impact sound combined with an explosion (that's just baked into one sound), but there's also a randomly selected dinosaur dismay sound that plays. It's more likely to choose more "crying" like sounds as the player's health gets lower.

An already fun game becomes a delight to play when its soundtrack is active and dynamic, even with just little simple behaviors like I described above. Yes there are some logistics to work out with making sure the correct data gets passed. But hey, BFD. It will be far from the most complicated thing you have to write in the larger scope of the game code.

In fact, FMOD and Wwise work like this. They don't have a central message dispatcher, but you effectively post events to their central systems and they react by playing a sound effect that was pre-designed by an audio implementor in an authoring tool. Think of it like giving your game a live DJ. He sits and watches what's going on, and triggers sound clips at the right times to keep things interesting, mixing them so they fit well into the preexisting audio environment.

\[EDIT\] Also, I see you've tagged this C#. Is this XNA, and if so are you using XACT? *If you are using XNA you should be using XACT.*

# Answer
> 0 votes
I agree with Maik Semder, that a message passing system may be over-engineering (for now anyway).

From what I understand, your class currently looks like the Bjorn "monolithic class" as can be seen in "A monolithic class" here.

I suggest you read that article, and, although a full component system would be overkill for now, if you read to "Splitting out the rest", that should give you a good way to abstract your behaviors and eventually maybe move to a more complex solution. It will give you a good base to start from anyway.

---
Tags: c#, architecture, sound
---


title: Pop up screen on libgdx

text:
# Question
Title: Pop up screen on libgdx
Hi I want to make a pause and credits screen for an android game with libgdx the idea I have is creating a new screen like a popup that pauses the background screen and then, I can render the screen I want to show. Please give me some info or ideas for this.

# Answer
Introduce a state variable. When the state is paused and not running draw a scene2d stage with the elements of your pause screen. Unpausing sets the state back to running, which then starts rendering and updating your game screen.

The overlay or popup effect can be achieved through an image.

So in short: use a switch case statement on the game state in your update and render methods.
> 4 votes

---
Tags: android, libgdx, screen
---


# Question
Title: Unable to find good parameters for behavior of a puck in Farseer
**EDIT:**

I have tried all kinds of variations now. The last one was to adjust the linear velocity in each step: `newVel = oldVel * 0.9f` \- all of this including your proposals kind of work, however in the end if the velocity is little enough, the puck sticks to the wall and slides either vertically or horizontally. I can't get rid of this behavior. I want it to bounce, no matter how slow it is. Retitution is 1 for all objects, Friction is 0 for all. There is no gravity. What am I possibly doing wrong?

In my battle to learn and understand Farseer I'm trying to setup a simple Air Hockey like table with a puck on it. The table's border body is made up from:

```
    Vertices aBorders = new Vertices( 4 );
    aBorders.Add( new Vector2( -fHalfWidth, fHalfHeight ) );
    aBorders.Add( new Vector2( fHalfWidth, fHalfHeight ) );
    aBorders.Add( new Vector2( fHalfWidth, -fHalfHeight ) );
    aBorders.Add( new Vector2( -fHalfWidth, -fHalfHeight ) );

    FixtureFactory.AttachLoopShape( aBorders, this );
    this.CollisionCategories = Category.All;
this.CollidesWith = Category.All;
this.Position = Vector2.Zero;
this.Restitution = 1f;
this.Friction = 0f;

```

The puck body is defined with:

```
FixtureFactory.AttachCircle( DIAMETER_PHYSIC_UNITS / 2f, 0.5f, this );
this.Restitution = 0.1f;
this.Friction = 0.5f;
this.BodyType = FarseerPhysics.Dynamics.BodyType.Dynamic;
this.LinearDamping = 0.5f;
this.Mass = 0.2f;

```

I'm applying a linear force to the puck:

```
this.oPuck.ApplyLinearImpulse( new Vector2( 1f, 1f ) );

```

The problem is that the puck and the walls appear to be sticky. This means that the puck's velocity drops to zero to quickly below a certain velocity. The puck gets reflected by the walls a couple of times and then just sticks to the left wall and continues sliding downwards the left wall. This looks very unrealistic.

What I'm really looking for is that a puck-wall-collision does slow down the puck only a tiny little bit. After tweaking all values left and right I was wondering if I'm doing something wrong. Maybe some expert can comment on the parameters?

# Answer
> 2 votes
The solution was finally found in the Box2D forum. The negine has a velocity threshold. If velocity drops below that it is set to 0. The default value is 1.0. I changed it to 0.1 and voilà it behaves correct, even when using linear damping.

The constant is defined in `FarseerPhysics.Settings.VelocityThreshold`

# Answer
> 0 votes
You need to raise your restitution value, to stop the puck from sticking. The restitution value determines the "bounciness" of your puck when it hits the wall.

A Restitution value of 1 meaning a perfect elastic collision.

Whereas, a value of 0 would mean a perfect in-elastic collision (Doesn't bounce at all).

Reference: http://en.wikipedia.org/wiki/Coefficient\_of\_restitution

# Answer
> 0 votes
The Farseer Physics Engine is an extension of Box.2D and as such you can use the extensive documentation available for Box.2D most usefull of which is the manual.

> Damping is used to reduce the world velocity of bodies. Damping is different than friction because friction only occurs with contact. Damping is not a replacement for friction and the two effects should be used together.

Personally I keep my damping pretty high as I'm simulating characters via hit boxes and I don't want my people to bounce. However, in you case I believe the dampening setting is high enough to cause the issue you describe.

Try setting the damping to something along the suggest lines of around a tenth.

> Damping parameters should be between 0 and infinity, with 0 meaning no damping, and infinity meaning full damping. Normally you will use a damping value between 0 and 0.1. I generally do not use linear damping because it makes bodies look floaty.

---
Tags: box2d, farseer-physics-engine
---


# Question
Title: Relating a point after an image is panned and zoomed
For Android, let's say you have a image of a map that you draw inside your view. On this map there are many, many "hot spot" locations where you want your user to be able to select. Given that there are so many, you want to give the user the ability to zoom the image, and since it can be zoomed, they need the ability to pan the image too.

Once the user pans and zooms though, the coordinates that originally related to the hot spots have changed since the location the user touches will be based on the view, not the image.

How do you translate the new coordinates back to what they would have been originally before the panning and zooming were done?

Here is the question asked on JavaRanch which may make this more clear:
http://www.coderanch.com/t/567402/java/java/translation#2577725

THANKS!

---

> You're trying to do a coordinate transform, yes?

No, not in the sense that I am doing anything like what I THINK you mean.

> What you need to do is apply the transform from the map space to view space in \>reverse, or rather undo said transformation.

Hmmm...there is no "map" per se, just the Android screen (the view port I guess you could say) and the image drawn onto it which CAN become larger than the screen.

> First store the location and magnification of your viewing area or camera somewhere.

Well, there is no "camera" as in what I think you mean. This isn't 3D, just 2D. The original magnification is 1. Not sure what I would need to store in this case.

> Assuming you store the magnification as something like real units/view units or area \>of map/area of view. You can then convert from view in magnified units to real units \>by doing screen location\*magnification. Divide if your ratio is flipped.

Real units? I'm dealing with pixels on a phone.

> Now that you have the location relative to the screen in real units you simply do \>camera location + relative location which gives you your map location. This does \>assume that camera position is in the map coordinate system.

Again, there is no camera position. This is just a phone with an image on it. No 3D. Just a human looking at an image on a phone.

> For camera to world transform: (location * magnification) + camera position

So given that there is no camera, what would be used here instead?

> For world to camera transform: (location - camera position)/magnification

Again, I am not sure that this is applicable here as there is no camera to have a position.

> remember the \*/ signs flip for view/real rather than real/view
>
> For something more elegant look into how graphics systems do coordinate transforms. \>For a 2D system without rotation I think the above is sufficient though.

I really appreciate the effort but I do not see this answer as answering the question. If you look at the code I linked to, I think the question will become much more clearly defined.

It's just an image on a phone that the user can pan and zoom. I keep a pan and a zoom multiplier around and know the touch point on the screen. No camera, no world coordinate system, nothing like that at all. Just an image on a phone that can be manipulated.

# Answer
You're trying to do a coordinate transform, yes? What you need to do is apply the transform from the map space to view space in reverse, or rather undo said transformation.

First store the location and magnification of your viewing area or camera somewhere. Assuming you store the magnification as something like real units/view units or area of map/area of view. You can then convert from view in magnified units to real units by doing screen location\*magnification. Divide if your ratio is flipped.

Now that you have the location relative to the screen in real units you simply do camera location + relative location which gives you your map location. This does assume that camera position is in the map coordinate system.

For camera to world transform: (location * magnification) + camera position

For world to camera transform: (location - camera position)/magnification

remember the \*/ signs flip for view/real rather than real/view

For something more elegant look into how graphics systems do coordinate transforms. For a 2D system without rotation I think the above is sufficient though.
> 4 votes

---
Tags: 2d, android, java, mathematics
---


title: Moving a sprite over a tile map

text:
# Question
Title: Moving a sprite over a tile map
I am working on a tile based game in Java. I have a 2D array of tiles (JComponents) in a GridLayout, this is fine for creating the world (I think), but I am stumped at how to move the sprite smoothly between tiles. Currently, each JComponent tile draws the world and the sprite in accordance with booleans representing state (i.e. to show the sprite or not to show the sprite), however, this is not smooth. The sprite simply disappears from one tile and appears in another.

Any ideas on how I could go about moving the sprite in a smooth manner?

I am new to the whole game dev thing, so please be patient.

Regards, Jack Hunt

# Answer
> 1 votes
If you wish to stick to the JComponents in a GridLayout approach (suggestions of the top of my head):

Make the sprites into components of their own.

Make your own container and override the layout functionality. Make the tilemap-container and any sprites children of this container.

Override `doLayout` to make the tilemap-container fill the available space (or something else, up to you), then position the sprites as wanted (or not, your choice, they might already be placed correctly by some other function). Make sure the tilemap-container is at the bottom (using `setComponentZOrder`).

The sprites now have position independent of the map and are drawn on top of it.

Edit: Alternatively you can create a layout manager that does this (i.e. instead of overriding `doLayout`), and use that. And now that I think about it that may be the more "correct" way of doing it. I have an idea for how to do this nice and easy but it's 3 in the morning and the margin's too small.

---
Tags: sprites, tiles, tilemap
---


title: Quality Current Free UDK Tutorials?

text:
# Question
Title: Quality Current Free UDK Tutorials?
I'm just getting started with the UDK, with experience in Unity, and would like a good tutorial series about getting to know my way around the basics of level design and a touch on programming. I have found some basic tutorials on level creation, but they are pretty old, and would like to know more.

Thank you!

# Answer
> 3 votes
Normally I would say this question is too broad and off topic for this site, but since there is one definitive answer to your question I'll give it: Google it

That being said I like these http://www.worldofleveldesign.com/categories/cat\_udk.php

# Answer
> 2 votes
Eat3d has a many high quality UDK tutorials then anybody else. Gnomon has 2 good tutorials on level creation and material.

Raven67854 on Moddb had created huge number of UDK tutorial on some very interesting topic that the commercial trainings doesn't cover. like , Fracture.

Before buying any try these tutorial first. These are from 3dbuzz and now they are **freely** available on UDN. Also check out other tutorials from 3dBuzz.

As always google and look into youtube for specific topic. Dont forget about, UDK forum. Its very active.

Hope this helps you to have a good start!

# Answer
> 0 votes
try checking out the youtube channel thenewboston, he went into quite a bit of content on using UDK. http://www.youtube.com/user/thenewboston

---
Tags: level-design, udk, unreal
---


# Question
Title: How hard is it to build for other platforms using the Unreal Engine 3?
Quick question to those that have used the Unreal 3 Engine for development. (Not the UDK).

How much work would it take to take a game made on/for Windows and output a working build on another platform?

Is it as simple as "File -\> Export -\> PS3" (or similar) or is there much programming involved?

# Answer
> 4 votes
Assuming that you have not done any source code modifications to the SDK itself and have built your game from scripts, then it's simply a matter of letting Unreal prepare the packages for the different platform.

Note that this is if Unreal supports the platform you're porting to, if not then you'll obviously have to modify the code that packages the data for runtime use and write new low level hardware handlers.

Building a game that works with different control inputs (keyboard vs. gamepad for example) and designing a GUI will be where most of your work time programming is spent after the hardware support is decided. That schedule is no different for Unreal than any other port, you can do a cheesy job fast or a proper redesign for the platform depending on your needs.

Finally you will have to handle the new platform's TRC (Technical Requirements Checklist) needs and submission+approval needs and it would be a big mistake to not factor in that additional work.

Summary: "how much work" and risk analysis are entirely dependent on your dev team and source project quality so I tried to give broad strokes to cover the main issues - but don't have a real answer to your specific question.

# Answer
> 1 votes
Technically, this should be a fairly easy thing to do. Not as easy as the list of steps you had up at the top, but pretty close. This is only because that the underlying hardware compatibility between the different environments (PC and PS3 are the ones in the example) are to be provided via the Unreal 3 engine from Epic. They tout that they have already done a significant amount of the work, knowing where to do the visual effects on the PS3 vs where they are done on the PC and the like. Writing an independent API for playing sound effects that either gracefully downgrades or has parallels for the different effects that can be done.

Now, If you are wanting to know how much work and effort it takes for a team to port their engine to another platform, then I refer you to Patrick Hughes' post as that starts to go into more detail there. However, I do believe you will find that one of the selling points of the Unreal 3 engine is multiple platform support.

On a side note.. if you go back to the announcement videos for the PS Vita (was that really last summer?) you can see an clip talking to the team behind Dungeon Defenders where they state it took them about a week to tweak their game to get it running on the PS Vita.. Of note, their game happens to run on the Unreal 3 Engine (and has already been released on iOS, Android and PC I believe... I own the iOS and PC versions at the least :))

---
Tags: unreal, cross-platform
---


# Question
Title: Is a frame-rate jump in my C++ iPhone game a show stopper and how do I find its cause?
Every 5-10 minutes there's a noticeable frame-rate hiccup in my game. Other than that my game runs very smoothly - again it's just one quick little jump every 5-10 minutes. Is this something I need to iron out or is it not a big deal?

How can I find what's causing this glitch? Is there a specific instrument I should use?

Here's some additional info:

* It happens less on an iPhone 4 compared to a 3GS.
* All my game objects use dynamic memory allocation with the default new and delete operators. I'm not using shared pointers. There are no memory leaks.
* The game is of the shmup genre.

# Answer
> 15 votes
One of the most important skills to learn as a programmer is how to locate and fix performance problems. The good news is that this process is easier today than it has ever been in the past. As mentioned in the comments, a frame rate stutter of 0.5 seconds is completely unacceptable for any game which demands reflexes from the player, so this is a great excuse to learn this skill that you'll use for the rest of your programming career.

My advice is that you ignore all the assumptions and random guesses that people are putting forward. You don't have to guess at the problem, you can just measure your own performance and know the problem for certain. For an iPhone game, all you have to do is run your game through Instruments. Just choose the menu option: **Profile** from the **Product** menu in Xcode.

This will build your program, launch it on device, and then start Instruments. Instruments will pop up a window asking what sort of profiling you want to do. It'll look a little like this (note that I'm profiling a MacOS app for my example, as I don't have an iOS project on hand to use for screenshots. When you do this, you'll choose **CPU** *Time Profiler* under the *iOS* heading, instead of MacOS X)

Then run your game until the stutter happens. After it does, go back to Instruments and hit the pause button. Instruments will look something like this:

The horizontal graph along the middle is how much CPU time was being used over time. You can see that my game used extra CPU time while launching (which I've highlighted in a red box), and that there was a spike of processing time a little later on (highlighted in a green box).

Additionally, the display at the bottom shows where your game is spending most of its time. The most important numbers are the percentages, which I've highlighted in a blue box. In this case, you can see that 3.2% of my time is spent inside of a function called *memmove*. (If I opened that up, I could see where I was most often calling that function from)

Now, those numbers are from the full runtime of my program (about 30 seconds in my case. Yours might be five or ten minutes, or however long it takes for your stutter to happen). So if you have a half second pause in five minutes of game play, the culprit probably isn't going to show up with a high overall percentage in your profiles. But luckily, you can tell Instruments precisely which bit of the timeline you're interested in by using the **Inspection Range** tools:

As you can see, I've now drilled down to see precisely what's slow at this specific point in my game. Looking at the output, we can see which bits of code are taking the most execution time. While 'memmove' was showing up as 3% of my time in total, in this bad performance spot, it's taking up more than 11% of my CPU time. In this screenshot I've expanded 'memmove', to show how you can see what functions called into the problem function.

Now in my case, what I'm using as an example isn't a real spike like yours; it's just me doing something that's a little more computationally expensive than when the game is idle; my game is still running at 60fps through this period. Yours would have a vastly taller peak in the graph, and instead of having a top item that's using 10% CPU, you'll probably have one that's using 50% or more. I've often seen spikes where a single function used 70% to 80% of CPU time.

Following these steps will help you determine -- with extreme accuracy -- exactly what it is that's using up time, so you'll know what part of your program to think about trying to optimise.

But if you can't figure out how to speed up that problem area (whatever it turns out to be), then do open another question to ask about how to improve that specific thing.

Finally, it's important to note that this answer is only barely scratching the surface of what Instruments can do. It is absolutely worth your while to look through Apple's documentation to learn even more options to drill more deeply into the performance metrics it can gather on your game.

# Answer
> 3 votes
The behavior sounds like garbage collection which is odd. I assume you're not doing any background loading or other stuff like that, or you'd have mentioned it.

The fact that iphone4 fares better than 3gs may either be because iphone4 has a faster CPU or the fact that it has more RAM ( http://www.labnol.org/gadgets/compare-iphone-4-with-iphone-3g/13855/ ).

Generally speaking, performing dynamic memory allocations in real-time applications is a no-no, so you should avoid it as much as possible. Keep buffers around, re-use them as much as possible. If you're using vectors, don't delete them, just empty (not resize) them.

# Answer
> 1 votes
Whether or not you need to fix that is up to you. On my projects, the definition of a show stopper has been whether or not it affects the gameplay or causes data loss. Is it something that would cause a player to crash their ship or end their game when it happens?, If this bug happens, does it nuke a player's game save?, etc.

You could try using the memory allocations instrument and see if you have any spikes in memory when that hiccup occurs. That was a problem in my last game - it would run smoothly like you've described, but hiccup after a while because I had run out of cached enemies to display, and the game engine loaded a few more up.

# Answer
> 0 votes
Have you tried initializing your std::vectors to a large size when the program starts up?? If the frame rate hiccup is related to a vector resize inside the game loop, this may help identify the issue.
You could also log your vector size, calculated frame rate, and a time stamp to a ring buffer in memory as your program runs. The goal here is to see if there is something "magical" going on within your game loop when you detect the drop in frame rate.

---
Tags: c++, iphone, frame-rate
---


# Question
Title: Benefits of attending highly selective colleges
I live in a pretty high-income community where teachers and parents tell you that if you ever hope to have a good income, you have to go to a good, selective college. However I'm one of the few kids at my school who has developed a love for programming software *(and games on occasion)*, and I've never had a teacher that's even understood computers; so I'm wondering if this statement is true for this the software profession as well.

**How much of a difference does attending a highly selective, generic school make when entering the software or game development profession?**

I've also found that almost any and all information on software development can be found on the internet or in a book. Which makes college *almost* seem unnecessary.

**How important is it to go to college at all when entering these professions<br>or starting your own software or game company?**

please try and give sources of information =)
**Thanks**

# Answer
> 3 votes
I've worked with about 50 different game programmers in the last 5 years, all of them have a bachelors in CS or Math. I can tell you that most interviewers don't care much about the exact school you went to, they care more about experience, and skills that you have. It's somewhat of a double standard, most interviewers want you to have at least a bachelor's degree, but they could really case less which school you got it from. Without a degree I would estimate that you'll miss out on more than half of your job opportunities just due to not even getting an interview. To properly cover your bases in the case where game programming doesn't work out for you, I would recommend a decent 4-year college that focuses particularly on computer science in some way, this will leave you with a degree that you can use for programming in any field. There are some colleges that offer degrees specific to game programming, however they're rarely accredited and you'll be left with a degree that makes it hard to move to non-game programming.

Apart from just the college, here's some general advice for getting into the industry. If you want to get into game programming I suggest determining which part of game programming you enjoy most and want to focus on, and spend time on that (e.g. A.I., physics, gameplay, graphics). Become an expert in that specialty, learn cutting-edge techniques, make demos and videos for a digital portfolio, and learn the languages that most companies are looking for. Also, keep in mind that most colleges you choose from will be teaching programming practices in general, not something specific to games, so you're going to have to take the initiative to apply the programming you learn to learning how it applies to games, in your spare time.

The language(s) and game engines you choose to learn will likely be based on the type of games you want to focus on. If you want to make web-based games then something like Flash, Unity (C# and Javascript), HTML5, and WebGL would be the likely choices. If you want to make AAA game titles for PC, Mac, and/or consoles then C++ is probably the most used. If you're making mobile games for platforms like Android or iPhone, C++ (iPhone), and Objective-C (iPhone), Java (Android-based devices), and Unity (iPhone and Android) are good choices.

I highly recommend looking through job listings at all kinds of gaming companies around the country, see what kinds of things they're looking for, find out what is most in demand so that you choose a specialty that is more likely to land you a job. Also be mindful of the future, technology is always changing very rapidly. The iPhone came out a little over 4 years ago, if you had just graduated from a 4-year college today the gaming industry would already be vastly different than when you had started school. Make sure you choose to learn languages and skills that will be relevant 5-10 years from now, not ones that are on their way out the door already.

# Answer
> 2 votes
The one thing that going to college will definitely establish is that you're capable of taking a 3 or 4 year project and sticking with it to the end. I'm not sure about the selective part - so long as they have a reasonably good reputation and teach the right kind of stuff I don't think you need to be overly concerned about that.

For programming, yes - you can learn almost everything online or in books. The danger is that you'll pick and choose the things you find interesting yourself and focus on them. There is a *lot* of (on the surface) boring groundwork that you need to focus on too, and some measure of more formal learning will help you discipline yourself to that.

A final advantage I can think of is that you can select to learn some topics outside of the programming sphere, which will give you a much more well-rounded experience.

# Answer
> 1 votes
I quickly dropped out of college and started making games after high school. That played a big role in getting my first job as a programmer where I did a lot of UI work. I grew that job as much as I felt I could, and began making a considerable amount of money there. I've since started working on mobile games on my own, building on the knowledge I've earned along the way.

My story might sound successful to some, and to others it might not. Whether I should have gone (or still should go) back to college is for the gods to decide. I will say this, though: it's my drive and passion that have allowed me to succeed as well as I have. I'm firmly of the opinion that in this industry, you can get by without higher education so long as you have a relentless thirst to grow and learn.

# Answer
> 0 votes
Take this with a grain of salt, i'm nobody to be saying this like it's a fact. Also, i don't understand what do you mean by sources, try looking at job offers, see what they want.

A generic college is going to teach you little to nothing about making games, however it'll teach you all the "boring" parts that you'll need to be good at making games, this means math, operating systems, databases, low level programming, algorithms, software engineering, amontst others. The way i treat my college is, i'll take a bit from every part of the industry, but i'll devote my free time to what i think is going to make me good at what i love, which is making games. You should be a part of an open source project, or working on your own projects. For me, college is just an extra 4 years of alot of free time to do my own research. A degree doesn't hurt, but i rarely hear a story where a degree makes or breaks the deal, you usualy take tests and do interviews, there are dropouts in the industry that are great coders and designers, but this shouldn't be an excuse to anybody. The game industry takes a specific kind of a person and people who do recruiting know it.

If you're ever unsure, look at job offers on gamasutra and other sites. There's plenty of different jobs that require different skills.

# Answer
> 0 votes
My perspective: I'm a student at NYU, been heavily involved in game development since sophomore year, worked on several projects, and I'm graduating from university this semester.

Fundamentally, successful people will be successful. There's no getting around that. If you have a shiny CS degree and 4.0 GPA from UC Berkeley, you may still get passed on for a game programming job by someone from Some Lesser Institution Of Learning(TM) if they're able to demonstrate strength in the skills and knowledge required for a position--especially if they have a cool playable portfolio. People in other industries may be impressed by where you got your degree from, but it seems like game people care less about it on average.

I'm attending one o'them debt monster "selective" colleges. I feel if I had gone to a less prestigious university back in my hometown, I still would have learned fundamentally the same things. However, what I'm really paying for is connections and opportunities that I might not be able to get at another school. Of course, all schools have opportunities and connections, they just have different types of opportunities and connections.

For example, I'm loving it in NYC, but large game studios tend not to last long here. I'd like to work at a large game studio to get some experience working on AAA games. This may have been easier had I been going to school in a location with those kind of studios around. Similarly, since NYC is obsessed with tech startups, I've been immersed in that environment. The location in which you study can influence the paths you take.

Of course you could always skip school and just move to an ideal location. But then you've gotta figure out rent and find a job right away, and maybe you still need to spend time building your portfolio and doing your independent study. It's doable, but college kinda puts you in this not-really-adult world where you can put a few of the real world concerns away for a bit while you learn.

**TL;DR** Location matters. Don't be lazy. Also, college is great!

# Answer
> 0 votes
This so much depends on so many things that there simply can't be a definite answer. Some communities value college more than others, and college costs more in some places than others.

Others have covered a lot of ground, but I'll give my couple cents.

Even if games is all you'll ever want to make, get a real education. What you study doesn't matter at all. Don't take comp sci if it isn't what you really want. You can study anything at all and get into games, as long as you have the drive to make games. In fact, having a medical, social psychology, history, philosophy or just about any unrelated degree combined with experience in programming might give you a better base for making games than your generic "game industry" school.

The world really needs more cross-dicipline people.

And to top this off, let's say you do end up making games, and find yourself in a situation not too uncommon, that it's not all that you expected it to be. Finding a "real job" with a "game" degree is bound to be more difficult than getting a "game" job using a "real degree".

# Answer
> 0 votes
For junior candidates, the best people I've seen usually come out of game development focus institutions (Guildhall, Digipen, that kind of thing), or have done work experience type stuff on their own (mods, solo projects). A Computer Science degree doesn't really prepare anybody for the practical matters of programming games.

In my experience, going to those kinds of schools is going to be more of a detriment than anything else. Getting into an MIT or the like might show something of value, and might put you higher up on the resume-responding priority than somebody who went somewhere else, but any good hiring process is going to weed out people who program like mathematicians (i.e. poorly).

On top of that, game programming is historically lower paying than other software engineering positions, so getting a really expensive degree really isn't worth it.

The benefit of going to those prestigious colleges is not the value of the degree itself, but the connections you make with smart and wealthy people. If you're not using that to your advantage, then you're kind of wasting the whole point.

# Answer
> 0 votes
> I've also found that almost any and all information on software development can be found on the internet or in a book.

This is true of almost every discipline known to mankind.

> Which makes college almost seem unnecessary.

But this conclusion is not.

Information itself is only part of the answer. The other parts are:

* Learning how to apply that information in practical situations;
* Showing you information that you might not have realised was relevant (eg. I learned about database normalisation, radio network collision resolution, web programming, and formal proofs of correctness - all of which have proven useful in gamedev, yet few of which would be something a self-taught game programmer would seek out)
* Repeated use of the information so that you have actually learned it, and don't need to refer back to books every 2 minutes;
* Testing to ensure you understand the key points;
* Getting feedback on how you have used the information to ensure you haven't misunderstood it;
* Seeing for yourself which information is good or bad, or which is most applicable to your situation;
* Experience of working with others towards a common goal;
* Experience of working to deadlines;
* Experience of having to concern yourself with the quality of your output;
* Receiving written certification from a trusted authority that you have mastered all of the above to a recognised standard.

All that stuff is priceless. Can you get a games programming job without it? Certainly - almost anything's possible. But you will have stacked the odds against you.

---
Tags: jobs
---


# Question
Title: Is Android not good for game development?
As I know Android is running on Java VM on top of Linux kernel. These so many layers may lower down the performance (FPS,etc.). Is Android still good for game development then?

# Answer
In Android, java files are compiled into class files via javac (as usual). Next, the dx tool converts the class file into a "dex" file. The dex file is optimized for mobile devices. Android's Dalvik virtual machine on the device runs the dex files. Dalvik uses a register based architecture (Java JVM is stack based). You can learn more by reading the performance section of this article: http://en.wikipedia.org/wiki/Dalvik\_(software)

Each application running under Android gets its own Dalvik virtual machine as a Linux process. To speed application start up and to minimize memory footprint, Android has a Zygote Dalvik virtual machine that is created at boot up. The Zygote instantiates the core library classes. The Application VMs connect to the Zygote following a binder IPC pattern (see https://stackoverflow.com/questions/4936531/do-apps-using-multiple-processes-share-a-dalvik-instance). The application's VM is forked from the Zygote so that it has the common libraries already mapped.
> 1 votes

# Answer
Keep in mind Android does let you run native code. If you don't want the Java layer, you don't have to have it for the bulk of your project.

(Some of the vital Android APIs are Java-only, but you can always set up a thin wrapper.)
> 1 votes

---
Tags: android, frame-rate
---


# Question
Title: Why might render target in DirectX9 fail to work?
I'm trying to render to a texture, but nothing is being drawn. Everything before SetRenderTarget is rendered properly, everything after second SetRenderTarget is visible on the screen. Just the part that should have been rendered to a texture is ignored.

Below is a Delphi code showing what I'm doing. What am I missing?

```
//Random texture size, non-power-of-two textures supported by card
//Tried with 512x512, same results
FStaticWidth := 806;
FStaticHeight := 413;

//Error checking code left out for clarity
//But every operation is checked

//Create texture
dev.CreateTexture(FStaticWidth, FStaticHeight, 1, D3DUSAGE_RENDERTARGET, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, FStaticText, nil);
FStaticText.GetSurfaceLevel(0, surf);

//Save everything;
dev.GetViewport(oldVp);
dev.GetRenderTarget(0, oldTarget);

//Change render target
dev.EndScene;
dev.SetRenderTarget(0, surf);
dev.BeginScene;

//Reset viewport
vp.X := 0;
vp.Y := 0;
vp.Width := FStaticWidth;
vp.Height := FStaticHeight;
vp.MinZ := -1000;
vp.MaxZ := 1000;
dev.SetViewport(vp);

//Draw
dev.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $FF112233, 1.0, 0);

//...whatever I do here, it's ignored.
//It doesn't appear neither on the surface, nor on the screen.
//Not even dev.Clear() above works.

//Restore render target
dev.EndScene;
dev.SetRenderTarget(0, OldTarget);
dev.BeginScene;

//Restore viewport
dev.SetViewport(oldVp);

//Dump the texture to a file
D3DXSaveSurfaceToFileW(PWideChar(AppFolder+'\static-surf.bmp'), D3DXIFF_BMP, surf, nil, nil);
//The file is a FStaticWidth x FStaticHeight bitmap,
//containing only black transparent ($00000000) pixels.

```

Here's how it looks like in PIX:

```
12570   <0x05AC9EA0> IDirect3DDevice9::GetViewport(0x0018FD40)
12571   <0x05AC9EA0> IDirect3DDevice9::GetRenderTarget(0x00000000, 0x0018FD80 --> 0x05ACA9B8)
12572   <0x05AC9EA0> IDirect3DDevice9::EndScene()
12573   <0x05AC9EA0> IDirect3DDevice9::SetRenderTarget(0x00000000, 0x05B53878)
12574   <0x05AC9EA0> IDirect3DDevice9::BeginScene()
12575   <0x05AC9EA0> IDirect3DDevice9::SetViewport(0x0018FD58)
12576   <0x05AC9EA0> IDirect3DDevice9::Clear(0x00000000, NULL, 0x00000003, D3DCOLOR_ARGB(0xff,0x11,0x22,0x33), 1.000f, 0x00000000)
12577   <0x05AC9EA0> IDirect3DDevice9::EndScene()
12578   <0x05AC9EA0> IDirect3DDevice9::SetRenderTarget(0x00000000, 0x05ACA9B8)
12579   <0x05AC9EA0> IDirect3DDevice9::BeginScene()
12580   <0x05AC9EA0> IDirect3DDevice9::SetViewport(0x0018FD40)

```

Render target 0x05B53878 remains empty (transparent black) after each event.

# Answer
Solved. You have to set DepthStencil surface along with RenderTarget, and those have to be of the same dimensions and formats.

```
FStaticText.GetLevelDesc(0, desc);
dev.CreateDepthStencilSurface(FStaticWidth, FStaticHeight, D3DFMT_D16,
    desc.MultiSampleType, desc.MultiSampleQuality, true, FStaticStencil, nil);

//...
dev.GetDepthStencilSurface(oldStencil);
dev.SetDepthStencilSurface(FStaticStencil);

//...
dev.SetDepthStencilSurface(oldStencil);

```
> 0 votes

---
Tags: directx
---


title: Using Sampler States in Effect file

text:
# Question
Title: Using Sampler States in Effect file
I have been reading a lot of different shaders and some have the preference of:

```
sampler depthSampler : register(s1);

```

Whilst others take the longer route:

```
texture depthMap;
sampler depthSampler = sampler_state
{
    // etc.
};

```

Is there any *real* difference between the two? Does one perform faster than the other?

# Answer
> 3 votes
Zacharmarz briefly touched on it in his comment; however, it's less about performance and more about configuration.

In the first example the sampler state is left uninitialized and works just like any other parameter (e.g. your `WorldMatrix`) - this would allow your game to change the sampler at runtime. Conversely your shader won't work if you don't initialize the sampler. Most often you will see this syntax in conjunction with custom `SpriteBatch` shaders as they would allow the `SpriteBatch` to provide crucial configuration.

In the second example the sampler state is 'hardcoded' into the shader. This means that once the shader is compiled it's set in stone - your game can't change it if it needs to.

Both techniques are just as viable as the other - it all depends on how you intend to use the shader. If you need the sampler configurable use the first, if you require that the sampler is always in a predictable state use the second. It is much more likely that you will be using the second method.

---
Tags: xna
---


title: How do RPG store and retrieve maps?

text:
# Question
Title: How do RPG store and retrieve maps?
I'm making a very basic online RPG (2d, and instead of sprites I use characters, like a roguelike) and I still haven't figured out how to store and retrieve maps. Until now I used a text file that are stored on the server. Should I store the map in the database and retrieve it as the player moves around? For example, if the player is in the position `[x, y]`, load all the tiles within a 15 tile radius.

Or maybe dividing the map in "sections" and then, depending on the player's location load a given section? Which is the best option?

Also, if I was to save the map in the database, which is the best data type to store it as a bi-dimensional array? `BLOB` maybe?

# Answer
> 4 votes
It would be better if you knew what kind of change will be involved. If your world is quasi-static you would like to distribute the basic map to all your clients and to comunicate the changes only to player that visit an area: this allow you setup map distribution services that don't use the same bandwith of your game server.

In this case you can validate the client version at login and redirect the user to the map sources if major changes to maps where happened since the last login.

The story is completely different if the contents are fully user generated.

In both cases you have to split the world in chunks: you probably do not load the whole world in memory when you render it. Don't do the mistake to size the map chunks tailored to the client needs, changes to client should not affect the server: add a level of indirection, the client probably have to load a few of chunks to work smoothly.

If you are on the web and you like to let your users to generate a lot of content, you may try to use couchdb as database backend. Using Couchdb you get a rest json based api, filtrable change notifications and using indexes you may look up the data fast.

The main advantages are the unstructured data and the near real time scalability. The first one let you to add data in a way that client can process only if they know how to, backward compatibility or ligth/full compatibility for example; the latter let you build a system that can grow from a couple of user to thousands.

This comes at the price of system design, the changes need time to propagate and collisions may occour so you have to think about this kind of advanced problems in the earlier stages of design: is the game worth the candle?

Intermediate cases exists, here you can try to mix the two strategies up so if immutable or near-immutable content exists, you should separate it from the rest of the contents and distribute them in an appropriate manner, while using from semi-structured to structured data provider for the contents more subject to changes.

# Answer
> 0 votes
It depends what exactly you mean by "maps". If you are just talking about the tile layout to display, then that's probably not necessary to put in a database. A database is meant for a massive quantity of data that needs to be sorted, like all the users of a website; for the relative handful of maps that a typical game has you can just store those as flat files and have the game use a plain old URL to retrieve them. In other words, what you're already doing (a text file stored on the server) is fine.

Now if you are talking about dynamic and persistent data about what is going on in the maps (eg. where other players are) then *that* data should go in a database. Similarly, if the maps are user generated then that's a whole different enchilada, because players will generate a lot of content; again, massive data that needs to be sorted goes in a database.

# Answer
> 0 votes
I've written a few games myself, not an RPG but wargames and this is how I do it (not necessarily the best way but it works).

As you state, store map data using x and y coordinates, so you might have the x and y and then terrain type, ie swamp, forest, castle etc.

Then you get the characters location and do some database query in a loop, you'll actually need a nested loop (loop for x and y).

Then display this on the screen, I find are useful for displaying map "tiles".

---
Tags: maps, rpg, databases, online
---


title: Working on an open source game

text:
# Question
Title: Working on an open source game
> **Possible Duplicate:**
> How can I get involved with open source game projects?

I am trying to get involved in working on an open sourced basic game, but I've never attempted this before. I haven't the slightest clue how to go about this, what I should know (not programming-wise, just in general) and such...

Not sure if this question fits your Q/A format but, what do you suggest? Are there any really good well documented open source games that are basic that I could work on, preferably something that is RTS? And if I've never done this before, is there anything I should look in to that applies to open source projects in general?

# Answer
> 4 votes
Sourceforge, Github, Google Code, and Assembla are rife with open source games of all types, and likely many of those teams would eagerly accept new membership.

Or failing that, the same places enable you to start your own open source game, should you decide that is your direction.

Github is especially easy... find something you want to work on, and fork it.

A warning, however: in researching these places and the projects on them, you are wandering into a vast wasteland of broken dreams and wishes.

Don't let that deter you, though.

---
Tags: game-design, open-source
---


# Question
Title: Do any games support different lighting effects according to whether a surface is wet or dry?
I've noticed that when driving at night, when the road surface is dry, my headlights appear to illuminate much further than when the road surface is wet. I presume that this is due to the differences in how my headlights is being reflected under wet and dry conditions.

In dry conditions, my headlight will reflect in a diffuse way, producing producing enough scatter to allow me to see the texture of the road for quite a long distance. In the wet however, the thin layer of water over the road surface, combined with the shallow angle of incidence, causes the light from my headlights to be reflected in a specular way and not back scattered to me.

Thinking about this, I realised that I can't remember ever having seen this effect being reproduced in a game.

* Has this wet/dry effect been implemented in any game?

+ If so, what is the name of the technique used to produce the effect?
    + If not, could this effect be produced without ray-tracing?

# Answer
I pretty sure such effects are already implemented in state of the art racing games. Look at the following video of GT5.. there's a change from a rainy to a dry night-scene, where you can clearly see that the view of the street is better when dry.

While I don't know the name of that effect (other than reflection/refraction), it is most certainly achieved using shaders. For a realistic simulation, you would need ray-tracing, but graphics in games trade realism for computation speed and use less sophisticated simulations. The goal is to make it *look* real (physically correct rendering doesn't really matter in a fast-paced game anyways).
> 3 votes

---
Tags: lighting
---


# Question
Title: Detecting collision between a sprite and many tiles
I have been looking at the following question:- Tile coordinates and am thinking of using this for collision detection in my tile game.

The set up in my game is similar to this, in that there is a grid of tiles, and the sprite will move to (x,y) coordinates. However, if I were to have an object such as a box in my world that is made from multiple tiles, how would I get the collision detection to work?

Any ideas welcome.

# Answer
> 5 votes
There are several ways to solve the problem of objects that are larger than your tiles.

Perhaps the easiest way is just to add the entity to every tile that it intersects with. Essentially the entity is in a wide range of tiles at any time. The is simple to implement but doesn't scale well for performance if your entities vary greatly in size.

A more flexible solution would be to use hierarchical tiles, where you have several tile sizes, and you place entities into the set of tiles that best fits their size. This works well if you have a fixed number of different entity sizes.

The most flexible solution would be a quadtree, which starts with very large tiles and recursively splits them so that they always fit the smallest object.

I drew a diagram of some simple cases to illustrate the ideas. The green boxes are the tiles that the gray object would be added to in that tile structure.

# Answer
> 1 votes
A number of different ways to approach this, all equally valid.

One of them is to break your multi-tile box into its component single tile objects.

The reason for picking tile-based over non-tile based is because dealing with tiles simplifies a number of things.

However, it also complicates a number of things.

You've just run into one of them.

---
Tags: collision-detection, sprites, tiles
---


title: delay camera xna

text:
# Question
Title: delay camera xna
I read this tutorial http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2/Camera\_delay.php but i didnot unsterstand it. Is there another way to delay the camera position movement without this Quaternion and the "up position"? Basically i want the camera move slowly to another location, and i tried this:

```
        view = Matrix.CreateLookAt(cameraPosition, cameraTarget, Vector3.UnitY);
        cameraTarget = position;
        cameraPosition = Vector3.Lerp(new Vector3(0,8,15), world.Backward * 15,1f);

```

i want the camera be 15 units from an object, and move slowly until it will be behind it, but this code dosen't work.

# Answer
Assuming that world.Backward is a constant this line of code is going to return the same value every time.

```
cameraPosition = Vector3.Lerp(new Vector3(0,8,15), world.Backward * 15,1f);

```

You want to lerp between the current location and target location.

```
cameraPosition = Vector3.Lerp(cameraPosition, goalPosition, 0.1f);

```

Lerp is the interpolation function below so if value1 and value2 are the same frame after frame then returned value will never change.

```
cameraPosition = value1 + (value2 - value1) * amount

```

Also you want a value less than between 0 and 1. Ex you value of 1.0f gives you. a value of .5 will move you half way to value2 in one tick. A value of .1 will move you a tenth of the way to value2. Below is why 1.0f is a bad weight.

```
cameraPosition = value1 + (value2 - value1) * amount
cameraPosition = value1 + (value2 - value1) * 1
cameraPosition = value1 + value2 - value1
cameraPosition = value2

```
> 1 votes

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


# Question
Title: XNA 4.0 problem Initializing Instanced Classes in for loop
Okay so this is kind of weird, I have some code that creates particle.cs instances

```
 public void AddParticle()
    {
        for (int i = 0; i < Density; i++)
        {
        particle = new Particle();
        Randomnum = new Random();
        Direction = Randomnum.Next(360);
        InitialVel = AngleToVector(Direction);
        particle.Initialize(Texture, Position, 10, 2, InitialVel);
        particles.Add(particle);
        }
    }

```

When I set a breakpoint on particles.add I can see that the InitialVel is different for each entry in the particles list. When it gets down to the draw function the initialvel is the same in each and every entry in particles list thus they all draw on top of each other.

the wierd thing is when i set the breakpoint at particles.add and f5 through each of the 10 steps of the for loop the game pops up after the break points are done and all 10 particles are going in random directions as intended but without the break points they are stacked on top of one another and the InitialVel are all the same when it reaches the for loop in the draw method.

Emitter.cs Particle.cs

# Answer
You should not be creating a `new Random()` in each call to `AddParticle()`, though you would expect each `Random()` call to use a new time-dependent seed. The problem is explained in MSDN:

> The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers. This problem can be avoided by using a single Random object to generate all random numbers.

This is why you see different behaviour when stepping through the code, because then several timesteps will surely pass between each `Random()` call.

The solution is straightforward, you already have `Randomnum` as a property of the Emitter, just seed it in Initialize() instead of AddParticle():

```
public void Initialize(Texture2D texture, Vector2 position,int density,int life,GameTime gameTime, float gravity)
{
    Randomnum = new Random();
    particles = new List<Particle>();
    Texture = texture;
    Active = true;
    Position = position;
    Density = density;
    Life = life;
    timeCreated = gameTime.TotalGameTime;
    timeToLive = TimeSpan.FromSeconds(Life);
    Gravity = gravity;
    yvel = 0;

    AddParticle();
}

public void AddParticle()
{
    for (int i = 0; i < Density; i++)
    {
    particle = new Particle();
    Direction = Randomnum.Next(360);
    InitialVel = AngleToVector(Direction);
    particle.Initialize(Texture, Position, 10, 2, InitialVel);
    particles.Add(particle);
    }
}

```
> 2 votes

# Answer
Don't create a random generator in each call to the AddParticle() method.

It will return always the same value.

Also you may want to pass a different seed to the the generator each time you create it, then you can use DateTime.Now.Millisecond as seed.

```
static readonly Randomnum = new Random(DateTime.Now.Millisecond);

public void AddParticle()
    {
        for (int i = 0; i < Density; i++)
        {
        particle = new Particle();
        Direction = Randomnum.Next(360);
        InitialVel = AngleToVector(Direction);
        particle.Initialize(Texture, Position, 10, 2, InitialVel);
        particles.Add(particle);
        }
    }

```
> 6 votes

---
Tags: xna, c#, debugging
---


# Question
Title: Making a multi-pieced rectangular breakable body with Farseer
Using Farseer 3.3.1 I want to create a rectangular BreakableBody with many pieces. Right now here is my code:

```
Vertices polygon = PolygonTools.CreateRectangle( 2.5f , 1.25f );
List<Vertices> triangulated = FlipcodeDecomposer.ConvexPartition(polygon);
BreakableBody breakableBody = new BreakableBody(triangulated, World, 1);
breakableBody.MainBody.Position = Vector2.Zero;
breakableBody.Strength = 5;
World.AddBreakableBody(breakableBody);

```

This code turns the rectangle into two pieces (cut from corner to corner). I have tried four of the five decomposing methods (Flipcode, Bayazit, CDT and Earclip). I also haven't been able to find any good examples of a rectangle being divided into multiple pieces.

Preferably, I am looking for a way to create random sized pieces, but cutting it into 32 cubes ( 8 x 4 ) would be fine also.

# Answer
> 1 votes
Farseer breaks apart the bodies along existing polygons, it will not create new ones for you.

You seem to misunderstand what decomposing is. It breaks apart complex polygons into the triangles necessary to represent it. It always takes 2 triangles to represent a polygon so that is why your body keeps breaking to 2 triangles.

Try something along the lines of the below (Note this is just of the top of my head)

```
List<Vertices> pieces = new List<Vertices>();
for (int x = -4; x < 4; x++)
  for (int y = -1; y < 1; y++)
    pieces.add(PolygonTools.CreateRectangle(1, 1, new Vector2(x,y)));
_breakablebody = new BreakableBody(pieces, World, 1);

```

---
Tags: xna, physics, farseer-physics-engine
---


# Question
Title: How to represent cliff faces in terrain?
I'm trying to figure out the best way to programmatically represent terrain in my game. I've been considering using a heightmap (or grid of evenly spaced vertices) to represent the surface of the terrain and a splatmap to allow smooth texturing. This would work for totally smooth terrain, but the problem is how to represent cliffs and sharp cliff faces.

The cliffs themselves would need to be rendered differently than the rest of the terrain. For example, they would need to have a different (non-stretched) texture visible on the front of the cliff, but if I used the splatmap for this, it would be impossible to have a sheer enough cliff face where the texture of the cliff is totally separate from the ground.

A picture says a thousand words so...

What are some general ways to store and/or render cliffs and other sharp differences in terrain height?

# Answer
> 7 votes
That picture looks like they are using an extra prop to create the cliff. If you want to use a plain height map to represent your terrain, this is pretty much the only solution. The good news is it is commonly used and works fine. The simplest solution (from a programming perspective) is to just place extra props as needed in the level editor. If you want to get fancy, you can have a tool that automatically selects from a set of props and shapes the terrain to match.

You could provide a facility to extrude faces on the height map, which will get you perfect vertical faces with just a little bit of extra complication, but that is not likely to look very good and will probably require the placement of some extra decoration anyway to cover up the hard edge.

The last option would be to forgo a height map all together and just make your terrain a full piece of geometry, but then you lose the nice simplicity of a height map.

---
Tags: graphics, graphics-programming, terrain, data-structure
---


# Question
Title: Computer animation in C++ and if it can be integrated in web designes
I have a PhD in Mathematics with some experience in C++ programming. I am very interested in computer animation, and would like to try to teach myself in C++.

My humble resources at the moment are: Borland Builder 6 and a Toshiba laptop with 1.49 GG of ram and a maths co-processor. Please give me as generous advise as you can, detailing what resources are essential, and if at all possible give me some idea of cost.

Finally, is it possible to integrate animation created in C++ in web design?

Thank you in advance for your help.

# Answer
Your question is very broad / not specific, but I'll take a stab.

**Skinning**

Are you wanting to animate 3d models? The most common approach to this is referred to as "skeletal animation," and essentially boils down to a lot of matrix multiplication. Each vertex in a model has one or more "bones" that it is influenced by, and the bones are connected to each other to form a "skeleton." Each bone has a 4x4 matrix that is used to describe its orientation relative to its parent bone. For example, an elbow bone might be the child of a shoulder bone, and the matrix of the elbow would express the elbow's orientation relative to the shoulder.

Each frame, you start with a single root node in the skeleton (perhaps the chest) and you assign the object's "world" orientation (another 4x4 matrix) to it. Then you traverse your graph of bones and multiply the bone's local orientation matrix by the parent bone's world matrix to get the bone's world matrix. This is often called the matrix palette.

Finally, each vertex in the model uses the matrices from one or more bones that it is "skinned" to to find its final location for the frame. For example, a vertex in the middle of ones leg would likely be influenced only by the leg bone, whereas a vertex near the shoulder might be influenced by two or more bones. Doing this would allow a model's arm to be raised while vertices near the shoulder would appear to "compress" (rather than fold into the upper body.)

**Animation**

Animation is generally achieved with keyframes in which the relative orientations of each bone are expressed. For example, an animation that depicts a model running might have a duration of 10 seconds and have keyframes every half second or so. To achieve a looping animation, the first and last keyframes can be identical. During playback of the animation, the skeleton will be "blended" between its nearest keyframes. This would have to take place before the world orientations of each bone are calculated.

**Tools**

There are free tools available for compiling C++, namely the Gnu Compiler Collection (GCC), as well as a free version of Microsoft Visual Studios. I'd recommend that you take advantage of a very recent version of one of these. I've been very pleased with GCC.

You might want to take a look at the video card that is available on your machine. You'll need something fairly recent to achieve some of animation techniques.

**C++ and the Web**

In part as a security measure, HTML is generally not capable of running native code, such as code written in C++. There are many different ways you could do 3d animation in the browser, perhaps the most interesting of which is WebGL (basically OpenGL bindings in Javascript.)

**Note** that there are other ways to do animation, and even skeletal animation can be achieved differently than described. For example, you can use quaternions to represent rotations instead of matrices.
> 2 votes

# Answer
First of all, I find merely impossible to learn a programming language without a clear project in mind. So you should first try to define more precisely what in computer animation you like. This is a vast domain containing (but not limited to):

* Character animation;
* Fluid simulation;
* Crowd simulation;
* Rigid bodies simulation;
* etc.

**Learn more about computer animation**

Two books I found globally interesting:

* Computer Animation Complete: All-in-One: Learn Motion Capture, Characteristic, Point-Based, and Maya Winning Techniques
* Computer animation: algorithms and techniques

**Learn C++ by yourself**

I suggest you read:

* Thinking in C++
* The C++ Programming Language

**Tools for C++ programming**

Forget Builder 6... Then, it depends on which OS you are programming:

* WINDOWS: Visual Studio express.
* MAC OSX: XCode.
* Linux: Eclipse + a lot of others...

Those are FREE and easy to start with for a non-programmer.

Hope this help.
> 0 votes

---
Tags: c++, graphics, animation
---


title: glBlendFunc transparency in cocos2d?

text:
# Question
Title: glBlendFunc transparency in cocos2d?
GL\_ONE, GL\_ONE

This makes the flamingoes transparent on:

http://www.andersriggelsen.dk/glblendfunc.php

but not in cocos2d using:

sprite.blendFunc = (ccBlendFunc){GL\_ONE, GL\_ONE}

How can I achieve a similar effect in cocos2d?

Thank you.

# Answer
> 0 votes
the sprite.blendFunc will be ignored if the sprite is part of spritesheet or atlas or whatever else has blendFunc

---
Tags: opengl, cocos2d, c
---


title: Transition between two Views

text:
# Question
Title: Transition between two Views
i want to animation the transition between game screens , in my game loop i have a function called `getCurrentScreen()` which returns a `Screen` object this Screen Class has a function called `present()` this function draw on the framebuffer , when i want to change to another screen i call `setCurrentScreen(Screen)` , so it will draw the screen i set ,  **What i want is to animation the transition between these screens**  any suggestion , is the a book or an article that discusses this

# Answer
Given your current design you could create a new `Screen` (`TransitionScreen` or whatever) that takes two screens for the constructor and maybe a fade-time. Then you would do something along the lines of`setCurrentScreen(new Screen(lastScreen, nextScreen, fadeTime))`. Your `TransitionScreen` would have to deal with mixing both framebuffer outputs (you might have to tweak your drawing method for this if each screen is drawing to the framebuffer directly on its own) and then after the given fade time it would `setCurrentScreen(nextScreen)` to fix the final screen.

This is a very-simplified method and doing it exactly like this will lead to poor code and lots of coupling, but with a bit of work you can make it. E.g. `TransitionScreen` shouldn't set the new screen itself because it'll couple with your *setScreen*, but instead raise a `TransitionFinished` event, flag transition as finished or something like that. Then your game loop should do the *setScreen* and you're good to go.
> 1 votes

# Answer
I worked on something similar before. I think the best thing to do is to have a sort of stack with your current screen on the top. For each screen have a Boolean value whether it covers up the draw of the screen underneath. So when drawing you start at the top of your stack and draw screens that are not covered up by a screen above it in the stack.

The good thing about this is that when you want to transition off a screen, you can push a new screen on top with the covering boolean set as false. You can then do your transition animation (for instance fade in the new screen) whilst drawing the underneath screen and at the end you can set the covering boolean to true so you no longer draw the screen below at all.
> 0 votes

---
Tags: animation, opengl-es
---


# Question
Title: How should I design my particle system to make it easy to add new particle effect types?
Recently I started designing a particle system for a game I develop. But I have some issues with it. I mean, it works but I have a feeling that my design isn't good enough.

So, basically I have a Particle class which contains the particle's vars and couple of functions:

```
class OBJECTATTRIBUTE_API Particle
{
protected:
     Vector3d position;
     Vector3d direction;
     Vector3d gravity;

     float life;
     float fade;

     float red;
     float green;
     float blue;

     bool isActive;
     bool isInit;

public:
     void Deinitialize();

     void SetPosition(Vector3d position);

     bool IsActive();
};

```

And I derive from that class the types of particles. Like this:

```
class OBJECTATTRIBUTE_API ParticleExplosion : public Particle
{
public:
    void Initialize();

    void Update();
    void Render();

    void Rejuvenate();
};

```

And at the end is the emitter. This is actually where I think my design fails. I make an emitter for every particle system and, at some point, I may have too much different emitters.

Here is an example of the particle emitter realisation:

```
// The base class
class OBJECTATTRIBUTE_API ParticleEmitter
{
protected:
    Vector3d emitterPosition;

    unsigned int particleTextureID;
    unsigned int particleCount;
    bool isEmitterStopped;

public:
    ParticleEmitter();
    ParticleEmitter(Vector3d emitterPosition);
};

// The derived emitter.
class OBJECTATTRIBUTE_API ParticleEmitter_Explosion : public ParticleEmitter
{
private:
   ParticleExplosion *particles;

public:
   void AddParticles(unsigned int particleCount);

   void Initialize();

   void Start();
   void Stop();

   void Reposition(Vector3d newPosition);
   void SetParticleTextureID(unsigned int particleTextureID);
};

```

And the question - Is my particle system design good? If not, what can I do to improve it?

**EDIT :** I was told that the question was too subjective, so I will try to add couple of specifications.

Firstly, I started making the particle system for explosion simulation and also some attack animations in my game. It works very well with that, so I think this goal is achieved.

Secondly, the performance hit is acceptable and I am OK with that.

And finally, the question was about is this design good for flexible adding of new particle effects implementation?

# Answer
I would decouple the particle type from a specific emitter. Have a base emitter and have it work with different particles.

For instance you can derive a SprayEmitter class deriving ParticleEmitter and you pass it the particles you want it to work with. The emitter can then call Set position on the particles to move them where you want them e.t.c.

Essentially the Emitter takes care of how particles are emitted regardless of their concrete type and the particles are only concerned about updating themselves.

I guess the above would be best achieved using a function pointer in the emitter with the signature to return an abstract particle. You can have a class sitting above the emitter that will pass it a function that creates a particular concrete particle so when you call AddParticles you can call this createParticle function and add the return to your array of particles in the emitter.
> 1 votes

---
Tags: c++, opengl, particles
---


title: Which Side Was Hit?

text:
# Question
Title: Which Side Was Hit?
I am working on an Android game and I have two objects A and B (both rectangles) and when they collide I simply want to know which side of B was hit. I have detected the collision fine, but I am having trouble figuring out which side of the rectangle B took the hit? Any ideas? Thanks!

# Answer
> 2 votes
You can calculate the centroid (it's easy to calculate, google for a formula) of both rectangles and compare them.

I'm saying this, because it's a general solution, i have no idea how you do your collision detection, there are plenty of variables here like size and speed of the rectangles (if your rectangles move too fast and you're not doing sweep testing, then you might "overshoot" and it'll look like the collision was from the other side). It's not the most elegant solution either, but you only do this once when the collision happens, so it shouldn't be too bad, though that depends on the amount of collisions. You're not giving enough information.

# Answer
> 8 votes
I suggest computing the Minkowski sum of B and A, which is a new rectangle, and checking where the centre of A lies relatively to the diagonals of that rectangle:

```
float wy = (A.width() + B.width()) * (A.centerY() - B.centerY());
float hx = (A.height() + B.height()) * (A.centerX() - B.centerX());

if (wy > hx)
    if (wy > -hx)
        /* top */
    else
        /* left */
else
    if (wy > -hx)
        /* right */
    else
        /* bottom */

```

**Edit**: use Minkowski sum and fix variable names

# Answer
> 0 votes
Compare A and B to see where they are in regards to each other.

A width 20 height 20 A xmin + pos, xmax + pos A ymin + pos, ymax + pos

Same above for B.

if A xmax + pos (left side) \< B xmin + pos A is on left of B, B left side hit..

etc etc.

# Answer
> 0 votes
Are you using the Rect class? http://developer.android.com/reference/android/graphics/Rect.html

If so, some simple comparisons will left you know which side collided... From the Rect class, you have attributes for the top (or North), the bottom (or South), the left (or West), and the right (or East).

For example, this test will determine if rectB's left side crossed rectA's right side:

```
if ((rectB.left >= rectA.left) && (rectB.left <= rectA.right))

```

Remember that rectB could collide with two sides. Image rect B's lower left hand corner crossing over rect A's upper right...rect B would've crossed over rectA's top and right edges.

Remember that if rectB is completely inside rectA, that would look like it crossed over all four sides of rectA!

---
Tags: android, java, collision-detection, physics, graphics
---


# Question
Title: Make a callback to android methods from libgdx
How can I make a callback from libgdx to an Android method? I want to use the method to overwrite a file in the internal memory.

# Answer
> -3 votes
I resolved it as if it was a simple callback in Java or a delegate in C# thanks

---
Tags: android, libgdx, callbacks
---


# Question
Title: How do I make a message based communication system between objects?
Just as I was told here, I need to make some kind of communication between objects in my game. Mainly, for achievements. How do I do this? My idea was to make every object have an array attached to itself called "messages", and then, when something happens, a message gets pushed there. At the end, I would have a big loop, where I would check messages that each object got, remove them, and act accordingly. I could also have a global array called "messages", and then I would iterate through it, and fire off events in different objects that the messages were sent to (in this case, a message would contain both a message, and some kind of an object ID), and then remove them. Is there a better way? Keep in mind that I'm working in Javascript.

I forgot to mention, we're talking about serverside Javascript running on Node.js, not in a browser.

# Answer
> 2 votes
Why don't you just register events?

Different objects act upon events they listen to, and you can attach some datas to these events (an object like {key: 'value', key2: 'value2'}, for example).

If basic events (click, change, etc) don't satisfy you, you can register custom events. An example of how to do this here : http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/

Edit : heh, even easier in Node.js ! There is an `event` module available. Look at this link : http://venodesigns.net/2011/04/16/emitting-custom-events-in-node-js/

# Answer
> 0 votes
JavaScript already uses events internally, so you could leverage that system for your game messages. While there's apparently a W3C specification for custom events, it isn't really supported in all browsers.

Here's an article that explains a possible implementation of custom events. On the other hand you could simply use a framework like YUI, which has custom events implemented and ready to use.

# Answer
> 0 votes
This calls for the Observer Pattern! Seems like Node.js already has something like it, called an EventEmitter. A similar question was asked in the Programmers StackExchange.

Hopefully this will start you on the right track!

---
Tags: javascript, objects, node.js, achievements
---


# Question
Title: A question regarding how to respond to 'events'
What is the best practice to use when events happen in a game? For example:

1. You have a sensor. When a particular game actor is near that sensor, a sound must be played and a door must be closed.
2. When a collision between characters `A` with animation `i` and character `B` with animation `j` happens, a special graphical effect, a sound effect and a decrease of life points of `A` and `B` should come into effect. Furthermore, `A` and `B` must be forced to return to some specific animation.
3. The user presses the left-key, so actor `A` must be moved.

What I would like to know is: do you play sound, move the player, close the door (calling the relevant methods, like `PlaySound(..)`, `CloseDoor()` or `MovePlayerLeft()`) directly in the event handler or do you use some sort of message based system, so that when the actor manager code is called, it sees that the player must be moved to the left and moves it to the left. Also, when the sound manager code is called, it sees that a particular sound must be played and plays it and so on...

Ps. I would really be happy to see some reference to books/papers/articles to read something related.

# Answer
There's no best practice really. It would depend a lot on the engine you're using, the complexity of the game, etc. If I was writing a small Flash game then I'd write the PlaySound call right into the sensor check for the player. If I was writing a bigger game using Unity or equivalent I would do the same, except the PlaySound call might well be implemented as a message (since you wouldn't want every object to know about all the possible systems that can result from all events).

Personally I wouldn't add a messaging system just for the sake of decoupling code - you obscure the flow of control for very little gain. But if you find your code is too tightly coupled, then sure, add a messaging system.

I would also stick to active changes ("when this happens, move the player to the left") rather than passive changes( "so that when the actor manager code is called, it sees that the player must be moved to the left and moves it to the left"). If you make things too passive then the flow of control becomes too awkward to follow and you can't easily track what has caused a change in an object's state. If you're sending messages, send them immediately (if possible) and act on them immediately (if possible).
> 1 votes

# Answer
gamedev.net link 1

gamedev.net link 2

The code in these articles is badly structured, just download the source and study it as you're reading.

Ad. 1: The sensor could act as an NPC that has a proximity list and sends apropriate messages to the elements on the proximity list or sends a message to the sound engine, etc.

Ad. 2: Animation is not a part of game logic. You can implement a messaging system where you send a message to the object B that reads "i'm enemy A and i just attacked you for 10 damage" and then the function handling this message could send a message to the graphics engine and tell it "i've made an attack, please display an attack animation for me". The fact that there's an animation playing along side of the event of dealing damage is a separate thing.

Ad. 3: Again, you send message to object A that says "change position" or "move 3 to right". The event of pressing a button is a part of reading input, not game logic. If you need information about how to read input, that's a whole different story.

The message handling function for a particular object could send messages to the sound and graphics engines, it depends on how you structure your game. You should be fine as long as there's no actual displaying or sound logic within the player or NPC class.
> 0 votes

# Answer
I agree with Kylotan's answer about "keep it simple, straight forward and avoid too many indirections".

But I want to add one exception:

When handling object deletion or "remove from scene" events, I found it very helpful to *not* immediately handle these messages (or events) by deleting objects right now. Instead, just set a flag "toBeRemoved" and shedule the actual deletion at some specified point in your main loop grouped together.

Also, try to minimize dependencies when destroying objects (small destructors / Dispose() functions / DeInit() / whatever). Or consider writing a separate "OnRemoved" function which gets called and where it is guaranteed that other referenced objects in the current frame are still exist (but whose OnRemoved may already have been called).

The reason are that you just will make mistakes and errors. And when it comes to deleting objects, errors very often end in null pointer access, AlreadyDisposedException or whatever is the equivalent in your language ;).

Its very easy to make mistakes where you accidently destroy objects that aren't there anymore *while* destroying that very same object. Or another common example, where you change a list (e.g. an event listener list) from a destructors while iterating over the very same list.

Just handling the actual removal later isn't a perfect solution. But many times, it turns crashes into glitches.
> 0 votes

---
Tags: architecture, events
---


# Question
Title: Coding for a really, really high-resolution display array
I've been tasked with building a real time "full screen" demo to run on a 5x2 array of 60+ inch LED TVs: or, in other words, a 20 megapixel display.

We've got a machine built that can run a single Win7 desktop spread across the displays at full resolution, and some pretty decent video cards.

My question is: aside from the ridiculous amount of work that my pixel shaders are going to be doing, are there any other limitations of DX10.\* that would come into play here that wouldn't on a more sanely sized viewport? I won't have access to the hardware until next week but I'd like to have something written by then that I can use to benchmark the system.

**Update**

While Imanaged to get this working on a single machine with a bunch of AMD EyeFinity (6 output) cards - to keep things working smoothly, the "easiest" way turned out to be to create a DX window per display as having a window span displays caused some performance issues - I also got it working pretty well by distributing the task across a group of machines, each of which drives two displays.

It was surprisingly easy. For my test XNA app, I added a GameComponent that captures some game state (camera position/orientation, etc.) and UDP-spams it across the local subnet per frame.

That component has a `Mode` switch (send or receive). If it's in `Receive` mode, it catches UDP datagrams and updates the game state with the information from the sender. `Send` mode just sends state packets, and, via a service/daemon, causes nodes to start or stop the client app. Any client can act as a "master", and switching a client into `Send` mode requests all other nodes to switch into `Receive`. It's pretty entertaining to see what happens when people are fighting over control.

Another neat benefit: I created a console app which processes a series of keyframe state definitions - location, time, etc. - interpolates as needed, and sends them using the same code as is used in the game engine. This lets me easily script movement, submit transforms from a web browser, etc.

All in all, it took about 50 lines of code to keep multiple copies of the app running in sync. Some additional complexity came from off-setting the camera position for each machine and correcting some perspective/projection annoyances, but most of that came down to a per-node configuration file.

# Answer
I would worry just as much about the hardware configuration as software. You don't have to run each TV at its native resolution, and screen size is different from resolution. I'll assume the 60" TVs are each 1920x1080 though, so native resolution across all of them is either 9600x2160 if you meant 5 rows x 2 columns of TVs, or 3840x5400 if you meant 5 columns x 2 rows.

The newest AMD Radeon card, a 7970 supports a resolution of up to 4096x2160 per display, at a maximum of two displays, if you're using DisplayPort 1.2 to transfer video. So it may get you close to native resolution, however it won't work with up to 5 TVs that way.

The AMD Radeon 6870 Eyefinity 6 supports up to 6 outputs at once, but only over a max resolution of 5760x2160. It also supports a Crossfire configuration which will help your performance quite a bit. Bear in mind the extra GPUs will not yield a greater max resolution.

Short of a completely custom display setup, or something to split your video signal to more monitors/TV, I'm not sure how you will be able to run on 10 displays at once. But if you have that capability, then what you're looking for is the fastest graphics setup that supports a resolution closest to what your native resolution is. Once you have that your best bet is just to keep your pixel shaders as cheap as possible, and avoid overdraw, which means calculating single pixels more than once. Frustum and occlusion culling, and depth sorting will help greatly in reducing overdraw. As far as a limit within DX10, I'm not sure of one that limits resolution, I'm sure there is one, but it's probably greater than any DX10 card that exists.
> 5 votes

# Answer
You can easily create a render target of equivalent size to test performance. You'll have to downscale it or zoom in when copying it to the back buffer until you get the real hardware.
> 6 votes

---
Tags: directx, resolution
---


# Question
Title: How to pin a body in case of collision in Box2D or Farseer?
I'm trying to get an understanding for the Box2D/Farseer physics engine by implementing a small air hockey simulation. There, I have the problem that the CPU player attacks the puck, kicks it, but also gets kicked back due to restitution. I would like the CPU player's mallet to be pinned to where it currently is; being able to kick others, but not getting kicked by something else.

I have tried setting its restitution to 0 but restitution is always the maximum of the two colliding bodies and as the puck has a restitution of 0.9, the mallet will also move.

I have also tried changing the mass of the mallet to a insanely high value but this influences damping again.

What is the best approach to really pin it afte collision?

# Answer
> I have tried setting its restitution to 0 but restitution is always the maximum of the two colliding bodies and as the puck has a restitution of 0.9, the mallet will also move.

I thought you came to conclusion that this was not true in the comment in another question?

Anyways the only thing I can think of is to use a sensor.

On BeginContact disable the body and set the Body.Position manually to a location beside the mallet. To pass/shoot I would sets its velocity in what ever direction and then re-enable the puck after its a certain radius distance from the player.
> 1 votes

---
Tags: physics, box2d, physics-engine, farseer-physics-engine
---