# Question
Title: Making a Video Splash Screen for an Android Based Game
I'm planning to make a video-based splash screen for the simple game app for Android under client's cigarette brand project. I was thinking if can this video file type, AVI, run on Android or not? Please suggest me.

# Answer
> 2 votes
If you just want to use the built in Media Player in Android, you can't play AVI files. See the list of all supported formats.

If for some reason you can't convert the video to any of the supported formats, you will have to implement your own media player which has codecs etc. You can take a look at FFmpeg. It is possible to compile for Android.

---
Tags: java, android, video, file
---


# Question
Title: Is it possible to design Android game(AndEngine) levels using XML?
I am developing a game. In the game there is a lot of levels. Is it possible to design game levels using XML? Or what are different ways to design game levels? Please help me. Give some link or example so that i can understand easily... Thanks

# Answer
Yes, it is possible. AndEngine has a Level loader that can do exactly what you need. I recommend going through these tutorials. In the final tutorial, creating a whole game, one of the chapters talks about level creating and loading. Look for a class named `SimpleLevelLoader`.
> 5 votes

---
Tags: android, andengine, level-design
---


# Question
Title: Newbie game programmer - Where do I start?
Okay, so I have been really inclined towards game programming this past few weeks. I have primarily been a web programmer and know a fair number of lanugages like PHP, Java, javascript, python, etc. I also know a little bit of C++ as I heard that it's used heavily in the game industry. I have no experience in game development, but I am a fast learner.(I am 15 so I guess I still have a lot of time.)

So, is there any language I should learn to develop 2d and 3d games? Also which IDE(free) is a nice place to start compiling your ideas(something like Polycode:- http://polycode.org/). I looked up Polycode but it was a little confusing for me to build it. I have a fair idea about what DirectX, OpenGL, SDL and shaders are but I have absolutely no clue about programming them. I know it's a little early to start jumping into this stuff already but you gotta start somewhere right? Please help me as I really want to get into serious game programming. Thanks!

I am running Windows 8 Pro 32 bit. Please suggest me any software accordingly!

# Answer
You really shouldn't post a question like this as it is clearly stated in the FAQ that you shouldn't...

---

Knowing some C++ is a great start and you should really focus on getting better at that. Learning some of the STL is a must if you plan on game programming with C++ IMO (e.g. vectors for automatic management of multiple sets of data).

It depends what you want to do as to where you should go from there

---

## For engine development and building a game atop that:

1. Become fluent at your language of choice. C++ is really good for speed and usability but will take longer to become fluent in than something like C#.
2. Learn a windowing API. Could be native, like X11 or GDI; or an abstraction, like SDL or SFML.
3. Learn a graphics API. OpenGL is the best choice in most cases (for it's cross-platform and open nature).
4. Learn the shading language appropriate to your API. GLSL for OpenGL, HLSL for Direct3D.
5. Learn an audio API. OpenAL and EFX is my recommendation, but you could use something like FMOD if you don't mind paying a licence when your game becomes commercial. One isn't better than the other; it is opinion to say so as anything built into FMOD can be put together with AL. If you learn OpenGL then OpenAL will be a lot easier as the API's are quite similar.
6. Possibly learn or create a scripting language for your engine/game. Learning one would be easier in the long run but creating one isn't the most difficult of things and would reduce dependencies while giving you full control over features.
7. Put all your skills to use and create a game!

You will need to learn a few other things like model, audio and texture file parsing but libraries can be used for things like that to make your life a whole lot easier.

AND atop all of that, you will need to be able to get or create models and audio for your game.

Try and keep it cross-platform; more money that way \>:D haha and it makes everyone happy when they can play your game on their OS of choice.

---

## For game design and creating a game with a pre-existing engine:

1. Learn the scripting language the engine gives you. e.g. Unity uses a JavaScript based language called UnityScript.
2. Learn how to create models, buy models online or find free ones(free as in can use it commercially). Blender is a great piece of software for model creation and is quite easy once you know how to use it. Make sure you convert or create your models in a format the engine can load!
3. Record some sounds, buy some online or find free ones. Make sure you convert or record all your files in a format the engine can load!
4. Put it all together!

This approach is less satisfying in the end but you will get your game out a LOT quicker than had you written your own.

---

You could use a pre-existing engine then move on to writing your own. That would help you familiarize yourself with game design before moving on to engine design.

I have been writing my own engine for a couple of months. So far I have got my own model format, basic scripting language, parser for both, OpenGL rendering, OpenAL audio and SDL for windowing. I am only 16 so it is definitely not too early to start.

Here's a picture of my engine after 2 months with about 6 years of C/C++ experience under my belt:
> 5 votes

# Answer
If you want to start making games fast and you already know Javascript then i would suggest looking into http://unity3d.com/ . It's a free IDE for creating 3D (and also 2D) games, comes with a big community so you can easily find many tutorials and free stuff for your project. It's quite easy to learn even if you don't have experience in making games.
> 2 votes

---
Tags: game-design, software-engineering, graphics-programming, game-industry
---


title: Ring and Pole - Box2d

text:
# Question
Title: Ring and Pole - Box2d
How I can make a b2Body in box2d so that it could form a ring which does not collide from the center just like a ring. like when we flick the object and there's another body (like pole), the pole can go inside from the ring.

like this:

# Answer
> 2 votes
I assume you want to view the scene from the side? Pretty easy to be done. Just create two circles that are connected to each others with some space in between:

```
O    O

```

You just draw the actual ring (the part not colliding) over the "empty" space.

---
Tags: box2d, cocos2d-iphone, physics
---


# Question
Title: How to deal with player inquiries (good, bad, and everything in between)?
I understand someone previously posted about dealing with bad suggestions from players. But I'd like to ask about dealing with inquiries in general.

When a game becomes popular, it's inevitable for you to receive heaps of emails from players (can be complaint about bugs, errors in purchases, etc). How do you usually handle these? Do you outsource these kind of things or do you try to answer the mails on your own during your free time? Or maybe create an online community like a forum?

# Answer
> 6 votes
You need a bug tracking system.

Here are some approaches in software engineering over the ages:

* **Dedicated systems.** Launchpad is the official platform for reporting, tracking and discussing the Ubuntu operating system's bugs. It's a free service available for anyone though. For medium-sized projects, I've had success with Trello.
* **TODO.txt**. For small projects, developers often implement a custom bug tracking system as a text file in the project root directory. Changing this is no fuss, as the bug tracker effectively lives in revision control like most of the project files. It takes a lot of effort to maintain correctly though!
* **Forums**. Dropbox has forums, where the devs take feature requests and bug reports. It's conversational and since a Dropbox account is all you need for posting, it has a low barrier for entry. However, it's unstructured: I suspect Dropbox need their own more structured issue tracker that someone periodically and manually feeds reports from based on threads in the forums.
* **Email**. For the first few years, Linus Torvalds manually accepted patches to Linux over email. Bug reports went on a mailing list. When Jamestown crashes to a script error, the error box requests to send the developers a log by email.

# Answer
> 2 votes
In my opinion it really depends on the scope of your project, the target audience, etc.

You should offer as many options as possible, especially ones that fit your actual community/customers:

* **Email** is something I'd consider a must-have. Give fans some form of contact if everything else fails. Noone expects instant answers, but it's still something that clearly shows "I don't want to ignore you".
* **Forums** are a great way to outsource part of customer support to the community itself. Just keep in mind that players or users can't solve everything on their own and you have to keep an eye on them and help where help is needed.
* **Ticket systems** should be considered mandatory if you've got things people can't discuss in public, like payment issues, account problems, etc. These can be handled through email as well, but ticket systems usually offer a far more organized structure making the whole thing a lot easier for both sides.
* **Idea collection** can be another thing, especially if you want to work with your community (e.g. determine what they really want next). You can use a forum section for this, but there are also dedicated solutions out there, e.g. getsatisfaction.com, where users can suggest things, they can vote on them, etc.

As for the actual scope, how much you do it yourself, whether you should hire other people to do it,... This really depends on your actual project. In my opinion you could simplify this question to one single formula: The more money you make, the more professional and faster your customer support should solve issues.

For example, if I notice a bug in some open source game, then I don't expect any immediate answer or "thank you". If it takes one or two weeks, it doesn't matter. However, if I can't log in to that MMORPG I'm paying monthly to actually be able to play it, I expect answers within 24 hours, maybe even the same day depending on the actual issue or severity.

If you're making enough money to pay one or two people to actually look after your customers (e.g. answering support enquiries or moderating forums), do so, if you think your overall image (and the community of course) profit from that. But don't forget that for some things like forum moderation you can as well include the community once again. Many dedicated fans will be more than happy to help you building a better community.

---
Tags: community-management
---


title: What options do I have for game hosting

text:
# Question
Title: What options do I have for game hosting
DISCLAIMER: I know this question starts to leave development island but it is very game development related and still think this is the best place.

I see many free MMOs/online desktop client games out there. I am baffled at the ability to fund such. I don't mind hosting myself but would at least like to have someone host a matchmaking service. If these indie devs really are pouring money down the server drain then I'm screwed but if some one can "learn me" :) some alternatives I would greatly appreciate it.

# Answer
You can host a simple matchmaking service on Google App Engine for free. It should be able to service many users. If it starts being really really popular, you can start paying for the service with what you earn.
> 10 votes

# Answer
You can also put off some server cost on one of the users after you setup a match. Have one random player (preferably with the best connection to all the other players) become the "host". If this player disconnects, then find the next best host and so on.
> 2 votes

# Answer
I know this question has already been answered, but especially with the recent release of the elastic beanstalk, Amazon's Web Services are another alternative.
> 1 votes

# Answer
What you really need to host a game is a **virtual machine** in the cloud.

A "VM in the cloud" is just an "instance" of an O/S running on some hardware on some server that has good internet connectivity. Multiple VM's can run on the same piece of hardware, (but that isn't a concern to you as the consumer). They promise you availability of certain minimums of CPU power and RAM usage. For all intents and purposes though you just have got a remote machine that you can SSH into (or Remote Desktop or whatever).

There are **2** major providers that I know of (others please feel free to add more) that offer reasonable prices.

1) Amazon Web Services' EC2 (from $0.02/hour). There are a lot of configurations to choose from, but if you don't even have an Amazon account yet, then that's good because you can get free use of a "micro" instance for 1 year (1 year is *from the date you sign up*, not from the date you kick on your first server).

If you've already had an account for a year, prices are around $0.02/hour. For a Linux "micro" instance. So in one month, that totals about $15 (744 hours/month).

---

2) Windows Azure (from $0.02/hour) offers *both Windows and Linux* VM's for the same price. If you want to program with Microsoft technologies, Azure is worth a try (I'm not sure about QOS vs Amazon) but it definitely seems the licensing premium is lower when you go through MSFT directly instead of renting a Windows box from Amazon.
> 1 votes

# Answer
Steamworks is an option if you don't mind being tied to their platform (not a huge loss since most gamers probably have Steam already).
> 0 votes

# Answer
If you want a very simple thing, you can find "free" stuff on the app engine and such, but also, you can run quite complicated stuff on slicehost.com and start with 20 bucks. You would be surprised of how much you can do with small slices. If you get more traffic than a couple hundred bucks can pay, you should be able to generate money somehow.
> 0 votes

---
Tags: server, client-server
---


title: Optimising skeletal animation

text:
# Question
Title: Optimising skeletal animation
I am implementing a skeleton system for my latest game. I am using my own linear algebra classes which already have some optimisations, such as separate transformPoint and transformVector functions which avoid some multiplications by 0 or 1. It is working well so my question is not HOW to implement skeletal animation.

My question is how to optimise the matrix multiplications. At the moment there are several full 4x4 multiplications and 1 inverse per bone. I need the inverse because this is not just for skinning but also physics and stuff. But there are many 0s and 1s in the homogeneous matrices which can be optimised out. Also, I want to be able to specify the degrees of freedom for each joint, and in which order they are calculated, so for example, a shoulder joint could rotate yaw then pitch, or pitch then yaw. The result would be different. Should I have a separate matrix constructor for each permutation, which I believe is 15?

I assume this is a common issue with skeletal systems, so is there a standard method for this? How do engines normally optimise forward kinematic calculations?

I calculate all the matrices for the bones, starting at the root and working outwards. Note: my bones are in an array that is sorted by heirarchy depth so a bone's parent's matrices will already have been computed.

Please note: this is not a questions about skinning, I have no problem with that.

# Answer
for the different matrix constructors: no it's easier to do a chained invocation `matrix = Matrix4d.identity().rotateYaw(yaw).rotatePitch(pitch).translate(attachPoint);`, and each of these rotate operations can be optimized (and the inverse calculated along side it)

the bottom (0 0 0 1) row can be optimized out easily by not even storing them (assume all matrices are homogenous) and using a more general algorithm for the perspective matrix of the camera
> 1 votes

---
Tags: matrix, optimization, linear-algebra, skeletal-animation
---


# Question
Title: Looking for detailed pathfinding examples
I am currently working on a 2D-TopDown game. Now I was looking for pathfinding algorithms. I read and understood A\* and Dijkstra. But there are still some questions I have. So I am looking for examples which cover the following topics when it comes to pathfinding:

1. Collision (Pathfinding should consider obstacles)
2. How are those algorithms implemented properly in game's AI? I mean do I have to calculate all possible paths? That could be an performance issue?!
3. I am not using tiles on my maps so how do I get the single nodes for a wighted graph (Dijkstra)?

I would be very pleased if somebody could point me in the right direction.

Thanks in advance!

# Answer
> 5 votes
I don't have any example in mind at the moment, but I'll try clearing your doubts.

Pathfinding algorithms work on graph structures (connection of nodes). A grid is an example of a graph, but it's not the only graph structure available for pathfinding. Basically, any kind of "set of nodes" will do.

If you don't have a tiled map, don't worry, you can still have nodes where you desire. A common thing to do is create a navigation mesh (nav mesh), a human-designed or procedurally-generated graph that places nodes in parts of your map you can walk into.

The above picture is a navigation mesh from World of Warcraft. The green nodes are used for pathfinding, and the polygons created by connecting those nodes sample the walkable space. This should clarify questions 1 and 3.

Another common practice is creating many grids on top of your current level architecture, every one more precise than the previous one, in order to speed up pathfinding.

Performance can be an issue, but you can be smart about it. If you don't need every single actor to find its own path, you could use influence maps or breadth-first search to crate a global map the actors will follow.

Check this video out: http://www.youtube.com/watch?v=DusL7kXSJlc

The goal (in this case the player), generates an influence map around him, and what the enemies do is simply move from areas with less influence to areas with more influence, no pathfinding involved on their part. You can generate multiple influence maps if you have more goals (for example, more "factions" battling each other in a RTS).

Pathfinding is a complex subject, but there are many resources you can find by googling. Let me know if you still have doubts.

# Answer
> 1 votes
Collision happens during graph traversal, "can I move from this node to the next?" is a collision check. Or in algorithm space, the cost to move from this node to the next is temporarily infinite if it is blocked.

You are using weighted nodes with costs associated with moving from one node to the next, right? Proper weighting fixes all sorts of stupid looking pathing =)

You **never** calculate all possible paths, you only need one best path, that's what all the methods you mention do. If you are working with multiple units then you either weight against spots already on a used path for subsequent queries or use some sort of flocking behavior to move the group along the one path.

If you don't have "tiles" then you must generate them yourself from the geometry of your levels. Please note that A\* is not restricted to working on a square grid, many people make this mistake.

If you are using some kind of 3D geometry I have used this method successfully before: find all the faces that are within 45deg of flat (i.e. no walking up walls); then build the weighted graph from center-points of these faces based on adjacency. A standard depth first search will get your path.

# Answer
> 1 votes
A\* and Dijkstra are quite a bit slow when you use it for a huge amount of units at the same time. You could use some simpler algorithms as *robust trace* and improve their found solution. The solutions from robust trace (which in a simple ways finds a way around obstacles) can be improved by checking at each position of the found path if it can walk the direct line of sight to any later position on the path. You should also improve robust trace by comparing the way "left" and "right" around an obstacle and take the shorter path. The algorithm with these optimizations should always find a way to a target (if it exists), even in a complex maze. The difference of the found solution compared to the optimal path is negligible in most cases.

You can reduce your collision problems by calculating the paths one by one by a global path planner, which keeps track of which position on the map is already planed to be blocked at a certain point in time. The unit will then either need to walk around the other unit or wait a bit, till it moved on. While this can cause performance issues, you can stick to a simple algorithm, that just plans a static route using the currently blocked fields on the map. While executing the plan a unit will eventually see it's planned path blocked. In such a case, let the unit execute its planned route for some more time (if possible) and observe if this special point on the map is still blocked. If it gets "unblocked", continue ... if does not get "unblocked" for a continuous time span (of e.g. for 3 seconds) the unit should plan a new route.

These algorithms will be have a well performance even on slow computers. I implemented them about 10 years ago on a PDA using a V30MZ processor (33MHz, 16-bit) to route about 200 units of a real-time strategy game. It worked very fluently ...

---
Tags: xna, c#, ai, path-finding
---


# Question
Title: Score system for "little bit more complex" snake game
I have created snake game. I can't think of good score system so that is is fair.

There is only one highscore list for all modes.

Player can choose any size of board \- Let's call that param "Board area", it is defined in cells. One snake segment takes one cell.

Player can choose any speed of snake \- Speed, in cells per second

I don't know how to calculate it so that score is fair for all players.

Firstly I thought of this: score = length * speed But is is not fair for players that reach end of board (nearly no free spaces to go, careful planing is needed to survive).

Then I thought that I need somehow award players that can survive for long in small amount of free place. The new formula looks like that: score = (length/board size) * (length * speed) But I still don't like it.

My score should reward players for: Longest snake, tight turning and planning (bigger multiplier when board is full), and speed at which they are playing.

# Answer
> 5 votes
I'd squeeze in another variable - `cells travelled` \- it could act as your "planning" score.

### Base

Given the core variables `speed`, `length`, `cells travelled`, the main formula could be:

`score = base * (length * speed)`

With `base` being:

```
base = cells traveled; // basically, this could prove enough

// optionally
base *= board size coefficient; // a coefficient based on board size could apply to base, this is for you to judge, but generally the idea is that the larger the board, the smaller the coefficient.
base *= prohibited cells; // prohibited cells ("walls") also being an applier - the larger the prohibited cells, the larger the coefficient.

```

### Tight turn

I'd give `tight turn` a constant value. So, once a tight turn happens: `score += tight turn * speed`. Though, `length` could act as a modifier again - `base += tight turn * (length * speed)`.
You could also apply a modifier to `tight turn` based on how tight it was by checking the distance between head and tail after turn.

### Fruits

In case you have "fruits" there, lets give them a constant value again `fruit`, once we eat one: `base += fruit * speed`.

### Extra mechanics

You can also implement extra mechanics. One variable being *cells travelled to get the fruit*.

The other being, *tail kiss* \- gives extra points once head, being perpendicular to tail, exchanges the last tail block.

---
Tags: c++, game-design, c, scoring
---


# Question
Title: AS3 + Flash IDE - Stage Boundaries and Collision in Sidescroller not working properly
I am trying to do a pretty simple sidescroller in Action Script 3 with Flash CS6 and I am currently stuck at the stage boundaries and the level scrolling.

My hero should move freely in the middle of the stage and should be stopped if he enters a position greater that 75% or smaller than 25% of the stage with the level starting to scroll unless the level reaches one of the ends (then he should be able to walk exactly to the stage boundaries). The Level is a wide movieClip which should later contain blocks to jump on and tweened enemy's.

Currently I have a Main.as class that instantiates the Level class, in which I have my hero. There are a lot of mistakes in the boundary code I think, but I am so stuck at the moment that I totally need some help.

Here's a link to all Files with the fla: JumpGame

Thanks in advance for all advices :)

The following calculations are currently done in my hero object with setter and getters to access them:

```
private function keyDownHandler(e:KeyboardEvent):void
    {
        trace("Keycode" + e.keyCode);

        if (e.keyCode == Keyboard.LEFT)
        {
            _accX = -0.2;
        }

        else if (e.keyCode == Keyboard.RIGHT)
        {
            _accX = 0.2;
        }

        else if (e.keyCode == Keyboard.UP || e.keyCode == Keyboard.SPACE)
        {
            if(_isOnGround)
            {
                _vy += _jumpForce;
                _isOnGround = false;
            }

        }
    }

    private function keyUpHandler(e:KeyboardEvent):void
    {
        if (e.keyCode == Keyboard.LEFT || e.keyCode == Keyboard.RIGHT)
        {
            _accX = 0;
        }
    }

    public function frameEvents():void
    {
        //Apply acceleration
        _vx += _accX;
        //Apply friction
        _vx *= _friction;
        //Apply gravity
        _vy += _gravity;
        //Limit the speed, except when the character
        //is moving upwards
        if (_vx > _speedLimit)
        {
            _vx = _speedLimit;
        }
        if (_vx < -_speedLimit)
        {
            _vx = -_speedLimit;
        }
        if (_vy > _speedLimit * 2)
        {
            _vy = _speedLimit * 2;
        }
        //Force the velocity to zero
        //after it falls below 0.1
        if (Math.abs(_vx) < 0.1)
        {
            _vx = 0;
        }
        if (Math.abs(_vy) < 0.1)
        {
            _vy = 0;
        }
    }

```

The boundaries are calculated in my Level class:

```
private function onEnterFrame(e:Event):void
    {
        trace("LevelX:" + this.x);
        trace("stage" + stage.width);

        _hero.frameEvents();

        _levelVX = _hero.vx

        //Hero Boundaries

        if (_hero.x < 0.25 * _viewWidth)
        {
            trace("Hero is in 25% Boundary");
            if (this.x > 0)
            {
                trace("Background is at the beginning");
                this.x = 0;
                _hero.x += _hero.vx;

                if (_hero.x < 0)
                {
                    trace("Hero is at the Beginning");
                    _hero.vx = 0;
                    _hero.x = 0;
                }
            }

            else if (this.x < 0)
            {
                trace("Background is NOT at the beginning");
                this.x -= _levelVX;
                _hero.x = 0.25 * _viewWidth;
                _hero.vx = 0;
            }
        }

        else if (_hero.x >= 0.75 * _viewWidth)
        {
            trace("Hero in 75% Boundary");
            if (this.x > -this.width)
            {
                trace("Background not at the end");
                this.x -= _levelVX;
                _hero.x = 0.75 * _viewWidth;
                _hero.vx = 0;
            }

            else if (this.x < _viewWidth - this.width)
            {
                trace("Background is at the end");
                this.x = this.width - _viewWidth;
                _hero.x += _hero.vx;

                if (_hero.x > _viewWidth -_hero.width)
                {
                    trace("Hero is at the End");
                    _hero.x = _viewWidth - _hero.width;
                }
            }

        }

        else

        {
            trace("Hero is Moving in the middle");
            _hero.x += _hero.vx;
        }

        if (_hero.y < 0)
        {
            _hero.vy = 0;
            _hero.y = 0;
        }

        else if (_hero.y + 100 + _hero.height > _viewHeight)
        {
            _hero.vy = 0;
            _hero.y = _viewHeight - _hero.height - 100;
            _hero.isOnGround = true;
        }

        _hero.y += _hero.vy;

    }

```

# Answer
Found another approach, hope this help anyone soon who is programming a sidescroller. Sadly my approach doesn't consider the maximum width for a level movieclip on the stage and it doesn't just render what's inside the stage boundaries. So much to improve, but anyways here is a working answer using custom event handlers:

Hero.as

```
    //EnterFrame function triggered in Main.as
        public function frameEvents():void
        {
            //Apply acceleration
            _vx += _accX;

            //Apply friction
            _vx *= C.FRICTION;

            //Apply gravity
            _vy += C.GRAVITY;

            //Limit the speed, except when the character
            //is moving upwards
            if (_vx > C.SPEED_LIMIT)
            {
                _vx = C.SPEED_LIMIT;
            }
            if (_vx < -C.SPEED_LIMIT)
            {
                _vx = -C.SPEED_LIMIT;
            }
            if (_vy > C.SPEED_LIMIT * 2)
            {
                _vy = C.SPEED_LIMIT * 2;
            }

            //Force the velocity to zero
            //after it falls below 0.1
            if (Math.abs(_vx) < 0.1)
            {
                _vx = 0;
                _isMoving = false;
            }
            if (Math.abs(_vy) < 0.1)
            {
                _vy = 0;
                _isMoving = false;
            }

            //Move Horizontally

            //Is Hero moving Left?
            if (_vx < 0)
            {
                //Check if Hero should move Left
                if ((_levelX >= 0) || (this.x >= 0.25 * C.GAME_WIDTH))
                {
                    //Move Hero Left
                    this.x += _vx;
                    _isMoving = true;

                    //Stop Hero at Left Level Boundary
                    if (this.x < 0)
                    {
                        this.x = 0;
                        _vx = 0;
                        _accX = 0;
                        _bounceX = 10;
                        this.gotoAndStop("standLeft");
                        _isMoving = false;
                    }
                }

                //Trigger Event to move Level right (Hero left walking motion)
                else
                {
                    dispatchEvent(new Event("levelMoves", true));
                    _isMoving = false;
                }
            }

            //Is Hero moving Right?
            else if (_vx > 0)
            {
                //Check if Hero should move Right
                if (_levelX <= C.GAME_WIDTH - _levelWidth || this.x <= (0.75 * C.GAME_WIDTH) - this.width)
                {
                    //Move Hero Right
                    this.x += _vx;
                    _isMoving = true;

                    //Stop Hero at Right Level Boundary
                    if (this.x > C.GAME_WIDTH - this.width)
                    {
                        this.x = C.GAME_WIDTH - this.width;
                        _vx = 0;
                        _accX = 0;
                        _bounceX = -10;
                        this.gotoAndStop("standRight");
                        _isMoving = false;
                    }
                }

                //Trigger Event to move Level left (Hero right walking motion)
                else
                {
                    dispatchEvent(new Event("levelMoves", true));
                    _isMoving = false;
                }
            }

            //Move Vertically

            //Move Hero up/down
            this.y += _vy;

            //Stop Hero at Top Level Boundary
            if (this.y < 0)
            {
                _vy = 0;
                this.y = 0;
            }

            if (this.y > C.GAME_HEIGHT + 120)
            {
                dispatchEvent(new Event("gameOver", true));
            }
        }

```

And the part in the Main.as that initializes the Level objects in arrays to move them later:

```
private function setUpGameObjects()
    {
        _gameObjects = [];
        _grounds = [];
        _platforms = [];
        _enemies = [];
        _gold = [];

        //Loop through all items on stage
        for (var i=0; i< _level01.gameObjects.numChildren; i++)
        {
            var currObject = _level01.gameObjects.getChildAt(i);

                //Identify the Ground Objects
                if (currObject is Ground)
                {
                    _grounds.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the Platform Objects
                else if (currObject is Stone)
                {
                    _platforms.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the Enemy Objects
                else if (currObject is Enemy)
                {
                    _enemies.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the JumpEnemy Objects
                else if (currObject is JumpEnemy)
                {
                    _enemies.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the BossEnemy
                else if (currObject is BossEnemy)
                {
                    _enemies.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the Gold Objects
                else if (currObject is Gold)
                {
                    _gold.push(currObject);
                    _gameObjects.push(currObject);
                }

                //Identify the House
                else if (currObject is House)
                {
                    _gameObjects.push(currObject);
                }

                //Identify the Finish Zone for Game completion check
                else if (currObject is FinishZone)
                {
                    _gameObjects.push(currObject);
                }
        }
    }

```

And finally my event handler that moves the level as soon as the hero triggers the event:

```
private function onLevelMoves(e:Event):void
    {
        for (var i in _gameObjects)
        {
            _gameObjects[i].x -= _hero.vx;

            if (_gameObjects[i].x < C.GAME_WIDTH - _levelWidth + _gameObjects[i].initX)
            {
                _gameObjects[i].x = C.GAME_WIDTH - _levelWidth + _gameObjects[i].initX;
            }

            if (_gameObjects[i].x > _gameObjects[i].initX)
            {
                _gameObjects[i].x = _gameObjects[i].initX;
            }
        }

        _level01.skyObjects.x -= _hero.vx;

        _level01.sky.x -= _hero.vx;

        if (_level01.sky.x < C.GAME_WIDTH - _levelWidth + _level01.sky.initX)
        {
            _level01.sky.x = C.GAME_WIDTH - _levelWidth + _level01.sky.initX
        }

        if (_level01.sky.x > _level01.sky.initX)
        {
            _level01.sky.x = _level01.sky.initX
        }

        _level01.hills.x -= _hero.vx * 1/2;

        if (_level01.hills.x < C.GAME_WIDTH - _levelWidth + _level01.hills.initX)
        {
            _level01.hills.x = C.GAME_WIDTH - _levelWidth + _level01.hills.initX
        }

        if (_level01.hills.x > _level01.hills.initX)
        {
            _level01.hills.x = _level01.hills.initX
        }

        _level01.mountains.x -= _hero.vx * 1/4;

        if (_level01.mountains.x < C.GAME_WIDTH - _levelWidth + _level01.mountains.initX)
        {
            _level01.mountains.x = C.GAME_WIDTH - _levelWidth + _level01.mountains.initX
        }

        if (_level01.mountains.x > _level01.mountains.initX)
        {
            _level01.mountains.x = _level01.mountains.initX
        }
    }

```
> 0 votes

---
Tags: flash, actionscript-3, side-scroller
---


title: Clip View for Game Play Scene

text:
# Question
Title: Clip View for Game Play Scene
This is a small basic tool for the game. I want small box that reside on one of the corner of the scene. In which I want to show preview of whole game scene.

I have read all the thing and try as much as possible to get the thing done. I use SingleSceneSplitScreenEngine for this purpose. Following is my code snippet.

```
public class TwoCameraView extends BaseGameActivity implements
            IOnSceneTouchListener {

    private static int CAMERA_WIDTH = 1024;
    private static int CAMERA_HEIGHT = 600;

    private Camera mCamera, mChasingCamera;
    private CameraScene mParentScene;

    private TextureRegion loadingRegion;

    @Override
    public Engine onLoadEngine() {
            mCamera = new Camera(0f, 0f, CAMERA_WIDTH, CAMERA_HEIGHT);
            mChasingCamera = new BoundCamera(0, 0, 100f, 100f, 0, CAMERA_WIDTH, 0,
                            CAMERA_HEIGHT);
            final EngineOptions engineOptions = new EngineOptions(true,
                            ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
                                            CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
            engineOptions.getTouchOptions().setRunOnUpdateThread(true);
            return new SingleSceneSplitScreenEngine(engineOptions, mChasingCamera);
    }

    private TextureRegion loadTextureRegion(int width, int height, String name) {
            BitmapTextureAtlas BitmapTextureAtlas = new BitmapTextureAtlas(width,
                            height, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            TextureRegion textureRegion = BitmapTextureAtlasTextureRegionFactory
                            .createFromAsset(BitmapTextureAtlas, this, name, 0, 0);
            getTextureManager().loadTextures(BitmapTextureAtlas);
            return textureRegion;
    }

    @Override
    public void onLoadResources() {
            loadingRegion = loadTextureRegion(1024, 1024, "loading.png");
    }

    @Override
    public Scene onLoadScene() {
            mParentScene = new CameraScene(mCamera);
            mParentScene.attachChild(new Sprite(0f, 0f, loadingRegion.deepCopy()));
            mParentScene.setOnSceneTouchListener(this);
            return mParentScene;
    }

    @Override
    public void onLoadComplete() {
    }

    @Override
    public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
            if (pSceneTouchEvent.isActionMove()) {
                    mChasingCamera.setCenter(pSceneTouchEvent.getX(),
                                    pSceneTouchEvent.getY());
                    return true;
            }
            return false;
    }

}

```

I have modify the SingleSceneSplitScreenEngine of AndEngine library as per the following.

```
public class SingleSceneSplitScreenEngine extends Engine {

    private final Camera mSecondCamera;

    public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions,
                    final Camera pSecondCamera) {
            super(pEngineOptions);
            this.mSecondCamera = pSecondCamera;
    }

    @Deprecated
    @Override
    public Camera getCamera() {
            return super.mCamera;
    }

    public Camera getFirstCamera() {
            return super.mCamera;
    }

    public Camera getSecondCamera() {
            return this.mSecondCamera;
    }

    @Override
    protected void onDrawScene(final GL10 pGL) {
            final Camera firstCamera = this.getFirstCamera();
            final Camera secondCamera = this.getSecondCamera();

            final int surfaceWidth = this.mSurfaceWidth;
            final int surfaceWidthHalf = surfaceWidth >> 1;

            final int surfaceHeight = this.mSurfaceHeight;
            GLHelper.enableScissorTest(pGL);

            /*
             * First Screen. With first camera, on the left half of the screens
             * width.
             */
            {
                    pGL.glScissor(0, 0, surfaceWidth, surfaceHeight);
                    pGL.glViewport(0, 0, surfaceWidth, surfaceHeight);

                    super.mScene.onDraw(pGL, firstCamera);
                    firstCamera.onDrawHUD(pGL);
            }

            /*
             * Second Screen. With second camera, on the right half of the screens
             * width.
             */
            {
                    pGL.glScissor(surfaceWidth - surfaceWidthHalf / 3, surfaceHeight
                                    - surfaceHeight / 3, surfaceWidthHalf / 3,
                                    surfaceHeight / 3);
                    pGL.glViewport(surfaceWidth - surfaceWidthHalf / 3, surfaceHeight
                                    - surfaceHeight / 3, surfaceWidthHalf / 3,
                                    surfaceHeight / 3);

                    super.mScene.onDraw(pGL, secondCamera);
                    secondCamera.onDrawHUD(pGL);
            }

            GLHelper.disableScissorTest(pGL);
    }

    @Override
    protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) {
            if (pTouchEvent.getX() <= this.mSurfaceWidth >> 1) {
                    return this.getFirstCamera();
            } else {
                    return this.getSecondCamera();
            }
    }

    @Override
    protected void convertSurfaceToSceneTouchEvent(final Camera pCamera,
                    final TouchEvent pSurfaceTouchEvent) {
            final int surfaceWidthHalf = this.mSurfaceWidth >> 1;

            if (pCamera == this.getFirstCamera()) {
                    pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent,
                                    this.mSurfaceWidth, this.mSurfaceHeight);
            } else {
                    pSurfaceTouchEvent.offset(-surfaceWidthHalf / 3,
                                    this.mSurfaceHeight / 3);
                    pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent,
                                    surfaceWidthHalf / 3, this.mSurfaceHeight / 3);
            }
    }

    @Override
    protected void updateUpdateHandlers(final float pSecondsElapsed) {
            super.updateUpdateHandlers(pSecondsElapsed);
            this.getSecondCamera().onUpdate(pSecondsElapsed);
    }

    @Override
    protected void onUpdateCameraSurface() {
            final int surfaceWidth = this.mSurfaceWidth;
            final int surfaceWidthHalf = surfaceWidth >> 1;

            this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf,
                            this.mSurfaceHeight);
            this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0,
                            surfaceWidthHalf, this.mSurfaceHeight);
    }
}

```

Using above method I can able to create corner window view that simulate whole view as I move my finger on the device. As I use split screen engine, it only handle half part of the screen. On next half part finger movement, does not occur any change in window view. Parent scene background show on full screen not half one. if you need more detail then I can provide you.

I got above suggestion from the following post. Two Camera View

If you have enough time then please run this code then only you get better understand my problem. Thanks in advance for your time and efforts.

# Answer
> 0 votes
I have solved this problem and share answer on the following post so other user can take benefit from it.

```
public class TwoCameraView extends BaseGameActivity implements
            IOnSceneTouchListener {

    private static int CAMERA_WIDTH = 1024;
    private static int CAMERA_HEIGHT = 600;

    private Camera mCamera, mChasingCamera;
    private CameraScene mParentScene;

    private TextureRegion loadingRegion, magnifyCircleRegion;

    @Override
    public Engine onLoadEngine() {
            mCamera = new Camera(0f, 0f, CAMERA_WIDTH, CAMERA_HEIGHT);
            mChasingCamera = new BoundCamera(0, 0, 125f, 125f, 0, CAMERA_WIDTH, 0,
                            CAMERA_HEIGHT);
            final EngineOptions engineOptions = new EngineOptions(true,
                            ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
                                            CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
            engineOptions.getTouchOptions().setRunOnUpdateThread(true);
            return new SingleSceneSplitScreenEngine(engineOptions, mChasingCamera);
    }

    private TextureRegion loadTextureRegion(int width, int height, String name) {
            BitmapTextureAtlas BitmapTextureAtlas = new BitmapTextureAtlas(width,
                            height, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
            TextureRegion textureRegion = BitmapTextureAtlasTextureRegionFactory
                            .createFromAsset(BitmapTextureAtlas, this, name, 0, 0);
            getTextureManager().loadTextures(BitmapTextureAtlas);
            return textureRegion;
    }

    @Override
    public void onLoadResources() {
            loadingRegion = loadTextureRegion(1024, 1024, "loading.png");
            magnifyCircleRegion = loadTextureRegion(256, 256, "magnifycircle.png");
    }

    @Override
    public Scene onLoadScene() {
            mParentScene = new CameraScene(mCamera);
            mParentScene.attachChild(new Sprite(0f, 0f, loadingRegion.deepCopy()));

            float pX = CAMERA_WIDTH - magnifyCircleRegion.getWidth() * 2f;

            HUD hud = new HUD();
            hud.attachChild(new Sprite(-magnifyCircleRegion.getWidth() * 0.115f,
                            -magnifyCircleRegion.getHeight() * 0.1f, magnifyCircleRegion
                                            .deepCopy()));
            mChasingCamera.setHUD(hud);
            mParentScene.setOnSceneTouchListener(this);
            return mParentScene;
    }

    @Override
    public void onLoadComplete() {
    }

    @Override
    public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
            if (pSceneTouchEvent.isActionMove()) {
                    mChasingCamera.setCenter(pSceneTouchEvent.getX(),
                                    pSceneTouchEvent.getY());
                    return true;
            }
            return false;
    }

}

public class SingleSceneSplitScreenEngine extends Engine {

    private final Camera mSecondCamera;

    public SingleSceneSplitScreenEngine(final EngineOptions pEngineOptions,
                    final Camera pSecondCamera) {
            super(pEngineOptions);
            this.mSecondCamera = pSecondCamera;
    }

    @Deprecated
    @Override
    public Camera getCamera() {
            return super.mCamera;
    }

    public Camera getFirstCamera() {
            return super.mCamera;
    }

    public Camera getSecondCamera() {
            return this.mSecondCamera;
    }

    @Override
    protected void onDrawScene(final GL10 pGL) {
            final Camera firstCamera = this.getFirstCamera();
            final Camera secondCamera = this.getSecondCamera();

            final int surfaceWidth = this.mSurfaceWidth;
            final int surfaceWidthHalf = surfaceWidth >> 1;

            final int surfaceHeight = this.mSurfaceHeight;
            GLHelper.enableScissorTest(pGL);

            /*
             * First Screen. With first camera, on the left half of the screens
             * width.
             */
            {
                    pGL.glScissor(0, 0, surfaceWidth, surfaceHeight);
                    pGL.glViewport(0, 0, surfaceWidth, surfaceHeight);

                    super.mScene.onDraw(pGL, firstCamera);
                    firstCamera.onDrawHUD(pGL);
            }

            /*
             * Second Screen. With second camera, on the right half of the screens
             * width.
             */
            {

                    pGL.glScissor(surfaceWidth - surfaceWidthHalf / 3, surfaceHeight
                                    - surfaceHeight / 3, surfaceWidthHalf / 3,
                                    surfaceHeight / 3);
                    pGL.glViewport(surfaceWidth - surfaceWidthHalf / 3, surfaceHeight
                                    - surfaceHeight / 3, surfaceWidthHalf / 3,
                                    surfaceHeight / 3);

                    super.mScene.onDraw(pGL, secondCamera);
                    secondCamera.onDrawHUD(pGL);
            }

            GLHelper.disableScissorTest(pGL);
    }

    @Override
    protected Camera getCameraFromSurfaceTouchEvent(final TouchEvent pTouchEvent) {
            if (pTouchEvent.getX() <= this.mSurfaceWidth) {
                    return this.getFirstCamera();
            } else {
                    return this.getSecondCamera();
            }
    }

    @Override
    protected void convertSurfaceToSceneTouchEvent(final Camera pCamera,
                    final TouchEvent pSurfaceTouchEvent) {
            final int surfaceWidthHalf = this.mSurfaceWidth >> 1;

            if (pCamera == this.getFirstCamera()) {
                    pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent,
                                    this.mSurfaceWidth, this.mSurfaceHeight);
            } else {
                    pSurfaceTouchEvent.offset(-surfaceWidthHalf, 0);
                    pCamera.convertSurfaceToSceneTouchEvent(pSurfaceTouchEvent,
                                    this.mSurfaceHeight - this.mSurfaceHeight / 3,
                                    this.mSurfaceHeight / 3);
            }
    }

    @Override
    protected void updateUpdateHandlers(final float pSecondsElapsed) {
            super.updateUpdateHandlers(pSecondsElapsed);
            this.getSecondCamera().onUpdate(pSecondsElapsed);
    }

    @Override
    protected void onUpdateCameraSurface() {
            final int surfaceWidth = this.mSurfaceWidth;
            final int surfaceWidthHalf = surfaceWidth >> 1;

            this.getFirstCamera().setSurfaceSize(0, 0, surfaceWidthHalf,
                            this.mSurfaceHeight);
            this.getSecondCamera().setSurfaceSize(surfaceWidthHalf, 0,
                            surfaceWidthHalf, this.mSurfaceHeight);
    }
}

```

---
Tags: andengine
---


# Question
Title: How do games deal with Z-sorting partially transparent foliage textures?
I was busy implementing basic transparency in a prototype I'm working on when something occurred to me.

In order for a given texture's transparency to work as expected, the (semi-)transparent texture must be drawn after whatever is behind it, right?

Well, if we take for example a tree or shrub in a game like Skyrim, the texture(s) that make up the foliage on that tree or shrub must include some transparency somewhere, right? A vertex-perfect leaf model would be far too resource-intensive. But the player can move around, and sometimes through, any plant at will, thus changing the relative position of all textures to the camera.

Doesn't this mean that the game has to constantly Z-sort *all* textures, both between models and even within a single plant model, whenever the player moves (so potentially every single frame)? Isn't *that* very resource-intensive? How do games with lots of partially transparent textures deal with this?

# Answer
For general transparency handling, you could use some form of order-independent transparency.

Typically, though, you sort by Z-distance along the camera view vector before rendering (you can get a "good enough for most uses" approximate with `dot(camera.view, object.worldpos - camera.worldpos)`). A high-powered rendering pipeline will sort all of its objects by constructing an integer key (Wolfire has a nice article on this I can't for the life of me find right now, sorry) and then radix sorting on that. The key would be something like `[alpha flag, depth, material index, mesh index]` all packed into a 32-bit or 64-bit integer. The depth should be reversed for opaque objects. The idea is to make it so that after sorting, objects are in the order to be drawn (opaque in a closest-first order, transparent in a farthest-first order, objects with identical materials or meshes grouped together).

The advantage of sorting everything is three-fold. First, it allows transparency to function without advanced order-independent techniques (most of which have their own significant downsides) by ensuring that transparent objects are always drawn after opaque objects and drawn in the correct order.

Second, it allows objects with similar or identical states to be batched together easily. E.g. if two scene nodes need the same shader it's more efficient to draw them together than to draw one, switch to another object/shader, and then switch back to the first shader to draw another object.

Third, it's can be highly beneficial on some hardware to draw opaque objects in a closest-first order. The reason being that hierarchical-Z and early-Z techniques commonly implemented in hardware will ensure that fragment shaders are not run for hidden geometry and hence will drastically cut down compute overhead and overdraw. Some hardware implicitly sorts fragments itself or has more GPU power available than the CPU has capability to sort objects, so as always, profile and test on target hardware.

For foliage specifically, as Nathan Reed commented, you can avoid all the extra work by just not doing real transparency. When you have enough similar objects like a ton of foliage textures you really can't tell the difference between "proper" blended transparency and just alpha-tested transparency. Same goes for things like hair and fur. Some transparent particle effects can also use different blending techniques and get away without being sorted especially.

It's not uncommon to have multiple passes to your renderer, say one that does the object sorting/batching for "normal" objects and then an entirely separate pass for quickly rendering large amounts of foliage or the like (where the sorting might be too expensive due to the sheer number of objects). Likewise you can avoid needing to get too fancy with the sorted key generation by simply putting all opaque and all transparent objects into separate render queues where the opaque queue is always sorted and rendered first.
> 5 votes

---
Tags: graphics, rendering, transparency
---


# Question
Title: SDL - BlitSurfaced Background Slowing Time Based Movement
Whenever I use BlitSurface to apply a background image, the movement of my characters is slowed drastically even though I have movement based on time:

```
SDL_BlitSurface( background, camera, screen, offset );

```

Though, if I simply fill the screen with white:

```
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );

```

The movement is exactly as I have it set.

Any idea why this could be happening?

# Answer
> 1 votes
Just a speculation: SDL\_BlitSurface is lagging you down.

Test how long SDL\_BlitSurface() takes; see if its significantly different from SDL\_FillRect(). This will affect your character movements depending on how you implemented your game loop and physics.

---
Tags: c++, movement, sdl
---


# Question
Title: Most practical isometric tile, or does it even matter?
I am asking for the most practical/convenient isometric tile. I have seen a lot of tiles, some like this (you have to zoom in somehow to see the pixels, sorry):

I know there are different types of isometric, but I am asking for the best one for games, not the most realistic one. Please ask further questions if something is not clear.

# Answer
Doesn't matter. Choose the one you want to work with and work with it. How you display the world is only a small part of the game, and if done correctly, can easily be changed later on if you find it's inconvenient or not the style you want.
> 3 votes

---
Tags: tiles, isometric
---


# Question
Title: Drawing a HUD above 3D with shaders in GL
In the old days you would just do `glOrtho` in Projection, reset Modelview-Matrix and draw in `[-1,1],[-1,1],0`.

But now-a-days we have shaders and I wanted to avoid the use of matrices. My code so far:

```
#version 130

uniform float sizeX;
uniform float sizeY;
in vec2 position;
in vec2 coord;

out vec2 texcoord;

void main()
{
  gl_Position = vec4(position.x * sizeX, position.y * sizeY, 0, 1);
  texcoord = coord;
}

```

Why does this not work?

If I use this instead:

```
gl_Position = ftransform();

```

The HUD is visible.

# Answer
> 2 votes
The values in `gl_Position` must still be in NDC range: `[-1,+1]`. If your input position is supposed to be pixels, you need to properly adjust such that position `0,0` maps to `-1,-1` and position `WIDTH,HEIGHT` maps to `+1,+1` which is what the matrix from `glOrtho` does.

Without a matrix, take any `x,y` and scale down by `2/width,2/height` then subtract `1,1` to transform to NDC.

```
gl_Position = position * vec2(2.0/sizeX,2.0/sizeY) - vec2(1,1);

```

Instead of passing those sizes each time, you could use a `vec2` uniform variable that already has `1/dim` calculated in it.

---
Tags: opengl, shaders, hud
---


# Question
Title: How do I elegantly teach players how to play?
I've been thinking about how puzzle platformers teach players how to play.

I like Super Meat Boy, particularly the way in which it teaches you without noticing you are being taught. It kept me excited and engaged. There's satisfaction in figuring out something yourself, even if it's simple and clearly forced by the level design.

Other than a "tutorial level" to teach each new skill or rule, are there other ways? What are the benefits and costs of each?

# Answer
> 15 votes
Do it like Super Meat Boy. I assume your game has levels of some sort since its a puzzle plat-former, so as you mentioned Super Meat Boy I believed it's a great example for your question.

In super meat boy, the way you control meat boy stays the same throughout the game, it's only the mechanics of the levels/environments that change. Therefore every mechanic the player needs to know is introduced in the first few levels. Please note these are not "tutorial levels," they take the same form as every other level in the game although they teach the player something new they are not presented as tutorial levels.

Basically, in Super Meat Boy the game gives the player a situation where there is only one solution and that solution involves some new skill that the player needs to be taught. Because as humans when we see a problem and can't solve it we will attempt to do something we haven't tried before. An example of this is when Super Meat Boy introduces the ability to jump up walls, the game gives the player a tall wall where there is no other way passed this obstacle except jumping up the wall (this is obviously a reference to Indie Game: The Movie). As a human, you will try to see if it possible to jump consecutively up the wall and get to the top. Instead of just telling the player in some obscure dialogue box you can jump up walls that the player might ignore.

This Super Meat Boy method is great, since, like you said, the player receives satisfaction from learning the new skill on there own rather than being told. It's also much easier for the player to remember this newly discovered skill because they had to think about it, whereas most people will just skip passed the text and just completely forget, and therefore may end up getting frustrated on a later level (usually blaming the developer for not telling them what to do).

**EDIT:** Like DinoDev82 said, *"Don't just do it like Super Meat Boy"*.

Here I just wanted to give an example and since you liked Super Meat Boy and it's method I felt it necessary to explain what that method is and how its works.

**Spoiler Warning: there some slight spoilers from braid that follow (nothing plot related)**

Another example you can look at is Braid, being a puzzle plat-former I feel it is also quite relevant. If you have ever played braid you'll notice it also teaches the player new skills through its level design rather than providing tutorials and text.

I particularly like the introduction of the green glow mechanics (I don't really have a decent way to describe it) as it is an example of what Stéphane Bura said about exploring a combination of skills and exploring the complexity of a skill. The picture above is the level where the player is first introduced to the real time green entities that don't reverse when the player reverses time.

By this time in the game the player has learnt about the Monstars and how to kill them, what a key is and what it does, how to reverse time etc. So since the player has learnt all of this previously the game can freely build on those mechanics or in this case alter them. The player knows that they need the key to unlock the door and continue. So they jump in the pit after the key (some people will do this without hesitation). Now the player realizes that they are stuck, however the player knows that there is one way out, reversing time, so that's what they do expecting the key to stay down in the pit, but it doesn't. Almost unknowing the player connects the dots and they now know green entities or objects are different and don't follow the reversal of time mechanics.

# Answer
> 3 votes
I totally agree with BeanBag's answer. Some additional advice:

* Introduce at most one new mechanism / skill per level.
* Ideally spend a bit more time on each new skill, like exploring its complexity in several consecutive levels, before introducing a new one.
* It's also best to explore combinations of skills (e.g. double jump + shoot) before introducing new ones (e.g. grenades).
* If a skill has not been required for a while, the player may have forgotten about it. If you do require it in a later level, remind the player early in the level with a simple obstacle that requires its use.
* Design gravy: Add secret areas in your earlier levels that can only be reached by a player who has mastered all the skills. This adds a lot to replayability.
* Tutorial gravy: We learn from observation too, not just experimentation. If you can have a NPC use the skill you want to teach, the player will have a much better understanding of what's expected of him.

# Answer
> 3 votes
The Indie game Thomas Was Alone presents the user with game rules and mechanics by means of dialogue, and narration from the main character's point of view. For example, the main character (red rectangle in image link below), Thomas, states that he doesn't like the look of the water below him, and that it gives him a strange feeling. If you fall into the liquid, Thomas dissolves and re spawns at the last checkpoint.

https://i.stack.imgur.com/qHnl3.png

The game doesn't say "Don't try to swim", it lets you experiment with the world. However some mechanics, especially the ones Thomas doesn't interact with, are presented as tool tips. These include how to move Thomas and how to interact with re spawn points.

# Answer
> 1 votes
For me the elegant way would be to have the option to skip the tutorial.

-Explain the interface. A few slides will do.

-Do not make the player feel that he is dumb, some people do not when they are "overtreated". Keep it short and quick and do not make anyone read a tome. I personally like to read, most simply skip and treat a tutorial like the EULA - you should read it but "who cares".

If the player unlocks an ability, after playing a while, and his UI changes make a short indication before starting the game; an arrow with a text highlighted in yellow cloud will do.

---
Tags: game-design, platformer, tutorials
---


title: Installing the right version of PyGame

text:
# Question
Title: Installing the right version of PyGame
I've been trying to install PyGame for Python, and can't seem to get Python to recognize that it's there. I use Python 3.3, and have a 64-bit Windows computer, but that's really all I know. The PyGame website has piles of different versions of the installer, but I can't seem to find the right one. Either they let me install it but then starts spitting errors (basically saying the module doesn't exist, when it does), or I get this sort of set-up program that keeps saying it's not in my "registry".

# Answer
> 1 votes
Pygame only works for 32-bits version of Python, so that's the reason it didn't find your Python installation on the registry.

In the Downloads section, the following can be read:

> windows 64bit users note: use the 32bit python with this 32bit pygame.

http://pygame.org/download.shtml

And I also recommend you to use Python 2.7 for compatibility reasons.

# Answer
> 1 votes
I have successfully used pygame on 64-bit Windows with both Python2.7 and Python3.3.

I used the installers from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame

Choose the appropriate one to match your Windows and Python versions, in your case: pygame-1.9.2pre.win-amd64-py3.3.exe

---
Tags: pygame
---


title: PyGame sprite assistance

text:
# Question
Title: PyGame sprite assistance
I've basically just started developing with PyGame and I am having trouble with the whole Sprite concept. I have been looking every where for guides on how to use it, I just can't seem to find any. I would like to know the basic concept of how it all works. This is the code I have been working on:

```
import pygame, sys, os, time
from pygame.locals import *

windowWidth = 320
windowHeight = 640
halfWidth = int(windowWidth / 2)
halfHeight = int(windowHeight / 2)

#main blocks width and height (32x32)
blockSize = 32

#rgb
red = [255,000,000]
green = [000,255,000]
blue = [000,000,255]
black = [000,000,000]
white = [255,255,255]

bgColor = black
playerColor = white
blockColor = green

fps = 60

assert windowWidth % blockSize == 0, "Too much space/not enough space for the ground"
floorAmt = windowWidth/blockSize
print floorAmt

floorY = windowHeight-blockSize
print floorY

floor = pygame.sprite.Group()

def main():

    global fpsClock, displayScreen

    inAir = False

    upVel = 0
    downVel = 0
    leftVel = 0
    rightVel = 0

    fpsClock = pygame.time.Clock()
    displayScreen = pygame.display.set_mode((windowWidth, windowHeight))
    pygame.display.set_caption("Jump Test")

    grass = pygame.image.load("grass.png")
    grass = grass.convert_alpha()
    grassRadius = blockSize

    floorDraw(blockSize, floorAmt, floorY, grass)

    while True:
        fpsClock.tick(fps)

        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
                raise SystemExit, "Exit"

        displayScreen.fill(black)
        floorDraw(blockSize, floorAmt, floorY)

        pygame.display.flip()
        pygame.display.update()
        fpsClock.tick(fps)

def floorDraw(blockSize, floorAmt, floorY, grass):
    for i in range(floorAmt):
        floorX = i*blockSize
        grassRect = (floorX, floorY, blockSize, blockSize)
        floor.add(grass)
        displayScreen.blit(grass, grassRect)

        v
if __name__ == "__main__":
    main()

```

basically I just want to know how to make these grass blocks into sprites in a group, so that when I add my player (also a sprite) I can determine whether or not he is in the air or not through the collision system. Can someone please explain to me how I would do this. All I am looking for is basically a kick starter because some of the documentation is quite bad in my opinion as it doesn't completely tell you how to use it. Any help is greatly appreciated :)

# Answer
Although it may be a bad design choice, the Sprite object is meant to be inherited and be managed as a group.

You did right by creating the **floor** as Group and adding each **grass** to it.

But what I would suggest is to *inherit* the Sprite object to class you created yourself. Usually my Entities starts with the following:

```
class Entity(pygame.sprite.Sprite):
    def __init__(self, x, y, width=1, height=1):
        pygame.sprite.Sprite.__init__(self)
        self.rect = pygame.Rect((x, y), (width, height))
        ...

```

It is an Sprite, but it contains the **Rect** object that you will want to use for a lot of reasons, like Bounding Box collisions and for moving your entity. Then, you can simple call

```
pygame.sprite.spritecollide(sprite, group, dokill, collided = None)

```

and have a list of Sprites that collide, so you can can manage them. More info on:

http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.spritecollide

In fact, Pygame have lots of collision detection methods that do the same thing: check for a intersection between two **Rect** objects.

You can look thought this book, it may be useful: http://inventwithpython.com/ There are also some tutorials over here and there, and the mail-list.

Hope that helps!
> 1 votes

---
Tags: sprites, python, pygame
---


# Question
Title: How do you get the collision plane when using AABBs?
My collision detection initially seemed to work well enough, but my answer to this question shows that I have went with SAT testing now instead. My goal was to find the plane at which to slide the player when a collision happens, not to implement a commonly used method that 'works well enough' such as Minimum Displacement.

A more accurate and unique question would probably be how to find the first plane of collision in a (possible) multi-object collision of 1 aabb to 1+ aabb objects. My answer below is what I've went with, but please add your own and I'll happily accept them if they provide more than my own answer.

As the picture below demonstrates, from one frame to the next, if the red square moved from bottom up as the arrow points, I need something to show that the bottom face of the black square is what was collided with (or the top face of the red square).

From the book "Real Time Collision Detection by Christer Ericson" I am using the following code to get the first and last contact times of an AABB to AABB collision. I iterate through all cubes around the player in the direction of their current velocity (ensuring their velocity is handled in small increments if too large) and get the first contact time, then I sort all collisions by said contact time. I've modified the code below to report which edge was collided with (if it didn't start out with a collision), and with all of these things I can get the answer I needed.

```
// Intersect AABBs ‘a’ and ‘b’ moving with constant velocities va and vb.
// On intersection, return time of first and last contact in tfirst and tlast
int IntersectMovingAABBAABB(AABB a, AABB b, Vector va, Vector vb,
float &tfirst, float &tlast)
{
// Exit early if ‘a’ and ‘b’ initially overlapping
if (TestAABBAABB(a, b)) {
tfirst = tlast = 0.0f;
return 1;
}
// Use relative velocity; effectively treating ’a’ as stationary
Vector v = vb - va;

// Initialize times of first and last contact
tfirst = 0.0f;
tlast = 1.0f;
// For each axis, determine times of first and last contact, if any
for (int i = 0; i < 3; i++) {
if (v[i] < 0.0f) {
if (b.max[i] < a.min[i]) return 0; // Nonintersecting and moving apart
if (a.max[i] < b.min[i]) tfirst = Max((a.max[i] - b.min[i]) / v[i], tfirst);
if (b.max[i] > a.min[i]) tlast = Min((a.min[i] - b.max[i]) / v[i], tlast);
}
if (v[i] > 0.0f) {
if (b.min[i] > a.max[i]) return 0; // Nonintersecting and moving apart
if (b.max[i] < a.min[i]) tfirst = Max((a.min[i] - b.max[i]) / v[i], tfirst);
if (a.max[i] > b.min[i]) tlast = Min((a.max[i] - b.min[i]) / v[i], tlast);
}
// No overlap possible if time of first contact occurs after time of last contact
if (tfirst > tlast) return 0;
}
return 1;
}

```

# Answer
> 0 votes
What a typical physics engine would do is identify the axis of minimum penetration. For axis-aligned shapes, this is trivial. The two possible axes are horizontal and vertical (each with possible directions).

You measure the overlap on each axis. Select the minimum. Then separate the objects by that amount. This will also tell you which of the surfaces came in contact. From which point you can apply physics simulation (i.e.: bouncing and friction).

Of course, if the object is moving fast enough, this can give the wrong answer. But at reasonable speeds, and at 60FPS, this works well enough for real-world use.

---
Tags: xna, c#, collision-detection, collision-resolution
---


title: 2-components color model

text:
# Question
Title: 2-components color model
RGB is the natural color model for OpenGL. But a lot of other color models exist. For example, CMY(K) for printers, YUV for JPEG, the little cousins YCbCr and YCoCg, HSL & HSV from the 70's, and so on. All these models tend to share a common property : they are based on 3 components.

Therefore my question is : Does it exist a 2-components color model ? I'm surprised to not find any. I was expecting something along the line of Hue+light could exist. I guess it cannot be as "complete" as a true 3-components color model, but a fine-enough approximation will be good for my usecase.

The end objective is to store the 2 components into a single BC5 texture (GL\_COMPRESSED\_RED\_GREEN\_RGTC2 in OpenGL). The 3rd component requires a second fetch into a second texture, which hurts performance.

# Answer
> 13 votes
Humans have trichromatic color vision, so the space of colors we can see is fundamentally three-dimensional.

(Well, for most of us, it is. Colorblind people may only have dichromatic or monochromatic vision, and there may be a small number of people who can (barely) distinguish an extra dimension. Also, technically, even normal humans do have a fourth type of photorector — the rods — but those are only active in low light conditions where normal color vision starts to fail, and are not believed to contribute to it in any significant way.)

You can encode the position of a color in this three-dimensional space in different ways, which gives us various color representations like RGB, YUV, HSL, Lab, XYZ, and so on. But the one thing all these color spaces have in common is that, in order to be able represent all colors humans can see, they need at least three coordinates.

(The reason CMYK uses *four* coordinates comes down to the limitations of printing technology, and specifically the fact that it's hard to get a good black just by mixing colored inks. The extra channel is, strictly speaking, redundant to the other three, but exposing it to the graphics software allows more detailed control of the printing process.)

Certainly, if you only wanted encode a subset of the colors, you could pick some two-dimensional surface within the three-dimensional color space and encode your colors as their position on that surface. A simple way to do that would be to take one of the existing three-dimensional color encodings and fix one of the coordinates at a constant value (or at some value that changes as a function of the other coordinates). For example, if you wanted all your colors to be maximally saturated, you could take the HSV or HSL color spaces and fix the S channel at 100%, leaving you the two other channels.

# Answer
> 3 votes
I know this is an old and already answered question, but I have a different opinion than @Ilmari Karonen.

*"Humans have trichromatic color vision, so the space of colors we can see is fundamentally three-dimensional."*

If you compare human vision to digital color model, our vision would be closest to L-RGB, therefore it is a **4-component color model** (it is very difficult to actually define color). This is because we have two types of cells: **rods and cones**. It is true that considering only cones, we have similar model to RGB, because there are **three types of cones**, sensitive to wavelengths that we call blue, green and red. But we also have rods, which are very sensitive to green wavelengths and our brain doesn't interpret this as green, but as light/dark. Cones are more active when there is more light, rods takes over in the dark, but both work together (you can't shut them down). It's one of the reasons some camera chips have 4 componets on a pixel (blue, red, 2x green). Of course the others and more significant reasons are spectral sensitivity, which peaks around the "green" light wavelength:

And also the fact you have square pixels that you cut into 4 subpixels...

Digital color models probably can capture "all colors humans can see". Different scientists will give you different answers. But 24-bit color space is more than enough. And we can't distinguish close colors next to each other anyway.

Computer screens always considered RGB human vision model to give us the most natural picture. CRT screens have three phosphore dots, LCD panels three sub-pixels. Some screens have 4 (with extra yellow I think).

Therefore three component RBG model is most natural and easiest to use and other models are just encodings of this model to allow subsampling and other manipulations. E.g. subsampling in YCbCr works, because human vision is more sensitive to light/dark contrast than color change (again we have more light/dark sensitive cells and also human brain works that way).

*IMHO a better 3-component 24-bit color model would encode Green using 10 bits and blue and red using the remaining 14 bits, then a better TV would use bigger green subpixel than the red and blue...*

**The reason why there is no 2-component color model is because there is no need for it.** You can create arbitrary color model, for 2-components "lightness and hue+saturation combined". Then create an 8-bit pallete for the hue+saturation combined channel. With 256 lightness values, you will have pretty good model. But it will be quite useless, hard to manipulate and unnatural and you will have to provide quite complex formula RGB-\>Your model-\>RGB.

So instead of trying to save bits using 2-components model, we just use 3-component model with subsampling.

Note that the old 256 palette can be considered a 1-component model. If you increase the palette storage to 16-bits, you will get 65536 palette 1-component model and so on.

## Conclusion

It doesn't matter how many components your model has! The most important thing is that naturally you capture RGB with our current technology and you reproduce RGB with current technology. This feels natural to human eye. Whatever you do between capturing and reproducing is upto you. We just invented color models that are easy to manipulate, encode or somehow useful.

---
Tags: opengl, textures, color
---


# Question
Title: Enter Key press event detect from textbox - Unity3D - C#
i am doing a project with Unity3D . in the interface there is a textbox. once user input some text and and press enter key then i want to read the text in text box. so please tell me how to programmatically detect the key press event in unity3D - C# using MonoDeveloper.

# Answer
> 2 votes
It's a little tricky. It's pretty confusing if you have a solid background with the web platform, JavaScript and DOM Events in partcular, where most of the events are abstractized in closures for each control.

In Unity, the Events are fired globally on `GUI`. You must then check them, and act accordingly.

### Theory

* while the `GUIWindow` is drawn, listen for your EventType on `Event.current` (the event that just happened).
* if needed, check it against your GUI controls.
* if all the requirements have been matched, do something.

### Implementation

```
using UnityEngine;

public class Somegui : MonoBehaviour
{

private string inputValue = "";
private bool windowShouldBeDrawnCondition = false;

void Update()
{
    // open dialog upon Enter
    if (Input.GetKeyDown(KeyCode.Return))
    {
        windowShouldBeDrawnCondition = !windowShouldBeDrawnCondition;
    }
}

void OnGUI()
{
    if (windowShouldBeDrawnCondition)
    {
        // draw dialog
        GUILayout.Window(0, new Rect(100, 100, 200, 0), DrawMyWindow, "Window Title");
    }
}

void DrawMyWindow(int windowID)
{
    // check for keydown event
    if (Event.current.type == EventType.KeyDown)
    {
        // no matter where, but if Escape was pushed, close the dialog
        if (Event.current.keyCode == KeyCode.Escape)
        {
            windowShouldBeDrawnCondition = false;
            return; // no point in continuing if closed
        }

        // we look if the event occured while the focus was in our input element
        if (GUI.GetNameOfFocusedControl() == "input" && Event.current.keyCode == KeyCode.Return)
        {
            SubmitInputValue();
        }
    }

    GUI.SetNextControlName("input");
    inputValue = GUILayout.TextField(inputValue);

    // in case nothing else if focused, focus our input
    if (GUI.GetNameOfFocusedControl() == string.Empty)
    {
        GUI.FocusControl("input");
    }
}

private void SubmitInputValue()
{
    // do not proceed if empty
    if (inputValue.Length > 0)
    {
            // do something
        Debug.Log(inputValue);

        inputValue = ""; // usually, upon sending, the field should be reset
    }
}
}

```

Cannot test this at the moment, but it should work.

I have given, I hope, pretty understandable and reasonable comments to grasp what is fully going on there.

---
Tags: c#, unity, gui
---


# Question
Title: Recommended graphic software for creating great graphics in game?
I came across a game called Trine2. It has a great graphics here is one image i captured here. Forgive me but I need 10 reputation to upload image so i use external sites.

How did they create that game? Its a 2d side scrolling game with 3d graphics? what applications they used? Is it Photoshop or illustrator then some 3d modeling software like blender? Or they only use a single graphic software? Theres also some shadow in character but i believe its OPENGL or Directx. Im more concern on how did they create such grapchis in 2d with 3d looks.

# Answer
> 1 votes
Direct answer to your question: I'm not sure what they used for this specific game, but I'm 99% sure it was 3ds max or Maya for the 3D models, Photoshop for the textures, and their game engine's level editor for laying out the scenes.

Beyond that direct answer: Ultimately software doesn't matter that much for the quality of the graphics. I mean, the reason I'm pretty sure about my guess is because those are the applications used for the majority of games, but even though most games use the same standard tools they vary a lot in graphics quality. It's about the artist making the art, not the software.

---
Tags: 2d, 3d, game-design, graphics, blender
---


# Question
Title: Efficient Collision Detection With Numerous Objects at Once
I am developing a 2D game with very large levels in which two teams(around 200 objects per team) fight against each other in planes, tanks, turrets,...etc. With every entity shooting bullets at their enemy it is expected that there would be a numerous amount of objects at one instant. What collision detection algorithm could I use to support collision for a massive number of entities at once? The objects are simple figures(rectangles and circles). Would a brute force approach suffice or break up the level into a grid?

# Answer
> 5 votes
Since your game is 2D, I would recommend using QuadTrees.

Here's a good tutorial to get you started: http://www.kyleschouviller.com/wsuxna/quadtree-source-included/

Another good one: http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/

# Answer
> 1 votes
If you have a bounded domain, then you can use a uniform subdivision. It is the simplest of all spatial subdivision systems.

However, if you have an enormous world, very sparsely populated then I would recommend spatial hashing. You simply use a hash map to fill buckets. It is fairly simply to implement, but you need a good hash function.

# Answer
> 0 votes
Other answers are surely worth a thought, but with just the tiny amount of 400 objects to test against, I would recommend you do profiling afterwards.

A simple brute force might turn out faster depending on your language and environment. Some runtime environments (like e.g. Java or Lua) might have blazingly fast array loops compared to very slow generic container like hashtables.

Of course, this is heavily dependend on how fast your collision tests with the actual objects are. Is some simple axis aligned bounding box checking or some sphere intersection enough? Or do you actually need to trace a 3D-ray against a mesh? (2D doesn't always means you don't have a third dimension where a bullet could go *over* some object..) \*)

\*) Edit: oh, I am sorry. You already mentioned that the objects are "simple figures", making my suggestion about a simple brute force even more interesting to try out.

---
Tags: c++, collision-detection, sdl
---


# Question
Title: Tile-based multiplayer game: server and client load
I'm developing a multiplayer tile-based game (imagine habbo) and having some trouble with the movement. The idea is to click on a tile (target tile) so your avatar moves there and everyone can see you moving there. In order to do that, there's a pathfinding function.

My first approach was: the pathfinding function was in the client and everytime the avatar moved a pixel (guided by the pathfinder) it sent a message to the server which broadcasted this update. This was obviously mad.

My second approach was to send to the server just the target tile. The server broadcasted this target tile, and each client ran the pathfinding function for each avatar in movement. I found problems with this because of synchronization: imagine two users moving that pass through the same tile at different times, maybe in one client with a little lag it happens that they pass through the same tile at the same time, so the pathfinder will stop one of them, as you can't walk over another avatar. This will lead to different positions in each client.

I've read some cases where the pathfinder runs in the server, the client just send the target tile and receives every x mseconds an update from the server with the pathfinding calculations for every avatar in movement (even himself). The problem I find here is how to set this "x mseconds" and that it might mean a lot of load to the server, handling all the pathfinding calculations...

What are the pros and cons of each approach?

# Answer
> 2 votes
Thats how we did it in Dungeons:

* Client sends the target-tile to the server.
* Server distributes the target tile to all clients
* Server and all clients run the same deterministic pathfinding and path walking algorithm.
* As a fail-guard, every now and then (like once every 3 seconds) the server sends his current position to all clients.

The clients check this fail-guard position towards their current positions. Usually there is no offset, but "things happen". Making a perfect deterministic path walker is very hard, especially when you have things like changing walk speeds and unit avoidance (we only had client-side unit avoidance so that wasn't a problem for us). Or for example when you run the process with "fast floating point operations" and do your walking in increments, any parallel float calculations may just drift off over time.

For us, the errors were usually so small, that we just set the client position to the received fail-guard update. But if you see bigger differences, or if you don't want or can't have a perfect deterministic path walker, then you could store the last received server position somewhere next to your current position and then "slerp" to this position over the next couple of frames.

# Answer
> 1 votes
You could try to recalculate and broadcast the path every time the character changes tile. It won't be as intensive as the per pixel approach but still have the benefit of calculating the actual current position of possible obstacles. You could also calculate the straight path to the end target, save this path on the moving character and on each tile moved calculate if the path is still valid or a detour is needed.

# Answer
> 1 votes
When creating multiplayer games with the client-server model, the server should keep the "master copy" of the simulation. That's what makes a server *authoritative*.

When a player clicks on a tile to move:

1. Send that tile position to the server.
2. Make the server determine if that tile position is valid to move to. This is where you can make sure the tile is in the map boundary, is valid, and the player can reach it.
3. If the tile position is valid, send a command to all the clients to update their simulation.
4. If there's an error, remember that the server holds the "master copy"! The server can send data to the client that synchronizes the game states.

> The problem I find here is how to set this "x mseconds" and that it might mean a lot of load to the server, handling all the pathfinding calculations...

How many clients do you want to handle at once? If you're not processing hundreds or thousands of players, performance should be something that you should test before you make assumptions. Give your update frequency an initial value, like 10 or 15 times a second. If you have issues with bandwidth or performance, you should make further tweaks.

One last note: NEVER blindly trust the client's data. The server should do input checking and remain in control when it matters.

# Answer
> 1 votes
I would recommend to run the pathfinding on the server. That's the best way to avoid any asynchronity between clients. It also prevents cheating in form of speed hacks or walk-through-wall hacks, because the server has full authority over the movement of the players.

But there is no reason to send the pathfinding information every x milliseconds again and again, because during most intervals it won't change. It's completely sufficient to send each path once. The only reason to communicate again while the path is executed is when the execution of the path is cancelled (like when the user clicks somewhere else or when an obstacle suddenly appears on the path).

The "update every x ms" pattern I am reading here again and again **is an anti pattern**. There is no reason to send any information which is redundant or easily predictable. When possible, only inform the clients when an information has actually changed. When an information changes predictable (like the position of an object moving with a constant speed in a constant direction), you only need to inform the player when this predictable vector changes.

---
Tags: multiplayer, tiles, server
---


title: Change animation speed of a 3D model

text:
# Question
Title: Change animation speed of a 3D model
I am working on a small simulator. There is a 3D character on the screen and it randomly plays an animation (I used `animation.PlayQueued(...)` command inside a `for` loop). Now I have added a slider ( `GUI.VerticalSlider` ) on screen. I want to change the speed of all playing animations of 3D character when change the value of slider.

I know to use `animation["animationNane"].speed=xx;` but my problem is I have to pass the parameter of animation name that I want to change the speed . but actually I don't want to change the speed of specific animation clip. I want to change the speed of whatever the animation running in my 3d character. How can I change the speed of whatever animation is playing?

# Answer
From the sounds of it, you want to change the speed of any animation playing. So, essentially, you want to change the speed of all playable animations. The `Animation` class inherits from `IEnumerable`, so you can iterate through all clips via a `foreach` loop.

C#:

```
foreach (AnimationState state in animation) {
    state.speed = 0.5F;
}

```

Unityscript (Pragma Strict):

```
for (var state : AnimationState in animation) {
    state.speed = 0.5;
}

```

The above will cause all the clips within the `animation` object to play at half speed. You can then change the speed back, or to whatever, whenever you need to.

Unity Script Reference - Animation

Unity Script Reference - Animation Scripting (Legacy)
> 2 votes

---
Tags: c#, unity, animation
---


# Question
Title: How does one update the physical state of an object after scaling it in Corona?
I am new to Corona and Lua. I have the following question:

I have an object `cake` with these physics parameters (doesn't really matters):

```
["cake1"] = {

                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -21, 62.5  ,  -36, 62.5  ,  -50, 55.5  ,  -58.5, 46  ,  -36, -38.5  ,  57, -40.5  ,  57.5, 34  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -7.5, -63  ,  -13, -61.5  ,  -12, -64.5  ,  -8, -64.5  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -12, -64.5  ,  -13, -61.5  ,  -17.5, -56  ,  -21, -52.5  ,  -18.5, -60  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -47, -37.5  ,  -58.5, 46  ,  -58.5, -33  ,  -53, -37.5  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -26, -52.5  ,  -21, -52.5  ,  -18.5, -52  ,  -9, -47.5  ,  -6.5, -41  ,  -36, -38.5  ,  -34.5, -46  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -36, -38.5  ,  -58.5, 46  ,  -47, -37.5  ,  -42, -39.5  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -6.5, -41  ,  -9, -47.5  ,  -6.5, -44  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   25, -40.5  ,  7, -40.5  ,  17, -42.5  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   48, -42.5  ,  57, -40.5  ,  25, -40.5  ,  32, -42.5  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   -18.5, -52  ,  -21, -52.5  ,  -17.5, -56  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   7, -40.5  ,  -36, -38.5  ,  -6.5, -41  }
                    }
                     ,
                    {
                    pe_fixture_id = "", density = 2, friction = 0, bounce = 0,
                    filter = { categoryBits = 1, maskBits = 65535, groupIndex = 0 },
                    shape = {   25, -40.5  ,  -36, -38.5  ,  7, -40.5  }
                    }

        }

```

and when I insert it to the scene I have the following result:

The `cake` is too large so I use `cake1:scale(0.5,0.5)` to change his size.The problem is that the physics didn't change automatically to apply to its new size and the result is:

**Are there any easy way to change the size of an object and the physics automatically fit to the new size or I have to rewrite them?**

# Answer
Make the values that define your physics body variables, not hard coded values. Then you can scale them at the same time you scale the sprite for your cake.

The easiest way is to move your hard coded values into an array, then loop through the array and scale the values the same as the sprite before creating the physics object.

An alternative, likely easier to implement, but **very** ugly way, scale all your hard coded values like so:

```
xScale = .5
yScale = .5

shape = {
-21*xScale,   62.5*yScale ,
-36*xScale,   62.5*yScale ,
-50*xScale,   55.5*yScale ,
-58.5*xScale, 46*yScale ,
-36*xScale,  -38.5*yScale ,
 57*xScale,  -40.5*yScale ,
 57.5*xScale, 34*yScale }
 }

```
> 2 votes

---
Tags: lua, corona-sdk
---


title: Ignore specific key press in textbox

text:
# Question
Title: Ignore specific key press in textbox
there is a text box on GUI in my application created using Unity3D. in the textbox user can input only the keys of "A-Z", "0-9" , "enter key" , "." and "," other key press should be ignored (not should print in textbox when typing). how to do this in Unity3D C#

# Answer
I'm assuming you're using GUI.TextField?

It doesn't appear that there's a built-in way to restrict the text field's legal input set, however, you can achieve the validation behavior you want by writing a script:

```
public class LimitInput : MonoBehaviour {
  public void OnGUI() {
    text = GUI.TextField(..., text);
    text = /* replace offending text here */
  }

  string text = string.Empty;
}

```

A simple implementation of the replacement might be along the lines of `text = text.Replace("!", "")` for example (to remove all `!` characters). To implement the specifics of your request, you'll probably want regular expressions.
> 5 votes

---
Tags: c#, unity, gui, interface
---