Sunday, January 9, 2011

Make CharacterControllers in Unity not collide with each other

I'm trying to spawn a number of CharacterControllers and have them move around an area, but they keep getting stuck on each other. Is there a way to make them pass through each other while still respecting the terrain's obstructions?

  • Your best bet is to probably use rigidbodys and capsule colliders (a script to get them to behave similar to a character controller can be found here) and then use Physics.IgnoreCollision to get them to pass through each other.

    zaratustra : Physics.IgnoreCollision works with CharacterControllers, thanks.
    From Tetrad

How does one measure and reward social aspects in virtual worlds?

Well this sounds like a pretty vague question but please bear with me.

I know of how Gaiaonline gave gold to people who participated in forum posts.

I'm curious if in theory these could be applied to social aspects of games like Second life or Sims Online.

The question what would be specific quantifiable actions/interactions could be measured tracked for rewards and achievements that would help build a community?

(this'll probably end up as community wiki though)

  • I don't know how Gaia online does, but beware that doing such a thing you might actually make both the forums and the game a worst place: people will spam the forum (ruining it) just to get gold in game, where they will have an unfair advantage over other people (ruining the game too).

    You must be careful to give this kind of rewards somehow only if you did something to earn it, not just farming posts or stupid things like that.

    Moreover, you will probabily want not to give actual game gold, but nice stuff, like the pet companions in wow that have no effect on gameplay but are cute.

    Wight : It depends entirely at what the defined actions will be. But the problem is it's hard to define quantifiable social actions.
    Lo'oris : I don't see any possible satisfying solution. Even if you gave "prizes" that bear no in-game power, and even if you gave them to selected users such as "you make a *contest* in the forum, who wins gets the prize", it would still screw the results: people would vote who they want to get the prize instead of voting who did the best work.
    lathomas64 : @ Lo'oris If the context is social actions I don't think that is contrary to the overall intended goal if people base who the vote for on social interactions.
    Lo'oris : @lathomas64: if you make a drawing contest and people vote their friend instead of voting the best drawing, it is totally bad.
    lathomas64 : If the point of the drawing contest was to reward the best artists then I'd agree. If the point of the contest was to encourage social interaction though I don't agree that this is "totally bad" and in fact has achieved exactly what you wanted.
    Lo'oris : Such as creating animosity because "you did the best work but you lost because you had less friends"? Nice job.
    From Lo'oris
  • There are many in-game social actions that can be tracked trivially, because they're already going to be database transactions:

    • Joining a team, and leading a team.
    • Joining a guild, and founding a guild.
    • Putting items up for auction.
    • Creating public spaces for other players.

    Additionally, your game systems can provide some affordances for socially-driven players:

    • Contests - costume contests, minigame (e.g. fishing) contests, point-to-point races. Players will host these events anyway. If you provide even minimal systematic hooks for them, you can track and reward them.
    • Newbie help zones / tutorials.
    • Community approbation (Stack Overflow's approach). Most games have some way to "downvote" other players. Provide a way to "upvote" them too.

    As for rewarding, a key point missed by many designs is that you need to award like with like to motivate people. Reward the players that progress in your combat with the +5 sword; reward the players that create your social spaces with socially-visible items like titles, clothing, or emotes.

    caspin : 'like with like' has been an issue in game design since DnD (before?). It's much easier to reward players for killing things than it is to reward players for making the game richer.
    Joe Wreschnig : Whether D&D rewards like with like is entirely up to the quality of your DM. D&D per se only prescribes combat rules and combat rewards; if your DM invented social rules but not social rewards, that's a crappy DM, not D&D's fault.
  • So first of all, most "pure social" games still have a lot of economics going on so there's a lot of economy-related stuff you could give achievements for. But assuming you mean the more social-type things, you could give achievements for:

    • Participating in a poll
    • Upvoting/downvoting something X number of times (I remember A Tale in the Desert had challenges where, for example, a player had to get their sculptures voted favorably by denizens of the world -- this would reward voting for that thing)
    • Joining the forum
    • Posting to the forum and having that post upvoted/thanked (to address the spam issue brought up by Lo'oris)
    • Karma-type rewards that can be bestowed by other players

    Honestly, you would do well to look at the Badges system on this very website, as well as karma systems in places like They do a relatively good job of encouraging users to be social in constructive ways.

    From DariusK

How to think about 2D scaling/rotation transformations

This is a kind of embarassing question to me since I'm getting more in-depth with XNA but some times my way of thinking about things in my head contradicts an example and I need to re-think it to make it work.

So let's say I am just working with a sprite that is 10 wide and 10 high.


When I apply a scaling matrix, am I just shifting the points back or scaling the X-axis and Y-axis in the LOCAL coordinate space of that sprite? I ask because on this page:


It shows the X and Y of the local axis the sprite is in being scaled down. So in my head, I think that a scaling means that you scale down the local axis space where the sprite is located which makes it smaller.


When I do a rotation matrix, am I rotating the local x and y axis of the sprite around the world origin or rather do I think about it as rotating the local coordinate space entirely around the world origin?


This to me is just moving that scaled image with those smaller x and y axis to some other point in the world.

  • For me, the easiest way to think about this is to remember that each coordinate space can be expressed in world coordinates by a vector from the world origin to the local origin which I just call the position vector and two (in 2D or three in 3D) basis vectors. Any translation moves only the head of the position vector (the tail is always anchored at the world origin). Rotation and scaling can affect all three (or four) vectors depending on the specific rotation or scale as well as the order you have applied transformations already.

    This, along with my knowledge that these transforms don't change the object in local space (a point at (1,0,0) is always at (1,0,0) in local space, no matter what the basis vectors are in world space), only its appearance in world space, allow me to visualize these transforms with relative ease.

    In essence you are thinking the right thing, but you must be aware that these transforms don't actually affect the local coordinate space of an object, only its mapping into world space.

    For example:

    I have a an object defined by {(0,0), (1,0), (1,1), (0,1)} in local space. The Position vector is (0,0), and the basis vectors are (1,0) and (0,1). In other words, my transform matrix is just an identity matrix and the object looks like a square with bottom left corner at the origin both in the world view and in a local view.

    If I were to apply a translation, say by the vector (2,3), only the position vector changes. My object is still defined as {(0,0), (1,0), (1,1), (0,1)} in local space, but the object in world space has been moved up and over. The object still looks like a square in both views however.

    If I were to then apply a scale, say by (1/2, 1/3), the position vector would be changed to (1,1) and the basis vectors would be changed to (1/2, 0) and (0,1/3). Note that my object is STILL defined as {(0,0), (1,0), (1,1), (0,1)} in local space, but if I view it in world space it is a rectangle that has been shifted up and to the right, not a square with bottom left corner at the origin as it is defined in local space.

    Rotations are very similar, but the changes in the basis vectors are not as easy to calculate in my head so I shall do a very simple example with a 45 degree rotation counter clockwise around the origin. The position vector would be changed to (0,sqrt(2)), while the basis vectors would be changed to ~(-0.35, 0.35) and ~(0.24,0.24). The object would now be a slanted diamond moved up in world space.

    Ilya : Awesome explanation. Now I picture this as more of a function where you input some vectors and get a new representation of that vector. A scale in my head is "what if I shrunk down those basis vectors in that matrix" so now I would get a shrunken image because those basis vectors are shrunk down as if I did that to the local space's x and y coordinates. So everything is the same in local space and this is more of a representation rather than a change.
    Chewy Gumball : Exactly, there is a transformation function from local to world space and applying these transformations only affects this function, not the object itself.
  • Think of it as rotating an entire coordinate system from one basis to another. That matrix can take any tuple in (R,R) and it would have a point in the new coordinate system.

    If I have a rotation matrix like this:

       0 -1
       1  0

    I pass vectors from my starting space, and they get turned into vectors in the finishing space. this include the axes [1,0] and [0,1] which get turned into [0,1], and [-1,0] (i.e. it gets rotated counter-clockwise 90 degrees.

    You may have noticed that the rotated axes are the columns of the matrix. In fact, the columns of a matrix represent the axes of whatever coordinate system you're transforming your numbers into by definition. That's because a coordinate system is just a way of representing a point in space in terms of its projection onto a bunch of independent vectors (blah blah).

    Hope this helps.

    Ilya : Yup, now I get it. Those basis vectors act as "template" axis for you to mess around with, as if you were actually committing real changes to the local x and y axis. Whatever output you get is what would have occurred in the local x and y axis (whatever you define your basis vectors to be) and the output goes into the world matrix. Thanks.

Your recommendation for path construction from a single background image?

So I currently have my background as a single PNG and some obstacles (like blocks as part of that PNG). In order to create a path, I currently store pixels above a unique green color (my hill) and use this to move the character. My question is, is it better to create something like a collision layer mask or somehow convert my PNG to a bunch of tiles? Is this possible?

  • Yes, it is strongly suggested that you move to a data driven map, with layers and tiles. It will make your life easier, your maps will be editable in other tools(like map editors). You could even think of randomly generating maps and much much more!

    Happy coding!

    Ilya : Is there any tool that you personally recommend (there are tons of these programs out there). Will I have to start from scratch or can these map editors load a png and then I can just define where my tiles will be?
    Cyclops : @Ilya, Tiled, which @Christopher recommended, does just that, takes a bitmap and uses it for tiles. Give it a try, it's a nice program.
    From DFectuoso
  • Two programs you should at least take a look at are Mappy and Tiled. A library for XNA integration with Tiled called TiledLib has been developed and could be of some use, if only to take a look at for ideas.

  • In Stendhal we use several layers of a map: ground, floor, objects, roof, roof_2. This way it is easy to create new maps based on images already created. We use two additional layers that only contain a green or red square called collision and protections.

    You may get some ideas from our map tutorial. The map editor "Tiled" is from

    From nhnb

What techniques enable web based games to update player's resources frequently?

Long ago there was this web-based game called Utopia (and I'm sure it is still around), turns are by per hour. You only get new gold/lumber or what-not every hour.

Some newer web based games have resources incrementing in finer resolution, like per minute. So say a player has a food production rate of 5 per minute - the player will have his food amount incrementing every minute. I am not sure if it is wise to constantly set a CRON job to update the SQL database, which I am assume what they are using, as it is web-based. Perhaps I am wrong, every minute.

What techniques do those web-based games use? Added on Edit: And can database can really handle the load?

  • I am in favor of KISS: "Keep It Simple, Stupid!"

    I see no reason why a cron job wouldn't work, and the upside is that cheap web hosting options often don't let you directly run commands, but they do allow you to run cron commands. So there's no need for an expensive dedicated server.

    You can also do your update code in PHP or your language of preference, by having the cron command either wget --spider or use the lynx text browser. The instructions at Configuring cron jobs have several example commands which you could use to ping your own page at an interval.

    Extrakun : I guess I am more concerned about a CRON job that runs every minutes updating the data of a few hundred users all at one time.
    bummzack : An update to several hundred datasets once in a minute is no problem for a modern Database. I don't know how your queries look like, but a single 'UPDATE' call should still perform nicely even with thousands of affected rows.
    Lo'oris : And in what world a cron job is considered "simple"? If you're not a sysadmin you'll likely get mad just at looking at its configuration file...
    Ricket : The world of webhosts, where they don't (usually) give you SSH access so they need to provide an easy interface to Cron. My webhost (Lunarpages) uses Cpanel, and I find it quite easy to use:
    From Ricket
  • Regarding the updates:

    Some use CRON jobs that hit a certain PHP page every so often.

    Some use CRON jobs, this time running a certain process.

    Another approach is to do 'just in time' updates - whenever any page is loaded, run through any pending updates and perform them at that point. This is generally what you have to do if you can't run CRON jobs or long-running processes.

    Finally, others are running the whole web application as one process, so they can update whenever they see it is time.

    The final system is the best if you have that option available as you can store the data in memory. Updating a few thousand players once per minute is trivial if you're just changing data in RAM rather than having to write to a traditional SQL database.

    But if you don't have that luxury, you can use some sort of caching. Something like memcached may be one option (dependent on your hosting) which is a half-way point between memory and a database. You can store transient values in memcache and only save them to the DB when absolutely necessary.

    Between memcache and a traditional SQL database there are other options, eg. the various key/value stores or document stores: stuff like MongoDB, CouchDB, the Amazon or Google offerings, etc... ie. all the systems under the umbrella term NoSQL. These typically don't give you the generic querying power nor always all the same safety guarantees of a traditional database but are often much faster in operation. (Which is not so surprising, as they are doing less for you.)

    But this is all assuming a normal database can't handle the load. In fact, in most cases it probably can. If I have to issue 10,000 UPDATE calls per minute to increase resource levels, that's not very scalable once you start adding everything else on top. But if you change that to update the resource for everybody with 1 SQL call, suddenly things look a lot more positive. So don't overestimate how expensive a certain feature is, as it can often be implemented in a more efficient form.

    From Kylotan
  • It seems to me that you could just store the production rates, the base resource level, and a last-updated timestamp. Then, whenever you need to know the actual resource level, you could just multiply the production rate by the elapsed time.

    Whenever the actual resource level changes - simply update the base level. Whenever the production rate changes, update the base level to the actual level, and the timestamp to the current time.

    This way, instead of updating every player (presumably including those not currently logged in) every minute, you're updating only rows that are actually actively being used by players.

    (If your game "ticks" once a minute, I imagine a "turn number" of some sort might be better than an actual timestamp.)

    A side-benefit of this system is that you can use the same logic used to update the database, and to predict values without modifying them - to only send the necessary information to the client (rather than updating once per minute), and to predict values on the client.

    Kylotan : This does actually require some understanding of complex mathematics in some cases. Consider earning interest on money - adding 1% interest once per month is not the same as adding 12% interest once per year. Second example, if the chance of an event happening in a given minute is 10%, the chance of it happening after 10 minutes is not 100%. Interestingly this is just a very slow demonstration of the physics problems people see in other games, and the same method can be used to address them, ie. use a fixed timestep and run it as often as needed to 'catch up'.
    The Communist Duck : Kylotan, I wouldn't class compound interest and multiple probability chances as complex mathematics. :P
    Kylotan : If your understanding of calculus is ok, then sure, it's not complex. But these things don't work with "just multiply the production rate by the elapsed time" and it's important to highlight that.
    Andrew Russell : It's a valid point. But I would hope that anyone implementing non-linear resource production in their games understands how it works ;)
    Kylotan : But they don't need to, if they are using the old periodic update. That's the whole problem I'm getting at - using this method introduces a new potential error that was not a possibility before.
  • Modern SQL databases that are commonly used (MySQL,Postgres,Oracle,MSSQL,etc) allow you to schedule stored procedures to be run with arbitrary time intervals. It's a very light weight method of running updates like this and removes the need to invoke external script or program to do it for you.

    This also allows the database to optimize the query you run just once, instead of doing it every time external script invokes it, so it's very useful from performance standpoint. Of course this only applies if your updates are trivial enough to be programmed in your databases own scripting language. Resource updates, automatic time interval log outs, record purging and the likes are excellent candidates for these scheduled stored procedures.

    Most likely the load your database is experiencing comes 99.9% from page loads, game engine updates and the like, as a popular game can easily have hundreds of thousands of queries per second. Compared to the load that arises from running a few queries (although ones that touch large portion of a table) once a minute or so, the load should not be an issue. That is, unless you update values that are indexed by the database. You should avoid updating indexed columns at all costs if you worry about performance.

    From Fuu
  • I remember having a look at some Planetarion clone's code. Everything's PHP, but the ticker code is in raw C - with C MySQL bindings. Because the data model was very simple the updates happen really fast.

    From Ariejan

Synchronizing clients with a server and with each other

What is the best way for keeping all clients synchronized with a server and with each other?

Currently, we have two approaches in mind:

  1. When a client sends something to the server, the server immediately sends out messages to all clients, which react immediately.
  2. Introducing some time delay, whereby the server sends out messages to all clients, with the directive, "act upon this at time t.

The second approach seems like it would more likely keep the clients all in better synchronization (since it caters for some degree of lag); but I wonder whether responsiveness would be lost to too high a degree (i.e. the user clicks 'jump' and there is a noticeable gap between pressing the button and actually jumping).

There is also the possibility of having clients calculate their own position (and not wait for servers to say "you have jumped"); but because of the inevitable lag, clients would get very out-of-sync.

Then there's the whole TCP vs. UDP question; because we want it fast, but I'd also hate for the server to say you're in a completely different location than you thought you were.

With all of these competing demands, it all gets very uncertain how we should approach this issue. Which of these approaches (or any other) would be best for keeping clients and server all in sync? Which ones are actually used in the industry?

  • The quick answer is: there is no best approach.

    Games all contain different architecture; every game will choose different sets of data to send in order to synchronize itself with other machines, which will affect the choices that you can make when choosing how to deal with lag.

    What you specify in option #2 -- that clients send messages to be acted on at a future time -- is definitely one approach. In fact, the Source engine uses a variant of this approach, where rendering is always 100ms behind local client actions; all machines attempt to operate on the same actions at the same time. This adds an artificial, imperceptible lag to the game in order to hide actual network latency.

    If you can't take this approach, you can also choose option #1, simply sending the most up-to-date data and upon receipt, use interpolation and extrapolation (client-side prediction) to try to hide latency. I've used this approach in at least one shipping game -- but again, it all depends on your game; there may be other approaches you can take.

    Finally, when choosing between TCP and UDP -- you probably want UDP. There are scenarios where TCP is a viable option for networking your game, but when you're making an action game, you want the latest data as soon as possible. If you can deal with dropped packets yourself, UDP is the better choice. (There are libraries, such as ENet, that provide a wrapper around UDP to replace functionality from TCP, such as reliable packets.)

    coderanger : You really don't want to use UDP. The overhead of a correctly configured TCP connection is minimal and the hell that is out-of-order delivery is something no one should have to live through.
    Blair Holloway : It's not a matter of overhead, though TCP adds some - the way TCP deals with dropped packets is fundamentally not good in games where a large latency between action and reaction can make a *huge* difference in playability. For a game like WoW, where actions are relatively infrequent, TCP works, but it would fall over flat in a game like CounterStrike, as a single dropped packet will throttle your connection and potentially make you "lag out" for a second or more.
    Blair Holloway : If you're going to use UDP, it really is best not to write it yourself; use a wrapper like ENet that does the hard work for you. But my original answer still stands -- UDP is the best way to go if you're making a game with any sort of fast-paced action.
    BarakatX2 : For me, RakNet made running a UDP connection for my game engine extremely easy. It has many options for how you want to send your packet ie. how to order them, should the packet be resent if dropped etc.
  • Since you mention Clients and Servers, i'm going to assume that you're talking about a Client/Server architecture where the Server is the authority on the state of all objects.

    Note: The alternative is a Peer-To-Peer architecture where the owner of an object is the authority for that object.

    There is already a well proven method for synchronizing moving objects using Client-Server architecture. It's called Dead Reckoning..

    A good way to implement this in a game would be like this:

    1. Clients send inputs to the server.
    2. Server updates the game objects (accelerations & directions) and sends them back to Clients.
    3. Clients use these updated values to simulate the movement of the objects locally.
    4. Occasionally, the server sends a position correction to avoid drift.
    5. Rinse; repeat.
    From JanSolo
  • Here's a couple of good links which cover an awful lot of game networking.

    And this is the first part of the more hands on networking series.

    For the history. 'we're sorry, but as a spam prevention mechanism, new users can only post a maximum of one hyperlink. Earn 10 reputation to post more hyperlinks.' Just look around his website, anyway.

What are the technologies that makes physics engines so good for raycasting?

Hello, again. This question is strictly related to this one so, what is the technology that makes physics engines suitable for raycasting? It is a particular data structure? Has it to do with the engine's internal representation of the objects? If so, how do they represent objects so to be able to make polygon-precise raycasting? Do they hold the whole information about a mesh?

  • I don't think there are specific technologies that are exlusive to physics engines which makes them so good for Ray Casting. It's more the fact that in general they have very good ray casting capabilities because that's what they use to determine collisions between objects in the simulation. These have generally been optimised and tested pretty well as they're a fundamental component to a physics simulation.

    Why re-invent the wheel if you can leverage existing, fast and well tested libraries?

    tunnuz : So which technologies do they use?
    Muttley : Joe has mentioned specific types of algorithms used, if that's what you mean by technology.
    From Muttley
  • Good physics engines:

    • Use algorithms and data structures with good theoretical ("big-O") properties.
    • Use specific memory allocators and data layouts for improved cache efficiency.
    • Use microoptimized code, that not just has good big-O runtime but is also known to generate efficient code on real compilers / machines (e.g. SIMD and specialized instructions like fsel).
    • Use a variety of good spatial subdivision techniques (octrees, BSP trees, spatial hashes).
    • Use different levels of checks of various costs (e.g. first AABB, then tri-tri).

Developing games in Go?

Google's new Go language is still in its infancy, and it has yet to find widespread real-world use or support. Even so, it seems like a promising experiment, and I wonder if it could have a future in game development. I haven't been able to find much game-specific discussion of Go elsewhere, and figured a CW discussion may be appropriate.

Some thoughts:

  • According to, Go programs "run nearly as quickly as comparable C or C++ code"--quick enough?
  • Is Go's garbage collection well suited for games?
  • How much mental re-tooling is necessary to create games in the land of concurrent goroutines?
  • Go is frequently called a "systems"-level language, with server software given as an example. It's hard not to think of multiplayer game servers when hearing this.

Your thoughts?

  • My take on your questions:

    • The language is plenty quick enough. The slower Java language is used for game development. Even Python (pygame) is used for game development, and it's significantly slower than Java. It all depends on the type of game and how processor-intensive it is.
    • Garbage collection in general is not very good for games. However, Go has a particularly bad garbage collection system (mark-and-sweep) which stops the world while it cleans up stuff. It'll be difficult to cope with and will cause something of a stop-and-go framerate.
    • A decent amount of mental retooling is necessary to create games with coroutines. Graphics and logic can't be concurrent in the traditional sense; but at a smaller level, parts of the logic are great candidates for concurrent goroutines (e.g. parallel processing of AI decisions, particle systems, etc.)
    • A multiplayer game server may indeed be a great candidate for the Go language.

    In my opinion, if you have a strong enough urge to try writing games with a language, go for it. Obviously if you're considering it then you have a passion to do so, and why not follow that passion instead of forcing yourself to conform to the norm? I could say a lot more but I've already said a lot in my answer the question, "Is Ruby a suitable language for game development?"

    Joe Wreschnig : "a particularly bad garbage collection system (mark-and-sweep)" mark-and-sweep does not inherently stop the world - Java has a concurrent mark-and-sweep collector for example, and Lua used a naive one for a long time - and a lot of the length of the pause can be controlled via a careful generational system. That being said, Go's _is_ stop-the-world mark-and-sweep. But the former, not the latter, is the issue for games. (The Ruby thread had some weird claims about this too.)
    TSomKes : The current Go GC system seems to be something of a placeholder: "The current implementation is a plain mark-and-sweep collector but a replacement is in the works" ( Replacement options have been discussed; I'm not aware of any firm decisions on the matter.
    Ricket : Joe, thanks for clarifying! I wasn't aware of that. And yeah TSomKes, I did see that, so we can keep our hopes up that Go will implement a better garbage collector at some point.
    From Ricket
  • Something else to think about is that since Go is still relatively new, there may not be bindings for a lot of the common libraries used in game development yet.

    TSomKes : Definitely the case. For example, I've come across two Go/SDL projects, one of which seems to have been abandoned. I've found a bare handful of (relatively small) games that use either of them.
    From Bob Somers
  • Do not use Go to develop a game, it will just be an albatross around your neck. The toolchain for game development extends so much deeper than just the language that you write things in that you're going to find obstacles at every turn that just won't be there if you just go with something established.

    Don't get me wrong, I love playing with new languages, but if you are trying to make games pick a language that has a community and support and you will be much better off.

    Joe Wreschnig : On the other hand, if you're just going to hardcode stuff on a small indie project to play with a new language, worrying about the "toolchain" is overrated.

Why do we use physics engines for collision testing or raycasting?

Hello. There is a thing I don't understand about game engines: why it is so common to use physics engines to do raycasting or collision testing?

Say that you have a 3D scene loaded in your scene manager (Ogre or whatever) and you have to do some raycasting. Is it really efficient to load all your objects in the physical or collision world just to test them for intersection? Why do game engines don't implement the same structures so you don't need to load a physics engine? This sounds like a waste of resources, especially if you don't need physics.

  • (Rigid-body) Physics is collision testing, raycasting, and response. There's no magic pixie dust that changes that combination into "physics engine" - if you need collision testing and raycasting, you need some kind of physics engine, whether you use an existing one or roll your own.

    tunnuz : That doesn't answer my question. Raycasting is a geometric technique, why it is implemented in Bullet, but not in Ogre? Why should I load Bullet to do raycasting on an Ogre scene? I guess this has to do with how the scene is represented in Bullet, so why this representation is not implemented directly in Ogre?
    tunnuz : I mean, the representation could be a BSP, which is also useful in Ogre for back-to-front polygon sorting in order to do polygon-precise transparencies.
    Joe Wreschnig : All you are asking is "Why doesn't OGRE include a physics engine?" or maybe "Why doesn't OGRE include a bad physics engine?" The answer is because plenty of physics engines already exist.
    Kaj : This is a bold statement, and not true. If you need raycasting and collision testing you need a collision detection engine. If you want the to simulate rigid bodies that respond to collisions you need a physics engine. The only reason people use physics engines for collision testing is that (a)you can have it resolve collisions for you to prevent penetrations and (b) since collision detection is such a huge and important part of any physics simulation the implementation is likely more optimal than something you could whip up yourself.
    Joe Wreschnig : @Kaj: Like I said unless you are making a game where the only response to collision is deletion, here's where the asker's thought process invariably takes you: "I don't need physics, just collisions and raycasts!" -> "But my objects move, so I need something aware of all the objects' motions each frame or I'll get tunnelling" -> "Oh crap I have penetration, now I need the collision code to move objects" -> "Now it's not stable, I need it to manage forces and inertia, not just flat-out move stuff" -> This is a rigid-body physics engine.
    Kaj : Hmmm, from his/her question I assumed he was asking 'if I only need raycasting or coldet', say for object picking or some sort of collection game, or heck a shooter where every collision if fatal. In that case no physics are needed at all, although in many instances, if you can't get away with sphere/sphere I'd opt to abuse a physics engine for that anyhow.
  • Is it really efficient to load all your objects in the physical or collision world just to test them for intersection?

    Yes it is efficient... for the programmer. There are lots of physics engines around and it's far easier to just use one - than to strip one down, or implement raycasting yourself.

    Talking about code (in fairly rough terms):

    You've got the code to create physics objects (you're not going to coldet/raycast against fully triangulated models, are you?) in a data structure that is efficient for doing coldet/raycast (you're not going to bruteforce it, are you?). And then some wasted code for various physical properties (and depending on the physics engine you can probably avoid much of this). Plus the CPU and memory requirements for the same (relatively small).

    Then you've got the raycasting code. You need that in any case.

    And finally the rest of the physics simulation code - which just sits in its binaries, never executed, never loaded to cache. Code doesn't take up much space anyway.

    So the "wastage" here is utterly minuscule. Especially compared to the massive effort involved in replacing or stripping down half a physics engine.

    Joe Wreschnig : You still need some of the code for physical properties ("this is one-sided", "this causes a sound when collided with") regardless of whether you use a "not physics engine" or a physics engine, unless your game is really boring. As for the physics simulation code, you will need some of that in order to perform stably when resolving collisions, unless the only thing that happens on collision in your game is death.
    dash-tom-bang : We used the GPU on the (first) PlayStation to do our raycasts. Render the scene real quick from the "shooter", each entity a different color. Whatever color the center pixel is tells you the thing you hit... :)
  • Raycasting and collision detection is a smaller subset of a physics engine. Therefore most people use physics engines for this task and they generally have a good implementation of these functions.

    You can use the the collisions detection and raycasting features of a physics engine without using the Rigid Body dynamics part. For example Bullet has a btCollisionWorld class that just does the basic collision and raycasting. btDynamicsWorld is built on top of that.

    ODE (another popular but older physics engine) uses OPCODE (downloadable as a separate library) for its collision and raycasting.

    From lloydw

How to Further My Game Dev Studies Away from Technology?

I'm a college student, and I have a really boring class every Tuesday that's 2 hours and 45 minutes long. It's an interesting situation... attendance is required and checked, and electronic devices aren't allowed, but discussion isn't required and the lectures don't really matter to the exams. So I sit there in the back of the room either dozing off, doing Sudoku, doodling on my paper, pen-spinning, or trying to secretly use my phone without getting caught. I find myself wishing I could use the time productively.

Just like when one sits down with paper and crayons and can't think of anything to draw, I find myself wanting to do something to further my game development skills (e.g. work on the design of a game) but as I sit there with a pen and paper and the professor droning on, nothing comes to mind.

Help me get through this tedious class! What are some things I could think through or work on, or how can I figure out things to think/work on? Or even things I could print out in advance and read or solve during class. Remember the constraint is that I have no access to technology...

And I'm not sure a book would be appropriate. Though now that I think of it, I should probably just read game dev books from the library. Why didn't I think of that before? Anyway I still want to hear suggestions! What would you do with this time, if you were in this situation?

  • Possible things I did in class before

    1. I would draw on paper it help you get ideas

    2. Think of a game design and play it on paper or in my head.

    3. Questioning the lecture is always helpful to warrant discussion to make things interesting it also builds communication skills.

    Joe Wreschnig : I don't think "mitigates" means what you think it means.
    From Wight
  • Here is what I'm doing when a lecture is making me fall asleep

    • Think of a game design problem and try to solve it, going through some of the games you've played seeing what developers did wrong, what you can improve, what decision you would have took if you were in the position to do so, etc.

    • Make up a short story, it doesn't have to be complicated, just some characters and how do you think they should interact with each other. (e.g: i often think of a story of a midget elf who is trying to make something out of himself even though all the bigger elves laugh at him and call him name).

    • Write down whatever quirky thoughts you have, be it programming or design, having it lay down on paper with pros and cons, this can give you a better idea of how to balance elements in a game, in my honest opinion when you think about a design you have to nibble on it for a long time to see if it's good.

    • This may sound "Inception" like but draw labyrinths, level flow is extremely important in any game, you don't want just a corridor with some rooms now do you?

    From student to student: don't upset the teacher, being discrete in these kind of situation, where you have no interest in the course, is the best way to go about it. All I've written above can be seen as paying attention or taking lecture notes, so no danger there :)

    From Cristina
  • Pay attention in class and bring something unique from the lecture into the next game you work on.

    5ound : Good answer. Even if the lecture has no relation to gaming, not taking your studies seriously nor paying attention to things are negative traits to bring into the workforce.
    Joe Wreschnig : It also prevents you from becoming a useless derivative designer. Imagine if Ken Levine had skipped his "useless" philosophy classes, or Will Wright his "useless" architecture or biology classes, if Shigeru Miyamoto had never taken up gardening because it wasn't related to a narrow view of "game design", or Jordan Mechner never studied the animation techniques of rotoscoping. Assuming game development is learnt primarily in classes titled "game development" is to admit to be an uncreative assembly line worker, with the hope of one day being promoted to uncreative assembly line manager.
    0scar : Aren't you assuming Will Wright thought biology and architecture was tedious, but because he sat through it anyway he became a good game designer? I don't buy that. I think Wright thought architecture and biology was interesting, and I think that if he found himself in a tedious class, he'd day dream and sketch, and that's why he's a good game designer.

Will the same Flash game business model work for HTML5 games?

One of the best ways to earn money with Flash games is by making sponsorship deals. The developer puts the sponsor's logo and a link to their site in the game and lets the game spread around the web. The sponsor gains money from the ads and the extra traffic to their website. Alternatively, they site-lock their game to their website (usually for a short period of time) so that people who want to play the game go to their website. It's true that one can remove the site-lock with some effort by decompiling the swf, but it's usually not done as it's not worth the effort and not legitimate. Another significant part of the Flash business model is to put advertisements in-game. There are other ways of earning money with Flash games, but from what I know, these two are the most prevalent ones.

Since HTML5 is necessarily open source, it makes me wonder if this model would still work for HTML5. Even if you obfuscate your js, it's much easier than Flash to copy the game, so maybe it's worth the effort for someone to copy the game to their (illegitimate) site. If you add your sponsor's logo and link or advertisements, it might be worth the effort to remove them for their site, something that I think is much harder to do with Flash games. Perhaps even the illegitimate site could claim that their site is better because there are no in-game ads. There's still the legitimacy barrier, but I wonder if it's strong enough.

Let's put aside all game development technical restrictions regarding HTML5 for this question (suppose for a moment that HTML5 works just as well as Flash for games). I have two very similar (pair of) questions. The first is, would the Flash business model work with HTML5? What changes to it would be helpful for HTML5 games? The second question is, what about the big picture for HTML5 games? Is adapting the Flash model really the best solution, or is there a better model for the HTML5 games world to "turn"?

  • I don't think a lot will change, actually. SWF files are easy to decompile. Yes, the ActionScript will have made some irreversible changes that will make the decompiled code harder to figure out (destroying variable names, inlining functions or whatever) but a Javascript obfuscator could do that as well.

    Hacking client software to remove ads is probably always possible, whatever language you use. So you have two options:

    • Make it as hard as possible so it's not worth the effort
    • Fight it the legal way, if there is one

    One possible issue might be that browser extension like AdBlock or Greasemonkey can more easily change the game at runtime.

    scytos : Can a Javascript obfuscator obfuscate as well as a decompiled AS3 code? Say I just want to remove the sponsor's logo and link from the main screen. Is it significantly easier (or possible to automatize) or is it the almost same thing comparing obfuscated js and decompiled swf? If it's almost the same, then I guess there shouldn't be much of a problem for HTML5 games.
    Bart van Heukelom : That depends on the obfuscator. I have never used one, but in theory they can do the same readibility-destroying things the AS3 compiler does.
  • You could tie users into using only your implementation by having part of your game logic on a server (hosted by AppEngine etc) which is accessed from the HTML, and check on the server that the caller is in fact yours.

    scytos : This is an interesting solution, but this would force developers to write part of their code to be run server-side, which is undesirable. Also, I think the caller can be spoofed in js, can't it?
    Bart van Heukelom : Unless the server will render the entire screen, removing ads will still be easy. You simply can't force anything on the client PC.
    From funkybro
  • HTML5 games face a lot of hurdles:

    • uncertain browser compatibility
    • stability
    • poor audio support
    • slow JavaScript execution speed
    • slow rendering speed
    • no designer tooling
    • source and assets are easily viewable / copyable
    • game is easily hackable while running
    • games embedded into other portals could run malicious code on the host portal
    • lack of in-game advertising infrastructure
    • game cannot be distributed to portals as a single file
    • games could potentially "leak out" of their frames onto the page if not embedded correctly

    So in summary, I don't think the current Flash game portal model will work for HTML5. I think where HTML5 might be successful is Facebook/Farmville style games.

    Bart van Heukelom : "Let's put aside all game development technical restrictions regarding HTML5 for this question (suppose for a moment that HTML5 works just as well as Flash for games)."
    Iain : Yeah but you can't put aside the technical restrictions of a technology! That's completely illogical.
    Bart van Heukelom : What I mean is the question is about the "code security" of Javascript, not about other features that may be missing or bad.
    Iain : Maybe I misunderstood, I just thought the question was "Will the same Flash game business model work for HTML5 games?", which takes in many different issues. There's no point ignoring some issues as they all inter-relate.
    scytos : You're right and you have a good list, but what I meant was to assume we're in a future where HTML5 is further developed. Most of these issues should be fixable with a lot of time and effort, but the fact that the code is open won't change. The particular obstacles I want to consider in your list are viewing/copying/modifying source and assets. What I'm wondering is whether these particular obstacles would stop the Flash business model to move over to HTML5.
    Iain : Oh OK - no, I don't think viewable source alone is a real stumbling block - it doesn't stop millions of other web site and apps. AS3 is still stupidly easy to decompile and there aren't millions of stolen Flash games out there.
    From Iain

Efficient way of drawing outlines around sprites


I'm using XNA to program a game, and have been experimenting with various ways to achieve a 'selected' effect on my sprites. The trouble I am having is that each clickable that is drawn in the spritebatch is drawn using more than a single sprite (each object can be made up of up to 6 sprites).

I'd appreciate it if someone could advise me on how I could achieve adding an outline to my sprites of X pixels (so the outline width can be various numbers of whole pixels).

Thanks in advance,

  • Greg.
  • I'm not sure of effiency, but the easiest way I can see would be to draw a larger version of the sprite in the colour you want selected first. Draw the sprite on top of that. You'll only see the edge of the first sprite, giving the effect of selection.

    EDIT: However, as you can see from the comments, this isn't a good idea.

    Iain : Just scaling up a sprite doesn't give a true outline
    The Communist Duck : I don't think it would, but it would be easy.
    Joe Wreschnig : Plenty of things are easy but don't solve the problem. For sprites with any kind of interesting silhouette a scale-up will produce absolute garbage.
    AttackingHobo : Scaling up will only look good for solid square or circular objects. If the shape is really wide, or tall, or has gaps it will look really bad.
    dash-tom-bang : Scaling up will give better results than doing nothing and would also be a useful step along the path to "perfection." While the graphical results won't be perfect, if this were for an internal tool it may be Good Enough.
  • I guess you need to draw all the pieces who each object to a single sprite first. Then I think you'd have to write a shader to detect the edges of the sprite a draw a pixel where-ever it finds an edge. I expect there must be some shaders out there already to do this, which you could either use or port.

    Joe Wreschnig : This kind of shader is surprisingly annoying to write, I've heard (we used it in one of our 3D games and kept running into unsightly edge cases). One thing you might want to consider is encoding the outline directly into the sprite texture with a specific color like (0, 255, 255, 0), and just have the shader transform that color when the sprite is selected. Then the shader is a trivial color change, and you have a high level of artist control over the outline and any details you want.
    From Iain
  • The simplest brute force approach is to build two copies of each sprite, a normal and a highlighted one. Then just swap them when highlighted.

    If you've got memory to spare there is no need to get more complicated then that. Plus artists have complete control over the look when highlighted so you can do an outline or anything else you'd like.

    Chris Howe : I think part of the problem is that the OP says each object can be made of multiple sprites. So I guess the outline has to be the outline of the combined object, instead of having a separate outline around each component sprite.
    AttackingHobo : Chris, it does not have to be the outline of the combined object, and it will work fine for an object made out of multiple sprites. Just do exactly what wkerslake said, but make sure you draw the highlighted sprites behind all of the normal sprites for that object. That way no matter how many sprites an object is made of, the highlight will only use slightly more than double the draw time for that object, which should be a lot less than generating the outlines at rendertime with the combined sprites.
    From wkerslake
  • How about for each sprite, also have another sprite that's an outline of the base sprite. When drawing an outlined object, draw the base sprites, then make a mask of the combined rendering, then draw the outline sprites excluding the mask.

    Chris Howe : Why not just draw the outline sprites first and draw the regular sprites over them?
    Joe Wreschnig : One reason not to do this (or Chris's suggestion) is because it uses twice as much texture memory; another reason is that the artist workflow is crap because you need to update two files every time you change a sprite.
    Chris Howe : Well yeah, you ideally wouldn't have two actual sprite assets. If you're using alpha-testing for your sprites you could put the outline into the sprite and give it an alpha slightly higher than your transparent areas. Then by controlling the alpha test reference value you can control whether the outline is visible or not. All I was saying is that if you have 2 versions of the sprites (whether its 2 assets or 2 states of the same asset) you should draw the outline version first, and then the normal version. This way you don't require any fancy shaders, masks, or whatever.
    jpaver : Chris's idea has merit; in addition having the artist update 2 files (or even the same asset) can be avoided if you produce a tool to generate the alpha for the outline sprites that runs as part of your asset/content pipeline. Texture memory may or may not be a problem, but separate outline sprites should be highly DXT compressible; possibly 1/6th the size of the original texture in video memory and with no fidelity loss.
    From gray
  • Depending on requirements, what might also be effective is just creating an outline on-demand for the sprite. I'm assuming your sprites have transparency, and are irregularly shaped rather than just being rectangles (while this would work fine for that, outline rectangles should be Trivial).

    when selected:
       outline = new sprite canvas of appropriate size
       for sprite in object:
          # use larger numbers for thicker outlines
          for x in (-1, 0, 1) and y in (-1, 0, 1):
             render sprite mask into canvas at x,y with desired color

    Note that you don't need to do this every draw (although I suppose you could), but just create the new outline sprite when switching sprites.

    Kaj : Yes, this is what I wanted to suggest as well. Render the masked sprite 1 pixel to the left, right, top and bottom of the original sprite, under the existing sprite. Many games used this method to outline rendered text, or with only 2 of the 4 positions to create a drop shadow.
  • By far the easiest way to do this (so probably the best way, unless you are really strapped for performance) is to have two copies of your sprites.

    • The regular version
    • A"fat", uncoloured version - basically a white version of your sprite X-many pixels "fatter" than the original.

    Draw your entire object using the "fat" version, then draw the regular version over the top.

    By making the "fat" version white, you can use SpriteBatch's built-in colour tinting to change the selection colour dynamically.

    To generate your "fat" verison I recommend writing a Content Pipeline Extension that can automatically take your original sprites, read their alpha channel, create a new alpha channel by sampling the maximum alpha channel in the original image X-many pixels around each pixel, and setting RGB = (1,1,1).

    You will have to make sure your sprites all have sufficient transparent border to add the outline (you could check this in the content processor - and even make room if necessary).

    If you only have a few sprites, then you could just use a good image editor (GIMP, Photoshop) and do it by hand: Alpha channel to selection, expand selection, selection to alpha, fill colour channels white.