title: How do 3d engines create frames?

text:
# Question
Title: How do 3d engines create frames?
I wanted to start on a little project of making a simple 3d engine, but I can't seem to find anywhere how 3d engines actually make frames. **(I don't mean the math behind the 3d projection**). Do they use bitmaps and edit the pixels, or do they use the GPU in some way? Also is editing the pixels in a bitmap using CPU or GPU?
**EDIT:**

I only mean after they do the math and find each pixel value for the frame how do they display the frame? Do they change the pixels in a bitmap while rendering a scene, or do they have an array that has all the pixels color values then use the GPU do display the pixels?

# Answer
This isn't too complex. In fact, it behaves a lot like a 2D game does.

When a 3D engine renders a frame, it typically does so in stages. Sort of like photoshop really. And this can happen either on the CPU or the GPU. For most game engines, it's now the GPU that handles this.

So... the engine first creates what is called a "Swap Buffer". It is basically a contiguous block of memory (holds two frames) that our final image will be rendered into. When the frame is finished, the game engine will swap it with the old frame.

When the game renders, it's usually done in multiple passes. These passes will be basically screenshots that the engine will use. So in a way, yes you are creating RGBA pixels, and then you edit them.

Each of these passes will be seperate pieces of the same scene. So... Albedo, lighting, shadows, depth, ect.

The engine will then composite all of these together into the final image.
> 1 votes

# Answer
All the projection and rendering is done on the GPU. When loading a level, the CPU reads meshes and textures from disk and uploads it to video memory of the GPU. In return, it gets integer numbers to later address those resources.

Every frame, the CPU sends commands to the GPU like "use mesh number 4 with texture number 7 and draw it". It also sends some data like the projection matrix and mesh positions. However we don't want to send more than needed every frame since the PCIe connection the the GPU is relatively slow.

When the GPU performs the rendering, the screen image is just treated like a texture of the size of the window internally. In fact, many engines draw to multiple textures in order to create more advanced graphics effects. Then, it is just another command that tells the GPU which image to send to the monitor.

By the way, the engine provides the code for both CPU and GPU (in form of shaders).
> 0 votes

---
Tags: 3d, gpu
---


# Question
Title: How to resize a button without resizing its text
I think it is done with the Anchors of the Rect Transform. I have tried all the possible combinations of the following default anchors:

Unfortunately, when I resize the button in the Scene, the text is always stretched:

# Answer
You're misunderstanding how RectTransform works. The basic Transform properties (position, rotation, scale) affect *all* 2D/GUI children regardless of what settings they have, just like they do with regular GameObjects. **Transform scaling thus completely ignores whatever anchors you have set on the children.**

RectTransform anchors determine *how* the object changes in reaction to the parent being modified, allowing you to fine-tune this relationship. A Middle-Left anchor makes the child ignore changes to the top, bottom, and right sides of its parent, but will move with the left edge as if you had moved the entire parent. The various Stretch anchors allow slaving to two or more sides at once--so a Middle-Stretch anchor would leave the child unaffected by changes to the parent's left and right sides, but stretching along the top and bottom to match its parent.

**So this means you almost never want to fiddle with the parent's scale (except for perhaps animations). Instead only change the parent's Width/Height/Left/Right/Top/Bottom parameters, and the child's anchors will do the rest.**

(Shameless plug: I wrote a script here that helps make RectTransform manipulations easier in code.)
> 2 votes

# Answer
You can try this

```
button.GetComponent<RectTransform>().sizeDelta = new Vector2(newWidth, newHeight);

```

Or just change the `Width`and `Height` of the buttons `RectTransform` component.
> 0 votes

---
Tags: gui, unity
---


# Question
Title: What would a good hacking gameplay look/feel like?
In real life, 'hacking' (that is, using brute-force attacks to guess a password) is not very interactive. In fact, it works pretty much independent of any user from the moment you press Return until it finds the password. Now, I am making a home project game in Unity where you are a computer, and you can interact with everything from cameras to door to explodable gas pipes. Now for difficulty and fun, some things are secured with passwords of varying difficulties. The passwords are chosen for each camera by the basic formula of picking a random integer number between **1** and (**10** to the power of **x**), where **x** is set in the editor under "security level".

Right now, for the purpose of creating other aspects of the game, hacking is simply pressing 'G' while pointing at a camera, letting the computer compare each number from 0 onwards until the guess matches the cameras passcode - then when it does, the camera becomes 'unsecured' and it can be switched to. Obviously, this is uber simplistic and is not the final gameplay. My problem is what *would* the final gameplay look like? I want it to be enjoyable and interactive (i.e. not just the computer randomly guessing upwards) but at the same time not corny and ridiculously unrealistic (i.e. not the absurd things seen in action movies which are nothing like actual hacking). I would prefer it somewhere in between, but I am stumped as to how it would look and feel. Any suggestions are welcome, and if there are any examples from a game that I can use for inspiration, that would be great too, thanks.

## Criteria

* Interactive
* Not super unrealistic or absurd
* Must guess passwords in a way which works with the (\> 1, \< 10**x**) formula

# Answer
I'm not a hacker, so I cannot ensure the following is realistic. However, it seems less absurd that most "hack" things in classic video games and could be enjoyable to play:

## Automatic tests

A classic way to try to crack a password: try every number from 1 to 10x automatically. The player can start a script and try to do other things while the script is running and shall stop when it would find the correct number.

This script would have a duration of 10x * T, where `T` is time between each attempt. This time can be a game-play feature, like depends of resources available by the player, or camera security system, etc.

### Systems update

Player can increase its CPU level in order to be able to make this kind of tests faster.

## Clues

To parry the last technique, many password systems block themselves after a precise attempt number, or ask for a captcha. The last method would be useless to those systems.

So another technique can be to give clues to the player about the password and force him to guess the complete number from them. Those clues can be found from other points than the camera (databases for instance) or can be given when the player enter a bad number.

Those clues can be:

* Above or under a precise number, like the one entered by the player on a failed attempt. `The number is below 1583098`
* How many different digits are there. `There are five different digits`
* How many digits of a kind is there. `There are two times the number 4`
* How many digits are common with another number, like the one entered by the player on a failed attempt. `There are 3 common digits with 78217`
* etc.

If a player deplete every attempts he had, the level can be failed, the camera blocked for the level or just points lost.

### Systems update

An interesting update here can be automatic captcha recognition, that would increase (or just suppress) the attempt limit for a protected system.

There may be several captcha levels or types, each one requiring an appropriate recognition skill to pass through.

## Generate them

A realistic approach could be that passwords are generated everyday from another computer, with an algorithm hashing a character string, maybe the past day password.

In that case, you can find today's password on two ways:

* Hacking the computer that generated it, if it saved a generation historic. (You would get every password generated by it, so don't link every camera with the same or make it well defended if you don't want to make your level too easy)
* Regenerate them like it did this night. For this, you shall need the algorithm and the used character string. Both can be found by different ways, so it can vary upon levels.

### A harder generation

In order to increase difficulty, you can here simply increase the password generation procedure. For instance, what if the password wasn't generated by one computer, but many, with each of them hashing the password on a different way?

*Here are very simple algorithms, but you got the idea.*

In order to regenerate it, you have to know the initial character string and the algorithm lists, as well as the order to use them.

The player can recover algorithms pretty much everywhere in the level, and then have to know in which order to apply them and on which initial number (or character string) to generate the good password. Once again, an attempt limit can avoid him to try every combinations until find the good one (that would be tedious.)

### Systems update

Sometimes, you may not intercept directly the algorithm used by a computer, but only sources/results historic. A big list of initial numbers and what are their respective results through the algorithm.

As in your game, algorithms would surely be a lot more complicated than in my example, it would be impossible to a human player to directly guess it, or even for a simple machine.
So a system idea can be algorithm guess from this kind of list. Your levels would be easier with this improvement, because you can get algorithms directly from old initial numbers and passwords lists, that might be simpler to find than hashing programs.

And once again, this guess skill may have a level, and the higher it is, the less operations samples you need to find the algorithm.

## Cloud

Another idea that have no direct link with passwords but interesting on the system update point is to integrate or simulate computers in your system.

If your player is a super-computer, I suppose it is already a lot of machines clouded together. So an idea can be to start a level with limited resources (mainly CPU power and memory), but once you completely hacked a system, you can integrate it to your cloud, adding its memory and its CPU level to yours.

Memory can be used to store data: algorithms programs, computers historic, game elements like evidences (videos for instance), etc. If you don't have remaining, you cannot store anything more, and it can stuck you in a level, for instance if you don't have enough memory to compare enough algorithm operations in order to guess it.

CPU level can be used for automatic tests (see above), but also for DDOS. DDOS is a simple operation that spam a network system in order to make it crash, or at least, lag.
So you can use it to make a security system nonfunctional as long as the player maintain the DDOS, but it won't have enough CPU level at start to make it on every security system, of course.

## Virtual machine

Instead of integrate a computer to its system, you can have a "virtual machine" system improvement that do the opposite: use a part of your resources to "simulate" another computer.

Let's say for instance that you made a computer crash, but before succeed to gather every data on it. If you have enough resources, you can use a part of your CPU level and memory (as much as it had) to create a virtual copy of it, and use it for instance to pass firewalls that wouldn't allow your player but would allow recognized computers.

## Systems update

On that part, initial resources (CPU level and memory) are key to capacity. So a simple, reliable and realistic improvement would simply be to increase it directly on your computer location, and start the level with an increased level of resources.
> 3 votes

# Answer
As someone who works for a company providing web based services with over a dozen servers, and protecting those servers against hackers, I can say that randomly guessing a password incrementally is a rather poor and inefficient way of going about hacking a system. Most systems log incorrect password attempts, and will lock the specified account or machine after so many incorrect attempts. Sometimes the lock may expire after X minutes, or it may stay locked until a system administrator unlocks it.

Most hacks these days are attempted against machines which are 'unsecured' or have a vulnerability in a piece of software installed - our company sees multiple attempts daily from hacking scripts pinging our servers and asking for common routes, usually trying to find the admin logon panel for common CMS (like Wordpress or Dupral). We run a custom CMS, so the admin logon exists elsewhere, so we throw 404 errors back at the hacking script.

Once a system has been identified, a hacker will then try and gain access through known vulnerabilities, such as targeting a Javascript resource which allows for code injection or a route which is known to be unsecured in unpatched versions. Or maybe sends data to a API on that service which doesn't require authorization and has a buffer overflow exploit which can be used to pass in malicious data to give the hacker system access. Or maybe its an open port that they can connect to (like an unsecured SSH channel)

Our company actually did end up having to re-secure an email server used by our clients that had been hacked (as we are the technology provider/maintainer), and that took several days to fix. Fortunately, there was no major damage apart from several thousand bouncebacks from spam emails clogging it up and blacklistings, but it did give me first hand knowledge of how hackers work, and how they exploit systems.

So Ideally, you'll want your automated hacking tool ingame to do several things.

1. Identify the target.
2. Identify what ports are open by pinging them (22 for SSH, 80 for HTTP, etc).
3. Identify what resources are being run (port 80, so we're looking for webservers, port 22, so we're looking for unsecured ssh ports).
4. Try and exploit known vulnerabilities that exist in common software used by the attack target to get in.
5. Gain access, and then configure the system to do what you want. Email server? Set up a spam bot. Company server? Steal user/company information. Joe Bloggs personal computer? Install rootkit/cryptolocker and then have him pay you to 'restore' his computer. Security system? Take control of cameras and electronic door locks. Also, change passwords/keys or wipe them to prevent people from getting in and stopping you.

As for an example from a game, while not completely realistic but probably is meant to work in a similar fashion to the approach described above by doing #1-4 automatically and then allowing you to do #5, you might want to look at Deus Ex: Human Revolution. Its hacking minigame requires you to use a 'Capture' program, which does what it says - it allows you to capture and gain access to locked personal computers to read emails, security systems to activate/deactivate cameras, security lasers turrets and robots, switch off alarm panels so guards can't use them to sound an alarm, etc.

In order to hack a system, you need to navigate a virtual file system, taking over different nodes and capture all critical nodes. However, each node carries with it a chance of detection, which may alert the security system to your presence, and will attempt to trace and remove you from the system. If caught, you get kicked out and the system goes into lockdown for 30 seconds. If you manage to avoid being caught and manage to secure all critical nodes before being caught, that system belongs to you. Sometimes you can also capture the security node, which counts as capturing all nodes, giving you all the rewards from the different node types.

Nodes include

* Directories (folders/nodes containing no useful information)
* Datastores (containing useful data received as XP usually or financial data received as ingame credits, sometimes one use hacking programs)
* API/Transfer/Spam/Access nodes (which affect other nodes in different ways - API makes all datastores easier to hack, Transfer makes one node easier to hack and another harder, spam nodes slow down the security trace and access nodes make the immediate nodes surrounding it easier to hack)
* Security nodes (which contain the enemy security system will will attempt to trace you and kick you out if it detects you)
* Critical nodes (which ultimately grant you system access).

However, some of the paths between nodes are one way, so there may only be a shortcut back towards from that the security system can use if triggered.

You can upgrade the program if you choose through the course of the game to make your hacks harder to detect (lowers security rating on nodes), allowing you to hack higher security systems, or improve the fortifying system which allows you to fortify individual nodes to slow down the security system if it detects you.

You can implement something similar in you game by requiring your hacking system to have different modules/upgrades/addons that allow it to attempt to hack different computers/software. You have to somehow acquire or improve these modules in order to hack different devices and gain access to them, or allow for easier hacking. You could have a similar web, which allows you to choose the route to take - do you take the longer route with many low ranked nodes and thus more (low) chances of detection, or the shorter route with 2 higher ranked nodes (that will most likely alert the security system on one of them) to the objective? And if the security system detects and starts tracing you, do you continue to try and get that datastore like node down the dead end, or focus on capturing the system to stop the trace and possibly prevent an alarm from sounding?
> 3 votes

---
Tags: unity, game-design, game-mechanics
---


title: View Matrix to Texture Matrix

text:
# Question
Title: View Matrix to Texture Matrix
I'm converting view coordinates to texture coordinates for both my shadow maps and Screen space reflections. I keep seeing this conversion in examples:

```
            var T = new Matrix
            {
                M11 = 0.5f,
                M22 = -0.5f,
                M33 = 1.0f,
                M41 = 0.5f,
                M42 = 0.5f,
                M44 = 1.0f
            };

            Matrix m = view * projection * T;

```

What is T and why does this "work"? I'm saying "work" because I not satisfied with the result but the problem may not lie here.

I would like to use and inverted view and projection and then adjust the coordinates from -1,1 to 0,1. But that doesn't work at all. What have I misunderstood?

# Answer
It's transforming the range from \[-1 : 1\] to \[0 : 1\] and inverting the y/u component for texture coords.

The standard formula is:

u = (x / 2) + 0.5

v = (y / -2) + 0.5.

There's a negative 2 here because tex coords are often vertically inverted. That is, the top left coord is (0,0). See here.

`T = [ 0.5, 0.0, 0.0, 0.0 ]
 [ 0.0, -0.5, 0.0, 0.0 ]
 [ 0.0, 0.0, 1.0, 0.0 ]
 [ 0.5, 0.5, 0.0, 1.0 ]`

M11 and M22 are the scaling for the X and Y coords, and inversion of the Y component. The range changes from \[-1 : 1\] to \[-0.5 : 0.5\] in X and \[-1 : 1\] to \[0.5 : -0.5\] in Y.

M41 and M42 is translation required to go from \[-0.5 : 0.5\] to \[0 : 1\] in X and \[0.5, -0.5\] to \[1 : 0\] in Y.
> 3 votes

---
Tags: opengl, directx, glsl, directx11, hlsl
---


# Question
Title: Using XBox 360 controller in Unity game - game doesn't recognize axis movement
I have a problem with the usage of XBox controller in Unity game. I connected the controller to the PC and it works fine, I also managed to use it in the game itself - I'm using "A" button to fire and Start to start the game and they work properly. However the game doesn't recognize the x-axis movement. I'm not sure if the problem is in the input settings or my code. This is how the Horizontal movement is defined in the game:

This is the code that handles the movement:

```
   float x = Input.GetAxis("Horizontal");
        Vector3 newPosition = new Vector3(transform.position.x + x*playerXMoveSpeed, 0, 0);
        newPosition.y = transform.position.y;
        newPosition.z = 0;

        transform.position = Vector3.Lerp(transform.position, newPosition, playerXMoveSpeed * Time.deltaTime);

        var limit = animator.SpriteRenderer.bounds.extents;
        if (transform.position.x - limit.x < leftBorder)
        {
            var capped = transform.position;
            capped.x = leftBorder + limit.x;
            transform.position = capped;
        }
        else if (transform.position.x + limit.x > rightBorder)
        {
            var capped = transform.position;
            capped.x = rightBorder - limit.x;
            transform.position = capped;
        }

        OnMove(gameObject);

```

All variables are more or less self explanatory, the OnMove is a delegate that just applies the transform to the gameObject in question. The entire code is inside a void method called Move(). That method is called inside an if statement:

```
if ((Input.GetAxis("Horizontal") != 0.0f || Input.GetButtonDown("Horizontal")) && !IsContinueDisplayed)
        {
            FollowTouch();
        }

```

Like I said, the game recognizes the other buttons, but not the x-axis, it doesn't move the character. The Input.GetButtonDown is there just so keyboard input would be supported also (and it works properly). Can you see the problem with this code or settings? Please advise.

# Answer
> 1 votes
I tested this myself and it worked just fine. I would suggest trying the other axis types to make help sure it's not your controller. Try changing the axis to "Y" for vertical, "axis 4" for the right stick horizontal, and "axis 5" for the right stick vertical. I'm assuming you have this in the FixedUpdate or Update events or this would never work.

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


title: WaitForSeconds isn't working

text:
# Question
Title: WaitForSeconds isn't working
I have a class which is changing the player speed. Here is the code:

```
using UnityEngine;
using System.Collections;

public class MultiplySpeed : MonoBehaviour {
    public int multiplier = 2;
    public Controls player;
    bool flag = false;
    void OnTriggerExit(Collider c){
        if(c.tag == "Player"){
            player = c.gameObject.GetComponent<Controls>();
            if(!flag){
                multiplySpeed();
                StartCoroutine(powerUp());
            }
            flag = true;
        }
    }
    public IEnumerator powerUp(){
        yield return new WaitForSeconds(10);
        backToNormal ();
        StopCoroutine(powerUp ());
    }
    public void multiplySpeed(){
        player.speed = player.speed * multiplier;
    }
    public void backToNormal(){
        player.speed = player.speed/ multiplier;
    }
}

```

I have two problems, the first one is that after starting the coroutine and the flag varaible is set to true, the method OnTriggerExit is called once again, and the flag is false and everything is executed again. The second problem is that the method backToNormal seems like it's never executed, it simply multiplies the speed and never take it back to normal.

Any help is appreciated.

# Answer
> 1 votes
To address question 1:

Based on this code, after the initial call to OnTriggerExit it will not begin the coroutine again because your flag is set to false. It would only ever fire again if flag is set back to true or there's another power up object firing a duplicate.

To address question 2:

It appears that it does in fact fire after 10 seconds, but if you aren't certain, I would suggest printing to the console when each method is fired like this:

```
public void multiplySpeed() {
    Debug.Log("multiplySpeed() has been fired.");
    player.speed = player.speed * multiplier;
}
public void backToNormal() {
    Debug.Log("backToNormal() has been fired.");
    player.speed = player.speed / multiplier;
}

```

If it still hasn't fired at this point, then that means the power up object has been deleted or something else stopped the coroutine. I would suggest removing the line:

```
StopCoroutine(powerUp());

```

because it could potentially end another power up objects coroutine early.

# Answer
> 0 votes
So you already have your answer marked, but there's a few things here that are more complicated than they need to be, and may be contributing to the issues as listed. I'd like to throw in a Coroutine pattern that I find myself using quite a bit. You can have the coroutine manage itself; there's little need for OnTriggerExit to worry about whether the coroutine should be activated or not.

```
bool running = false;
public IEnumerator testCoroutine()
{
    if(!running)
    {
        running = true;

        //Do stuff here

        running = false;
    }
}

```

This means that you can trigger the coroutine as many times as you like, and the coroutine itself will enforce only one instance of itself at a time is running (or executing, rather; copies will be spun up, but they will die after a single frame, since they can't get past the flag test).

On top of that, you can pass variables into coroutines; I'm not sure if you're aware of that or not, but it's the primary benefit over using Invoke() and friends.

Here's your code after I've taken a whack at it:

```
public float multiplier = 2.0f;

void OnTriggerExit(Collider c)
{
    if(c.tag == "Player")
        StartCoroutine(powerUp(c.gameObject.GetComponent<Controls>()));
}

private bool powered = false;
IEnumerator powerUp(Controls player)
{
    if(!powered && player != null)
    {
        powered = true;

        player.speed = player.speed * multiplier;
        yield return new WaitForSeconds(10);
        player.speed = player.speed/ multiplier;

        powered = false;
    }
}

```

This should eliminate your first problem (if I'm understanding it correctly) while incorporating the solution to your second. It's also much simpler to follow.

# Answer
> -1 votes
i really don't understand what exactly you need, but i hope this helps you.

```
using UnityEngine;
using System.Collections;

public class MultiplySpeed : MonoBehaviour
{

public int multiplier = 2;
public Controls player;
bool flag = false;

void OnTriggerExit(Collider c)
{
    if(c.tag == "Player")
    {
        player = c.gameObject.GetComponent<Controls>();

        if(!flag)
        {
            StartCoroutine(powerUp());
        }
    }
}
    public IEnumerator powerUp()
    {
       while(true)
        {
            multiplySpeed();
            yield return new WaitForSeconds(10);
            backToNormal ();

            flag = true;
            yield break;
        }
    }

   public void multiplySpeed()
   {
      Debug.Log("multiplySpeed() work!");
      player.speed = player.speed * multiplier;
   }

   public void backToNormal()
   {
      Debug.Log("backToNormal() work!");
      player.speed = player.speed/ multiplier;
   }
}

```

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


# Question
Title: How to send data from Unity to Mailchimp
I have followed the WWWForm script reference to try to connect Unity with Mailchimp. According with the log, the form is sent without errors. Unfortunately Mailchimp did not stored any data.

This is my code:

```
public class EmailSendButton : MonoBehaviour {

    public GameObject emailInputText;
    private WWWForm form;

    /// <summary>
    /// In the Inspector we tell Unity to call this function when the button is clicked.
    /// </summary>
    public void onClick() {
        StartCoroutine(SendToMailChimp());
    }

    // TODO It seems to be working but Mailchimp did not store anything
    private IEnumerator SendToMailChimp() {
        form = new WWWForm();
        string email = emailInputText.GetComponent<UnityEngine.UI.Text>().text;
        form.AddField("mce-EMAIL", email); // I have also tried with: form.AddField("email", email);
        WWW w = new WWW("http://bustogames.us11.list-manage.com/subscribe/post?u=8855252b454d05c2f913c1d2b&id=2ac022b22a", form);
        yield return w;

        if (!string.IsNullOrEmpty(w.error)) { print("Error sending the form: " + w.error); }
        else { print("Form sent without errors"); }
    }
}

```

This is the cut and paste code provided by Mailchimp:

```
<!-- Begin MailChimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
<style type="text/css">
    #mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
    /* Add your own MailChimp form style overrides in your site stylesheet or in this style block.
       We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="//bustogames.us11.list-manage.com/subscribe/post?u=8855252b454d05c2f913c1d2b&id=2ac022b22a" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
    <label for="mce-EMAIL">Subscribe to our mailing list</label>
    <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
    <div style="position: absolute; left: -5000px;"><input type="text" name="b_8855252b454d05c2f913c1d2b_2ac022b22a" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>

<!--End mc_embed_signup-->

```

# Answer
> 1 votes
I believe it is not the input id, but its name that is used as field name when a form is submitted. So I would use:

```
form.AddField("EMAIL", email);

```

Also, there seems to be a hidden input on the form provided by Mailchimp called b\_8855252b454d05c2f913c1d2b\_2ac022b22a, so you should also have the following line in your code:

```
form.AddField("b_8855252b454d05c2f913c1d2b_2ac022b22a", "");

```

And lastly, if the above is not sufficient, the form might require the submit button to be there, so you could also add the following:

```
form.AddField("subscribe", "Subscribe");

```

I hope this helps.

---
Tags: c#, unity, http
---


title: storing game options in java

text:
# Question
Title: storing game options in java
I'm making a game using java. I'm wondering what would be the best way to store games options (like screen height and width, full screen boolean and many other similar options the user can select) at run time?

Currently, I read the options from a text file so everything that comes out of the reader is a string. I would like to add the value of the string to the appropriate variable in as few steps as possible. I would also avoid having to code getters and setters for all variables there is and have a general getter and setter that takes the name of the option as a parameter. ex:

```
    public void set(String name, Object value){
        options[name] = value;
    }

    public Object get(String name){
        return (Object options[name]);
    }

```

I was thinking about a hashmap of variable names and values but the problem is: not all variables are of the same type, I'll have ints and doubles and booleans. so what would be the best way to store all those different variable types and access them with general calls? Should I leave them as Object and cast them as I need to use them? Or do i really have to set them all manually in my code (which would be quite the hassle should i decide to add more options down the line)?

UPDATE: So, here's the code i got so far for serialization but still not working:

Options.java:

```
public class Options implements java.io.Serializable{

//Final variables declaration
static transient final String SAVE_DIR = System.getProperty("user.dir") + "\\res\\saves\\";
static transient final String OPTION_FILE = "options.ser";

//Static variables declaration
public int s_width;
public int s_height;
public float fov;
private static transient Options instance;

private Options()
{
    this.s_width = (this.s_width == 0)? 800 : this.s_width;
    this.s_height = (this.s_height == 0)? 600 : this.s_height;
    this.fov = (this.fov == 0)? 60 : this.fov;
}

public static Options GetInstance()
{
    if(instance ==  null)
        instance = new Options();
    return instance;
}

```

Serializer.java:

```
public class Serializer {
private static Options o = Options.GetInstance();

    public static void loadOptions()
    {
        File dir = new File(Options.SAVE_DIR);
        if(dir.exists())
        {
            File file = new File(dir + "\\" + Options.OPTION_FILE);
            if(!file.exists())
            {
                saveOptions();
            }

            try {
                FileInputStream fileIn = new FileInputStream(file);
                ObjectInputStream in = new ObjectInputStream(fileIn);
                o = (Options) in.readObject();
                in.close();
                fileIn.close();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        else
        {
            dir.mkdir();
            saveOptions();
        }
    }

    public static void saveOptions()
    {
        File dir = new File(Options.SAVE_DIR + "\\" + Options.OPTION_FILE);
        try {
            if(!dir.exists())
            {
                dir.createNewFile();
                o = Options.GetInstance();
                System.out.println("otpion.ser created and initialised succesfully!");
            }
            FileOutputStream f = new FileOutputStream(dir);
            ObjectOutputStream out = new ObjectOutputStream(f);
            out.writeObject(o);
            out.close();
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

```

# Answer
From my experience working on codebases with millions of lines of code, and hundreds of settings encoded like this, I don't think it will be as much of a hassle as you think to have a getter/setter for each option. In fact, if you're using an IDE, it's actually fairly nice to be able to type "Options." and get a list of all the preferences in your app, rather than digging through files trying to remember if you named it "ScreenWidth" or "ViewWidth".

Make sure you're using java.serialization.io - Here's a good tutorial: http://www.tutorialspoint.com/java/java\_serialization.htm

That way the only thing you ever have to add is the getter/setter itself. Saving to disk takes care of itself (assuming you're only ever saving primitive data types).
> 0 votes

---
Tags: java, file
---


# Question
Title: Spline type to achieve a specific result
Is there a type of spline which can produce (approximately) the following result given the specified points indicated. I want to be able to specify how curved the corners are from the "centre points" so that I get "very square" corners to "very round" corners. Sorry about my shakey hand ! Points along a line should produce (roughly) a linear curve.

I found quite a few questions and answers online about this but they all seem to be B-spline related, and don't (I think) quite capture my constraints. If anybody knows what I'm looking for, direction to an online reference/article would be great.

My points always appear on an integer lattice (grid), and are always equally spaced.

I'm looking for something low complexity, but which I can pass a value, say `t` in `[0,1]` and returns the `(x,y)` position of the curve at that time. I realise I could probably build a function like this piece-wise, but wondered if there is a ready made spline solution (piece-wise equation) which could achieve the same result.

Maybe B-splines or NURBS are the answer, but maybe they are heavy on computation too...

---

Given Sirisian's answer below, I suddenly realised how Bezier curves work. Wow they really are a clever idea!

Everything seems centred around a single `t` value, e.g.

```
l1(t) = a+t(b-a)
l2(t) = b+t(c-b))
m(t)  = l1(t)+t(l2(t)-l1(t))

```

We can expand `m` to simplify if necessary.

---

I think B-Splines give a nice result, e.g. see below. It also has the advantage of not being restricted to a uniform grid. Not sure about speed of computation yet though...

# Answer
Seems like a simple quadratic Bézier curve would be sufficient.

https://en.wikipedia.org/wiki/B%C3%A9zier\_curve#Quadratic\_curves

Implementation-wise you'd just draw a line for horizontally or vertically connected nodes and then a curve for the other cases.

An alternative that would be more complex would be use to use an arc like in the SVG spec:

http://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands

There are implementation details in the spec for how it functions.
> 1 votes

---
Tags: splines
---


# Question
Title: How to avoid ghosting when pressing multiple keys?
I am working on a 2d side-scrolling pc game that uses SFML game library. The problem that I am not able to solve is that in many keyboards combination of three or more keys (like w + d + k) is not working. Is there any way to solve this issue?

# Answer
> 37 votes
You can't. At least, not as a game developer.

As a gamer, you can purchase more expensive keyboards with "anti-ghosting" features, but otherwise the limitation is part of the hardware itself, so there's nothing you can do in software to solve it.

Check out this demo page to see how keyboard ghosting works, plus a demo: https://web.archive.org/web/20150429053827/http://www.microsoft.com/appliedsciences/antighostingexplained.mspx

So your best bets are:

* Don't use a control scheme that requires too many simultaneous key presses
* Use game pads if they are available
* Let the player remap the keys so they can find a non-ghosting set of keys for their hardware
* If you must, stick to the left side of the keyboard (around `W``A``S``D`) because keyboards tend to avoid ghosting around here

Historically, many PC games used modifier keys (`Ctrl`, `Alt`, `Shift`) as part of their controls because these keys were wired to handle being pressed together with other keys, to avoid ghosting. This practice sort of fell out of favour during the 90s because the modifier keys were being used more and more by the OS, which would interfere with the game.

Later, certain genres of games had their controls coalesce around key clusters, most notably the FPS genre around `W``A``S``D` \+ mouse, but another example would be Japanese indie games around `Z``X``C` \+ arrows. In a self-fulfilling manner, since most games used these clusters, keyboard manufacturers also made sure that ghosting was minimised around this area, so if you stick to the same controls that other popular games use, you will also avoid ghosting.

Looking at your example, `W` and `D` are fine but `K` is not; are you by any chance using `K` as a directional control? If so, consider using the arrow keys instead.

# Answer
> 3 votes
Buy a better keyboard.

Ghosting is caused by the hardware itself. Even many gaming keyboards will still have this problem; they only invest in fixing the problem for "common" keys like WASD (but not 'K' for instance).

http://www.microsoft.com/appliedsciences/antighostingexplained.mspx

---
Tags: 2d, input, windows, sfml, side-scroller
---


# Question
Title: Unity + Oculus Rift - Setting field of view or rendering part of display
I need to render a small portion of the display to a texture.

I found a script to simulate a scissor rect by modifying the projection matrix - Unity 5 doesn't seem to provide any out-of-the-box scissor functionality. However, modifying the matrix in this way causes my scene to render monoscopic.

Suggestions? There used to be an `OVRCameraController` class that provided a `SetVerticalFOV()` method, but that appears to have been removed from the SDK.

# Answer
So, the best (only) way I've found of doing this is to modify the projection matrix before rendering. Given a scale and a center position,

```
var center = new Vector2(....);
var scale = new Vector2(....);

var zoomPanMatrix = Matrix4x4.Scale(scale);
/// offset view X (screen)
zoomPanMatrix.m03 += (1 - 2 * center.x) * scale.x;
/// offset view Y (screen)
zoomPanMatrix.m13 += (1 - 2 * center.y) * scale.y;

```

This creates a matrix that zooms in (scale) and pans to (center) the area of interest, *in screen space*.

On a side note, this also works if you want to, say, render a part of a larger image for a display wall, super-high res tiled image files, etc.

When rendering (I'm rendering to a texture, so this code is in `OnRenderImage()`)

```
var originalProjectionMatrix = cam.projectionMatrix;

cam.projectionMatrix = zoomPanMatrix * originalProjectionMatrix;

cam.Render();

cam.projectionMatrix = originalProjectionMatrix;

```

If you want to take advantage of this for frustum culling, do the above and clip against the resulting frustum.

There's probably a way to do this with an oblique projection matrix. Good luck with that. I also played with concatenating an offset orthographic matrix - which *should* work - but didn't spend a lot of time on it,

I have to modify `center` based on which eye is rendering to get real stereo, but it works fine.
> 0 votes

---
Tags: unity, graphics-programming, oculus
---


title: Pygame for python 3.5?

text:
# Question
Title: Pygame for python 3.5?
I just got Python 3.5 from this link.

Previously I had Python 3.4 and the Pygame version 1.9.2a0. It worked perfectly. However, my the new Python 3.5 isn't compatible with that version of Pygame that I had gotn for the 3.4. I Found the latest Pygame file from this link.

I downloaded the Pygame file, however, it is a .whl format file. What am I supposed to do?

I have tried looking it up all day yesterday. So far all I've figured out is something about pip and wheel and doing some commands like 'pip install' etc. etc. But I am completely lost. I never knew about pip or any of that before.

I am not even sure if there is a version of Pygame that works with Python 3.5, but I did try to find out by looking it up but I never found such information.

All I want is to get Python 3.5 up and running with Pygame and for it to work just as fine as it used to when I had Python 3.4. If Pygame is yet to be compatible with Python 3.5 that's fine, I'll just reinstall python 3.4 and the according Pygame file for it.

# Answer
> 6 votes
This site showed me how to do it: https://skellykiernan.wordpress.com/2015/01/04/python-pygame-install/

Note that the site uses Python 3.4.2 and pygame version 34cp, but I did it with Python 3.5 and pygame version 35cp and it worked perfectly.

---
Tags: python, pygame
---


# Question
Title: How to PRECISELY measure execution time of a code?
In order to compare algorithms speed, I measure execution time of a code part with a method similar to the one described in this question.

I am not operating on Windows, but on Linux, so I use `gettimeofday` function in order to measure time with microsecond precision.

My test program has a simple architecture:

```
int main()
{
    test_algorithm1(); // Measure execution time of algorithm1 and
    test_algorithm2(); // Measure execution time of algorithm1 and

    return 0;
}

```

My functions `test_algorithm1` and `test_algorithm2` have exactly the same structure:

```
void test_algorithmX()
{
    struct timeval before, after;
    time_t         elapsedUs;
    int            i;

    gettimeofday(&before, nullptr);
    for (i = 0; i < 1000000; i++) // Repeated 1 000 000 times for more precision.
    {
        // Code to measure here
    }
    gettimeofday(&after, nullptr);

    elapsedUs = after.tv_usec - before.tv_usec; // Elapsed microseconds
    elapsedUs += (after.tv_sec - before.tv_sec) * 1000000; // Elapsed seconds
    std::cout << "Elapsed time for algorithm X: " << elapsedUs << std::endl;
}

```

However, I face two problems:

* Measured time seems very random, especially with short algorithms. If I run many times the program, I can obtain results between 25 000 and 35 000 us.
* If I invert algorithms order in the `main` function (running test\_algorithm2 before test\_algorithm1), values change. It appears that the first one to be executed is slower. Values like **50 000/15 000** us may change to **40 000/20 000** if I invert them.

This is very problematic, because I sometimes measure algorithms of very close speed, and I cannot make a conclusion with this random.

Is there a better way to measure execution time? Or did I do something bad, like using the `gettimeofday` function?

# Answer
> 6 votes
For the kind of micro-optimisation that you are trying to do, **nothing will beat real-life usage patterns, with your algorithm embedded in a real program, consuming and producing real data**. There are tricks that you can use to get synthetic benchmarks that produce results that somewhat resemble reality, but for the most part they're a waste of time. Profile your program with the algorithm under real conditions, and measure how much time your program spends in the algorithm.

Books and careers have been made on this subject, so I'll only mention the two most egregious errors in your methodology:

**Compiler**

First, a simple error. For benchmarks, you always want to turn all compiler optimisations on, otherwise you're testing something different from the real thing. However, the problem is when you isolate an algorithm in a simple looping test like this one. If your algorithm does something really simple and with few side effects, the compiler could simplify parts of your algorithm away!

There are tricks you can use to prevent the compiler from making your benchmark artificially fast, but rather than fight the compiler, it's best if you **measure a real program and not a synthetic benchmark**.

**Cache**

How fast an algorithm runs on "modern" CPUs very much depends on the state of the cache. The CPU has a hierarchy of memory caches, each faster than the next but with smaller capacity. If it has to perform many different operations on different data sets, it has to constantly load and unload data to and from those caches. On the other hand, if it's running a single algorithm on a small dataset, chances are most of the time it doesn't have to do any loads/stores beyond the initial one. So when you run an algorithm one million times in a loop, you'll get performance that's much faster than if you run the algorithm once, and multiply the result by one million.

Furthermore, performance is sensitive to the size of the dataset - if it entirely fits into L1 cache, it'll be super fast; if it fits into L2 it'll be slower, L3 then a bit slower still, and so on. Take a sorting algorithm for example; if 100 elements fit in L1 but 200 can only fit in L2, then in the first case the CPU only ever needs to use L1, whereas in the second case it'll be also using L2 occasionally. So sorting two 100-element collections will be faster than sorting a single 200-element list. If you plot it out you'll get a step-like function:

Some more relevant information: https://stackoverflow.com/q/8547778/2038264

If you don't control the size of your dataset, and it happens to be near one of those step boundaries, you can get wildly fluctuating results. If your test dataset does not match real life scenarios, then you'll get performance that's wildly out of whack with reality. How your algorithm uses data also matters a heck of a lot: CPUs guess what data they need to load next, and are very good at it if the pattern is predictable - for example, if it reads data sequentially. In this case the CPU can just look ahead and prefetch the data. This is also the reason why for most use cases, `vector` vastly outperforms `list`:

https://softwareengineering.stackexchange.com/q/186966/81527

So if you want to use a synthetic benchmark, you need to understand how your algorithm uses data and mimick it. For example, when working on an algorithmic trading software, the typical use pattern was to be idle 99% of the time, and run once off a signal, so I constructed a benchmark that explicitly cleared the CPU caches before every run. Failing to do so would produce a result that was too fast by a factor of 3. For more complex algorithms, those conditions can be much harder to set up, which is why if you can, **always test with real data in real scenarios**.

# Answer
> 0 votes
Unfortunately there will always be some degree of randomness. But It's probably not in your best interest to use the gettimeofday function in Linux, as that can add in some overtime.

If the speeds keep jumping around each other, try taking a look at the algorithms Big-Oh and predict the worse case scenario. Then emulate it.

If you can support C++11, then include the chrono header. The Chrono header has a high res timer somewhere in the namespace.

std::chrono::high\_resolution\_clock

Be sure to check the documentation.

---
Tags: c++, optimization, timer
---


# Question
Title: Playing a sprite sheet animation in Cocos2D-x
I'm trying to create an animation using a sprite sheet in Cocos2D-x. I'm doing the following. The game doesn't crash but the screen is still blank.

```
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    auto cacher = SpriteFrameCache::getInstance();
    cacher->addSpriteFramesWithFile("BatmanRun-hd.plist");

    Sprite* someSprite = Sprite::create();

    // load all the animation frames into an array
    Vector<SpriteFrame*> frames;
    for (int i = 2; i <= 10; i++)
    {
        stringstream ss;
        ss << "run_" << i << ".png";
        frames.pushBack(cacher->getSpriteFrameByName(ss.str()));
    }

    // play the animation
    Animation* anim = Animation::createWithSpriteFrames(frames, 0.05f);
    someSprite->runAction(Animate::create(anim));
    someSprite->setPosition(100, 100);

    this->addChild(someSprite);

    return true;
}

```

Is there something I'm missing? Thanks.

# Answer
> 1 votes
Start the sprite with the first frame:

```
auto someSprite = Sprite::createWithSpriteFrameName("run_1.png");

```

Pay attention to the code you use for creating the animation: You are adding frames 2-10. That's ok if it's a single shot animation.

I assume that you want to repeat the animation - just from the name "run". You'll have to add frames 1-10 in the for loop.

```
someSprite->runAction(RepeatForever::create(Animate::create(anim)));

```

# Answer
> 0 votes
don't create a empty sprite node. when you do Sprite::create(), load the first frame as the parameter. That is used to init contentSize and bounding-box variable of the sprite. So, that might help.

---
Tags: c++, animation, cocos2d-x, spritesheet
---


title: Selecting Objects to Prefab Unity

text:
# Question
Title: Selecting Objects to Prefab Unity
So... I have a tree object and I have duplicated it to have many trees in the scene. So, I have about 200 trees in the scene. Before duplicating I forgot to add a tree as a prefab. Now, is there anyway to add a tree as prefab and make the other trees behave similarly.

Any Help would be appreciated. Thanks in Advance!!

# Answer
> 0 votes
Someone created a script for that: you can found it here on GitHub.

I report it here for completeness:

```
 @MenuItem ("Tools/Revert to Prefab %r")
 static function Revert() {
     var selection = Selection.gameObjects;

     if (selection.length > 0) {
         for (var i : int = 0; i < selection.length; i++) {
             EditorUtility.ResetGameObjectToPrefabState(selection[i]);
         }
     } else {
         Debug.Log("Cannot revert to prefab - nothing selected");
     }
 }

```

I have never used that, but I hope that you can find it useful.

---
Tags: unity, meshcollider
---


# Question
Title: Drawing order of 2D tiles with 3D bounding volume
I'm wondering which algorithm was used to draw the sprites of the video game Commandos in the correct order. Each sprite has a 3D bounding volume (either a polygon or a cylinder), this is how the developers stored the information:

```
POLY "NONAME",73,987,0,54,7,1   ;Name,CenterX,CenterY,CenterZ,Height,#Vertices,#Tiles
POINT        0,-37              ;Coord. X, Coord. Y
POINT        36,-18
POINT        36,-1
POINT        28,28
POINT        -21,37
POINT        -36,1
POINT        -36,-9
TILE          37, 581,  74,  83,   0,   0, 0,"ROC10010.RLE","   "   ;PosX,PosY,Width,Height

POLY "NONAME",70,816,0,120,4,1
POINT        0,-8
POINT        8,6
POINT        0,10
POINT        -8,-3
TILE          48, 434,  50,  98,   0,  41, 0,"POST0001.RLE","   "

POLY "NONAME",1557,4094,0,44,0,1
RADIO       17
TILE        1539,2588,  37,  55,   7,   0, 0,"DEPT0000.RLE","   "

POLYRAMPA "NONAME",626,952,0,48,40,4,1  ;Name,CenterX,CenterY,CenterZ,Height,HeightOff,#Vertices,#Tiles
POINT       43,-8
POINT       2,29
POINT        -36,-7
POINT       1,-45
TILE         590, 515,  85, 111,   0,   0, 0,"CASA0003.RLE","   "

```

The last object named 'POLYRAMPA' is used for stairs and ramps.
**Edit:** All bounding volumes are convex and don't overlap each other.

And here are some in-game screenshots:  The first three screenshots show the same map. Of course it's possible to fake the drawing order of this 'flat' map by sorting the sprites by their y-value.

But this approach won't work if the map is more complex, like the one at the bottom right.

**So my question is:** Which algorithm did the developers use?
**Bonus question:** Is there some source code available? (pseudocode or any object-oriented programming language would be great)

**Edit:** Sorting by the XYZ-coordinates of the bounding boxes center point doesn't work.
For example:
The objects on the left side have the same center points as the objects on the right. The cylinder on the left should be in the background but the one on the right in the foreground.

# Answer
> 1 votes
You will have to sort the sprites based on their bounding box and start drawing things from back to front. In order to be successful with this you'll have to apply a mapping from the 3D coordinates (which seem dimetric to me) to the screen coordinates. Height differences translate directly into an offset in the y-coordinate while movement along the oblique(?) axes on the ground scales with something like sqrt(2)/2.

You find a sample implementation of such sprite sorter in OpenTTD's code (mind, it's GPL, so consider that before looking at it; you don't want to commit a copyright violation by relicensing it): https://docs.openttd.org/viewport\__sprite\__sorter\_8h.html might be a starting point exploring the code.

---
Tags: 3d, sprites, bounding-boxes, draw-order, sorting
---


# Question
Title: How can I calculate when a spesific amount of time has passed
I am trying to get something to happen, when a spesific amount of time has passed(in my case it is in secounds). I have tried using this method:

```
   long elapsed = (System.nanoTime()-startTime)/1000000;
   if(elapsed > 1000)
   {
       score++;
       startTime = System.nanoTime();
   }

```

with the starttime beiing initiated in the constructor. But when I attack(part of the game) the app either:
chrashes
the things the game renders dissapears, and everything turns black.
I have tried asking google, but it in general gave me the save way. Any new improved ideas?

# Answer
> 0 votes
what kind of crash does it give you? have you tried to see if the

```
    (System.nanoTime() - startTime)

```

could be responsible?

try outputing it to the console with a

```
    System.out.printLn(System.nanoTime() - startTime);

```

also try outputing your elapsed variables and make sure it's not Null.

having a peak at the part of the code that causes the crash (you talked about attacking) might help. right now your code seems quite fine to me so taking it out of context is hard to debug.

---
Tags: java, android, timer
---


# Question
Title: Create entity from template in component-based engine
For my project I would like to use a component-based entities in C++. My current implementation is split to these parts:

* **Systems** \- Contain a map of components of certain class and operate on these. For example PhysicsSystem has a vector of PhysicsComponents.
* **Components** \- A component contains some public variables and a maybe a constructor to initialize them.
* **Entities** \- An entity for me is just an Id. It is however not stored anywhere, instead only its components are stored in systems in map (where key is entityId and value is pointer to the component).

My problem is creating instances of different objects in my game. I would like to define objects in XML (could be any text file format). For performance reasons this file should be parsed only once when the program is run.

That means I should create some template from it in my ObjectFactory and associate it with a name. Then I would simply call `factory.CreateObject("Player")` to add new entity to the game.

I am not really sure how to implement this without too much overhead code. Another concern is, that the I don't want my factory to know about the systems themselves. But because my components are stored in the systems and not an Entity object, I will need to use some messaging system to pass new components to their appropriate system.

**My question is**, how would I implement the object spawning with template for each object type? And how do some engines describe their objects with configuration files?

# Answer
Give your `ObjectFactory` class a `make_copy` function, that takes in an entity and can create a complete separate clone of that given entity, creating new components which are identical to the original entity's components and add these new component to the new entity. You can load this "origional" entity from file once and store it in some map or something with a name as key ( like "Player" ). This entity will now act as a template.

Later when you want to make an instant of that template, you can call `factory.CreateObject("Player");`, which would look up the map with `"Player"` and then make a copy of the template entity and return it to you and tada!

EDIT:

To solve your "Passing the component to systems" problem, Have a base `System` class which will have a pure virtual `AddComponent` function which would accept a pointer to component. Make all your Systems derive from this `System` base class. Then let the `ObjectFactory` store a list of pointers to these Systems and whenever it creates a new Component, it passes it to the respective system.
> 1 votes

# Answer
How do you currently communicate between systems? If you have some kind of messaging or event manager, you could have a `create_entity` message that gets send to all systems along with the parsed XML tree. Systems looks for tags describing their components and create them if found.

You could also share the component arrays between systems. For example you can create a `ComponentCollections` class and pass a reference to the constructors of your systems. It can be related and doesn't need to know about your component types. This way, a system can create complete entities. You may want one dedicated system to load and create entities though so that the other systems depend on as few components as possible.

This is also useful if the `RenderSystem` wants to access the world position of objects that is updated by the `PhysicsSystem`.

By the way, if you want cache-locality, the components must be stored consecutively in memory i.e. in an array or vector rather than a map. You can however have a map from entity id to vector index for random access.
> 1 votes

---
Tags: c++, entity-system, component-based, data-driven
---


# Question
Title: No output to screen using Multiple Render Targets and multisampling
I'm having a little trouble with XNA, but I doubt it's specific to the framework.

I draw a few 3d models to 1 rendertarget with multisampling turned on, and it works fine. If I draw the same scene to 2 rendertargets (of course the second one gets a different output (configured this in HLSL shaders)) with multisampling turned on, I get absolutely no output. Nothing. Blank. Also, when I render to both outputs but turn off multisampling, it works perfectly (but looks hideous due to a lack of antialiasing).

The strange thing is: This happens on my desktop (Nvidia GTX 560 Ti), but not on my laptop (Intel HD Graphics 4000, which sits on the CPU). On my laptop, it outputs just fine to both rendertargets and multisampling turned on.

Can anybody explain what could be wrong? I won't copy all my code here but just to clarify:

```
graphics.PreferMultiSampling = True
RT_Light = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents)
RT_Scene = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 0, RenderTargetUsage.PreserveContents)
device.SetRenderTargets(RT_Scene,RT_Light)
'Draw

```

Works but looks hideous

```
graphics.PreferMultiSampling = True
RT_Light = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents)
RT_Scene = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents)
device.SetRenderTarget(RT_Scene)
'Draw

```

Works but obviously only draws to one rendertarget

```
graphics.PreferMultiSampling = True
RT_Light = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents)
RT_Scene = New RenderTarget2D(device, ClientWidth, ClientHeight, False, SurfaceFormat.Color, DepthFormat.Depth24, 4, RenderTargetUsage.PreserveContents)
device.SetRenderTargets(RT_Scene,RT_Light)
'Draw

```

Works on my laptop, but not on my desktop.

Again, to clarify: The top picture is what my laptop shows (with multisampling and multiple render targets), and the bottom picture is what my desktop shows with the same settings:

# Answer
> 0 votes
Alright, I found out what the actual problem was. Let's ignore my laptop for a moment, I'll get back to it at the end of this answer. XNA uses DirectX 9. DirectX 9 does NOT support MSAA (Multisampling antialiasing) on MRT (Multiple render targets). Strangely though, instead of throwing an exception or showing a warning, I just don't get any output.

Fair enough, but why does it work on my laptop then? I'm assuming that my laptop's gpu is such a piece of crap that it doesn't support MSAA anyway, and my cpu does it instead. This is only an assumption (and we know a bit about assumption's family tree), so I'm open for suggestions. Anyway, for future reference, I hope this helps someone.

OH yeah, Solution: Switch to monogame. Monogame uses DirectX 11, which does support MSAA on MRT. Or of course only draw to a single render target, and then draw the same stuff to a different rendertarget all over again.

# Answer
> 0 votes
Depending on the age of your laptop, it is very possible that the onboard graphics inside your laptop do not support multisampling, while the graphics card in your desktop does.

According to the MSDN article on `PreferMultiSampling`:

> **PreferMultiSampling** is ignored if no hardware is available that supports multisampling.

Thus your game will not throw an error and will simply look crappy if the hardware can't mutlisample on the backbuffer.

So from here you have two options: let your users know that your game will only work on modern graphics cards or not use multisampling at all.

---
Tags: xna, shaders, multiple-render-targets
---


# Question
Title: Fixing enemy behavior state machine in Unity
I'm working on a state machine for my game's NPC.

The only thing I can't to get work properly is the hit sequence. The hits register. What I would like to happen is for the attack sequence (animation) to stop, play the hit animation sequence, & then go back to the chase/attack state using a coroutine.

Currently, the attack sequence seems to just loop through, ignoring the coroutine.

This script is attached to the NPC:

```
using UnityEngine;
using System.Collections;
/// <summary>
/// State pattern enemy.
/// Handles animation sequences & states
/// </summary>
[RequireComponent(typeof(AudioSource))]
public class StatePatternEnemy : MonoBehaviour
{
    public Transform[]             wayPoints;
    public float searchTurnSpeed   = 120f;
    public float searchDuration    = 5f;
    public float sightRange        = 15f;
    public float alertZone         = 20f;
    public float stopAtDistance    = 0f;      //used to stop chase
    public float hitSequenceTimer  = 1.25f;   //use to return to attackState
    public float animWalkSpeed     = 1f;
    public float animRunSpeed      = 1.75f;
    public float animPunchSpeed    = 1f;
    public float animGotHitSpeed   = 1f;

    public GameObject nmeFistL;
    public GameObject nmeFistR;

    public Vector3 offset = new Vector3(0,0.5f,0);//offsets raycast so it won't aim for foot

    public Transform eyes;
    public bool onAlert = false;
    public Transform chaseTarget;

    [HideInInspector]public float         playerDistance;  //player's transform info
    [HideInInspector]public float         alertSearchTimer;//increment timer search value
    [HideInInspector]public Vector3       enemyToTarget;   //player's Vector info
    [HideInInspector]public IEnemyState   currentState;
    [HideInInspector]public AlertState   _alertState;
    [HideInInspector]public AttackState  _attackState;
    [HideInInspector]public ChaseState   _chaseState;
    [HideInInspector]public HitState     _hitState;
    [HideInInspector]public PatrolState  _patrolState;
    [HideInInspector]public NavMeshAgent _navMeshAgent;

    public AudioClip sfxGrunterThreat;
    public float     sfxVolume = 0.125f;

    public AnimationClip nmeGotHit;
    public AnimationClip nmeIdle;
    public AnimationClip nmeJump;
    public AnimationClip nmePunch;
    public AnimationClip nmeRoar;
    public AnimationClip nmeRun;
    public AnimationClip nmeTaunt;
    public AnimationClip nmeWalk;

    AudioSource _sfx;
    RaycastHit  _hit;

    private void Awake()
    {
        _alertState  = new AlertState(this);
        _attackState = new AttackState(this);
        _chaseState  = new ChaseState(this);
        _hitState    = new HitState(this);
        _patrolState = new PatrolState(this);

        _navMeshAgent = GetComponent<NavMeshAgent>();
        _sfx          = GetComponent<AudioSource>();
    }

    // Use this for initialization
    void Start ()
    {
        currentState = _patrolState;
    }

    // Update is called once per frame
    void Update ()
    {
        currentState.UpdateState();
        Rayline();//remove later
        BeAlert();
        print(currentState);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag ("fireBall"))
        {
            ///create a hit state to move player
            ///back & play the hit animation after coroutine
            currentState = _hitState;
            StopAnim();
            Debug.Log("fire");
            StartCoroutine(EnemyHitSequence());
        }
    }
    public void BeAlert()
    {
        ///ensure the player is within alert zone
        float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
        if(playerDistance > alertZone)
        {
            nmeFistL.SetActive(false);
            nmeFistR.SetActive(false);
            currentState = _patrolState;
            //print("Outside alertzone: " + playerDistance);
        }
        else
        {
            //print("Alertzone: " + playerDistance);
            //print("AlertZone Timer" + alertZoneTimer);
            onAlert = true;
            enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);

            //check to see if player is in visual range & is hit with the rayCast
            if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player") && (playerDistance <= sightRange))
            {
                currentState = _chaseState;  //player is found & being chased
                StopChase();                 //player is being attacked
                // _attackState setUp is in stopChase method
            }
            else// <---player not found but is close, be on alert!
            {
                //currentState = _patrolState;
                if(onAlert == true)
                {
                    currentState = _alertState;            //look around for a bit
                    alertSearchTimer += Time.deltaTime;
                    ///if player isn't found, go patrol
                    if(alertSearchTimer >= searchDuration)
                    {
                        onAlert = false;
                        currentState = _patrolState;//nothing is found go back & patrol
                    }
                }
            }
        }
    }

    public void StopChase()
    {
        _navMeshAgent.speed = 3.5f;//slow down the navAgent

        float playerDistance = Vector3.Distance(chaseTarget.position, transform.position);
        //stop navMeshAgent to begin attack sequence
        if (playerDistance <= stopAtDistance)
        {
            ///set this up to go on attack
            /// ensure enemy is looking at player
            enemyToTarget = ((chaseTarget.position + offset) - eyes.transform.position);
            if(Physics.Raycast(eyes.position, enemyToTarget, out _hit, sightRange) && _hit.collider.CompareTag("Player"))
            {
                nmeFistL.SetActive(true);
                _navMeshAgent.Stop();
                currentState = _attackState;
            }
            ///ensure the enemy isn't hitting air
            /// & will always look for the player
            else
            {
                transform.Rotate(chaseTarget.position, searchTurnSpeed * Time.deltaTime, 0);
            }
        }
        print("in stop chase");
    }

    public void EnemyGotHit()
    {
        //print("CurrentState in enemyGotHit: " + currentState);
        //transform.Translate(0f,0.25f,-0.125f);
        AnimGotHit();
        //_navMeshAgent.Stop();
        //StartCoroutine(EnemyHitSequence());
    }

    IEnumerator EnemyHitSequence()
    {
        EnemyGotHit();
        print("CurrentState in hit sqnz: " + currentState);
        yield return new WaitForSeconds(hitSequenceTimer);
        //_navMeshAgent.Resume();
        currentState = _attackState;
        StopChase();
        print("CurrentState after switch in coroutine: " + currentState);
    }

    public void Rayline()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
        Debug.DrawRay(eyes.transform.position, forward, Color.green);
    }

    public void StopAnim()
    {
        GetComponent<Animation>().Stop("nmeWalk");
        GetComponent<Animation>().Stop("nmePunch");
    }

    public void AnimWalk()
    {
        GetComponent<Animation>().Play("nmeWalk", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        GetComponent<Animation>()["nmeWalk"].speed = animWalkSpeed;
    }
    public void AnimRun()
    {
        GetComponent<Animation>().Play("nmeRun", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        GetComponent<Animation>()["nmeWalk"].speed = animRunSpeed;
    }
    public void AnimPunch()
    {
        GetComponent<Animation>().Play("nmePunch", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        GetComponent<Animation>()["nmePunch"].speed = animPunchSpeed;
    }
    public void AnimRoar()
    {
        GetComponent<Animation>().Play("nmeRoar", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        //GetComponent<Animation>()["nmeRoar"].speed = animRunSpeed;
    }
    public void AnimTaunt()
    {
        GetComponent<Animation>().Play("nmeTaunt", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        GetComponent<Animation>()["nmeTaunt"].speed = animRunSpeed;
    }
    public void AnimGotHit()
    {
        GetComponent<Animation>().Play("nmeGotHit", PlayMode.StopAll);
        GetComponent<Animation>().wrapMode = WrapMode.Once;
        GetComponent<Animation>()["nmeGotHit"].speed = animGotHitSpeed;
    }

    public void SfxNmeThreat()
    {
        _sfx.PlayOneShot(sfxGrunterThreat, sfxVolume);
    }

}

```

Attack script:

```
using UnityEngine;
using System.Collections;
/// <summary>
/// Attack state stays within attack.
/// Exiting out of attack sequence is handled within
/// StatePatternEnemy
/// </summary>
public class AttackState : IEnemyState
{
    private float searchTimer;
    private readonly StatePatternEnemy enemy;

    public AttackState (StatePatternEnemy _statePatternEnemy)
    {
        enemy = _statePatternEnemy;
    }

    public void UpdateState()
    {
        Look();
        AttackSequence();
    }

    public void OnTriggerEnter(Collider other)
    {

    }

    public void ToPatrolState()
    {
        enemy.currentState = enemy._attackState;
        searchTimer = 0f;
    }

    public void ToAlertState()
    {
        enemy.currentState = enemy._alertState;
        searchTimer = 0f;
    }

    public void ToChaseState()
    {
        enemy.currentState = enemy._attackState;
        searchTimer = 0f;
    }

    public void ToAttackState()
    {
        /// create a mono behavior for attack & other animation sequences
        /// check for distance
        /// if player is in range
        /// attack
        /// else
        /// ToChaseState();
        Debug.Log("Attacking");
    }
    public void ToHitState()
    {
        enemy.currentState = enemy._hitState;
        searchTimer = 0;
    }
    private void Look()
    {
        RaycastHit hit;
        Vector3 enemyToTarget = ((enemy.chaseTarget.position + enemy.offset) - enemy.eyes.transform.position);
        if(Physics.Raycast(enemy.eyes.position, enemyToTarget, out hit, enemy.sightRange) && hit.collider.CompareTag("Player"))
        {
            //Debug.Log("player found in: " + enemy.currentState);
            enemy.chaseTarget = hit.transform;
        }
        else//if player is hidden then
        {
            //Debug.Log("player not found in: " + enemy.currentState);
            ToAlertState();
        }
    }
    private void AttackSequence()
    {
        //RaycastHit hit;
        //Vector3 enemyToTarget = ((enemy.chaseTarget.position + enemy.offset) - enemy.eyes.transform.position);
        //if(Physics.Raycast(enemy.eyes.position, enemyToTarget, out hit, enemy.sightRange) && hit.collider.CompareTag("Player"))
        //{
        //  Debug.Log("start attack");
        //}
        //face the player
        //enemy.transform.Rotate(enemy.chaseTarget.position,enemy.searchTurnSpeed * Time.deltaTime, 0);//original code
        enemy._navMeshAgent.transform.LookAt(enemy.chaseTarget.position);
        enemy.AnimPunch();
    }
}

```

Hit script:

```
using UnityEngine;
using System.Collections;
/// <summary>
/// Attack state stays within attack.
/// Exiting out of attack sequence is handled within
/// StatePatternEnemy
/// </summary>
public class HitState : IEnemyState
{
    private float searchTimer;
    private readonly StatePatternEnemy enemy;

    public HitState (StatePatternEnemy _statePatternEnemy)
    {
        enemy = _statePatternEnemy;
    }

    public void UpdateState()
    {
        Look();
        EnemyIsHit();
    }

    public void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.CompareTag ("fireBall"))
        {
            Debug.Log("!");
            enemy.currentState = enemy._hitState;

        }
    }

    public void ToPatrolState()
    {
        enemy.currentState = enemy._patrolState;
        searchTimer = 0f;
    }

    public void ToAlertState()
    {
        enemy.currentState = enemy._alertState;
        searchTimer = 0f;
    }

    public void ToChaseState()
    {
        enemy.currentState = enemy._chaseState;
        searchTimer = 0f;
    }

    public void ToAttackState()
    {
        enemy.currentState = enemy._attackState;
        searchTimer = 0f;
    }
    public void ToHitState()
    {

    }
    private void Look()
    {
        RaycastHit hit;
        Vector3 enemyToTarget = ((enemy.chaseTarget.position + enemy.offset) - enemy.eyes.transform.position);
        if(Physics.Raycast(enemy.eyes.position, enemyToTarget, out hit, enemy.sightRange) && hit.collider.CompareTag("Player"))
        {
            enemy.chaseTarget = hit.transform;
        }
        else//if player is hidden then
        {
            ToAlertState();
        }
    }
    private void EnemyIsHit()
    {
        //Debug.Log("HitState.cs");
        //Debug.Log("EnemyIsHit() state: " + enemy.currentState);
        //enemy.currentState = enemy._attackState;
        //Debug.Log("EnemyIsHit() After state switch: " + enemy.currentState);
        enemy._navMeshAgent.transform.LookAt(enemy.chaseTarget.position);
        enemy.StopChase(); // calling StopChase method goes back to attackState
    }
}

```

I could really use some help figuring this out.... Thank you

# Answer
> 0 votes
Added a boolean check to switch to the hit state & back:

```
private void AttackSequence()
{
    ///if the enemy got hit play the hit sequence otherwise keep attacking
    if(enemy.gotHit)
    {
        enemy.currentState = enemy._hitState;
        searchTimer = 0f;
    }
    else
    {
        enemy._navMeshAgent.transform.LookAt(enemy.chaseTarget.position);//always look at player
        enemy.AnimPunch();
    }
}

```

# Answer
> 0 votes
It seems to keep looping thru because it is heading back to Look then it finds you again and then goes right into the first attack over and over.

so in the chase state at the top of private void Look() add something like

```
float distance = Vector3.Distance(enemy.transform.position, enemy.chaseTarget.transform.position);
    if (distance < 5f)
        return;

```

you may also have to put that in the attack state also or setup the state update checks differently so you don't have to clog up the rest of the state scripts.

---
Tags: unity, c#, ai, state, npc
---


# Question
Title: OpenGL 3.3 tilemap rendering techniques?
I'm trying to draw regular 2D tiles to the screen from a single texture but there are a few ways to accomplish this and I don't feel like I know enough about rendering to assess the trade-offs properly.

First of all, I have *potentially* a lot of tiles to render. Each tile is 8-32px (depending on zoom factor) and on a Full HD monitor that's over half a million tiles (and over a million triangles) per layer, and I have two layers. While I'm not going to go out of my way to support massive screens that are zoomed all the way out, I do want a solid reliable experience for players with screens up to 2048x2048px at any zoom, which ends up being about a quarter of a million triangles (before non-tile sprites, effects, and HUD elements are added on top).

I've been getting a lot of conflicting advice on what is good and what is bad to do with regard to tilemapping... What's been the nicest method so far to work with is instancing 6 points, two triangles in a square configuration, and giving each instance a position and texture position. But now I'm told instancing with less than 100 vertices creates a lot of overhead... Using a geometry shader to produce vertices is also crazy expensive and impracticable for hundreds of thousands of triangles, apparently. Sometimes I'm told triangle strips are the say to go, but you have to add in messy degenerate triangles when you have tilemap gaps. Other times triangles are said to be better.

Do all roads lead back to a static baked in array of all corners of each tile for efficiency?

Also, when you move left, right, up, down... you need to add in more tiles to the side... but how? Is there a way to do this that isn't messy and complicated?

# Answer
> 3 votes
How about clustering them into "super tiles"? You could draw a group of tiles into a "super tile" that's, for example, 512x512px. You'd just fill each super tile once when it first comes on-screen, and then all you have to do is draw the super tiles to the screen.

To keep performance super smooth, you could prepare regular tile (not super tile) meshes for each super tile that's *not quite on screen*, and then draw them to a render target when needed. You could prepare those regular tile meshes over several frames to reduce the chance of "hiccups" in performance when you draw to a new super tile.

These regular tile meshes could be done any of the ways you mentioned -- instancing, geometry shader, or a static mesh. I'd recommend the latter since instancing and geometry shaders aren't really helping you any in this kind of situation, but they're also not really hurting in this kind of situation, either, since the overall performance is not really dependant on occasionally preparing a new super tile.

A variant on this "super tile" technique is to render individual regular tiles into their respective super tile only as needed -- so if only the edge of a super tile is on-screen, only those regular tiles on that edge will have been drawn into the super tile's texture. In this situation, since you're drawing relatively few new tiles at a time, the technique you use for rendering the regular tiles would be near-inconsequential, so this would especially be worth exploring if you *do* experience hiccups when creating new super tiles as per my first suggestion. The complication here is that you need to keep track of which regular tiles have already been drawn to their super tile, so you don't redraw regular tiles into their super tiles unnecessarily. That shouldn't be a huge problem, though.

# Answer
> 0 votes
My first thought is that you're rendering too many tiles. Are you really getting any kind of detail out of an 8x8px tile at 2048x2048 resolution? But that's probably not relevant to the question, unless you want to consider maybe reducing the number of tiles you're rendering to ease the load on the shader.

My second thought is that you should probably use a static mesh representing the entire visible portion of the map, with a few rows and columns extending outside of the viewport to eliminate visible redraw, then just texture each triangle with the visible tiles. You can figure out which tiles are visible by calculating which tile your camera is currently pointing at, but I'm sure you already know how to do that. Keep track of the offset within whatever tile you're pointing at (IE, "My camera is pointing at tile 3,2 with an offset of -2, -14") and you'll never need to actually generate any vertices at all.

Which means that yes, in terms of raw "least number of calculations" you can't get less than zero. You'll still have to apply a transformation matrix, but you'd be doing that regardless.

Another trick I learned back in the day (and similar to Jibb's "super tile" concept) is to render the entire screen to a single texture, and then just render that texture plus whatever's changed/been added since the camera last moved. At the time this didn't produce any noticeable performance improvements on the platform I was working on, but it may be worth considering.

As for how to add new tiles to the view, you are always going to be rendering WxH's worth of tiles. you just just change the starting tile. So if your screen is 100 tiles' worth wide, and your camera is pointing at tile 0, you render tiles 0-99. When the camera moves and is now over tile 1, you render tiles 1-100. And so on.

---
Tags: opengl
---


title: LibGDX Headless System.in

text:
# Question
Title: LibGDX Headless System.in
I started developing a little multiplayer game with LibGDX and Kryonet. I'm also using the headless backend for the server. So far everything went well, but now I'd like to create a command-line parser for the server. I found out that I should make that in a separate thread, so I made a class for that. But the `BufferedReader`'s `readLine()` method always returns with null (but it doesn't raise any exceptions). Here is the code I'm using:

```
public class ServerScreen implements Screen {
    boolean headless;
    Server server;
    CLIParser cliParser = null;

    public ServerScreen(boolean headless) {
        this.headless = headless;
        server = new Server();
        server.start();
        if(headless){
            cliParser = new CLIParser();
            cliParser.start();
        }
        System.out.println("SERVER STARTED");
    }

    //Screen overrides omitted...

    public static class CLIParser implements Runnable{

        public boolean started = false;

        public synchronized void start(){
            if(!started) {
                started = true;
                new Thread(this).start();
            }
        }

        public synchronized void stop(){
            started = false;
        }

        @Override
        public void run() {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println("cliParser run started");
            while(started){
                String line = null;
                try {
                    line = br.readLine();
                } catch (Exception e){
                    System.out.println(e);
                }
                if(line != null){
                    System.out.println("READ LINE: " + line);
                }
            }
        }
    }
}

```

The cliParser starts up successfully, but the readLine() always returns null, and doesn't even blocks the code from running. I don't get any exceptions. I tried the CLIParser in a dummy project, and it works fine, so I assume this could be an issue with the headless backend.

Here is the sample code I used:

```
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CliParserTester {

    public CliParserTester(){
        CLIParser cp = new CLIParser();
        cp.start();
    }

    public static void main(String[] args) {
        new CliParserTester();
    }

    public class CLIParser implements Runnable{

        public boolean started = false;

        public synchronized void start(){
            if(!started) {
                started = true;
                new Thread(this).start();
            }
        }

        public synchronized void stop(){
            started = false;
        }

        @Override
        public void run() {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            System.out.println(System.in);
            System.out.println("cliParser run started");
            while(started){
                String line = null;
                try {
                    line = br.readLine();
                    System.out.println(line);
                } catch (Exception e){
                    System.out.println(e);
                }
                if(line != null){
                    System.out.println("READ LINE: " + line);
                }
            }
        }
    }

}

```

# Answer
your gradle build probably didn't hook stdin as your System.in descriptor, try providing it to gradle with:

```
run{
    standardInput = System.in
}

```
> 1 votes

---
Tags: libgdx, input
---


# Question
Title: Will unlocking the framerate in XNA/MonoGame tell me how efficient my code is?
I have been unlocking the framerate in MonoGame via:

```
this.graphics.SynchronizeWithVerticalRetrace = false;
base.IsFixedTimeStep = false;

```

And using it as a basis for how efficient I am updating and drawing in the game.

At a resolution of **240 x 160** with nothing being drawn or updated except a frame counter I get an FPS value of **9,000** to **11,000** FPS.

If I add all my code back in it drops down to about **1,100** FPS.

Is this a good indication that my code is significantly slowing the GPU down (10x), and should I be concerned? The game is going to run at 60 FPS so I'm still pretty far away from that, but at what point in the unlocked frame rate should I be concerned?

GPU: AMD FirePro W5000 (FireGL V)

# Answer
Only crudely.

First, FPS is a not a linear measure. The difference between 11k FPS and 9k is extremely small (0.0000201 seconds per frame). But the difference between 60 and 2060 FPS (a 2k FPS delta, the same that exists between 11k and 9k) is 0.0161 seconds... much larger. It can thus be dangerous as a performance metric simply because large differences may or may not be that bad.

Using time-per-frame instead is a little easier to reason about, but even then it's still a very broad view of the situation. It just tells you how many seconds one frame of the game takes. It doesn't tell you *why*, unless you look at a large increase in frame time immediately after adding or enabling one particular feature.

It can be a basic barometer for deciding it's time to do more in-depth profiling. It's particularly bad to use FPS to determine if you are CPU or GPU-bound; GPU profiling isn't so easy as measuring time on the CPU (which is where your timing and FPS-computation code probably is).

As for when you should be concerned... well, you said yourself the game was targetting 60 FPS. If you start dipping near or below that, then you probably need to start thinking more carefully about your performance issues. Until then, I'd focus on making everything *work* and then worry about making it *fast*.
> 30 votes

# Answer
I don't see why you couldn't use it! Keep in mind that you may have to code differently to account for the differences between fixed/variable timestep, so if you're planning on making it fixed when you release, you'll need to make adjustments. See this article: http://rbwhitaker.wikidot.com/time-steps

> Is this a good indication that my code is significantly slowing the GPU down

Could be the CPU as well. I'd recommend periodically running Visual Studio's built in profiler (or whenever you see a large framerate drop) to find hot spots in your code.

> should I be concerned?

That obviously depends on the hardware you're targeting. You'll need to test your code against the lowest minimum requirement machines you're willing to support. If it runs at least 60 there, then I wouldn't be too concerned.
> 5 votes

---
Tags: monogame, frame-rate
---


# Question
Title: Frame-rate independent friction on movement in 2d game
I have been trying to implement a simple physics system for a 2D space game I am making. I have it pretty much working, but I have encountered an issue with the way I apply friction. I have tried several different ways of solving it, with different guides found online, but my math skills are lacking and it's difficult for me to translate the solutions to fit my problem.

I made a unit test that shows my problem:

```
            //Simulate a low FPS.
            //Accelerate body1 with 100 pixels/second, for a deltaTime of 1 (A single frame that took 1 second)
            body1.accelerate(100, 1);
            //Performe the physics with the dame deltaTime.
            body1.doPhysics(1);

            //Simulate a higher fps.
            //Accelerate body2 10 times, with 100 pixels/second for a deltaTime of 0.1 (A single frame that took 1/10'th of a second.
            for(int j=0; j< 10; j++) {
                body2.accelerate(100, 0.1);
                body2.doPhysics(0.1);
            }

            Debug.Log("Straight movement result "+body1.getPosition()+" --- "+body2.getPosition());

```

Which gives the result: "Straight movement result \[0.0, 50.0\] --- \[0.0, 39.31200662855\]"

My acceleration does not seam to be a problem. I have a unit test like the other one, to test the acceleration, and it shows no problems.

```
public void accelerate(double acceleration, double deltaTime) {
        Vector2f accel = new Vector2f(0, (float)(acceleration));

        //If power is negative, we want to go backwards.
        if(acceleration < 0)
            accel.setTheta(angle+90 - 180);
        else
            accel.setTheta(angle+90);

        velocity.x += (accel.x * deltaTime);
        velocity.y += (accel.y * deltaTime);
    }

```

In the `doPhysics` method, is where I calculate the friction. If I remove the friction calculations, the two values printed from the unit test are equal.

```
private static final float friction = 1.0f;//0.96f;

    private void doPhysics(double deltaTime) {
        //Save the velocity before applying friction.
        Vector2d velBefore = new Vector2d(velocity);

        //Then apply friction, with deltaTime.
        velocity.x -= (velocity.x * friction) * deltaTime;
        velocity.y -= (velocity.y * friction) * deltaTime;

        //And then calculate the average of the friction before and after friction and factor in deltaTime
        double realVelX = ((velBefore.x + velocity.x) * 0.5) * deltaTime;
        double realVelY = ((velBefore.y + velocity.y) * 0.5) * deltaTime;

        //Add the calculated velocity.
        position.x += realVelX;
        position.y += realVelY;
    }

```

I hope someone can see what I am doing wrong. I would really like my physics to be frame-rate independent and simple enough for me to understand.

# Answer
So I have struggled to get this right and this is what I currently use. The point is to have a friction value that is dependent on time and therefor works on low and hi end devices similarly.

```
//*** Set friction value
friction = 5f;

//*** Calculate Fiction decay
xRatio = 1 / (1 + (Time.deltaTime * friction));

//*** Decay velocity
velocity *= xRatio;

//*** Set Position
_position += velocity * Time.deltaTime;

```

Its been working well for me for years, I hope it helps.
> 6 votes

# Answer
Ok, think I got an answer for you. The short version: compute the friction force F = friction * velocity before you start the loop and apply it in do Physics() like this: v -= F * deltaTime.

Long version: the assumption you're making that it should work independent of frame time only works with constant acceleration, like the one you're applying in accelerate(). But the friction force is not a constant one: it varies at every moment in time and you're taking snapshots of it. When you're updating with a smaller time step deltaTime you're actually getting a more accurate answer than with the big time step (10x). But you want to get the same (less precise) answer in both cases and the way to do this is to consider the friction force only at the moments in time corresponding to the big step - basically consider the force constant over every 10 iterations with the small step. Hope you got the idea and I didn't confuse you.

Even more, you could write a simple equation for the case with just velocity affected by friction: v1 = v0 - dt * f * v0 = (1 - dt * f) * v0 which after n steps becomes vn = (1 - dt * f)^n * v0. This is clearly not equal to (1 - n * dt * f) * v0 which you get if you just update with an n times bigger step. Indeed a power is involved here, but I don't see any sense in using the pow() function in any way.

And just for my curiosity: why are you doing all those tricks with storing the old velocity and the average afterwards? It looks like some sort of trapezoid integration scheme but I don't see the point of it. Moreover why are you simulating two bodies at different time steps? In my opinion it's good practice to simulate all the bodies in the same loop with the same time step. You can scale the velocities directly if you want some bodies to move slower - if that's want you want to achieve.

And last I just want to mention that you call friction is really air drag or viscuous friction and it just may be what you want in 2d. The "real" friction is Coulomb friction which depends on the normal push, i.e. weight in your case: F = - mu * m * g. This one is constant - it decreases the velocity with fixed decrements instead of scaling it with \<1 factor at every update (you'll have to check at zero so it doesn't reverse your body but just makes it stand still). Air drag never really gets your velocity to zero, but very close.
> 4 votes

---
Tags: physics, timestep
---