# Question
Title: Which iPhone/iPod Hardware to Support for iPhone Game
I'm coming from a background of Android. I would like to figure out what kind of iBlah device hardware I need to support for iPhone game development; something like Android's OS distribution stats, but for iBlah hardware.

From my research, it seems that I need to support both iPod and iPhone. But which versions of hardware? is 3G still used? What about 3GS?

For example, the -S phones seem to have dual core instead of single-core CPUs.

I also worry about performance. In Android, I had a severely low-end phone, which meant pretty much anything that ran okay there ran okay on other phones. For iPhone, how do I figure out what to support in terms of performance?

# Answer
It depends on the country, but in most places you can still find 3GS hardware, so if you plan to support as much hardware as possible, you should go with 3GS.

*however*

The difference between consecutive versions of the iPhone is so large that you may want to consider dropping support for 3GS (and maybe even 4 and dare I say 4S). That way you have a nice guaranteed minimum set of features. Remember that people with old devices are not precisely the people who impulse buy apps, much less games (this is *especially* true in the iPhone customer base). Your most valuable customers *will* have the latest gadgets from Cupertino.

It's like supporting Windows 2000 (and maybe even Windows XP) for the latest high-end games. Some people may still be using that platform, but supporting it may not necessarily be necessary for your interests.

Related answer: https://stackoverflow.com/questions/5291823/breakdown-of-ios-versions-being-used
> 1 votes

# Answer
3GS is still being used. That's the oldest you'll support. I think you should also consider RAM.

The devices I have problems with are iPhone 3GS and iPod 4th gen not only because they have lower CPU, the RAM is also very low. If your game hogs too much memory, your game will keep crashing on it (even with proper memory management).

Here's the list: iPhone 3GS iPod 4th Gen iPhone 4 iPhone 4S iPhone 5 iPod 5th Gen (need to watch for this one)
> 0 votes

# Answer
Xcode comes with a built-in fully featured emulator for both iphone and ipad, so you just need Xcode at minimum, you can code for iOS without having a real device.

If you care about optimization the only solution is always buying a real device.

Also depending on what sensors and controllers you want to use, you can just consider to buy an iPod touch if you are not interested in the differences between an iPod and an iPhone. I also should add the fact that the GPU is basically the same for the latest 3rd and 4th gen of Ipod touch, iPhone 3GS and iPhone 4, the only new GPU is in the iPhone 4s and is not so revolutionary, so i think that you can go for an ipod Touch if you want a real device for just testing your app.
> -1 votes

---
Tags: iphone, hardware
---


# Question
Title: Application toolkits like QT versus traditional game/multimedia libraries like SFML
I currently intend to use SFML for my next game project. I'll need a substantial GUI though (RPG/strategy-type) so I'll either have to implement my own or try to find an appropriate third party library, which seem to boil down to CEGUI, libRocket, and GWEN. At the same time, I do not anticipate doing that many advanced graphical effects. My game will be 2D and primarily sprite-based with some sprite animations.

I've recently discovered that QT applications can have their appearance styled so that they don't have to look like plain OS apps. Given that, I am beginning to consider QT a valid alternative to SFML. I wouldn't have to implement the GUI functionality I'd need, and I may not be taking advantage of SFML's lower-level access anyway. The only drawbacks I can think of immediately are the learning curve for QT and figuring out how to fit game logic inside such a framework after getting used to the input/update/render loop of traditional game libraries.

When would an application toolkit like QT be more appropriate for a game than a traditional game or multimedia library like SFML?

# Answer
Here's a report on using QT from one guy who tried to use it in his game-like project.

http://www.shamusyoung.com/twentysidedtale/?p=15904

His conclusion? Don't.
> 1 votes

# Answer
Qt is easy to learn. The only issue i found was performance, since the framework is built for convenience more than anything. That, as always, depends on what kind of a game you're making. For you, it's an RPG, so i'm guessing there's going to be alot on the screen and the standard painting library is probably not going to cut it, while the I/O library is perfectly fine, since slight input lag is not fatal. To solve the drawing issue you could use the OpenGL widget, though that may prove to be unnecessarily complicated if you just want to render large amounts of sprites efficiently.

However, you can implement a game loop in Qt without using signals and slots, you just have to call processEvents() when you want to read input instead of running the application with exec() once. This lets you potentialy only use Qt for I/O and GUI. Then you can use SFML for easy and efficient drawing inside of Qt. Here's the official tutorial on integrating Qt and SFML.
> 0 votes

# Answer
There are also gui libraries made for sfml, like SFGUI, GuiChan and others.
> 0 votes

---
Tags: gui, qt
---


# Question
Title: Numerical stability in continuous physics simulation
Pretty much all of the game development I have been involved with runs afoul of simulating a physical world in discrete time steps. This is of course very simple, but hardly elegant (not to mention mathematically inaccurate). It also has severe disadvantages when large values are involved (either very large speeds, or very large time intervals).

I'm trying to make a continuous physics simulation, just for learning, which goes like this:

```
time = get_time()
while true do
    new_time = get_time()
    update_world(new_time - time)
    render()
    time = new_time
end

```

And `update_world()` is a continuous physical simulation. Meaning that for example, for an accelerated object, instead of doing

```
object.x = object.x + object.vx * timestep
object.vx = object.vx + object.ax * timestep -- timestep is fixed

```

I'm doing something like

```
object.x = object.x + object.vx * deltatime + object.ax * ((deltatime ^ 2) / 2)
object.vx = object.vx + object.ax * deltatime

```

However, I'm having a hard time with the numerical stability of my solutions, especially for very large time intervals (think of simulating a physical world for hundreds of thousands of virtual years). Depending on the framerate, I get wildly different solutions.

How can I improve the numerical stability of my continuous physical simulations?

# Answer
> 3 votes
Plain C code:

```
#include <stdio.h>
int main(int argc, char **argv)
{
    int i;
    double manyX = 0.0;
    double oneX = 0.0;
    double vx = 0.0;
    double ax = 0.5;

    double oneTimeSlice = 100000.0;
    double manyTimeSlice = 1.0;

    // calculate one big 1,000,000 timeslice
    oneX += oneTimeSlice * vx + (0.5 * ax * oneTimeSlice * oneTimeSlice);

    // calculate 1,000,000 1-unit-long timeslices
    for ( i = 0; i < 1000000; i++ )
    {
            manyX += manyTimeSlice * vx + (0.5 * ax * manyTimeSlice * manyTimeSlice);
            vx += manyTimeSlice * ax;
    }

    printf("One Time Slice: %f\n", oneX);
    printf("Many Time Slices: %f\n", manyX);
    return 0;
}

```

output:

```
One Time Slice: 2500000000.000000
Many Time Slices: 250000000000.000000

```

I'm not seeing the difference you're claiming.

I think you're more likely to be having simple floating point precision problems than numerical stability problems, under the constraints you've specified.

---
Tags: physics
---


# Question
Title: Animation Trouble with Java Swing Timer - Also, JFrame Will Not Exit_On_Close
So, I am using a Java Swing Timer because putting the animation code in a run() method of a Thread subclass caused an insane amount of flickering that is really a terrible experience for any video game player.

Can anyone give me any tips on:

* Why there is no animation...
* Why the JFrame will not close when it is coded to Exit\_On\_Close 2 times

My code is here:

```
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

import java.net.URL;

//////////////////////////////////////////////////////////////// TFQ
public class TFQ extends JFrame {

DrawingsInSpace dis;

//========================================================== constructor
    public TFQ() {

        dis = new DrawingsInSpace();

        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());

       this.setContentPane(dis);

       this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setTitle("Plasma_Orbs_Off_Orion");
        this.setSize(500,500);
        this.pack();

        //... Create timer which calls action listener every second..
        //    Use full package qualification for javax.swing.Timer
        //    to avoid potential conflicts with java.util.Timer.
        javax.swing.Timer t = new javax.swing.Timer(500, new TimePhaseListener());
        t.start();
    }

    /////////////////////////////////////////////// inner class Listener thing
    class TimePhaseListener implements ActionListener, KeyListener {

        //  counter
        int total;

        // loop control
        boolean Its_a_go = true;

        //position of our  matrix
        int tf = -400;

        //sprite directions
        int Sprite_Direction;
        final int RIGHT = 1;
        final int LEFT = 2;

        //for obstacle
        Rectangle mega_obstacle = new Rectangle(200, 0, 20, HEIGHT);

        public void actionPerformed(ActionEvent e) {
            //... Whenever this is called, repaint the screen
         dis.repaint();

        addKeyListener(this);
        while (Its_a_go) {
            try {
            dis.repaint();

            if(Sprite_Direction == RIGHT) {

            dis.matrix.x += 2;

            } // end if i think
            if(Sprite_Direction == LEFT) {

            dis.matrix.x -= 2;

            }

            } catch(Exception ex) {
                System.out.println(ex);
            }
        } // end while i think
        } // end actionPerformed

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyTyped(KeyEvent event) {
            // TODO Auto-generated method stub
            if (event.getKeyChar()=='f'){
                Sprite_Direction = RIGHT;
                System.out.println("matrix should be animating now ");
                System.out.println("current matrix position = " + dis.matrix.x);
            }
            if (event.getKeyChar()=='d') {
                Sprite_Direction = LEFT;
                System.out.println("matrix should be going in reverse");
                System.out.println("current matrix position = " + dis.matrix.x);
            }

        }

    }

    //================================================================= main
    public static void main(String[] args) {
        JFrame SafetyPins = new TFQ();

        SafetyPins.setVisible(true);
        SafetyPins.setSize(500,500);
        SafetyPins.setResizable(true);
        SafetyPins.setLocationRelativeTo(null);
    SafetyPins.setDefaultCloseOperation(EXIT_ON_CLOSE);

    }
}

class DrawingsInSpace extends JPanel {

 URL url1_plasma_orbs;
 URL url2_matrix;
 Image img1_plasma_orbs;
 Image img2_matrix;

// for the plasma_orbs
Rectangle bbb = new Rectangle(0,0, 0, 0);
// for the matrix
Rectangle matrix = new Rectangle(-400, 60, 430, 200);

public DrawingsInSpace() {
    //load URLs
    try {
        url1_plasma_orbs = this.getClass().getResource("plasma_orbs.png");
        url2_matrix = this.getClass().getResource("matrix.png");
    } catch(Exception e) {
        System.out.println(e);
    }
    // attach the URLs to the images
    img1_plasma_orbs = Toolkit.getDefaultToolkit().getImage(url1_plasma_orbs);
    img2_matrix = Toolkit.getDefaultToolkit().getImage(url2_matrix);
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // draw the plasma_orbs
    g.drawImage(img1_plasma_orbs, bbb.x, bbb.y,this);

    //draw the matrix

    g.drawImage(img2_matrix, matrix.x, matrix.y, this);

    }

} // end class

```

# Answer
Your timer event has an infinite loop. This blocks the event dispatch thread, blocking any other GUI events like painting or the frame closing from occurring.

Learn the Java code conventions, they make your programs much easier to read. Variables should not start with an uppercase letter.
> 5 votes

---
Tags: java, animation, gui, timer, swing
---


# Question
Title: Render graphics using Doubles in Graphics2D
Currently, I have a JFrame for my game to render in, and I'm using Graphics2D for drawing (The games graphics are fairly simple 2D sprites). However, my delta variable is a double, and all of the Graphics 2D methods (And Grpahics) use int. I tried to type cast the delta to an int, but it just rounds down to 0. So my question is, how can I render graphics using Graphics2D in Java with coordinates that are doubles. Can I convert it to work with Graphics2D if there is no built in way? Or, is there a graphics library that can support doubles for coordinates?

# Answer
Graphics class uses integer coordinates for all operations, but Graphics2D provides API with float and double accuracy. You can use Graphics2D.draw(Shape) and Graphics2D.fill(Shape) to get sub-pixel accuracy in rendering. You should also probably enable antialiasing for the Graphics2D object.

```
public void paintComponent(Graphics graphics) {
    Graphics2D g = (Graphics2D)graphics;
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.draw(new Line2D.Double(10.5, 10.5, 20.5, 20.5));
}

```

Alternatively you can scale, rotate and translate Graphics2D object or manipulate the AffineTransform directly. This might be needed if you want to draw images to double coordinates.
> 2 votes

---
Tags: java, rendering
---


# Question
Title: Displaying total playing seconds at end of game
Creating a simple survival game.

When the player has been caught I want to display the amount of seconds that they survived for.

How do I go about this?

# Answer
> 4 votes
One fairly simple way to do this is to just make a variable called "SecondsSurvived" to either Player class or GameplayScreen/whatever. Then in the update method, if the game is not paused/stopped/ended, increment SecondsSurvived variable by ElapsedTime. Then when the player dies, simply use that SecondsSurvived variable as you like. So something like this:

```
public class GameplayScreen
{
     private float _secondsSurvived = 0f;
     private Player _player;

     ...

    public void Update(GameTime gameTime)
    {
         ...

         if(_player.IsAlive && this.IsActiveScreen)
         {
              _secondsSurvived += (float)gameTime.ElapsedGameTime.TotalSeconds;
         }
    }
}

```

Remember to reset \_secondsSurvived to zero everytime the game restarts.

# Answer
> 4 votes
When your round starts, save the current time, e.g. copying `DateTime.Now`.

Once the round is over, compare your old value with the current `DateTime.Now` and you should end up with the time span representing the length of the game (keep in mind that the precision is limited and different based on your operating system, but it's usually around 10-16 ms).

---
Tags: c#, xna-4.0
---


# Question
Title: Rendering different materials in a voxel terrain
Each voxel datapoint in my terrain model is made up of two properties: density and material type. Each is stored as an unsigned integer value (but the density is interpreted as a decimal value between 0 and 1). The density values are used to generate a mesh with the marching cubes algorithm.

My current idea for rendering these different materials on the terrain mesh is to store eleven extra attributes in each vertex: six material values corresponding to the materials of the voxels that the vertices lie between, three decimal values that correspond to the interpolation each vertex has between each voxel, and two decimal values that are used to determine where the fragment lies on the triangle.

The material and interpolation attributes are the exact same for each vertex in the triangle. The fragment shader samples each texture that corresponds to each material and then uses the aforementioned couple of decimal values to interpolate between these samples and obtain the final textured color of the fragment.

It should work fine, but it seems like a big memory hog. I won't be able to reuse vertices in the mesh with indexing, and each vertex will have a lot of data associated with it. It also seems pretty slow. What are some ways to improve or replace this technique for drawing materials on a voxel terrain mesh?

# Answer
Due to the sheer volume of data in your average voxel world, it will be challenging to draw much geometry with your approach, before hardware limits are reached, without some kind of spatial subdivision approach. You also need to be highly efficient in packing data at the bit/byte level.

**Method: RLE**

Enter Run-Length Encoding (RLE) compression as a popular option. Voxels are stored columns, as in the following example:

`6E1G9A`

Which means, from top to bottom, "6 earth, 1 grass, then 9 air".

So instead of storing a byte or more for every voxel, let alone every vertex, you instead create compressed columns of data that allow you to upload far more to the GPU, as uniform variables (GLSL lingo, not sure what they're called in HLSL). Instead of voxels scattered in 3D space, you have a single mesh representing each columnar run of homogeneous voxels (y-axis).

From a mesh building perspective, the idea is that you would then evaluate these RLE columns, fragment them into there individual *runs*, and create 8 vertices per run. You would simultaneously set up a uniform variable (GLSL) for any additional data you might need for that run, and upload the lot.

You would want to keep the full run-length encoded columns "from fundament to heaven", so to speak, on the CPU side, but you would send *individual runs* up to the GPU. This is because there will be breaks in a column where meshes end and new ones begin; think of a cross-section of an (x, z) area where there is a cave or air-pocket; you would have to end one columnar mesh where the floor is, and start another where the roof begins. You might have to do this several times in a single (x, z) location.

You largely want to avoid conditional logic / loops in shaders wherever possible, so try to do that sort of thing on the CPU side -- especially as regards basic geometry (see the next method for more on why I say "basic" geometry).

Where RLE gets more difficult is where you have to store eg. lighting, cellular automata or other information as well as data on materials. This causes a higher ratio of fragmentation if the same RLE container is used for that data, since the data is no longer as homogeneous as it was; hence, it may be better to simply upload separate runs for other elements that may affect rendering, such as lighting.

**Method: Geometry shader**

One way you could do things would be to maintain data for every vertex, but where each vertex represents a voxel. You could then use a geometry shader to spawn an individual cubic geometry for each voxel. This will depend very much on your size per voxel and intended viewing distance (one reason why MineCraft's view distance is so short is that it spams geometry like crazy, brute force). Furthermore, you would use bitflags to pack as much data into whatever space you do allocate per voxel, as possible. For instance, if you only need 32 types of voxel, then use the 5 least significant bytes to represent that, and 3 most significant bytes to represent other data, rather than wasting those last 3 bits (good for 2^3=8 values) and starting a whole new byte. Using bitwise operators to extract that data back out again, is available on the GPU side only in newer versions of GLSL and HLSL (you'll need to check which versions, exactly).

**Method: 3D spatial subdivision**

I'm not going to go into this too heavily as it is a fairly intense topic more likely to be addressed in computational geometry and rendering research papers than in game engine tech, but what RLE does is to do compression in one axis only, the y-axis. This makes the problem easier to consider in some senses, as it becomes, in many ways, a 2-dimensional planar problem. However, it also introduces it's own concerns; eg. by biasing detail axially, maintaining steady framerates when viewing in different directions can become problematic. Slabs-based approaches are similar in that they have again not utilised compression in all 3 dimensions. OTOH, KD-trees and octrees are two common, highly efficient data structures for the construction of voxel spaces by compressing in all 3 axes as opposed to just one or two. KD-trees are potentially more efficient overall, but contain arbitrary structure and so are more complex to process. Octrees have a regular structure but suffer from heavy processing costs at the corners of very large regions, though they can be very efficient elsewhere.

**Method: Unstructured 3D clustering, hybrids**

Point cloud data offers a relatively new (to the games industry anyway!) method of storing and rendering data, but is very much experimental technology and so almost certianly not suitable for your purposes. However, like KD-trees, the arbitrary placement of voxels or voxel-sets might provide real value to you in terms of reducing processing cost and memory requirements on the CPU *and* GPU sides. You may be able to combine the characteristics of several of the above methods into a solution that is most efficient for you. This is what I've done in my engine, though I won't share specifics. :)
> 10 votes

---
Tags: shaders, terrain, voxels, procedural, materials
---


# Question
Title: Curiosity on any Smartphones that Run on Android 2.3.3 with Different Screen Reoslution
I have a question regarding about any smartphones that run only in *Android 2.3.3*. Is the size of screen or the screen resolution is always **HVGA** or does it have capable of running this OS (*Android 2.3.3*) on big screen size (**4" to 5"**) at about **720x1280**?

I'm thinking of the game's compatibility depending on the version of the Android OS and the screen resolution, which affects the change of coordinates especially for assigning touch buttons and drag-n-drop at exact location, before I'm gonna decide to make one. My program works on the Android 4 ICS and Jellybean, however, will that work on *Android 2.3.3* in spite of precise touch coordinate or just dependent on the screen resolution (regardless how large it is) as the X and Y coordinate?

And take note, I'm using Eclipse IDE for Java developers.

# Answer
> 1 votes
Since Android's rendering is OpenGL ES based, I can see absolutely no reason whatsoever why resolution should make any difference at all. The Hexxeh Chromium Builds run on any and all types of devices (netbooks, desktops, phones, whatever), so I cannot see how screen resolution can be an issue. Android is just a fuller featured branch of Chromium.

I have a Samsung Galaxy S (1, not 2 or 3) running 2.3.3 at 480×800, FWIW, in answer to the title of the question rather than the detail about higher resolutions.

---
Tags: libgdx, coordinates, resolution, screen, aspect-ratio
---


title: Quadtree collapsing

text:
# Question
Title: Quadtree collapsing
Okay so i've spent a few days learning what a quadtree is and how to implement one. So far I have a quadtree that when I click inside a leaf it subdivides, I wondering how do I get the previous subdivisions to collapse back up, so that only one area is subdivided at a time?

This is what mine looks like: (1. initial mouse click) (2. another mouse click)

The aim to to eventually track the position of my mouse and subdivide the area it is in dynamically.

*THE OVERALL* aim it to use this to create a terrain mesh and subdivide based on the camera. But I've gone right back to basics to get an understanding of how this will work.

Any advice would be grand! - Caius

# Answer
**Terminology first:** I refer to quadtree quads as "nodes" within the quadtree structure, and I refer to flat array elements as "cells".

Every individual quad, at each subdivision depth, should have it's own wireframe view component. You should also have a flat 2D array that represents all of the quadtree *leaf* (i.e. deepest level) nodes in your entire root node. We'll call this a *presence array*. Basically this array shows us which cells have objects in them. You should have one such array for the *last* frame/update, and one for the *new* frame. At the start of every frame/update, determine deltas from the presence arrays by comparing their cells at each respective `[x, y]` location, and recording any differences into lists as follows:

1. `enteredInto` holds corresponding leaf nodes for any cells that changed from not present in `last` array -\> present in `new` array.
2. `departedFrom` holds corresponding leaf nodes for any cells that changed from present in `last` array -\> not present in `new` array.

I would keep each of these as `List<T>`.

These sets can each hold multiple entries because your object may be sitting over an intersection of four (or more) leaf cells, and because the object may be larger than a single cell.

Using these sets, you can flag each leaf node with a boolean to either render or *not* in the current frame/update. As soon as a leaf node is turned on for rendering, all of its ancestors must be automatically turned on for rendering, as well, right up to the root. I would implement this in a `set`ter method, such that as soon as you set any lower level node, it walks up its ancestor list, setting flags all the way to the root. Be sure to switch off "just departed" cells before switching on "just entered" cells.
> 3 votes

# Answer
Implement the following methods: Add(point), Remove(point), Move(point) Move is not completeley necessary as it can be simulated by Remove and Add but that's less efficient.

Use the following mouse events: press -\> Add, release -\> Remove, drag -\> Move

I assume you implemented your Remove and Move functions recursively. Return a boolean value from each Remove call in your Node, so you will know exactly which recursive path removed a point. If this value is true for a certain node, check if that node has any elements or child nodes inside. If it has neither, undo the subdivision.

Another approach may be to track the number of points inside each node (including children). This trades some computation time for memory and may actually be more efficient.

And a side-note: your example is not the best to demonstrate a quadtree. The idea behind quadtrees is that you only subdivide once a node has reached a certain number of points inside. If you only track one position (mouse pointer) you don't even have to subdivide at all. Instead, create a number of points that move around randomly.
> 1 votes

---
Tags: quadtree
---


title: Getting to math applications gradually

text:
# Question
Title: Getting to math applications gradually
I'm currently getting a formal degree related to computation, in particular my current focus is numerical programming, scientific computing and machine learning. I'd love to apply that knowledge in game dev and expand it with statistics, probability theory, and graph theory (probably even linear algebra). The question is: which spheres of gamedev are filled with such math stuff, is it possible to advance in those without being a part of a group of people and how to get to it gradually?

P.S.: I've got experience with commercial java dev and am getting my hands on C/C++ at the moment, however, I'm opened to go ahead and try Unity3D and etc.

# Answer
> 2 votes
I recently answered a similar question, albeit from a different perspective, on math.se, on this very same topic.

# Answer
> 2 votes
Game AI will encompass all those types of math. Making an intelligent AI system is a very challenging task. This task will rely heavily on machine learning, statistics, probability theory and graph theory.

Another area would be in procedural generation. Creating a world and most if not all the items in it intelligently, without much manual content generation is an excellent goal. Simulating the creation of goods, their use and resulting location in the world would be very interesting.

More procedural generation tasks may include:

* Generation of a detailed history of a world. Wars fought, the naming of lands, the rise and fall of leaders, plagues, etc.
* Character creation for NPC characters. With the traits of their ancestor y and personal histories.

There are a number of mini-games you can make with this kind of math background as well. For example:

* Simulating the spread of disease and the efforts to combat it
* Generating efficient travel networks for transportation between nodes (cities, planets, etc.)
* Simulation of evolution of player made organisms.
* and so on.

Most of these things you can start small with and develop solo. They may not have fancy graphics or spectacular effects, but they'll demonstrate your potential and develop your skills.

You do it gradually like any other task you're learning in life. Start very simple, create something small that can be improved over time with more and more complexities.

---
Tags: mathematics, game-industry
---


# Question
Title: How can I detect and compensate for system related lag?
The best example I can think of is Doom 3. It seemed to me that if there was any kind if lag the game would pause and then resume without "fast forwarding" to catch up. I'm trying to figure out a good practice to use for lag detection in JavaScript.

# Answer
> 3 votes
First Rq : A key rule in Javascript : avoid system lag, with a very simple principle : do not feed the garbage collector.
So : Reuse your Arrays, do not create closures, use integers and not strings, pool your objects, ... a lot of simple rules too long to explain in a few words.

Now that you've done that, to avoid a slow-down/ fast forward behaviour, you have to to handle the time and timers by yourself. And drop a frame or more if you have to.

Rq : A secondary benefit of handling your game time/timers is that it will allow to nicely pause the game, and even to go faster or bullet-time if you want.

So how to handle your game time ?
Inside your run() loop you should measure the time between two calls (delta), and add up that 'real' time to your game time... Unless (and that's the trick) too much time elapsed (there was a pause or a system lag) : in that case you consider that just one frame elapsed.
Scale that time delta to allow bullet time / fast speed.

And for the game timers either :
a) you implement your own game timers (gameSetTimeout/gameSetInterval) (somehow complex)
b) you only check your entities against the game time for time-related actions.
expl, for a human that turns into a zombie after a given time :

```
if (this.isDead && (gameTime - this.DeathTime > ZombieToHumanTurnTime)) {
                this.type          = 'zombie';
                this.isDead        = false   ;
                this.isLivingDead  = true    ;
                this.target        = 'brain' ;  // :)
           }

```

(you can write this in a neater way with a : if (this.shouldTurn()) ... )

So now that you have your game time, you must have your entities update depending on game time :

So with delta = delta between current game time and previous frame game time :

```
this.update ( delta ) {  // position update for a simple entity having velocity.
    this.x = this.x + this.velocity.x*delta; // depends on dt (ms)
    this.y = this.y + this.velocity.y*delta; // depends on dt (ms)
}

```

Notice that window.performance.now is a much more accurate timer available (with a polyfill) on almost all current platforms.

---
Tags: javascript, lag
---


title: How to implement smooth flocking

text:
# Question
Title: How to implement smooth flocking
I'm working on a simple survival game, avoid the big guy and chase the the small guys to stay alive for as long as possible.

I have taken the chase and evade example from MSDN create and drawn 20 mice on the screen.

I want the small guys to flock when they arent evading. They are doing this, but it isnt as smooth as I would like it to be. How do i make the movement smoother? Its very jittery.# Below is what I have going at the moment, flocking code is within the IF statement, when it isnt set to evading. Any help would be greatly appreciated! :)

```
   namespace ChaseAndEvade
      {
 class MouseSprite
{
    public enum MouseAiState
    {
        // evading the cat
        Evading,
        // the mouse can't see the "cat", and it's wandering around.
        Wander
    }

    // how fast can the mouse move?
    public float MaxMouseSpeed = 4.5f;

    // and how fast can it turn?
    public float MouseTurnSpeed = 0.20f;

    // MouseEvadeDistance controls the distance at which the mouse will flee from
    // cat. If the mouse is further than "MouseEvadeDistance" pixels away, he will
    // consider himself safe.
    public float MouseEvadeDistance = 100.0f;

    // this constant is similar to TankHysteresis. The value is larger than the
    // tank's hysteresis value because the mouse is faster than the tank: with a
    // higher velocity, small fluctuations are much more visible.
    public float MouseHysteresis = 60.0f;

    public Texture2D mouseTexture;
    public Vector2 mouseTextureCenter;
    public Vector2 mousePosition;
    public MouseAiState mouseState = MouseAiState.Wander;
    public float mouseOrientation;
    public Vector2 mouseWanderDirection;

    int separationImpact = 4;
    int cohesionImpact = 6;
    int alignmentImpact = 2;
    int sensorDistance = 50;

    public void UpdateMouse(Vector2 position, MouseSprite [] mice, int numberMice, int index)
    {

        Vector2 catPosition = position;
        int enemies = numberMice;

        // first, calculate how far away the mouse is from the cat, and use that
        // information to decide how to behave. If they are too close, the mouse
        // will switch to "active" mode - fleeing. if they are far apart, the mouse
        // will switch to "idle" mode, where it roams around the screen.
        // we use a hysteresis constant in the decision making process, as described
        // in the accompanying doc file.
        float distanceFromCat = Vector2.Distance(mousePosition, catPosition);

        // the cat is a safe distance away, so the mouse should idle:
        if (distanceFromCat > MouseEvadeDistance + MouseHysteresis)
        {
            mouseState = MouseAiState.Wander;
        }
        // the cat is too close; the mouse should run:
        else if (distanceFromCat < MouseEvadeDistance - MouseHysteresis)
        {
            mouseState = MouseAiState.Evading;
        }
        // if neither of those if blocks hit, we are in the "hysteresis" range,
        // and the mouse will continue doing whatever it is doing now.

        // the mouse will move at a different speed depending on what state it
        // is in. when idle it won't move at full speed, but when actively evading
        // it will move as fast as it can. this variable is used to track which
        // speed the mouse should be moving.
        float currentMouseSpeed;

        // the second step of the Update is to change the mouse's orientation based
        // on its current state.
        if (mouseState == MouseAiState.Evading)
        {
            // If the mouse is "active," it is trying to evade the cat. The evasion
            // behavior is accomplished by using the TurnToFace function to turn
            // towards a point on a straight line facing away from the cat. In other
            // words, if the cat is point A, and the mouse is point B, the "seek
            // point" is C.
            //     C
            //   B
            // A
            Vector2 seekPosition = 2 * mousePosition - catPosition;

            // Use the TurnToFace function, which we introduced in the AI Series 1:
            // Aiming sample, to turn the mouse towards the seekPosition. Now when
            // the mouse moves forward, it'll be trying to move in a straight line
            // away from the cat.
            mouseOrientation = ChaseAndEvadeGame.TurnToFace(mousePosition, seekPosition,
                mouseOrientation, MouseTurnSpeed);

            // set currentMouseSpeed to MaxMouseSpeed - the mouse should run as fast
            // as it can.
            currentMouseSpeed = MaxMouseSpeed;
        }
        else
        {
            // if the mouse isn't trying to evade the cat, it should just meander
            // around the screen. we'll use the Wander function, which the mouse and
            // tank share, to accomplish this. mouseWanderDirection and
            // mouseOrientation are passed by ref so that the wander function can
            // modify them. for more information on ref parameters, see
            // http://msdn2.microsoft.com/en-us/library/14akc2c7(VS.80).aspx
            ChaseAndEvadeGame.Wander(mousePosition, ref mouseWanderDirection, ref mouseOrientation,
                MouseTurnSpeed);

            // if the mouse is wandering, it should only move at 25% of its maximum
            // speed.
            currentMouseSpeed = .25f * MaxMouseSpeed;

            Vector2 separate = Vector2.Zero;
            Vector2 moveCloser = Vector2.Zero;
            Vector2 moveAligned = Vector2.Zero;
            // What the AI does when it sees other AIs
            for (int j = 0; j < enemies; j++)
            {
                if (index != j)
                {
                    // Calculate a vector towards another AI
                    Vector2 separation = mice[index].mousePosition - mice[j].mousePosition;

                    // Only react if other AI is within a certain distance
                    if ((separation.Length() < this.sensorDistance) & (separation.Length()> 0) )
                    {
                        moveAligned += mice[j].mouseWanderDirection;

                        float distance = Math.Abs(separation.Length());
                        if (distance == 0) distance = 1;

                        moveCloser += mice[j].mousePosition;

                        separation.Normalize();
                        separate += separation / distance;

                    }
                }
            }

            if (moveAligned.LengthSquared() != 0)
            {
                moveAligned.Normalize();
            }
            if (moveCloser.LengthSquared() != 0)
            {
                moveCloser.Normalize();
            }

            moveCloser /= enemies;
            mice[index].mousePosition += (separate * separationImpact) + (moveCloser * cohesionImpact) + (moveAligned * alignmentImpact);

        }

        // The final step is to move the mouse forward based on its current
        // orientation. First, we construct a "heading" vector from the orientation
        // angle. To do this, we'll use Cosine and Sine to tell us the x and y
        // components of the heading vector. See the accompanying doc for more
        // information.
        Vector2 heading = new Vector2(
            (float)Math.Cos(mouseOrientation), (float)Math.Sin(mouseOrientation));

        // by multiplying the heading and speed, we can get a velocity vector. the
        // velocity vector is then added to the mouse's current position, moving him
        // forward.
        mousePosition += heading * currentMouseSpeed;
    }

}

```

}

# Answer
Going to go back to the beginning and go about setting a leader and having the rest of the mice follow. Been told that might get me the needed results.
> 0 votes

# Answer
The typical solution for jittery movement is to use linear interpolation to between movements.

Also, you don't want to set the position directly, only update it based off of velocity (and you can go further and only set the velocity based off of realistic acceleration, and even further and only change the acceleration at realistic jerk. Or just make sure you don't change the velocity too much :)).

Here where you're setting the position directly:

```
mice[index].mousePosition += (separate * separationImpact) + (moveCloser * cohesionImpact) + (moveAligned * alignmentImpact);

```

Needs to be set to a `targetPosition`. Then every update, move the mouse towards the `targetPosition` at the mouse current speed.
> 1 votes

# Answer
Maybe you could have a look here: http://3carrotsonastick.wordpress.com/2012/11/01/boids-in-c-xna/
> 1 votes

---
Tags: c#, xna-4.0, ai
---


# Question
Title: How are dependant quests generated in Guild Wars 2?
I recently read that Guild Wars 2 uses a system where the creation of quests depends on which actions user took when they were presented another quest. An example was: There might be a quest to protect a person. If users do not take this action, the person might be kidnapped and later there is a quest to rescue this person.

Is there any information on whether the creation of these quests is somehow automatic? From the article it sounded like automatically, but from the specific example you could also guess that people just created a task-set where they added conditions (Task 1 taken: OK; Task 1 not taken: Show Task 2).

From what I heard about AI they might also have implemented some sort of a huge neural network to make decisions?

# Answer
Where did you read this? It is quite incorrect.

In Guild Wars 2, your personal storyline ("quests") branch only at specific points designated by the designers. Those branches are gated on either your character creation choices (such as which class of society you hail from) or choices you make in conversations with important NPCs during your storyline.

All of the character creation choices are very explicitly spelled out in your character creation "mad lib" and all the conversation choices during the game have unique conversation icons and very explicit text saying "once you choose this you can't change your mind" (or similar).

Similarly, events that occur within the world have gating conditions whereby some of them will not start or become available without players having completed another event already, and other events are controlled by the success or failure of precursor events. For example, in the human starter zone, an event can occur where bandits try to poison a water supply. Two different subsequent events can occur depending on whether or not the player base manages to defend the water supply. This is entirely pre-scripted.

There is no AI or dynamic cleverness going on at all.
> 3 votes

---
Tags: mmo, rpg
---


title: Twitter integration

text:
# Question
Title: Twitter integration
My computer game is powered using Love2d in Lua, there is dead space in the menu of my game and I'd like to fill it up with something. So I'll like to put a twitter feed there, how can I receive all the twitter posts created by AND mentioned from @stickydestroyer; how can I make it look good and code the actual thing.

I know I have to use some sort of cURL module, but how can I get the feed AND make it looking nicely?

# Answer
> 3 votes
You'll probably want to use the REST API to recover a user timeline and/or a mentions timeline.

To make requests you'll probably want a socket and JSON API for Lua. You find a specific example involving the use of both of those APIs to talk to a different REST API (not Twitter's) here, which you can probably adapt to use for Twitter based on their documentation.

What you'll get from the Twitter endpoint is JSON data, which you can then format as appropriate to make it look nice within the context of your game.

---
Tags: lua, twitter
---


# Question
Title: Why are only some of my objects being rendered?
Every time I create a new asteroid the previous one is no longer rendered?

I did some debugging and printed out the size of Array-List 'Small' and when a new asteroid is created it doesn't go down, so the thread is still there it's just not being rendered, Why?

StatePlay:

```
    package me.bleedobsidian.astroidjump;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

public class StatePlay extends BasicGameState
{
    int stateID = 10;

    Player player;
    Asteroids asteroids;

    StatePlay(int stateID)
    {
       this.stateID = stateID;
    }

    @Override
    public int getID()
    {
        return stateID;
    }

    @Override
    public void init(GameContainer gc, StateBasedGame sbg) throws SlickException
    {
        ResManager.loadImages();
        player = new Player();
        asteroids = new Asteroids();
    }

    @Override
    public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException
    {
        g.setAntiAlias(true);
        player.render(g);
        asteroids.render(g);
        g.drawString("Asteroids: " + Asteroids.small.size(), 10, 25);
    }

    @Override
    public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException
    {
        player.update(gc, delta);
        asteroids.update(delta);
    }

}

```

Asteroids:

```
package me.bleedobsidian.astroidjump;

import java.util.ArrayList;
import java.util.Timer;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SpriteSheet;

public class Asteroids
{
    public static ArrayList<Asteroid_Small> small = new ArrayList<Asteroid_Small>();

    static SpriteSheet small_sprites = new SpriteSheet(ResManager.asteroids_small_ss, 32, 32);

    static Image small_1 = small_sprites.getSubImage(0, 0);
    static Image small_2 = small_sprites.getSubImage(1, 0);
    static Image small_3 = small_sprites.getSubImage(2, 0);
    static Image small_4 = small_sprites.getSubImage(3, 0);

    static boolean asteroids = true;

    static int diff = 0;

    Asteroids()
    {
        Task_Asteroids TaskA = new Task_Asteroids();
        Timer timer = new Timer("Asteroids");

        if(diff == 0)
        {
            timer.schedule(TaskA, 0, 4000);
        }
        else if(diff == 1)
        {
            timer.schedule(TaskA, 0, 3000);
        }
    }

    public static Image chooseSmallImage(int i)
    {
        if(i == 0)
        {
            return small_1;
        }
        else if(i == 1)
        {
            return small_2;
        }
        else if(i == 2)
        {
            return small_3;
        }
        else if(i == 3)
        {
            return small_4;
        }
        else
        {
            return small_1;
        }
    }

    public static void level_manager(float x)
    {
        if(x < 1000)
        {
            diff = 0;
        }
        else if(x < 2000)
        {
            diff = 1;
        }
        else if(x < 3000)
        {
            diff = 2;
        }
        else if(x < 5000)
        {
            diff = 3;
        }
        else if(x < 10000)
        {
            diff = 4;
        }
        else
        {
            diff = 5;
        }
    }

    public void update(int delta)
    {
        for(int s = 0; s < small.size(); s++)
        {
            Asteroid_Small as = small.get(s);
            as.update(delta);
        }
    }

    public void render(Graphics g)
    {
        for(int s = 0; s < small.size(); s++)
        {
            Asteroid_Small as = small.get(s);
            as.render(g);
        }
    }

    public static void setAsteroids(boolean tf)
    {
        asteroids = tf;
    }
}

```

Asteroid\_Small:

```
package me.bleedobsidian.astroidjump;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;

public class Asteroid_Small
{
    private static Image me;

    private static float x = 0;
    private static float y = 0;
    private static float speed = 0;
    private static float rotation = 0;
    private static float rotation_speed = 0;

    Asteroid_Small(Image i, float x, float y, float rs, float sp)
    {
        me = i;

        Asteroid_Small.x = x;
        Asteroid_Small.y = y;
        Asteroid_Small.rotation_speed = rs;
        Asteroid_Small.speed = sp;
    }

    public void update(int delta)
    {
        x -= speed * delta;
        rotation += rotation_speed * delta;

        me.setRotation(rotation);
    }

    public void render(Graphics g)
    {
        g.drawImage(me, x, y);
    }
}

```

Task\_Asteroid:

```
package me.bleedobsidian.astroidjump;

import java.util.TimerTask;

public class Task_Asteroids extends TimerTask
{
    public void run()
    {
        if(Asteroids.diff == 0)
        {
            int randImage = (int) (Math.random() * 4);
            int randHeight = (int) (Math.random() * 480);

            Asteroids.small.add(new Asteroid_Small(Asteroids.chooseSmallImage(randImage), Player.x + 960, randHeight, 0.05f, 0.04f));
        }
    }
}

```

# Answer
Have you used a `System.out.println(i)` call inside your asteroid render loop to check whether it is in fact being iterated over multiple times? -- If it's not that loop, it's something else.

Also, you may want to ensure that the positions of your asteroids are not overlapping, by building some minimal test case. That's more than likely where the problem lies -- it probably *is* rendering everything, but you just see it rendering one because they're overlapping.

Frankly, from long experience, I suspect that your problem comes in where you batch your asteroids into one big `Asteroids` object. That is not good structure. Having one class/struct per asteroid is, and then iterating through them as individual loops, in your `StatePlay` glass, in each of its `update` and `render` methods.
> 2 votes

---
Tags: java, lwjgl, slick
---


title: Creating a UML Diagram

text:
# Question
Title: Creating a UML Diagram
For part of an assignment, I'm creating a networked version of asteroids, I need to include a UML diagram for the design, tbh i dont even know where to begin. How do you start one off?

# Answer
UML (as an "assignment") is usually done for software engineering classes, right? And these usually want plain object orientied software design.

So start of with thinking what objects are there in the game and derive classes from them. Like there is a spaceship, so why not having a `Spaceship` class? Or there are asteroids flying around, so make an `Asteroid` class.

Of course these two were pretty obvious. A bit more difficult is stuff like the network manager (that one is still ok, you just have to think about what to send over the network and who is responsible), the collision management etc.

Actually, from what I experience this only comes out when you are trying it and see what works and what problems arise. Thus, I do not like UML diagrams that much. They are good, when you already know how something works, but definitely for somebody who just begins in an area. But it’s school, しかたがない (we cannot change it).

Maybe you also want to search for **Component-based game design**. However, it’s not that easy to understand (as there seem to be different flavours etc.) and I am still trying in practice how it works (best).

So much for the starting point. Hope you get on with it.

Also consider searching for random game framework tutorials on the net to see how game programs usually work. E.g. they are not event based (unlike usual window-click applications), but have a game loop. Some beginning frameworks in my eyes would be XNA for C# (good tutorial base) or pygame for Python.
> 3 votes

---
Tags: game-design
---


# Question
Title: Should I amortize scripting cost via bytecode analysis or multithreading?
I'm working on a game sort of thing where users can write arbitrary code for individual agents, and I'm trying to decide the best way to divide up computation time.

The simplest option would be to give each agent a set amount of time and skip their turn if it elapses without an action being decided upon, but I would like people to be able to write their agents decision functions without having to think too much about how long its taking unless they really want to.

The two approaches I'm considering are giving each agent a set number of bytecode instructions (taking cost into account) each timestep, and making players deal with the consequences of the game state changing between blocks of computation (as with Battlecode) or giving each agent it's own thread and giving each thread equal time on the processor.

I'm about equally knowledgeable on both concurrency and bytecode stuff, which is to say not very, so I'm wondering which approach would be best. I have a clearer idea of how I'd structure things if I used bytecode, but less certainty about how to actually implement the analysis. I'm pretty sure I can work up a concurrency based system without much trouble, but I worry it will be messier with more overhead and will add unnecessary complexity to the project.

# Answer
A casual analysis:

# Why threads?

Simply running each user's code in a separate thread is easy. But two threads don't always get equal processor time.

The classic example is to start two threads, one of which prints `A` and the other `B`. You'll see `ABABAB` a lot, but eventually `ABABBA` happens, sometimes even `ABBBA`, sometimes even `ABBBBA`. Most operating systems provide no guarantee that threads get equal time *in the short term*.

Depending on the game though, a small short-term advantage may be negligible.

# Why bytecode?

Bytecode restrictions get you closer to absolute fairness, as they are "closer to hardware", or as close as you'll likely want to get. Allowing only a certain number of bytecode instructions per tick from each entity is equivalent to implementing fair multithreading (except, of course, the loss of multi-core optimisations that the OS cannot do on custom "threads"). Battlecode allows 6000 bytecode instructions (of Java?) per tick.

Mojang's 0x10c (multiplayer, in development) emulates DCPU-16 architecture, which admittedly is a pretty ridiculous length to take this to. However, it is an example of going all the way to (at least virtual) hardware.

# tl;dr

If short-term differences are important, study the possibility of bytecode. Else threads.
> 4 votes

---
Tags: java, multithreading, metaprogramming
---


title: Windows Phone 7 Networked Game

text:
# Question
Title: Windows Phone 7 Networked Game
Im creating a multiplayer asteroids type game for the Windows Phone 7, 2 players can challenge each other over who will get the highest score. On each players phone the opponent is displayed and both go about shooting asteroids and enemies. In an assignment I have due I would like to talk about the packet design, what would be the least amount of info that I can send over the connection? Instead of constantly having to send each players position, asteroid position, bullet position and enemy position etc. Or would all that data constantly need to be sent?

# Answer
This is not trivial.

In general you want to make your game predictable. You also need to synchronize the clocks in both clients. If you do this there is no need to send the asteroids position every frame because both clients will be doing the same simulation. After a given number of frames you make sure that the simulations have not changed. Once you have done this you can send each player input and repeat the simulation of what happened in the other client exactly.

This is one of the most known articles and a good introduction. It's a postmortem on how they built Age of Empires multiplayer.

You can also check this fantastic one. The author has written a multiplayer Asteroids game. There is a second article in his website with more details.
> 2 votes

# Answer
You can send whatever you want. Typically you only need to send what has changed. You can also group things to send to minimize traffic.
> 0 votes

---
Tags: networking
---


title: FlasCC requirements and limitations?

text:
# Question
Title: FlasCC requirements and limitations?
It is now available for download. It says you need twice\* as many bits as I have. Why would you need more bits to compile code? Does that mean you need more bits to run flash games writtes with flasCC

Did anyone try it out and happens to know the answers?

http://gaming.adobe.com/technologies/flascc/

```
Minimum system requirements
    Flash Player 11 or higher
    Flex SDK 4.6 or higher
    Java Virtual Machine (64-bit)
Windows
    Microsoft® Windows® 7 (64-bit edition)
    Cygwin (included)

```

\*This is meant as a joke. however I do own a 32-bit laptop and I am wondering why you need 64-bit. Afaik - You only need 64-bit if you want to run a system that has more than 4gigs of memory. Why would any flash game require more than 4 gigs of memory.

The only system that is 64-bits and does not have 4gigs of memory that I can quickly recall is that hilarious Nintendo that came ages ago with a Motorola CPU.

# Answer
> 1 votes
64bit does not only mean access to more memory, it also means larger word size. So larger instructions. I'm not sure why FlasCC requires it, but it clearly does (as shown in the minumum system requirements).

I was able to run the demo on both x86 (32 bit) and x64 (64 bit) systems. So it appears the 64 bit is only required for the compiler.

# Answer
> 1 votes
My guess is that they are forward-looking and see that a 64-bit build will be needed eventually (esp. related to stuff like unreal engine), and don't want the hassle of supporting both 32bit and 64bit versions.

# Answer
> 1 votes
http://www.adobe.com/devnet/games/articles/flascc-tips-tricks.html

Adjust Java memory allocation

Although it is strongly recommended that you use 64-bit Java with flascc, some developers have been able to use 32-bit Java for certain, small applications. In this case, if the machine has limited memory, you may need to reduce the Java heap specification (the default is –jvmopt="-Xmx1500m") to a smaller number, for example, –jvmopt="-Xmx256m". You can do this when invoking GCC in the makefile. For example:

So there is a way. It is good to know people are able to run the demo. It would look lame if your app was 64-bit only in 2012 although it will be find in 2016 imho.

---
Tags: c++, flash, requirements, flascc
---


# Question
Title: Client AI calculations vs. Server AI calculations
I have been thinking about a game which would have an AI, and the AI would ideally do extensive calculations thinking many turns in advance. I am curious if there is some way to put most of the burden of the AI calculations on the client while still preventing cheating. Obviously some processing has to be done on the server, but is there a way to find some happy middle?

# Answer
> 4 votes
You are right that when a client does the AI calculations for its own player, it's an invitation for cheating. But what you could do, is make each client do the AI computations for randomly chosen other players.

Players could then still screw with the games of others, but as long as the computation tasks are sufficiently anonymized, there would be no incentive for them to do so. Should this still be a problem, you could send each computation task to three different random clients, and kick the one which returns a result different from the two others. That way a cheater needs at least two clients which cooperate AND be lucky enough that the server randomly assigns them the same computation task which ALSO happens to be worth manipulating.

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


title: Adapting Javascript game for mobile

text:
# Question
Title: Adapting Javascript game for mobile
I'm currently developing a Javascript web game for desktop users. It is a sort of tower-defense game that relies on mouse input only, developed on canvas using EaselJS. In the future, or perhaps simultaneously, I would like to adapt the game for mobile devices.

I can see at least 3 potential areas in shifting from desktop to mobile: 1. resolution size and UI rearrangement, 2. converting mouse events to touch events, 3. distribution as native app wrapper or mobile Web.

What would be the best strategy to facilitate this desktop to mobile conversion? For example, should I try to code the game for both platforms, or port the game UI over to mobile by branching the code base. Should I just publish on the mobile Web or wrap the game in a native app framework? And if I were to code for both platforms using the same codebase, should I register both click and touch events, or remap click events to touch using dispatchEvent?

# Answer
1) Resolution doesn't have to be an issue, depending on your game logic. If your world is "larger" then your screen resolution, simply create some way of moving the world left/right - up/down. You could also implement scaling depending on the resolution.

On a computer you can listen to keydown events, on a tablet you could use the tablets rotation to move the top down camera while you touch the screen on a specific place (button etc.) or you could use swipes to do this.

UI arrangement can indeed be quite different, mobile phones have less space then tablets, which have less space then 24" desktop monitors etc. I would try to make my interface be as 'hideable' as possible -\> when you click on a small icon of part of the screen the menu pops up.

2) Converting mouse events shouldn't be that big of an issue unless you are using right mouse button or drag/drop. If your game only responds to clicks then this could work on a mobile device by default.

3) Use phonegap or similar tool to publish html/js apps to multiple platforms at the same time. I don't know the specific requirements for the app to work with phonegap, but their site explains all.
> 3 votes

---
Tags: javascript, mobile
---


title: Generating triangles from a square grid

text:
# Question
Title: Generating triangles from a square grid
I have a 2D square grid of values representing terrain elevations, and I want to generate triangles from that grid to make a 3D view of the terrain. My first thought was to split each square diagonally into 2 triangles, however the split diagonal can clearly be seen, especially from the top :

Is there a recommended way to generate triangles to remove/reduce this effect ?

# Answer
> 4 votes
Your terrain reminds me of the practicle example (Height Interpolation) used in the Delaunay Triangulations chapter (PDF) of Computational Geometry: Algorithms and Applications. Although they generate an irregular triangle mesh from a height map, the part on *illegal edges* might still apply to your regular triangle mesh.

The idea is there are two ways you might flip the edge for every four neighbouring grid vertices (I'll refer to these as a *quad* later on). They define an edge as illegal *if we can locally increase the smallest angle by flipping that edge*. The chapter then leads up to using a Delaunay triangulation to get an illegal edge free mesh, but since you have a regular grid you can suffice by running through all *quads* and decide the splitting edge based on the length, like so:

```
def get_triangles(quads):
    # quad layout:
    # 0--1
    # |  |
    # 3--2
    for quad in quads:
        if quad[0] - quad[2] < quad[1] - quad[3]:
            # NW-SE edge is shortest
            yield triangle(quad[0],quad[2],quad[3]) # lower-left triangle
            yield triangle(quad[1],quad[2],quad[0]) # upper-right triangle
        else:
            # NE-SW edge is shortest
            yield triangle(quad[1],quad[2],quad[3]) # lower-right triangle
            yield triangle(quad[0],quad[1],quad[3]) # upper-left triangle

```

Choosing the shortest splitting edge should result in a more natural terrain with a relatively small amount of work.

**Bonus:** With a lot more work you can do even better by taking into account your height map's global features like peaks, ridges, valleys and drainage flow paths. For an introduction have a look at Section 3.2 and 3.5 of this article: Digital Elevation Models: overview and selected TIN algorithms.

# Answer
> 5 votes
It won't look good to you unless you tessellate the mesh more finely (use more triangles, use a bigger grid, and have the elevation changes go *much* slower)

Your normals are off a bit. To find smoothed normals at a vertex, you have to take *several* cross products at each vertex, sum the normals you find, then normalize that normal.

For example,

Here you would find the vectors `a`, `b`, `c`, `d`, and the normal at the center vertex would be:

```
n1 = a x b
n2 = b x c
n3 = c x d
n4 = d x a

finalNormal = (n1 + n2 + n3 + n4).normalize()

```

You could also use the other 4 (diagonal) vectors, but that is really overkill. If you use 4 vectors it will almost look the same as if you use 8 vectors.

# Answer
> 3 votes
I can think of a few approaches, here's a few in order of work required (but probably increased quality)

First: alternate edge direction; this should be easy to implement

```
.---.---.---.    .---.---.---.
| / | / | / |    | / | \ | / |
'---'---'---' -> '---'---'---'
| / | / | / |    | \ | / | \ |
'---'---'---'    '---'---'---'

```

Second: choose edge direction based on edge length. Check whether / or \ is shorter and pick that - or the longer one. Test and see which looks better. The bad side about this approach is that it requires a little bit more work.

Third: Implement algorithm to "turn edges". For each edge you find two triangles (on the both sides of the edge) which form a quadrilateral. The edge that splits said quad can be "turned" to form two different triangles. Note that the "turnable" edges include the original horizontal and vertical edges. Run several passes over the geometry to minimize the edge lengths.

Fourth: Discard squares to begin with and while your source data may still be square-based, just sample it for the height values based on some sampling algorithm. Point sampling is fine if you first scale your source data way up.

After discarding squares, things get more interesting; what kind of mesh to use? Hexagons? Subdivided polygons based on amount of noise within the polygons (so flat areas use less polys than bumpy ones)? Random data?

You may also want to pick up the classic, "Texturing & Modelling, procedural approach" http://www.amazon.com/Texturing-Modeling-Third-Edition-Procedural/dp/1558608486

# Answer
> 1 votes
Based on the image you provided, I would say that you are on the right track, and the next step is to enable smooth shading on the mesh. Currently, you are seeing hard edges in the lighting on adjacent triangles because each triangle is being flat shaded. The normal of only one of the vertices is being used to do lighting calculations, rather than the normals of all three vertices being interpolated across the face of the triangle (or the lighting at each vertex being interpolated, depending on whether you're using per-pixel or per-vertex lighting, respectively).

In older OpenGL implementations, enabling smooth (Gourard) shading would be done with the following line:

```
glShadeModel(GL_SMOOTH);

```

but note that this is now deprecated in favor of the programmable pipeline. Fear not, though, as it will still work if you work with an older OpenGL library (and it may also be supported in the most recent version; someone may correct me if I'm wrong about that). To go off on a brief tangent, learning OpenGL via the deprecated immediate mode is sometimes preferred because it's a little more straightforward than the programmable pipeline.

Anyway, the smooth shading is also dependent upon the normals of your vertices being set correctly, which seems to already be happening, upon examination of your image. If, for whatever reason, they are not quite correct, I'd be happy to update this answer to provide some direction on how to calculate them.

Hope this helps :)

Update: To calculate the normals for proper lighting, you can use the following rule: the normal for a vertex is equal to the average of the *face* normals of the triangles it is a part of. The face normal of a triangle is calculated by taking the cross-product of two of its edges. So, for one of the corners of your mesh:

```
A-----B
|   .`|
| .`  |
C`----D

```

You can calculate the face normal of `ABC` by taking `BA x BC`, and the face normal of `BCD` to by taking `BC x BD`. Averaging the two resulting vectors together and normalizing the result gets you the normal for `B`. For vertices in the middle of the mesh, you will be calculating and averaging the face normals of eight triangles. Note that this is the method which bobobobo provided in his answer. I hope that this summary acts as a good complement to it.

For this kind of calculation, it really pays to store your mesh in a Half-Edge data structure. This makes traversal of the triangles much easier, and also allows you to implement subdivision and decimation of the mesh in case you need it later on.

---
Tags: opengl, terrain, grid, tessellation
---


# Question
Title: GestureListener's fling method doesn't get called
I'm using `SimpleGestureDetector` from the libgdx-users Wiki as my `InputProcessor`. I set it in the `created()` method:

```
Gdx.input.setInputProcess(new SimpleDirectionGestureDetector(charController));

```

`charController` is my class which implements the `DirectionListener` interface defined in the `SimpleDirectionGestureDetector` class and it is responsible for moving the player character. However the character doesn't change direction when I'm performing a fling action in any direction. I've checked and the `fling()` method in the `SimpleDirectionGesture` class doesn't get called and I have no idea why, since everything seems good. What am I doing wrong?

# Answer
Hope this will help you. If not - let me know, maybe I will make small test app for you.
> 0 votes

---
Tags: java, android, libgdx, touch
---


# Question
Title: If statement causing xna sprites to draw frame by frame
I’m a bit new to XNA but I wanted to write a simple program that would fire a cannon ball from a cannon at a 45 degree angle. It works fine outside of my keyboard i/o if statement, but when I encapsulate the code around an if statement checking to see if the user hits the space bar, the sprite will draw one frame at a time every time the space bar is hit.

This is the code in question

```
if (currentKeyboardState.IsKeyUp(Keys.Space) && previousKeyboardState.IsKeyDown(Keys.Space) && !skullBall.Alive)
        {
            //works outside the keyboard input if statement   //{
            skullBall.Position = cannon.Position;
            skullBall.DeltaY = -(float)(Math.Sin(MathHelper.ToRadians(45)) * 50/*39.7577*/ * time + 0.5 * (gravity * (time * time)));
            skullBall.DeltaX = (float)(Math.Cos(MathHelper.ToRadians(45)) * 50/*39.7577*/ * time);
            skullBall.Alive = true;           //}
        }

```

The skull ball represents the cannon ball and the cannon is just the starting point. DeltaX and DeltaY are the values I’m using to update the cannon balls position per update. I know it's dumb to have the cannon ball start at the cannons position every time the update is called but it’s not really noticeable right now.

I was wondering if after examining my code, if anyone noticed any errors that would cause the sprite to display frame by frame instead of drawing it as a full animation of the cannon ball leaving the cannon and moving from there.

# Answer
```
if (currentKeyboardState.IsKeyUp(Keys.Space) && previousKeyboardState.IsKeyDown(Keys.Space) && !skullBall.Alive)

```

Every frame the above statement is checked and of course its only true when you've pressed the space bar while it was depressed last frame. So all the code in the statement is indeed only executed once every time that you press space bar.

I think this is what you meant to write

```
if (currentKeyboardState.IsKeyUp(Keys.Space) && previousKeyboardState.IsKeyDown(Keys.Space) && !skullBall.Alive)
{
    skullBall.Position = cannon.Position;
    skullBal.Alive = true;
}

if(skullBal.Alive)
{
    skullBall.DeltaY = -(float)(Math.Sin(MathHelper.ToRadians(45)) * 50/*39.7577*/ * time + 0.5 * (gravity * (time * time)));
    skullBall.DeltaX = (float)(Math.Cos(MathHelper.ToRadians(45)) * 50/*39.7577*/ * time);
}

```

Try to think more about why this works and your original code doesn't. You have to think what needs to happen frame-by-frame and programming accordingly. Think of behaviour but don't directly implement but deconstruct into decisions that can be made each frame.
> 2 votes

---
Tags: xna, sprites, input, keyboard
---


# Question
Title: How do I run my XBOX XNA game without a network connection?
I need to demo my XBOX XNA game in college. The college doesn't allow this type of device to connect to the network. I deployed my game to the Xbox and it is sitting in the games list along with my other games. It runs fine with a network connection but when its offline it comes up with an error message saying its needs a connection to run the game.

This makes no sense, the game is deployed on the Xbox memory, it must be some security policy or something!

Is there any way around this? The demo is on monday!

# Answer
> 5 votes
Basically you're out of luck. XBLIG games, whether published or unpublished, require an Internet connection to run. I see two alternatives:

1) Use a mobile phone to set up your own mini-network and somehow give your Xbox an Internet connection.

2) Use a laptop to demo your game instead. XNA games run on PC. Xbox controllers can be plugged into a PC via USB (if your controllers are wireless you need to buy a receiver). Laptops can be plugged into external displays, if that's a needed feature (and most colleges should be well-equipped for plugging laptops into projectors already).

---
Tags: xna, networking, xbox, deployment
---


# Question
Title: How can I derive force vectors from velocity vectors?
I'm making a 2d shooter ala Geometry Wars. I've got my own simple physics at work driving the background grid and all my entities. To move anything in the world I apply a Vector2d force to it. The 'engine' calculates the resulting acceleration and therefore the velocity.

I am trying to port some code I found which implements the classic 'Boids' flocking algorithm, but the code I have works by calculating the Boids' velocities directly, so If i use it as is, it bypasses my physics engine. How I can translate the velocity vectors into force vectors that I can apply to the Boids and which will result in the proper velocities via my physics engine.

# Answer
> 6 votes
It depends how your physics engine works, but you can probably use Newton's second law:

```
F = m × a

```

Where `m` is the mass of the object and `a` is its acceleration (a vector). The acceleration is the `dv/dt` derivative, which can be approximated by dividing the change in velocity by the timestep:

```
F = m × (velocity - previous_velocity) / timestep

```

Of course this only works reliably if the force you're applying is the only one affecting the entity. Otherwise you may experience numerical inaccuracies.

---
Tags: xna, physics
---


# Question
Title: Question on the implementation of my Entity System
I am currently creating an Entity System, in C++, it is almost completed (I have all the code there, I just have to add a few things and test it). The only thing is, I can't figure out how to implement some features. This Entity System is based off a bit from the Artemis framework, however it is different.

I'm not sure if I'll be able to type this out the way my head processing it. I'm going to basically ask whether I should do something over something else.

Okay, now I'll give a little detail on my Entity System itself. Here are the basic classes that my Entity System uses to actually work:

* Entity - An Id (and some methods to add/remove/get/etc Components)
* Component - An empty abstract class
* ComponentManager - Manages ALL components for ALL entities within a Scene
* EntitySystem - Processes entities with specific components
* Aspect - The class that is used to help determine what Components an Entity must contain so a specific EntitySystem can process it
* EntitySystemManager - Manages all EntitySystems within a Scene
* EntityManager - Manages entities (i.e. holds all Entities, used to determine whether an Entity has been changed, enables/disables them, etc.)
* EntityFactory - Creates (and destroys) entities and assigns an ID to them
* Scene - Contains an EntityManager, EntityFactory, EntitySystemManager and ComponentManager. Has functions to update and initialise the scene.

Now here's the issue(s)... in order for an EntitySystem to efficiently know when to check if an Entity is valid for processing (so I can add it to a specific EntitySystem that wants the Entity), it must recieve a message from the EntityManager (after a call of activate(Entity& e)). Similarly the EntityManager must know when an Entity is destroyed from the EntityFactory and the ComponentManager must know when an Entity is created AND destroyed from/in a Scene.

I do have a Listener/Observer pattern implemented at the moment, but with this pattern I may remove a Listener (which is this case is dependent on the method being called). I mainly have this implemented for specific things related to a game, i.e. Teams, Tagging of entities, etc. So... I was thinking maybe I should call a private method (using friend classes) to send out when an Entity has been activated, deleted, etc.

i.e. taken from my EntityFactory

```
void EntityFactory::killEntity(Entity& e)
{
      // if the entity doesn't exsist in the entity manager within the scene
      if(!getScene()->getEntityManager().doesExsist(e))
      {
         return; // go back to the caller! (should throw an exception or something..)
      }

      // tell the ComponentManager and the EntityManager that we killed an Entity
      getScene()->getComponentManager().doOnEntityWillDie(e);
      getScene()->getEntityManager().doOnEntityWillDie(e);

      // notify the listners
      for(Mouth::iterator i = getMouth().begin(); i != getMouth().end(); ++i)
      {
              (*i)->onEntityWillDie(*this, e);
      }

      _idPool.addId(e.getId()); // add the ID to the pool
      delete &e;                // delete the entity
}

```

As you can see on the lines where I am telling the ComponentManager and the EntityManager that an Entity will die, I am calling a method to make sure it handles it appropriately. Now I realise I could do this without calling it explicitly, with the help of that for loop notifying all listener objects connected to the EntityFactory's Mouth (an object used to tell listeners that there's an event), however is this a good idea (good design, or what)?

I've gone over the PROS and CONS, I just can't decide what I want to do.

# Calling Explicitly:

## PROS

* Faster?
* Since these functions are explicitly called, they can't be "removed"

## CONS

* Not flexible
* Bad design? (friend functions)

# Calling through Listener objects

(i.e. ComponentManager/EntityManager inherits from a EntityFactoryListener)

## PROS

* More Flexible?
* Better Design?

## CONS

* Slower? (virtual functions)
* Listeners can be removed, i.e. may be removed and not get called again during the program, which could cause in a crash.

P.S. If you wish to view my current source code, I am hosting it on BitBucket.

# Answer
> 5 votes
What's critical to understand is that **any** event dispatcher / listener type system, already has a loop running inside it's implementation (or is part of a greater loop such as your update loop), polling periodically to see whether any event dispatches have been received, and in that case direct the call to the attached listeners / handlers. The only difference between that loop and your code is that you don't generally see that loop, if it's a language feature or part of an external library. But it is there.

Take for instance Java and C#. In C#, there is a delegates system which handles this polling internally, under the hood. In Java, however, there are no special keywords or mechanisms to do this -- you simply set it up yourself. The Java event dispatch/listen paradigm is very useful to understand, because it shows you exactly what is going on under the hood in languages like C# and Flash/AS3/JS.

So my advice to you is: If you've no explicit event subsystems already in place, then just poll per update. That way, you have just one loop -- your game loop. Of course, you can wrap this polling per update up in an event listener system if that is more comfortable for you (see my comments in the final paragraph). Ultimately, it's much the same thing. If you already have background code managing an event dispatcher / handler subsystem, then make use of what is already there.

The reason I suggest that you avoid additional looping is that conditionals are costly operations. So the fewer loop iterations, the better.

Overall, I would always recommend that you set up and use an event listener system if possible, as architecturally this is a good choice and abstracts this concept into it's own set of classes. Event listeners will run through an extant list of functor-based handlers to call, rather than explicitly checking some constant `n` memory locations for nullity first before referencing the functor in question. IMO this alone is worth the trouble.

You might also consider something like the signals pattern.

# Answer
> 3 votes
I am also using Artemis as the basis for a C++ game and I had a similar consideration. Looking at your source code and knowing Artemis, EntitySystems will want to be notified about Entities being added/removed/activated/deactived. Rather than propogate this information through events you could use either signal/slots (boost has an implementation and you appear to have that as a dependency already) or simple function pointers.

For instance, your EntityFactory could have "lifecycle" signal:

```
    enum SignalType {
        ENTITY_ADDED = 0,
        ENTITY_CHANGED = 1,
        ENTITY_DELETED = 2,
        ENTITY_ENABLED = 3,
        ENTITY_DISABLED = 4
    };

typedef boost::signals2::signal<void (SignalType, EntityPtr)> EntityLifecycleSignal;

```

Any class interested in lifecycle updates would need to implement a slot method:

```
 void EntityStatusChange(SignalType signalType, EntityPtr entityPtr);

```

Then your EntityFactory can raise the signal as appropriate:

```
// tell the ComponentManager and the EntityManager that we killed an Entity
  getScene()->getComponentManager().doOnEntityWillDie(e);
  getScene()->getEntityManager().doOnEntityWillDie(e);
entityLifecycleSignal(ENTITY_DELETED, e);

```

Another thing to consider is changing it such that each EntitySystem maintains an intrusive linked list of entities that it cares about (determined via Aspects) and a single entity is capable of being added to multiple EntitySystems. When an entity is destroyed it can simply be unliked in place without notifying the systems. So your code example might look something like this:

```
  // tell the ComponentManager and the EntityManager that we killed an Entity
  getScene()->getComponentManager().doOnEntityWillDie(e);
  getScene()->getEntityManager().doOnEntityWillDie(e);

  //Unlink from all EntitySystems
  e->entitySystem1Link.Unlink();
  e->entitySystem2Link.Unlink();
  .....

  _idPool.addId(e.getId()); // add the ID to the pool
  delete &e;                // delete the entity

```

You might also add said logic to the destructor. Initially I rolled my own intrusive linked list implementation but then, wisely I think, switched to the one discussed here: http://www.codeofhonor.com/blog/avoiding-game-crashes-related-to-linked-lists

With this strategy an entity can easily be added and removed from one or more EntitySystems without the need for event notifications or even a multitarget callback. Looking at your source though, it appears you intend to give EntitySystems a hook to do custom code when an entity is removed:

```
            void EntitySystem::remove(Entity& e)
            {
                    _entitiesToProcess[e.getId()] = NULL;

                    // call the virtual fn
                    onRemovedEntity(e);
            }

```

If you want to maintain this hook you are back to multitarget callback.

# Answer
> 0 votes
# Don't Change Anything

You missed one serious PRO of calling your entity manager explicitly: easy predictability. Well, you did mention "can't be removed," but it's so much more than that.

Given that in order for this entire entity system to work, you require that `EntityFactory` and `EntityManager` collaborate to manage the lifecycle of `Entity` objects, and other objects being able to subscribe to `Entity::killEntity` events is merely a way for other code to hook into this event, your initial approach is what I would have done.

What if you unintentionally add a listener in the wrong order? What if you unintentionally remove the `EntityManager` listener? Yeah, the answer to those questinos are "Don't do that!" but separating a call that is ***absolutely required*** from calls that are purely optional is a good, and pretty basic, defensive programming technique. Don't cause problems for yourself in order to adhere to some sort of pure architecture.

# Maybe Change Something

You might want to actually consider putting the `entityManager->doOnEntityWillDie(e)` calls after you've iterated through the listeners. This would be treating the `entityManager->doOnEntityWillDie(e)` as part of the "dying" process by convention.

You could even provide `willDie` and `hasDied` signal slots/virtual calls.

---
Tags: c++, architecture, entity-system
---


title: How do I draw a dotted or dashed line?

text:
# Question
Title: How do I draw a dotted or dashed line?
I'm trying to draw a dashed or dotted line by placing individual segments(dashes) along a path and then separating them. The only algorithm I could come up with for this gave me a dash length that was variable based on the angle of the line. Like this:

```
private function createDashedLine(fromX:Float, fromY:Float, toX:Float, toY:Float):Sprite
{
    var line = new Sprite();
    var currentX = fromX;
    var currentY = fromY;
    var addX = (toX - fromX) * 0.0075;
    var addY = (toY - fromY) * 0.0075;
    line.graphics.lineStyle(1, 0xFFFFFF);

    var count = 0;

    // while line is not complete
    while (!lineAtDestination(fromX, fromY, toX, toY, currentX, currentY))
    {
        /// move line draw cursor to beginning of next dash
        line.graphics.moveTo(currentX, currentY);

        // if dash is even
        if (count % 2 == 0)
        {
            // draw the dash
            line.graphics.lineTo(currentX + addX, currentY + addY);
        }

        // add next dash's length to current cursor position
        currentX += addX;
        currentY += addY;

        count++;
    }
    return line;
}

```

This just happens to be written in Haxe, but the solution should be language neutral. What I would like is for the dash length to be the same no matter what angle the line is. As is, it's just adding 75 thousandths of the line length to the x and y, so if the line is and a 45 degree angle you get pretty much a solid line. If the line is at something shallow like 85 degrees then you get a nice looking dashed line. So, the dash length is variable, and I don't want that. How would I make a function that I can pass a "dash length" into and get that length of dash, no matter what the angle is?

If you need to completely disregard my code, be my guest. I'm sure there's a better solution.

EDIT: To clarify, I can't use vectors (unless they're easy to implement, I'm not even sure how vec2 works) also I'd like the dash length to be based on neither line rotation NOR line length. So, no scaling the line to get the dash length.

# Answer
> 3 votes
I would generate such a dashed line with two vectors.

First create a normalized vector that indicates the direction of your line.

```
vec2 lineVec = vec2(toX-fromX, toY-fromY)

```

Then split that into two scaled vectors to represent the visible part of the line and the gaps.

```
vec2 dashVec = lineVec.scale(lineSize)
vec2 gapVec = lineVec.scale(gapSize)

```

Then simply alternate between the two as you step out creating vertices along the way.

```
length = 0
position = lineStartPosition

while(length < maxLength)
   addVertex(position) //start of dash and end of gap
   position += dashVec //space out the dash
   addVertex(position) //end of dash and begining of gap
   position += gapVec //space out the gap
   length += dashVec.length + gapVec.length
addVertex(position) //to cap off the line

```

You may want to check the end position more accurately, since this can easily go over the maximum length. In theory (if I'm not missing something) this would give you equal length lines no matter the rotation.

---
Tags: mathematics, lines
---


# Question
Title: how to move the camera behind a model with the same angle? in XNA
I'm having difficulty moving my camera behind an object in a 3D world. I'd like to have two view modes:

1. for fps (first person).
2. external view behind the character (third person).

I've searched the net for examples but they don't work in my project.

Here is my code used to change the view when F2 is pressed:

```
 //Camera
        double X1 = this.camera.PositionX;
        double X2 = this.player.Position.X;
        double Z1 = this.camera.PositionZ;
        double Z2 = this.player.Position.Z;

        //Verify that the user must not let the press F2
        if (!this.camera.IsF2TurnedInBoucle)
        {
            // If the view mode is the second person
            if (this.camera.ViewCamera_type == CameraSimples.ChangeView.SecondPerson)
            {
                this.camera.ViewCamera_type = CameraSimples.ChangeView.firstPerson;

                //Calcul position - ?? Here my problem
                double direction = Math.Atan2(X2 - X1, Z2 - Z1) * 180.0 / 3.14159265;
                //Calcul angle - ?? Here my problem

                this.camera.position = ..
                this.camera.rotation = ..

                this.camera.MouseRadian_LeftrightRot = (float)direction;
            }
            //IF mode view is first person
            else
            {
                    //....

```

# Answer
You try to calculate the angle between the current camera position and the current player position but `Math.Atan2` returns a radian so you don't need the `* 180 / PI` part so that part is wrong.

However I don't know why you need the angle between the camera position and the player position. Assuming the camera points forward as seen from the player:

From 1st person to 3rd person you just need to do something like this:

`camera.Position = camera.Position - Vector3.Normalize(Camera.LookAt) * distance + Vector3.Up * height`

This will place the camera `distance` behind the player and will move the camera up by `height`.

From 3rd person to 1st person:

`camera.Position.X = player.Position.X` `camera.Position.Z = player.Position.Z` `camera.Position.Y = camera.Position.Y - Vector3.Up * -height`

This will move the camera back to the position of the player and will lower it to the original height.
> 2 votes

---
Tags: xna, c#, 3d, rotation
---


# Question
Title: Drawing a texture at the end of a trace (crosshair?) UDK
I'm trying to draw a crosshair at the end of my trace.

If my crosshair does not hit a pawn or static mesh (ex, just a skybox) then the crosshair stays locked on a certain point at that actor - I want to say its origin.

Ex: Run across a pawn, then it turns yellow and stays on that pawn. If it runs across the skybox, then it stays at one point on the box. Weird?

How can I get my crosshair to stay consistent? I've included two images for reference, to help illustrate.

Note: The wrench is actually my crosshair. The "X" is just a debug crosshair. Ignore that. /// Image 1 /// /// Image 2 ///

```
/***************************************************************************
* Draws the crosshair
***************************************************************************/
function bool CheckCrosshairOnFriendly()
{
local float             CrosshairSize;
local vector            HitLocation, HitNormal, StartTrace, EndTrace, ScreenPos;
local actor             HitActor;
local MyWeapon          W;
local Pawn              MyPawnOwner;

/** Sets the PawnOwner */
MyPawnOwner = Pawn(PlayerOwner.ViewTarget);
/** Sets the Weapon */
W = MyWeapon(MyPawnOwner.Weapon);

/** If we don't have an owner, then get out of the function */
if ( MyPawnOwner == None )
{
    return false;
}

/** If we have a weapon... */
if ( W != None)
{
    /** Values for the trace */
    StartTrace = W.InstantFireStartTrace();
    EndTrace = StartTrace + W.MaxRange() * vector(PlayerOwner.Rotation);
    HitActor = MyPawnOwner.Trace(HitLocation, HitNormal, EndTrace, StartTrace, true, vect(0,0,0),, TRACEFLAG_Bullet);
    DrawDebugLine(StartTrace, EndTrace, 100,100,100,);

    /** Projection for the crosshair to convert 3d coords into 2d */
    ScreenPos = Canvas.Project(HitLocation);

    /** If we haven't hit any actors... */
    if ( Pawn(HitActor) == None )
    {
        HitActor = (HitActor == None) ? None : Pawn(HitActor.Base);
    }
}

/** If our trace hits a pawn... */
if ((Pawn(HitActor) == None))
{
    /** Draws the crosshair for no one - Grey*/
    CrosshairSize = 28 * (Canvas.ClipY / 768) * (Canvas.ClipX /1024);
    Canvas.SetDrawColor(100,100,128,255);
    Canvas.SetPos(ScreenPos.X - (CrosshairSize * 0.5f), ScreenPos.Y -(CrosshairSize * 0.5f));
    Canvas.DrawTile(class'UTHUD'.default.AltHudTexture, CrosshairSize, CrosshairSize, 600, 262, 28, 27);
    return false;
}

    /** Draws the crosshair for friendlies - Yellow */
    CrosshairSize = 28 * (Canvas.ClipY / 768) * (Canvas.ClipX /1024);
    Canvas.SetDrawColor(255,255,128,255);
    Canvas.SetPos(ScreenPos.X - (CrosshairSize * 0.5f), ScreenPos.Y -(CrosshairSize * 0.5f));
    Canvas.DrawTile(class'UTHUD'.default.AltHudTexture, CrosshairSize, CrosshairSize, 600, 262, 28, 27);
    return true;

```

}

# Answer
If you aren't hitting anything, your HitLocation will be vect(0,0,0). In cases like this, you just need a:

```
if(HitActor == none)
{
   HitLocation = EndTrace;
}

```
> 1 votes

---
Tags: game-mechanics, udk, unreal
---


title: Input/Output console window in XNA

text:
# Question
Title: Input/Output console window in XNA
I am currently making a simple game in XNA but am at a point where testing various aspect gets a bit tricky, especially when you have to wait till you have 1000 score to see if your animation is playing correctly etc. Of course i could just edit the starting variable in the code before I launched but I have recently been interested in trying to implement a console style window which can print out values and take input to alter public variables during run-time.

I am aware that VS has the immediate window which achieves a similar thing but i would prefer mine is an actual part of the game with the intention that the user may have limited access to it in the future.

Some of the key things i have yet to find an answer to after looking around for a while are:

* how i would support free text entry
* how i would access variables during runtime
* how i would edit these variable

I have also read about using a property grid from windows form aps (and partially reflection) which looked like it could simplify a lot of things but i am not sure how I would get that running inside my XNA game window or how i would get it to not look out of place (as the visual aspect of is seems to be aimed just for development time viewing).

All in all I'm quite open to any suggestions on how to approach this task as currently I'm not sure where to start. Thanks in advance.

# Answer
> 4 votes
I use `XNAGameConsole`.

http://code.google.com/p/xnagameconsole/

It was written for XNA 3.1, but I updated it to XNA 4.0. You can find those changes here:

http://code.google.com/r/jameswalkoski-xnagameconsole-xna4/source/browse

# Answer
> 3 votes
You could also simply use AllocConsole.

AllocConsole is a Win32 Windows native function. In short, the AllocConsole method allows you to allocate a standard Windows console to the calling process. Once you have done this, you can use standard C# console input/output within your application using `Console.ReadLine()`, `Console.WriteLine()`, etc.

To use this method you need to use using `System.Runtime.InteropServices;`

Shortened Example:

```
using System.Runtime.InteropServices;

[DllImport("kernel32")]
static extern bool AllocConsole();

private void Form1_Load(object sender, EventArgs e)
{
    AllocConsole();
    Console.WriteLine("Hello Console!");
}

```

More info regarding the native function is here: MSDN

# Answer
> 0 votes
All of the below is assuming Windows development.

1. Right click your game in the solution explorer and click properties.
2. Click the application tab.
3. Change the `Output Type` to `Console Application`.

You would have to write a command parser or use an existing one. Your code that takes in the command will have to parse it and then perform some action that you have given it. I've used this project for command paring and found it very useful. I don't think there is any automated way to change the variables.

# Answer
> 0 votes
You could add a scripting engine that can change your variables on the fly and contains an immediate mode. There are implementations of LUA and other scripting languages that are portable to XNA.

Not to self advertise but I had this same problem so I've recently added a JavaScript interpreter to XNA Its not 100% bug free, but you can take it for a spin and then port it to your game. I think it's exactly what you need. http://roy-t.nl/index.php/2012/06/05/using-javascript-as-a-script-engine-in-xnac/

# Answer
> 0 votes
A very simple approach to this is displaying the desired variables as text on the game screen, using SpriteBatch.DrawString(). Of course, this does not readily allow for input. You can, however implement an in-game console if you want to give the player access to your commands.

---
Tags: c#, xna, input, code-reflection
---