title: Game log format for MMO servers

text:
# Question
Title: Game log format for MMO servers
A log of game events (as opposed to error / debug logs) for an entire cluster/shard is very useful for a commercial MMO that is in a live production environment, providing vital support for customer service, and the means for historical analytics.

The project that I am currently working on uses a relational database to store all of the game event logs, and while that method works fine it seems to me that the read-only, chronological nature of the logs would allow for a more efficient storage format.

I'm not sure where to begin learning about building custom binary log formats, however. What are your experiences with creating custom log formats, or any recommended papers / articles on the subject?

# Answer
> 7 votes
In Stendhal we solved the performance issue by adding game events to a queue and then processing them asynchronously in the background.

In our case the events are not just records but objects which have a little bit of logic because in some cases we need to do two inserts with a link between them. For example the first time a item is handled in game, it needs to be inserted into the item table first before an item-event can be logged.

But writing the log is only one side of the problem:

**What questions do you want to answer with the logs?**

It is easy to just read the complete log in chronologically order; or to filter it for one player.

But there might be questions like:

* Which items has Anton put on the ground that have been picked up by Beth yesterday? Which player owns them now? (Anton complained about his item being stolen)
* How much time does an average player need to reach level 100? Which players have been significantly faster? only for first characters?
* Are there players that handle huge amounts of game-money? To which players is it passed? Without anything valuable in return?
* Are weak players able to kill strong creatures that they should not be able to kill legally?
* ...

In Stendhal we use a relational database for game logs because that is the easiest way to allow performant ad-hoc queries. If you use a custom log format, you basically have to code all those queries when need arises. And doing that with sufficient performance gets rather difficult.

Our gameEvents table has 51,429,139 rows (last year) and we have a dedicated itemlog table which has 60,360,657 rows (all time) for 15,893,831 items.

# Answer
> 4 votes
What do you mean by efficiency? Whether it's size on disk or query speed, a relational database is almost certainly going to beat or equal your proprietary binary format, and be much easier and more flexible to use.

Each table you use in a relational DB pretty much lets you specify to the exact byte how much space per row you're going to allow. If you're not logging plain text - and *"log of game events (as opposed to error / debug logs)"* implies that you're not, or at least don't need to - then the fixed-width field approach of a relational database is rather close to optimal in terms of space, which makes them pretty fast in the first place. On top of that relational databases are pretty handy at making indexes for very fast access, and optimising queries to make the most of them.

So I'd recommend sticking with what you've got.

# Answer
> 3 votes
It is true you could probably save a few bytes with a custom format, or ever just gzipped text, storage is cheap so it really isn't worth optimizing for anymore. What is more important is deal with things like I/O buffering and querying, both of which an off-the-shelf SQL server probably does pretty well. If it is working for you on those fronts, I would run with it. We wrote our own buffering log server which writes to custom files and then has a separate parser program to read it into a database for queries, I wouldn't recommend it.

# Answer
> 0 votes
Relational databases these days are knocked for being inefficient, but when storing the type of logs you're talking about, you don't really need efficiency because they won't be constantly accessed by the game or its users - only your team will need to read the data.

So "efficiency" doesn't matter that much. What matters more is ordering the data in a way that makes it easy to tell the story of what users are doing in the game. Your developers will generally need to consume this data and display it in an interface that's easy to read for analysts and analysts will sometimes need to query the data to dig deep into user behavior. For instance, if players are purchasing a certain item before an update, but stop purchasing it after an update, an analyst will benefit by writing certain queries that expose certain numbers about behavior surrounding that purchase to determine why users no longer buy it. It's best if they have a standard query language to work with that is well documented. If they have to make these queries into a custom binary format their jobs will be made MUCH harder, and that's INEFFICIENT.

Generally game events look something like this (this is DeltaDNA's format in particular)

```
{
 "eventName":"specific event code – eg. gameStarted",
 "userID":"ABCD1-4321a879b185fcb9c6ca27abc5387e914",
 "sessionID":"4879bf37-8566-46ce-9f3b-bd18d6ac614e",
 "eventTimestamp":"yyyy-mm-dd hh:mm:ss.SSS",
 "eventParams":
  {
   "platform":"WEB",
   "param1":"stringParam",
   "param2":true,
   "param3":1234,
   "param4":["a","b","c"]
  },
}

```

The event usually includes an event name, a userID, a session ID, timestamp, and parameters that allow you to record whatever data you find useful to record surrounding that event. And in my experience, relational database formats are the best for recording such a structure.

---
Tags: mmo, server, events, scalability
---


# Question
Title: Methods of player retention and conversion in MMO games?
What are other retention and conversion (free to play to paying to spender) strategies in MMOs?

I know some like promotions, social viral, content generation, intentional imbalance, perks and community management.

# Answer
Clever economic manipulation.

Say you've got two people playing the game. Frank has a lot of money (he's a millionaire in real life) but not a lot of time ingame. He wants to get some really awesome and expensive equipment and go kill Starfuries (they are the best thing to kill) but he has no interest in grinding ingame to gradually get the gear he wants. He does not care, in any sense, about the $15/mo monthly fee for your game. He will probably forget to unsubscribe because he cares so little.

Bob, on the other hand, is a highschool student. He has no money and absolute tons of free time. Huge amounts of it. He's managed to get his mom to pay for a few months of subscription, but that won't last forever.

So here's what you do. You make an ingame item, a "Hunter's License". A Hunter's License can be traded on the auction house ingame. It can be redeemed for a month of subscripton time, and it can be purchased out-of-game for $15, it just shows up on your character.

Frank buys a pile of Hunter's Licenses and sells them on the Auction House. Bob spends a few days farming money and buys his Hunter's License for the month. Everyone wins:

* Frank wins because he doesn't have to do the grinding he finds so boring.
* Bob wins because he gets to play the game for free.
* You win because you're getting Frank's money (which you would have gotten anyway) and Bob's money (which you wouldn't have gotten otherwise.) Additionally, you haven't mucked with the ingame economy - you haven't spawned any powerful items, you haven't started "selling gold", you're just letting people trade gametime around.

This has been used very successfully with both Eve Online's PLEXes. A variant micropayment system, using ingame tradable items as necessary reagents for almost every production and trade, can be seen with Puzzle Pirates' Doubloons. Another variant can be seen with Kingdom of Loathing, which sells powerful unique items (kind of iffy) that, again, can be traded on the auction house (suddenly makes them far less iffy, because you don't need out-of-game money to get your edge.)

Remember: every person who spends PLEXes and Doubloons is giving you money, *even if they personally never gave you any money*. Trading is a good thing! Let the economy help you!
> 15 votes

# Answer
Some recently popular ones

1. Refer-a-friend. Generally you give bonuses to both the referrer and the referee.
2. Social media broadcasts. More and more games will want to post stuff to Facebook and Twitter as basically free advertising. The new Warhammer 40k game is even rewarding players for this.
3. Rich kid syndrome. Asian MMOs are notorious for this, putting pay items up that are clearly better than ones that can be earned within the game. Tread lightly here, western markets have been very hostile to this.
4. Selling simplicity. Things like selling +%XP potions or pre-leveled characters for a game with a low level cap (think Guild Wars' PVP character system). This is generally better received than the above, but still hard to pitch.
5. Veteran rewards. Pretty simple and every MMO I know of does it.
6. Fast client download. The longer it takes to try your game, the lower the conversion rate is.
7. Non-decimal currency. There is a reason that MS' Live points are 80 == $1.00. By keeping people's mental math off balance you can produce the illusion of lower prices.
> 4 votes

# Answer
This is a good question because it applies to all free to play games that are monetized with microtransactions. What you're basically asking is: “How do I get players to become engaged in a game after they download and once they're engaged, how do I get them to spend money?” How a developer addresses this question is key to whether their game succeeds or fails.

How people usually answer this question on forums like Stackexchange though is with randomly picked strategies that have SOMETIMES worked for SOME developers, which is incomplete. To answer this better it's best to look at this from the perspective of player's lifecycle through the game.

Generally a player's lifetime engagement with your game looks like this

* Acquisition (ads, viral invites, press, etc.)
* Early Retention (getting the user to decide to engage beyond the first few sessions)
* Engagement & Long-term retention (once a user decides to play, how do you keep them doing so for as long as possible)
* Monetization
* Leaves game (usually called "churn")

So coming up with strategies for "retention and monetization" mean you maximize the numbers at each point in the above flow. Firstly, to do this, you want to come up with a way of measuring your performance at each step, which is usually done by measuring user behavior with gameplay events, which look something like the format below, and then analyzing it later to establish behavioral patterns

```
{
 "eventName":"specific event code – eg. gameStarted",
 "userID":"ABCD1-4321a879b185fcb9c6ca27abc5387e914",
 "sessionID":"4879bf37-8566-46ce-9f3b-bd18d6ac614e",
 "eventTimestamp":"yyyy-mm-dd hh:mm:ss.SSS",
 "eventParams":
  {
   "platform":"WEB",
   "param1":"stringParam",
   "param2":true,
   "param3":1234,
   "param4":["a","b","c"]
  },
}

```

Once developers collect this data, they can begin to analyze it by looking at any immediately visible trends that emerge. Once a large enough dataset has been gathered, developers will usually develop statistical modes to establish patterns in player behavior.

These statistical models seek to establish:

**User Segments:** Developers put players into different behavioral cohorts based on their play style. This is done so that individualized content and features can be targeted towards individual user segments.

**Unique value of each segment:** Each player segment has a different value. Some will spend more money, some will be extremely viral & invite a lot of other users, some will serve to engage other users. Once players know the value of each segment, they can add new content and features to the game that maximize the value of each individual user segment.

**Create custom KPIs relevant to their game's retention, engagement and monetization:** Since games are all different, developers will define metrics that define success for their individual game so that they have custom measures of success at each phase of the player lifecycle. Examples might include:

* Casino game: Number of free-to-paid conversions per blind level
* Casual arcade game: Number of hard sessions on hard levels prior to paid conversion
* Social combat game: Number of losses or wins before initial purchase

And so once this firm grounding in understanding users is established, we can take a look at the strategies developers use to maximize player retention, engagement, and monetization.

---- **Monetization** ----

What will work for any given game is different, but some free-to-paid conversion techniques that have seen success recently are:

**Advancement pain points:** Points in the game where users are interested in advancing but it is difficult to advance without buying premium items. Games that require "grinding" to advance use this a lot as do games that are level-based (multiple levels the user plays which get progressively harder)

**Provide a competitive impulse:** Many games that feature a competitive or P2P mechanic allow people to spend to get ahead of other players. (Personally, when I spend on mobile games, it's usually to better PWN other players.)

**Play limitation:** Users have limited plays or lives and have to wait a certain amount of time before playing again without paying for more tries. Games such as Family Feud 2 and Bejeweled Blitz employ this strategy as a primary monetization tactic.

**Time-to-completion:** Tasks that take certain amounts of time that can be sped up with premium currency. Many games that have a building mechanic often employ this tactic.

**High-priced offers/Social distinction:** Design expensive offers for players that allow major advantages or major distinction. This will give highly engaged players an incentive to convert to whale-level spending. Many game types offer this, but MMOs or social games with lots of direct player interaction can rely on this more.

You want to ensure you really know your player segments so that you can target individual play styles with content that they’ll be most likely to buy.

----**Retention**----

Some retention strategies used frequently by successful developers include:

**Heavy immersion in enjoyable experiences:** The game gets people into the most enjoyable core gameplay mechanics fast

**Smart Tutorials:** Tutorials recognize how much help a user needs and offers more if they do need more help, and less if they don't.

**Predictive individualization:** Ability via predictive behavioral modeling to determine what a user likes within the first 5 minutes of play and to customize the experience to maximize their involvement in gameplay mechanics and content they love. This strategy is hard to pull off because it requires statistical modeling.

**Care Obligations:** Creating timed tasks that users must come back to finish

**Early Customization:** The ability for players to customize their in-game avatars or possessions. Establishes an early sense of ownership

**Early re-engagement notifications:** Re-engagement push notifications, emails, and social network notifications

**Eliminating Error:** Error is ESPECIALLY damaging to early retention. In a player's first hours and minutes they are very skeptical of your game and error in this phase absolutely kills retention. So again, you'll really want to make sure you integrate a good QA process and a log management tool like Loggly to monitor error while the game is live. It seems like a no-brainer, but MANY MANY developers miss this point and end up losing the cash and time they invested into the game to easily manageable errors.
> 3 votes

# Answer
Dan Cook has a great blog post about this. His post is from the perspective of Flash games and not MMOs, but at the end of the day the principles are the same: you're offering something free to play, with some kind of premium content that is worth paying for, and trying to convert customers.

http://www.lostgarden.com/2009/08/flash-love-letter-2009-part-2.html
> 2 votes

# Answer
Here's an article about a talk in GDC Europe that also somewhat answers my question.

http://www.gamasutra.com/view/news/29983/GDC\_Europe\_To\_Succeed\_In\_FreeToPlay\_Exploit\_Human\_Weaknesses.php

Not the best view though but is helpful anyways.
> 0 votes

---
Tags: game-design, mmo, marketing, free-to-play
---


title: Interpolating rotated objects

text:
# Question
Title: Interpolating rotated objects
I've finally got interpolation working to 'smooth' out movement, however it doesn't seem to work for objects that are rotating (around their own center) - when I try to do this, the objects in question 'wobble'.

**Note: I'm not talking about interpolating the actual rotation but rather the movement of a rotated object**

So, let's say I have an object moving from left to right. Using the code below (with interpolation), it moves nice and smoothly. However, after rotating the object (let's say by 45 degrees, but this could be any angle), it's no longer moving smoothly, it still moves along it's path (left to right in this case) but it's no longer smooth.

**Main Game Loop**

```
@Override
public void onDrawFrame(GL10 gl) {

    //Grab time
    newTime = System.currentTimeMillis()*0.001;
    frameTime = newTime - currentTime;
    if ( frameTime > (dt*25))
        frameTime = (dt*25);

    currentTime = newTime;

    accumulator += frameTime;

    //Save game-state and update logic
    while (accumulator >= dt){
        saveGameState();  //Back up positions before updating them
        updateLogic(); //Update logic
        t += dt;
        accumulator -= dt;
    }

    //Get the amount to interpolate by
    interpolation = (float) (accumulator / dt);

    //Interpolate positions and render
    interpolate();
    render(interpolation);
}

```

**Rotation Code**

```
public void rotate(float x, float y, float angle){

    //Rotate the quad
    Matrix.setIdentityM(mRotationMatrix, 0);
    Matrix.translateM(mRotationMatrix, 0, centreX, centreY, 0f);
    Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 0.1f);
    Matrix.translateM(mRotationMatrix, 0, -centreX, -centreY, 0f);
}

```

**Edit**

OK so it appears this is the problem:

* During logic update, sprite is moved and rotates it around it's center (using it's new/current X and Y to calculate it's center).
* Get's to render()
* Render method interpolates position creating new 'throwaway' coordinates at which object should be drawn
* Render method draws sprite at it's 'render' x and y coordinates
* Logic update moves and rotate **around it actual x and y - not it's 'rendering x and y**
* and so on

So as you can see, it's being rotated, not around the coordinates that it's been drawn at but at it's actual coordinates. I can't rotate it around it's render coordinates, because the rotation is done within the logic update, not during the render call, therefore, it would be rotating it around it 'old' render position, not the next one and I won't know the new render coordinates until the next render call which means.........

That the only way I can do this, is to actually translate / rotate the sprite within the render routine and **not** the logic routine.

I've tried this and it works, but not sure I'm happy about piling more 'logic' into my render routine.

Is this an 'acceptable' model? How else can I achieve rotation while keeping the object nicely interpolated?!

# Answer
from looking at the docs I have found your issue

> public static void rotateM (float\[\] m, int mOffset, float a, float x, float y, float z) Added in API level 1
>
> Rotates matrix m in place by angle a (in degrees) **around the axis (x, y, z).**
>
> Parameters:
>
> * m source matrix
> * mOffset index into m where the matrix starts a angle to rotate in degrees
> * x X axis component
> * y Y axis component
> * z Z axis component

`Matrix.rotateM(mRotationMatrix, 0, angle, 0, 0, 0.1f);`

looks like this function is meant to rotate around an axis and your passing the axis of ( 0,0,0.1f ) when you probably mean to be rotating this object around its local origin

**local origin rotation: (this is what you want to be doing)**

**rotation around world point: (this is what you are currently doing)**

this would very probably change position, thus ruining your interpolation

you can change your rotateM call to look like this

`Matrix.rotateM(mRotationMatrix, 0, angle, ORIGIN_X, ORIGIN_Y, ORIGIN_Z);`
> 1 votes

---
Tags: sprites, movement, opengl-es2, game-loop, interpolation
---


title: Using crittercism with Unity

text:
# Question
Title: Using crittercism with Unity
I want to use crittercism with my Unity project. In Unity I am developing a game for iOS and Android platform. I did enough Google searching to come to the conclusion that Unity doesn't support this by itself and there aren't much tools out there to help me.

Can someone suggest a way to do it?

If not, is it possible for me to get access to the editor logs of Unity programmatically so that I can send these logs to my server directly. (I'll however still need to know when a crash occurs.)

I was thinking of a "hack". Please tell me if it is doable. On building the project, Unity creates an xcode project for iOS. I was thinking of opening the xcode project itself and putting the relevant commands to send the logs to crittercism, in case a crash occurs. However I am not able to think of a way to do this with Android.

# Answer
It doesn't look like crittercism offers any library that you could use with Unity. There's a chance that you could take the HTML5 version, which is in Javascript, and either rework or extract certain parts in order to use them in UnityScript, but I fear some of the error reporting will assume that it is running in a browser context and will be unable to communicate back with the server.

So I don't think there is any way you can use this tool from a Unity app directly. It might be worth contacting the developers and suggesting they support Unity in future. Your workaround for iOS might work.

I don't think that Debug.Log output appears in final builds of the game, so I am not sure how much use it will be to try and send those to your server. But there might be some log output you can use, and the different locations of the log files are here: http://answers.unity3d.com/questions/9739/how-can-i-find-editor-log-file.html I don't know if the directory can be reached programmatically from within your code.
> 1 votes

# Answer
Sounds like you're interested in things like Crash Data, stack traces, tracking 3rd party vendors etc. Another option to do this is to perhaps use Loggly. It's different from Crittercism it's geared more towards consume & visualizing game logs than automatically categorizing performance data but they have a REST API which will allow you to use it in Unity and you can log the exact same information (transaction logs, device used, monitor service provider HTTP response times, crash/exception logs).
> 0 votes

---
Tags: unity, exceptions, crittercism
---


# Question
Title: Blurring part of the screen - optimisation
I develop 3d menu and sometimes I need to blur only part of the screen. I use a forward rendering. I create a frame buffer object with 3 color attachments. Rendering looks like this:

* bind fbo
* render objects which are blurred to the first texture
* bind the first texture
* perform vertical blur and save a result in the second texture
* bind the second texture
* perform horizontal blur and save a result in the third texture
* unbind fbo (render to the default fbo)
* bind the thrid texture
* render the third texture
* render objects which are not blurred

I can use subroutines to reduce overhead during switching shaders. I also found the following article . Do you have any other ideas how to optimize above rendering ?

# Answer
That is the standard way of doing a Gaussian blur however, you can use only 2 textures like this:

* bind the original texture
* blur horizontally to the second texture
* bind the blurred horizontally texture
* blur vertically to the original texture
> 1 votes

---
Tags: opengl, glsl
---


title: Ways to improve player retention

text:
# Question
Title: Ways to improve player retention
I've recently released my first free to play game on Android and I've spent a few £ on advertising to try and get players involved and see what happens.

Below are my retention stats courtesy of Google. Judging by the colour coding 50% is good \<30% is not so good, but in reality I have no real idea what these numbers should look like. So this question has two parts really.

What are ok/good numbers for Days 1, 2, 7 and 30? So I know what I should be targeting, and what are good ways to increase my numbers to get the to that level. There are the obvious things such as notifications, but what are the less obvious strategies that a novice is unlikely to think of?

# Answer
> 4 votes
I'll let someone with actual experience on Google's retention stats for popular games and so on answer your first question.

As for the second question, the short answer is to design your game with retention in mind. Your goal is to make the player come back to your game and your game should try to make him come back as part of its core.

Things you might want to keep in mind and apply based on your situation (in no particular order):

* Avoid things that make your game a chore to play through (i.e. make a fun game). Examples of such things are very slow loading times, very poor performance, crashes, bugs, poor controls, huge amounts of work for very little reward (tip! you might want to let your player be able to achieve *something* instantly when he comes back to your game. It doesn't have to be something *huge*) and so on.
* Balance the difficulty accordingly, don't make your game frustrate the player. See this for more on the topic: What is an optimum failure rate that will keep people coming back to my game?
* Do not annoy the player. Begging for him to come back or harassing him is annoying.
* Periodic notifications are good. Don't exaggerate, otherwise you'll annoy the player. Make notifications meaningful, otherwise you'll annoy the player. Making it obvious that your game is nagging him to play some more each day is a sure way for the player to uninstall the product.
* Introduce time/duration based mechanics. Make a house take a while to build, and the player will return later on to see it finally being built and start building another house (hopefully).
* Introduce periodic special events. Let the player know that one week from now something awesome will happen and he has to be there to see it.
* Update your game often, add more content. Dead games are not favored by players who are looking for games to play long-term.
* Try to build a community around your game. Integrate social networking services. Raise some hype. Make your players talk to each other. Letting the players make friends within a game is a great way to make them come back to your game and interact some more. Communities tend to keep games alive for a very long time.
* Make the game look like it's been made for the player that's playing it, not for some category of players in which he has been thrown. That means you should let the player personalize his experience as much as possible. He's much more likely to keep a game that feels like it's "his". Custom loadouts, custom avatars, custom names, custom signatures and so on, all can be used here. Translations also help. Making your game speak the player's native tongue may go a long way towards him liking it.
* Don't be afraid to try a new strategy with a new game if you see your game is dying. Any hot game cools down eventually, so having some new ideas with you at all times is mandatory to survive anyway.
* Track the players' activity in your game. See what they do most often, what they like and what they don't. Optimize your updates according to the data you get.
* Use what you've learned with your previous games in your new games.
* Talk to your player and let his opinion matter. Planning a nice update? How about asking your players what they want? Use polls, or even better, ask the player questions directly in the game: "What would you like to see in the next update?" Use the feedback to plan your content accordingly. At the same time, you let the player know he's being listened to, and he's more likely to come back to your game to see his ideas become reality.
* This may or may not be cost effective in some cases: make as many of your key mechanics for retention as possible work together with a server on which you can customize their properties. Want to update the price of certain consumables and advertise it as a sale? Just set the properties (values, start date of the sale, duration of the sale and so on) on your server, and all of the games will automatically adjust according to them. This ensures you'll always adapt quickly to new situations.

---
Tags: game-design, game-mechanics, analytics
---


title: Gun Bobbing Algorithm Math Explanation

text:
# Question
Title: Gun Bobbing Algorithm Math Explanation
I stumbled across this really neat algorithm which I don't fully understand. It simulates a camera's bobbing effect commonly witnessed in first person shooters while running/walking. I'm mainly unsure about the timer and translation by totalAxes calculations.

Would someone with some more math skills than myself care to explain it on a comment by comment basis? If so, that's much appreciated.

```
    Vector3 localPosition = transform.localPosition;

    if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0)
    {
        timer = 0.0f;
    }
    else
    {
        waveSlice = Mathf.Sin(timer);
        timer = timer + bobSpeed;
        if (timer > Mathf.PI * 2)
        {
            timer = timer - (Mathf.PI * 2);
        }
    }
    if (waveSlice != 0)
    {
        float translateChange = waveSlice * bobDistance;
        float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
        totalAxes = Mathf.Clamp (totalAxes, 0.0f, 1.0f);
        translateChange = totalAxes * translateChange;
        localPosition.y = midPoint + translateChange;
    }
    else
    {
        localPosition.y = midPoint;
    }

```

# Answer
OK, I'll do my best. Having more information about `horizontal` and `vertical` would be helpful though, but I'll try to guess. I'm assuming here that those two variables contain information about the movement of the player (or the position of the controller analog stick, which would have the same effect).

```
Vector3 localPosition = transform.localPosition;

// If the player does not move, set the timer to zero. This will cause the
// else clause of "if (waveSlice != 0)" to be active in this call.
if (Mathf.Abs(horizontal) == 0 && Mathf.Abs(vertical) == 0)
{
    timer = 0.0f;
}
// If the player moves, calculate the sine of how long the player was
// moving.
else
{
    // This is the most important part. The heart of bobbing here is
    // a sine wave, meaning a transition between -1 and 1 with smooth
    // speed decreases at the upper and lower bounds. See footnote.
    waveSlice = Mathf.Sin(timer);

    // bobSpeed is simply the speed at which the bobbing moves. Since
    // timer is the parameter to the function "sine/Mathf.sin", this
    // determines how fast you advance on the sine.
    timer = timer + bobSpeed;

    // Clamp timer, preventing overflow. 2π is chosen since this is
    // the circumference of a circle with radius 1 (which is what is
    // used in "waveSlice = Mathf.Sin(timer)").
    if (timer > Mathf.PI * 2)
    {
        timer = timer - (Mathf.PI * 2);
    }
}
// If there is any translation of the gun position (from the default
// position)...
if (waveSlice != 0)
{
    // ...calculate how far the gun moves from its default position
    // (bobDistance is one half of the maximum bobbing travel distance
    // (because it moves up and down relative to origin).
    float translateChange = waveSlice * bobDistance;

    // totalAxes is the sum of both absolute stick movement directions
    // clamped to [0, 1], meaning it is an approximation of the movement
    // speed. This means that movement speed is calculated by fitting the
    // stick locations in a diamond. A circle (the shape a stick can move
    // in in meatspace) would be more appropriate, but also more expensive
    // to calculate (you need a square root), so I guess this is enough.
    float totalAxes = Mathf.Abs(horizontal) + Mathf.Abs(vertical);
    totalAxes = Mathf.Clamp (totalAxes, 0.0f, 1.0f);

    // (Possibly, depending on how far the stick is pushed) reduce the
    // amount of translation to be done. This means less bobbing when
    // the player moves slower.
    translateChange = totalAxes * translateChange;

    // Set the position of the gun either up or down from where its default
    // position is (remember that translateChange can be positive or
    // negative).
    localPosition.y = midPoint + translateChange;
}
// If not, put the gun at its default position.
else
{
    localPosition.y = midPoint;
}

```

The long comment aboive `totalAxes` is a bit hard to explain without more drawing, I the above doesn't help you I'll try to explain it further.

If the trigonometry used here is very unfamiliar to you, I encourage you to read up on it. There is a lot of that stuff in video games, and the more you grasp it, the easier it is for you to understand code written by others and solve your own problems when they come up. And it's really not that difficult once you get the hang of it. The internet is full of different approaches of explaining it, just look around until you find one that suits you.

*Footnote:* For the way waveSlice gets calculated based on the timer, have a look at this GIF where the blue line corresponds to `timer` and the red line to `waveSlice`. Also remember that timer only ever increases or gets reset.
> 2 votes

---
Tags: c#, unity, mathematics
---


# Question
Title: How to handle a negative coordinate 2d map with a growing map size
I love this procedural generation theory and have been messing around with it. However I'm having trouble wrapping my head around how to store my map data. Usually I store my map data in a 2d array and that works in a limited space. However my map grows as the player explores new territory. So the size of the map changes and what's more the array will only support positive indices. So if the player tries to explore west or north he runs into a black abyss of nothingness. But I what more map to generate in those directions. Unfortunately those are the negative coordinate parts of the map. Is there a way to support a negative coordinate as the player explores new area? Here is an example of the problem in action.

https://76295db93db3812642fa5ba984c042fa81ffc37c.googledrive.com/host/0B6H3TRExU5M9eEkyd2FreHhiNlU/

Try moving West or north and you'll run into the edge of the map.

# Answer
You need to handle your map in chunks/tiles of fixed size.. and only keep the chunks in the immediate vicinity of your player actually on hand at any moment (out to whatever view distance you feel is reasonable)

As the player crosses a chunk boundary, you add new chunks in the direction of movement, remove them behind the player, and keep going.

If you are working on a truly endless world (or at least endless in terms of the scale of double precision coordinates) then you need to setup a system that does its best to keep the camera fairly close to the scene/world origin... I've handled this in one of my own tech demos by layering a double precision positioning system on top of the typical float positioning in most game engines... when the player moves in the world, every so often the camera will offset the float positions of everything such that the camera is close to 0,0,0 in world space coords

This is called a Camera Centric positioning system and is about the only sane way to handle large terrain spaces or even solar systems where you want to have accurate coordinates even for things that are too far away to be currently visible.
> 1 votes

# Answer
You can build a graph data structure to handle the changes between chunks.

Depending on exactly how you want the chunk boundaries to work, you may or may not need to render more than one chunk at a time. Many games have chunk boundary hallways that are Z or other sight-line blocking shapes. These are so that the game can fresh load the next chunk before you get there.

If your terrain is generated in a deterministic way (after random seeding maybe) you could just regenerate it as the player walks around and not even have to keep a record of it, so your 2D array would always be just a bit larger than the map (to allow monsters to be one or two tiles off the edge).

Example:

```
if (playerX < 0)
    nextChunk = currentChunk.westChunk
    if (nextChunk == null)
        nextChunk = new Chunk()
        nextChunk.eastChunk = currentChunk
        currentChunk.westChunk = nextChunk
    currentChunk = nextChunk
    playerX = currentChunk.maxX

```

With the above pseudocode, you only create new chunks when the player reaches them but they stay in place if the player ever goes back. You'd need to do the other directions as well of course, but this should give you a start.

Looking at the code behind your site, I think that what you call map is the same thing we're calling chunk, except chunk has a few more properties to connect to each other. Your map drawing code could either deal with neighboring chunks, or more easily only display one chunk at a time.
> 0 votes

# Answer
Most important thing i see about your issue is to keep a good separation of concerns.
When you wonder about 'negative array indexes', you have an issue because you mix the concern of knowing where the player is, and the concern of how you build/store your world data ('map').

Have a camera object, that will define what is the center of the current view and a view scale (zoom). The canvas + the camera gives you a view port : on each render, you can easily compute the viewable rectangle in world coordinates.
Now, give your World an interface that uses only world coordinates: Now you're freed from the index issue, you can move/copy/... the array(s) that represent your world without breaking anything in your game.

The best way to model the world depends on your game : can the user come and go anywhere ? Is the map only horizontal/vertical, do objects re-spawn, ...???

I the general case, you can use a fixed-size array that covers, say, 4 times the screen.
Handle a offset on x and y : that would be the center of the array (two indexes, centerIndexX, centerIndexY), and the related world coordinates (centerX, centerY).
Rough pseudo-code :

```
   function drawWorld(camera) {
      // if the view rect does not intersect the stored part of the world...
      if (!intersect(camera.rectangle, world.rectangle) {
         world.generate(camera); // generate a view centered on the camera
      }
      // where is the camera within the world ?
      var tileRatioX     = ( world.centerX - camera.centerX ) / word.tileSize;
      var tileOffsetX    = Math.floor(tileRatioX);
      var tileRemainderX = tileRatioX - tileOffsetX;
      tileOffsetX       += world.centerIndexX ;
      // ... same for y
      // compute width/height of the view in tiles
      var tileHalfWidth = Math.floor(0.5*(camera.width) / word.tileSize);
      // same for height
      // draw
      for (var i=tileOffsetX-tileHalfWidth, ix=0; i<tileOffsetX+tileHalfWidth; i++, ix++) {
           for (var j=tileOffsetY-tileHalfHeight, jy=0 ; tileOffsetY+tileHalfHeight ; j++, jy++) {
              var currentTile = world._tileArray[i][j];
              // draw CurrentTile at (ix,iy)*tileSize + (tileRemainderX,tileRemainderY)
           }
      }
  }

```
> 0 votes

# Answer
For situations like this where I want an endless map with possibly negative coordinates, I use a hash table instead of an array. In JS, the easiest thing (maybe not the cleanest) is to use an Object:

```
function Map() {
    var contents = {};

    function index(x, y) {
        return x + "," + y;
    }

    function set_map(x, y, value) {
        contents[index(x, y)] = value;
    }

    function get_map(x, y) {
        return contents[index(x, y)];
    }

    return {get: get_map, set: set_map};
}

var m = new Map();

```

Negative coordinates work just fine in this system. For example, after running `m.set(-3, 5, 'A')`, the map contents will be `{ '-3,5': 'A' }`. You can call `m.get(-3, 5)` and it will return `'A'`. Anything that isn't defined in the map will return `undefined`. And any parts of the map that haven't been explored yet won't take up space in the map.
> 0 votes

---
Tags: 2d, javascript, procedural-generation, html-canvas, rpg
---


# Question
Title: How do console games avoid port forwarding with user hosted servers?
On AAA xbox games (Call of duty, etc.), the company acts as a matchmaking service but the users host all of the games. Because not everyone has ports forwarded on their router, how do these games create an accessible server without relying on port forwarding?

In other words, how would one (on a high level) implement NAT to NAT connections?

The only thing I can think of is:

1. Try to open up a port via UPNP
2. If that fails, use a centralized relay server (latency!) or host on the centralized server

Is that a suitable idea or is there a better option?

# Answer
It's called NAT punchthrough. Today costs of dedicated servers are so low (and advantages of having it are so much better) almost nobody uses it. When you're behind NAT your router will forward packets from outside to you only if you initiated communication first, so router has mapped that outside IP and random port to your computer.

Solution: basically when user hosts (P2P hosting) a game, all clients (all games) start sending packets to host and host sends packets to them, so hosts opens up to packets from outside after few tries. It's actually more complicated then that, here's what RakNet's documation on NAT punchtrough says:

> NAT Punchthrough Algorithm Peer P1 wants to connect to peer P2, both of whom are connected to a third Non-NAT system, F
>
> Peer P1 calls OpenNAT() with the RakNetGUID (unique identifier) of P2 to F.
>
> F returns failure if P2 is not connected, or already attempting punchthrough to P1.
>
> F remembers busy state of P1 and P2. If either P1 or P2 is busy, the request is pushed to a queue. Otherwise F requests most recently used external port from P1 and P2. P1 and P2 are flagged as busy.
>
> If either P1 or P2 do not respond punchthrough fails with ID\_NAT\_TARGET\_UNRESPONSIVE and the busy flag is unset. Otherwise, F sends timestamped connection message to P1 and P2 simultaneously.
>
> P1 and P2 act identically at this point. First, they send multiple UDP datagrams to each other's internal LAN addresses. They then try each other's external IP/port as seen by F. Ports are attempted sequentially, up to MAX\_PREDICTIVE\_PORT\_RANGE.
>
> If at any point a datagram arrives from the remote peer, we enter state PUNCHING\_FIXED\_PORT. Datagrams are only sent to that IP/port combination the remainder of the algorithm. If our reply arrives on the remote system, the NAT is considered bidirectional and ID\_NAT\_PUNCHTHROUGH\_SUCCEEDED is returned to the user.
>
> When NAT is open, or if we exhaust all ports, P1 and P2 send to F that they are ready for a new punchthrough attempt.
> 3 votes

---
Tags: networking, multiplayer
---


# Question
Title: Using sky for indirect lighting - should I remove the sun?
I'm attempting to achieve slightly more realistic ambient lighting in outdoor scenes using the sky cubemap.

When rendering an object, I first calculate the direct lighting contribution using standard phong diffuse and specular shading from each light source. In outdoor scenes, this is usually a directional light used to model light from the sun.

I then add in the indirect diffuse lighting contribution by sampling a high mip level of the sky cubemap at the normal to the surface. However, it recently occurred to me that, since my sky cubemaps contain the sun, I am actually including the contribution from the sun twice! I'm introducing a directional light to model the sun in the direct lighting stage, then introducing further lighting from the skybox itself.

My question is this: Should I modify my sky cubemaps so that they don't include the sun, or should I just remove the directional light instead?

# Answer
MooseBoys is right when he says

> integrate the hemisphere about the normal

And to some extend you are also right when you say that a low mipmap is doing that, but not 100% mathematically correct.

What you need to have physically speaking, is a convolution with a cosine lobe in linear space. What you get with the mipmap sampling, is a convolution with a box window in gamma space.

Now, iI'm not saying it will give completely different results, its a good way to approximate the physically accurate model, with hardware support and ease of implementation ! You can keep it this way if you want. If you want super crazy physically correct precision, then I suggest you download AMD CubeMapGen modified by Sebastien Lagarde, and check the GUI box "irradiance", then you can export the result as .dds and instead of sampling the mipmap you can sample the irradiance map.

Now, you need to take the Sun OFF your skycube before you generate the irradiance map, because you WILL, like you feared, apply the sun 2 times !
To do that, just down-tone the sun corolla area to a brightness that has similar values with the surrounding (e.g. manually with Gimp). Its enough. Physically speaking, a sun as a directional light should get values of about 20/25, with an exposure of 1, it would simply saturate everything in an SDR renderer. If you have a range-compressor tonemapper you could get away with this kind of values. If you have an SDR renderer, you want to pre-tone-map manually the intensity of your directional light, to something near 1 so that you don't saturate things. But in that case, the contribution from your irradiance map will be unusually high, it would make sense to premultiply it with the same down-tone filter after its baked by cubemapgen. (again, in a full HDR pipeline, you care not about those things, its handled in real time).

EDIT: Here is the values we find in a classic HDR sky map:
> 2 votes

---
Tags: directx, lighting, sky, skybox
---


# Question
Title: Light Propagation Volumes: Anisotropic filtering of volume data
I've implemented the Cascaded Light Propagation Volumes algorithm (no indirect shadowing yet) for real-time diffuse global illumination detailed here and here. It works fine but I'm still trying to fix one artifact in particular.

**Short summary**

You may skip this if you already know how the algorithm works.

The algorithm works by storing lighting information in the form of spherical harmonics in a 3D grid, where initially the data in each cell of the grid comes from rendering an extended shadow map (reflective shadow map) that also includes color and normal information, besides depth. The idea is that essentially all pixels seen by a light source are the cause of the first bounce of indirect illumination, so you store the required information alongside the ordinary depth buffer you use for shadow mapping, and sample all the data to initialize the 3D grid. The information in the 3D grid is then propagated iteratively by (for each iteration) propagating the information in one cell to all of its 6 direct neighbours (above, below, left,right, top, bottom). To light the scene using the information in the grid, you apply a full screen pass over your scene, and for each rasterized pixel you have the world space position of the rasterized surface available (e.g. from G-Buffers in deferred shading), so you know which cell of the grid a certain pixel on screen belongs to.

This is working fine for the most part, here are two images without simulated GI and just a hardcoded ambient term, and next to it an image with the LPV algorithm. Notice colored reflections on surfaces, better depth detail, etc.

**Problem**

When looking up the cells during the lighting stage, trilinear interpolation (using hardware texture filters) is used to smoothly interpolate data between the center of a cell, its neighboring cells, and the actual looked up texture coordinate. Essentially, this interpolation mimics the propagation of the lighting information at the center of a cell to the concrete pixels around the center where the information is looked up. This is required because otherwise the lighting would look very rough and ugly. However, since trilinear interpolation doesn't take into account the direction of light propagation of lighting information encoded in a cell (remember, it's in spherical harmonics), the light can be incorrectly propagated to the looked up pixel. For example, if the radiance encoded in the cell only propagates towards (1,0,0) ("the right"), everything that's to the left of the center of the cell should receive less light than what is stored at the center, and everything that's to the right should receive more, but trilinear interpolation does not take that into account.

This causes light bleeding incorrectly trough walls when the cell sizes in the grid are big compared to the surfaces in the scene (this is necessary because you need big cells to propagate light far into the scene with as few propagation iterations as possible). This is what it looks like:

As you can see (from the shadow outlines at the top right), the scene is lit by a directional light source somewhere above the scene to the top left. And since there is only one cell separating the outside of the atrium and the inside, the light bleeds through and the wall to the left is incorrectly illuminated.

**Actual question**

The author suggests a form of manual anisotropic filtering to fix this. He gives a radiance gradient (I'm assuming of the SH coefficients sampled from the current cell) towards direction of the surface normal n as:

And states

> Thus, by comparing the radiance directional derivative with the actual radiance direction, it can be calculated whether the radiance distribution starts further than its trilinear interpolation for this point.

My question(s):

In the equation, the function c(x) seem to be the SH coefficients at point (x). So the radiance gradient seems to be computed like a normal numerical derivate as the weighted difference of SH coefficients at points x - (n/2) and x + (n/2). However, what is c(x) in my context? Currently I'm assuming that c(x) refers to the trilinearly interpolated coefficients at surface location(x), but I'm not sure at all, since I don't know how that is supposed to give you more information about the directional distribution of the SH coefficients.

And how is that gradient then used to change how the sampled lighting from the cell is applied to the surfaces, exactly? The author just writes "comparing the radiance directional derivative with the actual radiance direction", but this is pretty vague.

He mentions using a "central differencing scheme" and references these slides for the central differencing of SH coefficients, and also references this paper which shows the derivations of the gradient, but right now I can't draw any useful conclusions from them.

# Answer
> 4 votes
The central difference has been introduced by an AMD paper when they did some demo with crystal flying in a tunel, from memory.

The `c` function doesnt have to be something precise, just an idea of, e.g, radiance, so just evaluate the SH using your current normal.

Then what you do with that, is that you down-tone, using an empirical factor, the radiance using this differential. But only do you downtone if the differential implies the light flow goes away from your current normal.

Basically the idea is to empirically detect the fact that if you go in the direction opposed to the normal of your wall, the light flow is diminishing slowly, because it propagages in the air (on the other side). But if you probe a bit in front of your normal, you will notice a sudden drop of flux, it means the cell you are sampling now is actually a leak.

I have found that it works in 70% of the cases, but if applied carelessly, it can creates very strange black holes effects, or hue shifts (pink, green...) on very dark areas that contains a light leak otherwize. This is because you have 3 LPV for each colors, the central difference tends to give different results. If you are capable, try to use the greyscale lightness to evaluate the central difference dampner, and use a common reduction factor to all color channels later.

Without this hack, normally you should not get much radiance at all anyway, because the normal you use to evaluate the SH is opposed to the flux direction. Howver as you notice, the 2-bands SH used in LPV are not enough in fact, and have a strong DC component that gives this powerful leaks. This is why LPV is impractical for geometries that are not tightly controlled by an LPV-aware artist, that will give every wall a minimal thickness to reduce leaks.

Also some companies (like square enix) use manually designed blocker walls to kill the leaks, like the geometry volume should give you. (the geometry volume helps to reduce the leaks, but the RSM retroprojection to voxelize the scene is too partial in most cases and creates aliasing at the LPV cell level which gives the leaks an even worse look because they vary intensity weirdly).

You can only suck it down and try to mitigate the problems by giving LPV a less-strong final word on the final indirect light, use a constant term with a weight (0.5 ?) and the LPV could contribute to the remaining 0.5 of the indirect light. Also try to implement the geometry volume, it will diminish the problem. And finally the central difference.

---
Tags: global-illumination
---


# Question
Title: How to know when graphics driver or card changes
I'm about to start work on implementing GLSL binary shader compilation and I was curious how to handle the cases when the shaders need to be recompiled, such as when the driver (or perhaps even the graphics card itself) changes. Are there any mechanisms out there to do these types of things, or is this just a "delete the shader cache folder if you update your driver" type of thing? I did a quick search on here and Google and didn't see anything that looked promising.

Edit: or am I just ignorant and GL will let me know when a recompile is necessary?

# Answer
> 2 votes
`INVALID_OPERATION` will be returned by `glProgramBinary` if the binary code is rejected. If this happens, you must recompile the GLSL source code the usual way and then use `glGetProgramBinary` in order to grab the new binary shader.

So, basically, something like like this rough pseudo-source:

```
load_shader(path):
  binary := load_binary(path)
  if binary != null:
    glProgramBinary
    if glGetError() != GL_NO_ERROR:
      load_source(path)
  else:
    load_source(path)

load_source():
  source := load_text(path)
  glSource
  glLink
  glGetProgramBinary
  save_binary()

```

---
Tags: opengl, glsl
---


title: Unity plane that is normal to Z axis

text:
# Question
Title: Unity plane that is normal to Z axis
I want to create a plane that will be normal to the Z axis, but I am having difficulty visualizing what rotation it needs to have.

I want to have a top-down view upon the plane such that I can use the X and Y coordinate system for position, and the Z axis for height.

It seems intuitive for me to point the camera in the same rotation as this plane, and give it an orthogonal view and a positive Z value (and set gravity to have a negative Z value), but I seem to be fighting against the grain and running into more issues than I should be, so I would like to ask what rotations I should be using for this.

What rotation should I use for the plane? can the camera share the same rotation? (assuming I want the top to be +y and the right to be +x as seen from the camera.

# Answer
Luckily for you, you don't actually have to deal with any of this! Instead of actually creating a top-down world, you can use Unity's built-in 2D mode, and create sprites instead of cubes and planes, to make it look like it is top down. 2D mode makes the camera line up automatically, and have the depth appear to be non-relevant, though it is. Also, there are already a lot of utilities, both from Unity and in the asset store, for things such as drawing certain sprites on top of others, if you don't want to draw them based on z-depth. Keep in mind that collision and things like that will be implemented a bit differently in 2D, but that should not be a huge problem if you have experience with 3D. Finally, if you need some help or suggestions, you can always visit the learn section of the Unity website!

In addition, if you have your heart set on using 3D models for some reason, you can create a plane in 2D mode, and rotate it around it's x-axis by -90 degrees. Note that the rotation is negative, as the plane only has one visible side, which is not shown when the rotation is positive. The default main camera (I am not sure of the others) will automatically line itself up with the plane, if it is in 2D mode, which is very convenient.
> 4 votes

# Answer
For that orientation you described you want to use the following Euler rotations:

```
//Camera     (0, 0, 0)
//Plane/quad (0, 0, 0)

```

In this setup the x value will move the object "East" and "West". The Y position will move it "North" and "South" and the Z value will be "Altitude".

It is worth noting that the coordinate axes in Unity are different from some 3D modeling programs. (Y-up vs. Z-up) So its worth checking your import settings because that can cause some confusion especially if the models have come from different sources.
> 1 votes

---
Tags: unity, 3d, perspective
---


# Question
Title: Using Bullet physics engine to find the moment of object contact before penetration
I would like to use Bullet Physics engine to simulate the objects in 3D world.

One of the objects in the world will move using the position from 3D mouse control. I will call it "Mouse Object" and any object in the world as "Object A"

I define the time before "mouse object" and "Object A" collide as t-1 The time "mouse object" penetrate "Object A" as t

Now there is a problem about rendering the scene because when I move the mouse very fast, "Mouse object" will reside in "Object A" before "Object A" start to move. I would like the "Mouse Object" to stop right away attach to the "Object A". Also If the "Object A" move, the "Mouse object" should move following (attach) the "Object A" without stop at the first collision take place.

This is what i did

I find the position of the "Mouse Object" at time t-1 and time t. I will name it as pos(t-1) and pos(t)

The contact time will be sometime between t-1 to t, which the time of contact I name it as t\_contact, therefore the contact position (without penetration) between "Mouse object" and "Object A" will be pos(t\_contact)

then I create multiple "Mouse object"s using this equation

pos\[n\] = pos(t-1) * C * ( pos(t) - pos(t-1) ) where 0 \<= C \<= 1

if I choose C = 0.1, 0.2, 0.3,0.4..... 1.0, I will get pos\[n\] for 10 values Then I test collision for all of these 10 "Mouse Objects" and choose the one that seperate between "no collision" and "collision".

I feel this method is super non-efficient. I am not sure the way other people find the time-of-contact or the position-of-contact when "Object A" can move.

# Answer
> 1 votes
The bullet 2.x API offers a "convexSweepTest" which is kind of doing what you have implemented: A ray cast with a shape. Although possibly more efficient. I would look into that.

---
Tags: collision-detection, mathematics, bullet-physics
---


# Question
Title: Bullet: Get steepness or slope between positions
In a CharacterController object, there is

```
setMaxSlope(btScalar slopeRadians)
The max slope determines the maximum angle that the controller can walk up.

```

But how about knowing it in advance? Like check if the position where the character will move next is walkable (i don't know the correct word) or not? Is that possible? Any suggestions on how should I go about this?

# Answer
> 0 votes
You could sense ahead of your characters movement with a ray-cast or a bunch of ray-casts depending on your desired accuracy. Then calculate the slope angle in front of your character by using the polygon's slope directly or in case of multiple ray-casts, calculate some approximation.

I did this when I first started out with a Kinematic Controller. But eventually, the controller had too many shortcomings and I implemented my own as I describe here:

https://stackoverflow.com/questions/25605659/avoid-ground-collision-with-bullet/25725502#25725502

---
Tags: bullet-physics
---


# Question
Title: Unity: how to apply programmatical changes to the Terrain SplatPrototype?
I have a script to which I add a Terrain object (I drag and drop the terrain in the public Terrain field).

The Terrain is already setup in Unity to have 2 PaintTextures: 1 is a Square (set up with a tile size so that it forms a checkered pattern) and the 2nd one is a grass image:

Also the Target Strength of the first PaintTexture is lowered so that the checkered pattern also reveals some of the grass underneath.

Now I want, at run time, to change the Tile Size of the first PaintTexture, i.e. have more or less checkers depending on various run time conditions. I've looked through Unity's documentation and I've seen you have the `Terrain.terrainData.SplatPrototype` array which allows you to change this. Also there's a `RefreshPrototypes()` method on the `terrainData` object and a `Flush()` method on the `Terrain` object. So I made a script like this:

```
public class AStarTerrain : MonoBehaviour {

    public int aStarCellColumns, aStarCellRows;

    public GameObject aStarCellHighlightPrefab;
    public GameObject aStarPathMarkerPrefab;
    public GameObject utilityRobotPrefab;
    public Terrain aStarTerrain;

    void Start () {
            //I've also tried NOT drag and dropping the Terrain on the public field
            //and instead just using the commented line below, but I get the same results
        //aStarTerrain = this.GetComponents<Terrain>()[0];
        Debug.Log ("Got terrain "+aStarTerrain.name);

        SplatPrototype[] splatPrototypes = aStarTerrain.terrainData.splatPrototypes;
        Debug.Log("Terrain has "+splatPrototypes.Length+" splat prototypes");
        SplatPrototype aStarCellSplat = splatPrototypes[0];
        Debug.Log("Re-tyling splat prototype "+aStarCellSplat.texture.name);
        aStarCellSplat.tileSize = new Vector2(2000,2000);
        Debug.Log("Tyling is now "+aStarCellSplat.tileSize.x+"/"+aStarCellSplat.tileSize.y);
        aStarTerrain.terrainData.RefreshPrototypes();
        aStarTerrain.Flush();
    }

//...

```

Problem is, nothing gets changed, the checker map is not re-tiled. The console outputs correctly tell me that I've got the Terrain object with the right name, that it has the right number of splat prototypes and that I'm modifying the tileSize on the SplatPrototype object corresponding to the right texture. It also tells me the value has changed. But nothing gets updated in the actual graphical view.

So please, what am I missing?

# Answer
It seems you forgot to reassign the Splat texture back :

```
public class AStarTerrain : MonoBehaviour {

public int aStarCellColumns, aStarCellRows;

public GameObject aStarCellHighlightPrefab;
public GameObject aStarPathMarkerPrefab;
public GameObject utilityRobotPrefab;
public Terrain aStarTerrain;

void Start () {
        //I've also tried NOT drag and dropping the Terrain on the public field
        //and instead just using the commented line below, but I get the same results
    //aStarTerrain = this.GetComponents<Terrain>()[0];
    Debug.Log ("Got terrain "+aStarTerrain.name);

    SplatPrototype[] splatPrototypes = aStarTerrain.terrainData.splatPrototypes;
    Debug.Log("Terrain has "+splatPrototypes.Length+" splat prototypes");
    SplatPrototype aStarCellSplat = splatPrototypes[0];
    Debug.Log("Re-tyling splat prototype "+aStarCellSplat.texture.name);
    aStarCellSplat.tileSize = new Vector2(2000,2000);
    splatPrototypes[0] = aStarCellSplat; // <- here
    Debug.Log("Tyling is now "+aStarCellSplat.tileSize.x+"/"+aStarCellSplat.tileSize.y);
    aStarTerrain.terrainData.RefreshPrototypes();
    aStarTerrain.Flush();
}

//...

```

Which by the way you could have done this way :

```
splatPrototypes[0].tileSize = new Vector2(2000,2000); //No referencing issue this way

```

(And then refresh but i'm not even sure it is needed at this state)

EDIT :

There is some parameters in objects which cannot be referenced and i believe

```
splatPrototype.tileSize

```

is one of them so if you do :

```
SplatPrototype aStarCellSplat = splatPrototypes[0];

```

then aStarCellSplat is a clone of splatPrototypes\[0\] but does not references it. sometimes cloning to get the initial value and iterate from it is good especially when you modify complex structure, but in this case a simple parameter call is easyer.

And keep track of your clones, if you clone do not forget to assign back
> 1 votes

# Answer
to make blue lines via shader, you need to have the texture\_uv in the surface function, or in the fract function...

to make blue/grey grid lines in shaderlab, you have to add a total of 4-5 lines to the shader, inside the surf function:

xline = ceil(frac(uv.x\*.1)-.75); yline = same for y

grid = max(xline,yline);

o.albedo.blueval = grid.

then you can change yoru grid size using 1 call to the shader, to change the shader value, .l makes a 10 meter grid, change that value to ajust grid size, .75 makes a grid 3/4 of the area of the screen.

then tweak the color adding maths to the same that was used on the previous version /splatmap.
> -1 votes

---
Tags: unity, textures, software-engineering, terrain
---


# Question
Title: How can I optimize performance when updating tiles?
So I'm making a side-scrolling adventure type game in Java. The worlds are procedurally generated, so I can't manually place tiles. Therefore, I every 20 ticks (1/3 second) I update every block's tile on the screen. I know this is a terrible solution, and it's causing a bit of lag. I tried only updating the blocks' tiles once when it was created, but it doesn't work well with the way I've programmed my world generation.

Basically, how the ground is generated is the top layer of ground is generated first, then when the player gets close enough, the layers below are created.

```
public void testForBlocks()
{
        topTaken=false;
        bottomTaken=false;
        rightTaken=false;
        leftTaken=false;

        for(int i=0;i<handler.screenBlocks.size();i++)
        {
                Block b = handler.screenBlocks.get(i);
                if(b.solid)
                {
                        if(b.oneWay==oneWay)
                        {
                                if(b.x==x&&b.y==y+32)
                                        bottomTaken=true;
                                if(b.x==x&&b.y==y-32)
                                        topTaken=true;
                                if(b.y==y&&b.x==x+32)
                                        rightTaken=true;
                                if(b.y==y&&b.x==x-32)
                                        leftTaken=true;
                        }
                }
        }

        setSprite();
}

```

This means that if I only update the tile's position once, the tile won't recognize that there is a block below it yet(because there isn't), and will be assigned the wrong tile.

**Basically, my question is: How can I update tiles, while keeping it efficient?**

I feel like I'm missing an obvious solution. Can anyone help me? Thanks in advance. :)

# Answer
The solution was provided by William'MindWorX'Mariager: Only update the tiles in the camera view if the camera view has moved a certain amount, and leave everything else alone. At least, that's how I perceived it, and it worked pretty well.
> 0 votes

# Answer
I have two possible solutions.

1) Generate a seed in the beginning of the load. Then load an original world using said seed. A large chunk of the world, you can then use that seed to generate large amounts of the new world while using minimal memory, and the original world will give you enough of a buffer till you get to that section.

2) Generate a group of areas. Then simply recycle them. Kind of like a biome generation. Specific biomes (or areas in this case) will be loaded from past areas. No generation needed except for the loading of old areas.
> 1 votes

# Answer
Just generate the complete map before the start of the game, generating it while playing seems silly to me, but I don't exactly know what your goal is. Then just render the the visible tiles to the screen. When a tile needs to be updated just update it, if you have too many tiles that needs updating on a single frame just update the tiles visible first and put the rest on hold, maybe a list that gets worked on after X on screen tiles have been updated.
> 0 votes

# Answer
So IF I understand this correct you are dynamicly creating some nodes(tiles) which define the "game" engine. These nodes are connected by vicinity so that each node has a specific number of neighbour nodes and it all works great.

The part of where the issue comes in is that those neighbour nodes need to exist for you to be able to define what sprite should be used to DRAW that node and the question is how to only update the nodes that have not yet been updated but have all the neighbour nodes?

Then the straight forward solution would be that once you create a new node (probably not yet ready to draw) you need to update all its neghbour nodes instead of self. Or rather yet update all the neighbours and the node itself just to be sure.

To make a solution a bit better you should add a boolean value indicating the validation so `if(valid==false) update()` where update would set the sprite (or whatever needs to be done) and set the valid property to `true`. So whenever a node is generated get all the nearby nodes and iterate through them using this procedure...
> 0 votes

---
Tags: java, tiles, optimization
---


title: Parsing .sc2replay files

text:
# Question
Title: Parsing .sc2replay files
How do I parse StarCraft 2 replay files (*.sc2replay*)? Is there an API?

I know of Sc2gears, but it doesn't quite fulfil my needs.

# Answer
The Starcraft 2 replays are stored as MPQ a compressed file-format developed and used by Blizzard. On the bottom of the Wiki page you'll also find links to MPQ parsers.

Maybe you'll also want to have a look at the following open-source projects: WARP (a Starcraft 2 replay parser written in Java) or phpsc2replay (a replay parser written in PHP).

**Update:** As of now, there's also a Python library out there that can read a lot of the replay data: sc2reader. This is most likely the best option that is currently available (as of March 2013).

**Update 2018:** sc2reader is now maintained by `ggtracker`. Anyway `sc2reader` is hosted now on PyPi so maybe the best way is to `pip install sc2reader` and find it on sc2readers pypi page
> 16 votes

# Answer
*Disclosure: I'm the author of Scelight and Sc2gears.*

---

Blizzard released an official, open-source SC2Replay file parser library called **s2protocol** written in python:

https://github.com/Blizzard/s2protocol

That is the most complete, up-to-date, official replay parser. It is considered the *reference implementation*. It is quite low-level though.

There is another project called Scelight (which is the successor to Sc2gears). In Scelight there is a setting (a combobox): `Skill level`. If you set this to `Developer` (this requires a tiny programming task to be solved first to prove your developer skills to unlock it), a whole bunch of new information is displayed for opened replays in the **Inspector** tab of the Replay Analyzer which are intended for developers only including the internal structure of replays including every last bit of it, hex viewer and much more.

Scelight also has an extension interface called External Module API which has a well documented API. The External Module API provides access to SC2Replay parser and both low and high-level replay internal datastructures and tools.The javadoc of the External Module API is also available online here:

https://scelightop.appspot.com/scelight-ext-mod-api/

**Edit:**

Both Scelight and Sc2gears have been open-sourced, you can see exactly how they do it (both projects count more than 100,000 lines of code):

**https://github.com/icza/scelight**

**https://github.com/icza/sc2gears**
> 9 votes

# Answer
I played with parsing the SC2 replay files a while back. You can view what I've done and what I've been able to reverse engineer (as well as bunch of links to helpful sites at the bottom):

http://wiki.spectralcoding.com/project:sc2inspector
> 2 votes

---
Tags: file-format, starcraft-2, replays
---


title: Automatically select back buffer format

text:
# Question
Title: Automatically select back buffer format
In D3D9, you could set `BackBufferFormat` to `D3DFMT_UNKNOWN` in the presentation parameters and D3D would select the format for you.

However, in D3D10, if I set the swap chain descriptor's `BufferDesc.Format` to `DXGI_FORMAT_UNKNOWN`, I get this error:

```
D3D11 ERROR: ID3D11Device::CreateTexture2D: A Texture2D does not support the following Format (0, UNKNOWN). [ STATE_CREATION ERROR #92: CREATETEXTURE2D_UNSUPPORTEDFORMAT]

```

By the way, if I'm calling `D3D10CreateDeviceAndSwapChain`, why am I getting a D3D11 error? I guess in Windows 8.1 d3d10 is implemented with d3d11 behind the scenes. Strange. Back to the question, I want to have D3D select the back buffer format for me, is it possible?

**Edit**: If it's not possible to select automatically, where can I find a good rationale to select it myself? The amount of choices is baffling.

# Answer
The choice of which backbuffer format to use comes down to four considerations:

1. The target feature level for the hardware you are supporting determines what backbuffer formats are available. See the "Display scan-out" options listed in the DXGI documentation for each feature level. For example, to support all feature levels you have to use `DXGI_FORMAT_R8G8B8A8_UNORM`, `DXGI_FORMAT_R8G8B8A8_UNORM_SRGB`, or `DXGI_FORMAT_B8G8R8A8_UNORM`. Note that on older drivers (i.e. first-generation WDDM 1.0 Windows Vista drivers on Feature Level 10.x cards; 9.x feature level devices always support BGRA) `DXGI_FORMAT_B8G8R8A8_UNORM` may not be supported.
2. If you are going to use Direct2D/DirectWrite interop, then you must use `D3D11_CREATE_DEVICE_BGRA_SUPPORT` which means you have to be using BGRA-supporting drivers (i.e. WDDM 1.1 or later on Feature Level 10.x+ devices). if you are using Direct2D on the backbuffer, you should use `DXGI_FORMAT_B8G8R8A8_UNORM`.
3. If you are doing gamma-correct rendering and want to rely on the automatic gamma correction built into Direct3D, then you should use an SRGB format such as `DXGI_FORMAT_R8G8B8A8_UNORM_SRGB` or `DXGI_FORMAT_B8G8R8A8_UNORM_SRGB`.
4. If you are wanting to use '10-bit scan out' extended color space (i.e. "High Color" or "Deep Color") in full-screen mode, then you should use `DXGI_FORMAT_R10G10B10A2_UNORM` which requires feature Level 10.0 or later hardware. You can use `DXGI_FORMAT_R16G16B16A16_FLOAT` but it tends to take up far too much memory and bandwidth at HD resolutions.
> 2 votes

---
Tags: directx10, windows-8, initialization
---


# Question
Title: Game Architecture and Separation of Concerns
I'm trying to build a "simple" Tetris game, but I want to have enough flexibility to add a few things:

* The game can be played by a human, or (if the human presses a certain key) an AI is swapped in.
* The rendering code should be "configurable". That is, the user may enable or disable animations, or speed them up.

MVC initially looks like a good fit: the game itself is encapsulated in a `Game` object, providing some methods to interact with it (`moveLeft`, `rotate`). The `Controller` would handle user input or AI. The View just renders the game, and gets notified of updates by the Game itself whenever something interesting happens (`PieceMoved`, `LineDestroyed` and so on).

However, my problem mostly lies in "What if I want a blocking animation?"

When lines are destroyed, I want to do a "falling" animation where the top lines crush the bottom lines (or whatever), but since this animation may take some time, I want to avoid updating the game (that is, piece gravity) until the animation is completed.

Does it make sense to have the Controller do something like...

```
void update() {
    input.process()
    render.update()
    if (!render.blocked()) {
        game.update();
    }
}

```

Is MVC a bad fit for this? What's a good way to separate concerns in games?

(I am using libGDX, but my question isn't limited to it.)

# Answer
I wouldn't bother that much with trying to fit the game in the mold that comes with MVC or any other pattern until I know for sure that it's the simplest way to develop it. Especially since most of the time you'll implement multiple known patterns in the same program, or alter patterns after you notice they don't quite fit in your program the way they were formally described.

Here's how I'd architect Tetris. It contains traces of Strategy.

Put your board in the middle, and let it keep track of the state of things (position of pieces and so on).

```
class Board
{
    private bool isBusy(); //Don't accept player input, or update non-graphics
                           //make it return true if you're playing an animation.
    public void Update()
    {
         //Make pieces move and so on, if not isBusy()
    }

    public void ApplyMove(Move move);
}

```

Define an interface that will be common among board interactors.

```
interface BoardInteractor
{
      void Update(Board board);
}

```

Your player will implement BoardInteractor.

```
class Player : BoardInteractor
{
       public void Update(Board board)
       {
            if (UserPressedLeft)
            {
                board.ApplyMove(LeftMove);
            }
            //and so on
       }
}

```

Your AI will also implement BoardInteractor, and will simulate a player.

```
class AIPlayer : BoardInteractor
{
         public void Update(Board board)
         {
              //Make your AI seem smart here.
              Move move = calculateBestMove(board);
              board.ApplyMove(move);
         }
}

```

Cover both things in a Game class that will keep things together.

```
class Game
{
      private Board _board;
      private BoardInteractor _interactor;

      private void changeInteractor(BoardInteractor newInteractor)
      {
            _interactor = newInteractor;
      }

      public void Start()
      {
            _board = new Board();
            _interactor = new Player();
      }

      public void Update()
      {
            if (UserPressedSpecialKey)
            {
                 changeInteractor(new AIPlayer());
            }
            _board.Update();
            _interactor.Update(_board);
      }
}

```

I find that I have reached a proper separation of concerns in my games when I can take out as many components of the game as possible, and keep the others running independently (e.g. if you take out the interactors completely, the board can still exist, and on the screen you'll see bricks constantly falling in a particular direction; interactors just give hints to the board).

A goal close to that is to also make components interchangeable. This helps with easy prototyping, testing and extensibility (I can easily define multiple types (with different levels of intelligence?) of Tetris AIs and try them out as I wish, by changing between AIs at runtime, for example).
> 4 votes

---
Tags: architecture, mvc
---


title: Algorithm for staying "alive" forever

text:
# Question
Title: Algorithm for staying "alive" forever
I am implementing a game where the player is playing(sliding) the little red rectangle and the purpose is to not hit the black rectangles and to not move out of the inner blue rectangle. The black rectangles are moving in trajectories from left to right(right to left) and from top to bottom(bottom to top). The speed they are moving with is constant e.g. 5 pixels. You can get a better idea in this video.

One of the game modes is the following - 2 paths will be proposed by the game displayed as arrows and one of them may lead to "death", while the other will always be the right one and the user will have to choose one of them until he makes the wrong choice. The movement directions can only be top,bottom,left or right and not diagonal and the speed of the red rectangle is constant e.g. 6 pixels and the black rectangles speed is 5 pixels. I am struggling with the algorithm for the "successful" direction for more than a week and what I have done so far is the following :

* Generate a random float number between 1.0 and 2.0 seconds and then divide the generated number by 0.030 for example to get the number of moves that will be made by the black rectangles and red rectangles.
* Calculate the black rectangles and red rectangle move points that will be made for the following time session by multiplying the number of moves by the speed which is 5px for the black rectangles and 6px for the red rectangle.
* After I know the speed of the black rectangles and the number of moves I can tell their position in any time of the current time session.
* Move the red rectangle to the left until it is being hit and remember that result e.g. 15 moves until hit. Do the same thing for right,up,down direction.
* Sort the direction by the moves that can be made before hit in ascending order.
* Move the red rectangle in the direction in which the most number of moves can be made.
* Do the same thing until the time session ends i.e. the random float number generated in the first step.
This solution works most of the time, but some times it leads to a position where an escape is not possible. The problem is not in the code, but in the algorithm logic. For example look at the following image :

---

As you can see the red rectangle will go to a position where it will be stuck by two of the black rectangles. The best possible solution in this situation would be to move to top 1 time and then to left and after that to top, because the black rectangle in the top left corner is going to top, but I really have no idea how to solve this task. What would be the optimal way to accomplish this task.
Thank you in advance!

# Answer
I would try using a heuristic. From what I can tell there are at most 5 areas to move around in and 4 passages between them. As the bars move around, the 5 areas, we will call them, top, left, center, right, and bottom, are either expanding or contracting. Your heuristic could be based on whether an area is expanding or contracting. Obviously, it would be preferable to move into an area that is currently expanding. Actually, the most optimal area would be behind one that is expanding while the area clockwise to it is contracting. In other words, you will have the most time to maneuver in to and out of an area that is behind a bar that just left the edge and is moving towards the center, while the bar clockwise to it is moving from the center to the edge.

Examining your picture, the optimal place to move to would be behind the left bar. As you move up one, and then to the left, a space will open up behind it. At this time the top bar is moving up and out of the way. This gives you plenty of time to move around.

So your heuristic could work like this: 1)an area is most desirable when the bar for that area is at the edge of the screen. As the bar moves towards the center and back towards the edge, that area becomes less desirable. 2) A passageway is most desirable right after the bar that blocks it starts moving from the center to the edge. It decreases in desirability as it moves to the edge and back towards the center.

You can then move the red block towards the most favorable passage to the most favorable area. The value of your heuristic can be arbitrary. What is important is that it makes sense. You can have it to be a value of 100 when the bar is at the edge. By the time it reaches the center it the value could be 50. And as the bar heads back out to the edge it could drop down to 0. Or perhaps when the bar reaches the center the heuristic is 75, and when the bar get halfway back to the edge it is 50. Then as it gets closer to the edge it starts increasing. This might give you a chance to start moving in the right direction ahead of time.

Just to be clear, what I am calling a passage would be the region just above the left bar, the region to the right of the top bar, the region below the right bar, and the region to the left of the bottom bar.
> 1 votes

---
Tags: algorithm, ios, path-finding
---


title: How to pathfind over an obstacle?

text:
# Question
Title: How to pathfind over an obstacle?
How to represent the following situation best - agent (`@`) needs to get to the goal(`$`). The path is blocked by a moat(`~~~`). A rake (or some other device, like waterwalking boots) is available that will make it possible to cross the obstacle.

```
.....~~~...   . ground
...=.~~~...   = rake
.....~~~.$.   ~ water
.@...~~~...   @ agent
.....~~~...   $ goal

```

How to properly pathfind from `@` to `$` provided there is no immediately available path? Should my path have not only cost but also prerequisites?

**UPD**: The problem is the goal is not accessible and rake is just one of many possible objects on the map. Question then is "how to make the agent understand that it needs the rake?"

# Answer
I'm thinking about a stack of goals, pathfinding will have to be annotated:

* Start with a goal `get $`
* Try find path to `$` \- path exists with waterwalking capability required.
* Push goal `get waterwalking`.
* Goal stack is now `get waterwalking, get $`
* Somehow find that rake gives waterwalking, let's rename it to boat.
* Path to rake. Top goal reached, pop it from stack, goal is `get $`.
* Path to `$` \- now we have capability and can reach goal.
> 6 votes

# Answer
The whole path finding stuff is just a search for shortest path over a graph. to solve your problem the only change you need to apply is to add some extra edges (representing the path boat can take), and do a simple path find algorithm. it doesn't matter whether you use BFS, Dijkstra or A\*, just implement a normal path finding algorithm with some extra edges. for more information about path finding in a graph check wiki page
> 3 votes

# Answer
I'd do this with some kind of behavior tree solution - you path to the goal, and take note of all the obstacles that has been blocking your A\*. If you fail, you check if there are objects that can help overcome those obstacles, in that case, path to that object. Repeat. This means that the agent needs to try to path to the goal and fail before getting the idea of using tools though, which might take time, especially if there's a huge world of tiles that all need to be checked. Might not look too out of place that the agent takes some time to contemplate on how to solve the problem though.

I can imagine a real, hardcore solution however. Add another dimension to you path finding grid. So in the case of a 2D map, you make the pathfinding grid 3D. In this simple example this new dimension would only have a depth of two, but in a real game it would get large quickly.

At z=0 you map the terrain during normal circumstances, meaning that water tiles are considered impassable.

At z=1 you map the terrain as it is while having the rake, meaning that water tiles are considered walkable (but if you have for example wall tiles, those might remain solid).

The path finding is an ordinary A\* in the x and y dimensions, meaning that every grid cell is considered to have access to its neighbors. In the z dimension however, the A\* is NOT allowed to spread.

Except where the rake is. The rake object acts as an opening between z=0 and z=1 in the path finding grid.

This means that the A\* will flood fill outward in z=0, hit the water, and run out of options - then it'll spread to z=1 through the rake tile, and at z=1 (where water is walkable) find its way to the goal. The effect is that the NPC whithout hesitation moves to the rake, and then moves the shortest path to the goal.
> 2 votes

---
Tags: ai, path-finding
---


# Question
Title: libGDX How to make camera follow the player?
I'm having some trouble getting the camera to even work at times. Thankfully, its some-what working now. I'm trying to get the camera to follow the players movement but nothing happens.

(cut out the parts that are useless)

```
public class GameCore extends Game  {
private OrthographicCamera cam;
private Player player;
private ShapeRenderer shape;

@Override
public void create() {
    cam = new OrthographicCamera(1280 ,720);
    cam.translate(Gdx.graphics.getWidth()/2, Gdx.graphics.getWidth()/2, 0);
    cam.update();

    shape = new ShapeRenderer();
    player = new Player();
    player.setPos((int)cam.position.x, (int)cam.position.y);

}

@Override
public void dispose() {

}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    super.render();
    player.render(shape, cam);
    player.update();

}

```

GameCore class (my main one)

```
public class Player {
    public int x,y;
    public int dx, dy;
    public int width, height;
    public double area;
    public int hp;

    public Player(){
        hp = 100;
        width = 1150;
        height = 500;
        area = width*height;
        x = Gdx.graphics.getWidth()/2;
        y = Gdx.graphics.getHeight()/2;
        dx = 5;
        dy = 5;

    }
    public void render(ShapeRenderer shape, OrthographicCamera camera){
        shape.setProjectionMatrix(camera.combined);
        shape.begin(ShapeType.Line);
        shape.circle(x, y, 32);
        shape.end();

    }
    public void update(){
        if(Gdx.input.isKeyPressed(Input.Keys.A)){
            x -= dx;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.D)){
            x += dx;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.S)){
            y -= dy;
    }
        if(Gdx.input.isKeyPressed(Input.Keys.W)){
            y += dy;
    }
}
    public void setPos(int x, int y){
        x = this.x;
        y = this.y;
    }

    public int getX(){
        return x;
    }
    public int getY(){
        return y;
    }
}

```

Player class

Hopefully someone here can also point out if i'm doing something wrong with the camera -\_-. The docs don't really provide much information on how these classes are used. Thank you! :D

# Answer
> 2 votes
This is very simple, actually. You don't need to translate the camera (that is dealing with Matrices, I think?) using the "translate" method. You can simple set the camera's position to your sprite's position (assuming you use the x-y coordinates where (0, 0) is the bottom-left corner. Or extend the "Sprite" class; either way should work).

In your camera object, use the "position" Vector3 (x and y only):

```
cam.position.x = player.getX();
cam.position.y = player.getY();
cam.update();

```

I'll rewrite your code for you:

```
public class GameCore extends Game  {
private OrthographicCamera cam;
private Player player;
private ShapeRenderer shape;

@Override
public void create() {
    cam = new OrthographicCamera(1280 ,720);
    cam.update();

    shape = new ShapeRenderer();
    player = new Player();
    player.setPos((int)cam.position.x, (int)cam.position.y);
}

@Override
public void dispose() {
}

@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 0, 0);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    super.render();

    //Here we set the camera's position to the player's position
    cam.position.x = player.getX();
    cam.position.y = player.getY();
    cam.update();

    //Then we render the player
    player.render(shape, cam);
    player.update();
}

```

Your Player class should stay the same, I think. If all is well, your player should stick in the middle of the screen when it moves, and the camera should move with the player.

---
Tags: java, libgdx
---


# Question
Title: Does libGDX support the Xbox One controller?
I just bought a Xbox one controller and i'd like to test my game with it. I use the `Controllers` extension from libGDX and it works fine, at least with my PS3 controller.

I get some weird results when i'm polling the axis of the controller with libGDX. The values are ok for Y axies but not for X ones. I mean, for X axis, values are really weird, sometimes, when the stick is fully pushed to the left, the value is not even negative, same goes for the right, sometimes value is negative. I don't know why but values seems inconsistent for X axies, Y axies work fine.

Concerning buttons, they are all detected except for the dpad.

I am using the drivers available here. I tested the controller with several games, it works fine so i think it's related to libGDX.

Do you think the Xbox One controller is not supported yet? Can it be a driver issue? Should I use another way to poll controller states? If yes, is there a good and up to date library to do so?

Thanks.

# Answer
There are two types of controller input. There is DirectInput, and there is XInput. PS3 controllers use DirectInput, while XInput is Microsoft's choice (they made it for the xbox, I think). Both of these controllers are supported in LibGDX. However, they are different in how you get data. For example, DirectInput doesn't handle analog trigger buttons, while xInput does.

Xbox One controllers, with the current drivers, just simulate Xbox 360 controllers, and use XInput. You need the correct mapping for it to use it in LibGDX (just like OUYA; except Badlogic supplies the OUYA mappings and not the 360 mappings).

I found this mapping floating around the internet for Xbox 360 controllers:

```
public class Xbox360Pad
{
   /*
    * It seems there are different versions of gamepads with different ID Strings.
    * Therefore its IMO a better bet to check for:
    * if (controller.getName().toLowerCase().contains("xbox") &&
                  controller.getName().contains("360"))
    *
    * Controller (Gamepad for Xbox 360)
      Controller (XBOX 360 For Windows)
      Controller (Xbox 360 Wireless Receiver for Windows)
      Controller (Xbox wireless receiver for windows)
      XBOX 360 For Windows (Controller)
      Xbox 360 Wireless Receiver
      Xbox Receiver for Windows (Wireless Controller)
      Xbox wireless receiver for windows (Controller)
    */
   //public static final String ID = "XBOX 360 For Windows (Controller)";
   public static final int BUTTON_X = 2;
   public static final int BUTTON_Y = 3;
   public static final int BUTTON_A = 0;
   public static final int BUTTON_B = 1;
   public static final int BUTTON_BACK = 6;
   public static final int BUTTON_START = 7;
   public static final PovDirection BUTTON_DPAD_UP = PovDirection.north;
   public static final PovDirection BUTTON_DPAD_DOWN = PovDirection.south;
   public static final PovDirection BUTTON_DPAD_RIGHT = PovDirection.east;
   public static final PovDirection BUTTON_DPAD_LEFT = PovDirection.west;
   public static final int BUTTON_LB = 4;
   public static final int BUTTON_L3 = 8;
   public static final int BUTTON_RB = 5;
   public static final int BUTTON_R3 = 9;
   public static final int AXIS_LEFT_X = 1; //-1 is left | +1 is right
   public static final int AXIS_LEFT_Y = 0; //-1 is up | +1 is down
   public static final int AXIS_LEFT_TRIGGER = 4; //value 0 to 1f
   public static final int AXIS_RIGHT_X = 3; //-1 is left | +1 is right
   public static final int AXIS_RIGHT_Y = 2; //-1 is up | +1 is down
   public static final int AXIS_RIGHT_TRIGGER = 4; //value 0 to -1f
}

```
> 1 votes

---
Tags: libgdx, controllers
---


# Question
Title: Why are my target-following objects rotated the wrong way?
I writing a script that would make my players reach a target destination. It looks like this so far:

```
private void MoveTowardsGoal() {
    if (Vector3.Distance (reachGoalTarget.transform.position, transform.position) > 2.0f) {
        rDirection = (reachGoalTarget.transform.position - transform.position).normalized;
        if (rAcceleration < rMaxSpeed) {
            rAcceleration += 0.5f;
        }
        rVelocity = rDirection * Time.deltaTime * rAcceleration;
        transform.Translate (rVelocity,Space.World);
    }
}

```

It works fine: The objects move towards the destination point. However, I want them to move looking at the target in the forward direction (forward z axis). Currently they move with their x axis facing front.

I tried a simple rotation inside `Start()` like `transform.LookAt(reachGoalTarget.transform)`. With this, they look in the forward direction but then they completely move off their initial positions by rotating themselves to reach the goal.

What am I doing wrong?

# Answer
> 1 votes
The function Start is executed only once, when the script is first activated. It doesn't get called over and over again like Update(), that's why the LookAt doesn't work. Try putting a transform.LookAt inside the MoveTowardsGoal function and check for the objects position, if it reaches its goal revert the rotation back to its original.

---
Tags: unity, rotation, steering-behaviors, bug
---