title: How to do this sprite motion blur?

text:
# Question
Title: How to do this sprite motion blur?
Some of you may know fraxy...

Basically, I was watching this video: http://www.youtube.com/watch?v=uL7zWdDCtOE And there are some times where some sprites spin really fast (4:00 mark for example), and I cannot figure how the motion blur effect was done.

I looked in the game folder, and found the sprite, it certainly does not has the blur added to it (in fact, it is even a .bmp! Not a PNG or anything that supporta alpha natively), and the engine IF using OpenGL, may not be clear (the resolution is fairly low too), also nothing else is getting blurred (so the effect is localized to some sprites... if you pay attention there are other moving objects that get blurry too).

So, how they do this glowing blur?

EDIT: On the video I am talking about the two things "spinning" in the left and right edge of the screen, they are shooting, and the sprite of their bullets are the same as their own sprite, but if you pay attention as they spin their sprites leave a trail, actually if you put the video some seconds before, you will see with the screen more empty, and the effect can be seen clearly.

EDIT2: I don't think Fraxy use shaders, and I am sure it does not use OpenGL either (since it run on computers that don't run OpenGL games). I know it is easy to do with shaders, with per-pixel calculations, I am asking how to do WITHOUT them.

# Answer
> 11 votes
Difficult to tell from the video exactly what you mean, but the simplest method of doing a sprite-based motion blur would just be to render the sprite several times, with some form of translucency.

You could buffer the previous positions for use as the trail, or you could use a small time-step in the animation to render sub-frames.

From the video in question I'd suggest a basic additive blend would work, which means you don't need alpha either in the texture or even in the vertex - just darken the sprite for the "trail".

Over-writing the same pixels makes them brighter, for the glow. If you have even a very dark glow around the object in the original image, you'll get a glowing halo if you additively blend a bunch together.

Alternatively you could use a basic HDR-like hack as a post-process. Take the image without any glow, threshold it so you only have very bright pixels, blur it a lot, and add it back in to the original. TBH I don't think that's necessary here.

# Answer
> 1 votes
I couldn´t see what you meant in the video, but for doing some motion blur I would store the sprites motion vectors and use then to do the blur. Rendering the sprite multiple times don´t look that good in my opnion.

If the sprite is spinning you would need the motion vectors for each pixel and this can be costly.

# Answer
> 0 votes
Doing this with out a shader is going to be costly anyway. The only non costly way of doing this is without shaders is using multiple sprites as explained by Jason D. If you place the sprites progressively over the image you will still get the effect you are looking for with spinning sprites.

# Answer
> 0 votes
JasonD's answer was also acceptable for me.

Here is the code block I wrote. I create 2 extra sprites and put delay of 1-3 frames and see the effect I want:

```
public class BlurFollower : MonoBehaviour {

  //Generally values between 2-4 are well for me.
  public int DelayInFrames;
  //The sprite that we will follow
  public SpriteRenderer TargetSpriteRenderer;
  //The transparent sprite that will follow target
  public SpriteRenderer GhostSpriteRenderer;

  Vector3[] _positions;
  int[] _sortOrders;

  void Awake () {
    //At the begining there are no sprites
    GhostSpriteRenderer.enabled = false;
    _positions = new Vector3[DelayInFrames];
    _sortOrders = new int[DelayInFrames];
  }

  //when wait time (enough frames passed) this will be set true.
  bool delayCompleted = false;
  //frame counter
  int  count;

  void Update () {

    //Record targets position and sorting order.
    //You may also record sprite if you need it.
    _positions[count] = TargetSpriteRenderer.transform.position;
    _sortOrders[count] = TargetSpriteRenderer.sortingOrder;

    //Increase frame counter
    count++;
    //If we waited enough; open the ghost image.
    if (count == DelayInFrames) {
      count = 0;
      if (!delayCompleted) {
        delayCompleted = true;
        GhostSpriteRenderer.enabled = true;
      }
    }
    //Now counter is referencing to oldest positions/orders we have; so use them:
    if (delayCompleted) {
      GhostSpriteRenderer.transform.position = _positions[count];
      GhostSpriteRenderer.sortingOrder = _sortOrders[count];
    }
  }
}

```

---
Tags: graphics, graphics-programming, graphic-effects, special-effects
---


# Question
Title: Very weird C#/XNA bug, not drawing a magenta dot
My C# code is drawing all the colored dots except the magenta one. Here's the code:

```
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+20), 2, 0, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+22), 2, 1, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+24), 2, 2, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+26), 2, 3, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+28), 2, 4, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+30), 2, 5, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+32), 2, 6, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+34), 2, 7, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+36), 2, 8, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+38), 2, 9, A); // this is the only one not showing up
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+40), 2, 10, A);
        scr_draw_dot((Int16)(mmbxo-20), (Int16)(mmbyo+42), 2, 11, A);

```

The scr\_draw\_dot code:

```
    public void scr_draw_dot(Int16 xx, Int16 yy, byte ds, byte cn, float A)
    {
        for (byte j = 0; j < ds; j += 1)
        {
            for (byte i = 0; i < ds; i += 1)
            {
                // TODO: major weird bug here, not drawing the pink dot (cn == 9)
                oGcn.TG.scr_dpp(oGcn.TG.Tiles_Dots, (Int16)(xx+i), (Int16)(yy+j), cn, 0, 1, 1, Color.White*A);
            }
        }
    }

```

and the scr\_dpp code from TG:

```
    public void scr_dpp(Texture2D pic, Int16 xx, Int16 yy, Int16 sx, Int16 sy, Int16 sw, Int16 sh, Color C) // draw pic partial
    {
        if (pic == null)
            return;

        // this draws a piece of a picture taken from the source (s) xywh and drawn at xx yy
        SB.Draw(pic, new Vector2(xx, yy), new Rectangle(sx, sy, sw, sh), C);
    }

```

The pic used (Tiles\_Dots) is a little unusual. It's a 13x1 PNG file that holds 13 colored dots. The tenth dot (index 9) is magenta. Here's a screenshot:

I already checked the PNG for transparent alpha in the magenta dot and did not find it. What on Earth could be causing this bug?

Some more info: originally XNA 4.0, but actually using MonoGame now with DirectX 10 targetting .Net 4.0. I still use XNA to compile the .XNB files such as that Tiles\_Dots. This is a 100% 2D game, not 3D, and I use the scr\_dpp (draw pic partial) everywhere to draw pieces or frames from a grid of animations. Never had a problem with it until now.

Screen shot of what's being drawn:

I blew up the minimap so you can see the pink dot is missing. BTW, that orange dot on the checkered minimap represents the orange chess piece, and there are supposed to be pink dots for the pink chess pieces too. The first code block earlier was drawing a vertical line of dots for testing purposes.

**EDIT:** here's the draw code, which indeed switches rendertargets:

```
    protected override void Draw(GameTime dt)
    {
        GraphicsDevice.SetRenderTarget(RENTAR); // change rendertarget BEFORE SB.begin

        if (GGG.GameState == GCN.GSType.Level)
        {
            SB.Begin();
            GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
            GraphicsDevice.Clear(Color.Transparent);

            GGG.scr_draw_levelshadows();
            SB.End();
        }

        GraphicsDevice.SetRenderTarget(null); // change rendertarget NOT INSIDE SB.begin SB.end

        SB.Begin();
        GraphicsDevice.Clear(Color.White);
        GGG.scr_draw();

        if (GGG.GameState == GCN.GSType.Level)
        {
            float A = (float)GGG.show_shadows_i/GCN.i_show_max;

            scr_drt(RENTAR, new Rectangle(0*GGG.bxo, 0*GGG.byo, 800, 600), Color.White*(A*0.1875f));
            GGG.scr_draw_level2();
        }

        // do tooltips
        if (GGG.tttxt != "")
        {
            scr_dtt((Int16)(GGG.MS.X), (Int16)(GGG.MS.Y-(Int16)(Math.Round(fnt_CM8.MeasureString(GGG.tttxt).Y + 2))), GGG.tttxt, Color.White);
            GGG.tttxt = "";
        }

        SB.End();
        base.Draw(dt);
    }

```

The reason for switching rendertargets is to draw the shadows as one giant black mass which is then adjusted alpha, which is then drawn back onto the screen. Otherwise the shadows would blend like a ven diagram with a darker region in the intersections, which is not how it should look in real life.

# Answer
> 3 votes
What you're experiencing is the color key part from the XNA content processor. You can find the setting in the properties windows. What you want to do is disable color key entirely.

---
Tags: c#, xna, monogame
---


# Question
Title: How do C++ games handle memory allocation failure?
I am aware of several games which are written in C++ but do not use exceptions. Since handling of memory allocation failure in C++ is generally built around the `std::bad_alloc` exception, how do these games handle such a failure?

Do they simply crash, or is there another way to handle and recover from an out-of-memory error?

# Answer
> 63 votes
Same as all average programs: They don't.\*

For most applications there is no customer expectation that they continue working once memory runs out. All games fall under these "most applications". Spending time and money to work on an edge case which the customer doesn't expect to work doesn't make sense.

The question is similar to the following:

* How do you install a game if the harddisk is full?
* How do you still run the game at high fps on a PC below minimum specs?

The answer is the same: These are the users' problems. The game doesn't care.

---

\*Actually, they usually do a high level catch of the exception, and use memory that was pre-allocated at the start of the game in order to try to log the event before crashing/terminating. The log then allows customer support to waste less time on the issue.

# Answer
> 22 votes
Typically this kind of scenario never happens.

Firstly, virtual memory on modern operating systems means that it's highly unlikely to happen in normal operation anyway; unless you have a runaway allocation bug, the game will be allocating memory from the OSs virtual address space and the OS will be looking after paging in and out.

That's all well and good, but it doesn't really apply to consoles or older OSs, so secondly, games don't even do lots of small dynamic allocations using standard library allocators anyway. Instead what they'll do is allocate a large pool of memory one-time-only at startup, and draw down from that pool for any runtime allocations which are required (e.g. by using C++ placement new or by writing their own memory management system on top of it).

That also protects against memory leaks because rather than having to track and account for each small individual allocations, a game can just throw away the entire pool to reclaim memory.

And thirdly, games will always set a minimum specification and budget their memory usage within that. So if a game is specified to require 1gb of RAM, that means that so long as its memory usage never exceeds 1gb, it never needs to worry about running out of RAM.

# Answer
> 2 votes
Well, mainly, the same way we did it before exceptions existed - the old "check the return value approach". If an allocator doesn't use exceptions, it will usually return `null` when an allocation fails. A well written game will check for that and handle the situation in whatever way is safe. Sometimes, this means terminating the game (e.g. `std::terminate`) or at least reverting to last known safe state (e.g. when you allocate from a pool, you can safely dispose of the whole pool even when it's in an unsafe state).

Many games do use exceptions for cases like this even then. When someone says "avoid using exceptions in game code", what they usually mean is "only use exceptions for truly exceptional cases, not for mundane flow control". The setup for catching an out of memory exception is cheap - the cost is mostly in the throw, and the complications you get with handling the exception. Neither of those is very important in a typical out of memory case - you almost always want to terminate anyway.

Mind you, most games will just crash. This isn't as crazy as it sounds - you usually have some memory usage as a target, and make sure your game doesn't reach that limit (for example, by using a unit count limit in an RTS game, or by limiting the amount of enemies in a section of an FPS). Even if you don't, you usually don't run out of memory on any reasonably modern system - you run out of virtual address space (in a 32-bit application) or the stack, for example. The OS already pretends that you have as much memory as you ask for - that's one of the abstractions virtual memory provides. The point is, just because you have 256 MiB of physical RAM doesn't mean that your application can't use 4 GiB of memory. Some games might not even mind too much that all of their data isn't in physical RAM all the time (as long as the application doesn't need to touch that data, it can stay on disk, for example).

# Answer
> 1 votes
***Catching an exception*** and ***Deciding to do what when and exception is raised*** are two different things.

You need to have complex logic to free up memory which is not needed by your program. Worse, if any other running program or library is leaking the memory then you have no control on it

Only good thing you can do it to shutdown gracefully and that's what most of the programs will chose to do. You can't even decide to wait till memory will be available because it will make your program unresponsive.

---
Tags: c++, resource-management, memory
---


title: Long delta time and collision detection

text:
# Question
Title: Long delta time and collision detection
When player's computer stutters/he tabs out of game stopping requestAnimationFrame calls, movement system tied to the delta time creates a huge leap, bypassing probable collisions. This allows player to cheat, for example avoiding projectiles by tabbing out and tabbing back in. What are solutions to such a problem, other than pausing the game when delta time is too high?

Attached simple system suffering from this problem - run the code, tab out, wait a while, then tab back in - you shouldn't see the "PEW" in console.

```
function Box(x, y, w, h, moving) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.moving = !!moving;
    this.colliding = false;
}

Box.prototype.move = function(dx, dy) {
    this.x += dx;
    this.y += dy;
};

Box.prototype.testCollision = function(target) {
    return (Math.abs(this.x - target.x) * 2 < (this.w + target.w)) &&
           (Math.abs(this.y - target.y) * 2 < (this.h + target.h))
    ;
};

var boxes = [
    new Box(0, 0, 100, 100, true),
    new Box(200, 200, 100, 100)
];

function updatePosition(dt)
{
    var time = dt / 1000;

    for (var i = boxes.length - 1; i >= 0; i--) {
        if(boxes[i].moving) boxes[i].move(100 * time, 100 * time);
    }
}

function updateCollision()
{
    for (var i = boxes.length - 1; i >= 0; i--) {
        for (var j = boxes.length - 1; j >= 0; j--) {
            if (i === j) continue;

            if(boxes[i].testCollision(boxes[j])) {
                boxes[i].colliding = true;
                boxes[j].colliding = true;
                console.log("PEW");
            } else {
                boxes[i].colliding = false;
                boxes[j].colliding = false;
            }
        }
    }
}

var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');

function render()
{
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (var i = boxes.length - 1; i >= 0; i--) {
        var box = boxes[i];
        if (box.colliding) ctx.fillStyle = '#FF0000';
        else ctx.fillStyle = '#BADA55';

        ctx.fillRect(box.x, box.y, box.w, box.h);
    }
}

var lastTime = 0;

function update(time)
{
    var dt = time - lastTime;

    updatePosition(dt);
    updateCollision();
    render();

    lastTime = time;
    requestAnimationFrame(update);
}

requestAnimationFrame(update);
```

```
<canvas width="500" height="500"></canvas>
```

# Answer
You're putting graphics drawing and game logic in the same package. They should be separate, so if you tab out the game stops drawing itself, but the logic keeps running in the background (so you don't go through collisionable elements).
> 2 votes

# Answer
When you move the objects, and then test if you collide with something, then obviously you will not register hits if one step is big enough so that you completely pass through the collider.

So don't.

Take the starting point, and the direction of motion, and pre-calculate the next collision point (thats a bit more involved, but possible) and the distance at which it will happen.

If your delta time times velocity is bigger then this distance, there will be a collision, and not only will you detect the collision, but also have a much more precise figure for the point at which the collision actually happened.

Another solution - albeit only a band-aid fix - is to not stop the simulation, as @TheMatrixIsReal suggested. This will not solve the original problem, though, and on slow machines, fast-moving objects might pass through walls during normal gameplay.

Another possibility is to keep the "physics" (which handle the collision detection) on fixed delta-times. This is also commonly used because of the predictability, but also has the aforementioned "Passing through wall" problem for high velocities.
> 2 votes

# Answer
I realize you asked 'apart from pausing', but why? Any game that is going to potentially cause the player to fail because they had to stop seeing what is happening is already in a very bad position. Pause the game when they tab out.

Let the user close any other programs they have running then come back to the game.

If their computer is too slow, they should upgrade. If your code is too slow, optimize that.

I would carefully think of every other alternative before encourging the user to tab out to make the game playable.
> 1 votes

---
Tags: game-loop
---


# Question
Title: GameMaker: how to make one non-physical object collide with a fixture?
I've searched a lot and i couldn't find the answer. I'm developing a platformer game where i need the player to stay on ground but i don't want to use build-in physics to make him move. The ground is a multi-point fixture, since i've read using objects lowers performance. However, if I set the player as non-physical object, he doesn't collide with the ground.

# Answer
> -1 votes
Two ways of doing it, *way1* use GameMakers built in buggy physics (GREAT RIGHT?)... So lets ignore that, skip to *way2* and build your own set of physics for it, you could do this by setting your own physics, something along the lines of the following;

*Code Example*

```
#v_speed =0.5;
h_speed =0.5;
vsp =v_speed*grav;
grav = v_speed -1;
//Something like this
vsp = grav*v_speed;
if (vsp<10) vsp +=grav;

```

This is just something quick, youl need to tweek it more for yourself.

---
Tags: platformer, game-maker
---


# Question
Title: Unity and C# - Cube with random directions
I want to create a similar line RigidObject in Unity c# just like in the iOS game Circle:

So far I placed a cube object that is extended by length.

So, how would you approach to create such an object?

I tried with a for loop where I was trying to add a cube at the end of the other, but the rotation messed everything up.

I don't want to create a prefab, since I want the lines to be random and different every time the player starts the game.

# Answer
> 1 votes
Use an Edge Collider to map the collision, and a Line Renderer to render the line. Both of them take an array of points, and will make the line/collider as you specify.

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


# Question
Title: Best way to test if some point on a line if in front of another point on the same line in 3D
I have a line in 3D defined by point P0 and direction vector D. For given input point P on a line defined as above, I want to test if P is in front of point P0. The code will be used in GLSL fragment shader.

So far, my best solution is following GLSL function:

```
bool IsInFront(vec3 P, vec3 P0, vec3 D)
{
  float d = length(P - P0);
  vec3 Pp = P0 + d * D;
  return (length(Pp - P) < 1.0E-4);
}

```

Explanation is simple. d is distance between P and P0, and there are only two possible positions on a line where a point with distance d from point P0 can be on a line: in front, or behind point P0. Then I just check if positive point is same as input P.

However, this code uses precision 1.0E-4, and recalculation of input point P. Is there a faster and numerically more stable way to do this?

Regards

# Answer
> 1 votes
I think I found an answer by myself.

```
bool IsInFront(vec3 P, vec3 P0, vec3 D)
{
  vec3 D2 = P - P0;
  float c = dot(D, D2);
  return (c > 0.0);
}

```

In this solution, D2 is unnormalized vector from P0 to P which is either in same or opposite direction compared to D. c is cosine similarity between D and D2 multiplied by length of vector D2. It is either length of vector D2, or negated length of vector D2 depending on it's orientation.

# Answer
> 0 votes
Not sure if its relevant (Not 100% sure what your actually asking, but ill attempt my advice anyway) but use a raycast, this will then have a function that allows you to measure the "ray's" distance between the player and an object, or 2 objects if you prefer.

---
Tags: 3d, glsl, geometry
---


# Question
Title: How would intensive AI pathing be done server-side in an MMORPG?
Take WoW or Runescape for an example. You have an incredibly large map, filled with cities and forests, each filled with people and monsters.

Monsters roam around an area at random that is `25x25 tiles` big (ambiguous). This is done server-side, so every player than comes across this area sees the same location of the same monster, and when a player attacks/kills that monster; other players see it too.

How is this calculated without being a massively intensive task? If you have 500 different types of monsters, all of which have 5 maximum spawned, you'll be calculating 2500 different paths continuously.

# Answer
> 8 votes
I think the "MMO" aspect of the question here is mostly irrelevant (although it does provide trade one major optimization for another, discussed later); the core issue is the same as would be faced by any game with large worlds and many gameplay entities that need pathing.

There's a handful of things you can do to help with this. The tl;dr is to make sure you only path when you really *need* to, to do things hierarchically if possible (divide-and-conquer) and to choose the cheapest algorithms you can. Presented in no particular order, I'd consider some combination of these options:

* One solution is to do the path computation hierarchically. If the world is divided into a hierarchical spatial structure (as it probably should be, as doing so is important for lots of other computational optimizations), you can build connectivity information for each level of that hierarchy and path via that coarser graph instead. Most pathfinding algorithms scale in cost with the size of the domain, and by doing initial pathing at a coarser subdivision of the world you can drastically reduce the domain. This is sufficient to set the character moving in basically the right direction, and when they get close enough you can switch to something more detailed.
* Another solution is to do the pathing in buckets. If you have 500 entities, tick pathing for 250 in one frame, and the other 250 the next frame (et cetera). You can achieve a decent boost this way, although you have to be careful not to use *too many* buckets because then the lag in an entity beginning to walk its path will be apparent if that entity is, say, in the last of ten buckets.
* You can also use less "accurate" methods than A\*, which are also less computationally expensive. A\* is the "go-to pathing algorithm" because it can find optimal paths, which sounds great from a technical perspective, but from a gameplay design perspective it's not always so great: perfect isn't *real*, and entities that act too perfect (especially if they can compute the most optimal path over distances longer than they could see) stick out like a sore thumb often. "Cheating" AI isn't so fun, so reducing the accuracy (and expense) of a pathing solution can get you benefits in both domains. Edge-following algorithms, pathing between major landmarks instead of a per-tile or per-graph-node basis, or starting to walk a path before it is complete (allowing you to spread path computation over *N* frames) are various ways to achieve this.
* In a single player game you could use distance to the player's focus point to weight pathing, and process the paths of distance objects far less frequently. This is rarely worth doing in an MMO since usually somebody will be near enough... but on the other hand, if you have a server cluster you can instead try to farm the path calculations out among *N* different machines.
* You also, you know, not calculate paths for all of those entities. Have entities move in pre-calculated wander or patrol paths most of the time; these are simple point-to-point movements that are extremely cheap to process. You only need to engage pathing for the entities when a player disrupts them and they need to path to the player to attack and follow, until they hit a tethering distance from their spawn point and give up and return to it.

# Answer
> 1 votes
Mob movement in most MMORPGs is usually extremely simple. You rarely see mobs actually do complex paths. Most run around aimlessly near their spawn area, sometimes you have them follow a predetermined route of waypoints. Neither requires any complex route finding at all, especially because players and mobs do not block each other in most MMORPGs.

You only see actual pathfinding when they engage a player. And even then they usually have a very short range in which they follow the player, so the path-length is considerably small. The smaller the range, the less there is to compute.

Also, most MMORPGs only have a very short sightrange. Players only receive updates about mob movement in a very small range around their character, so they usually still scale quite linear.

All of that combined results in a game which isn't actually as CPU and network-intense as one would think.

---
Tags: ai, server
---


# Question
Title: libGDX - Why do I have to use camera.setToOrtho what does it do?
I am very confused about camera matrices and I don't know where to start my studying. Maybe I have to study OpenGL, but I don't know C++ ...

Ok so I have a camera, Box2d world and a Box2d body.

```
private World world;
private Box2DDebugRenderer b2dr;
private OrthographicCamera cam;
private Body player;

@Override
public void create () {
    //Create the world without gravity
    world = new World(new Vector2(0, 0), false);
    b2dr = new Box2DDebugRenderer();
    //I create my camera
    cam = new OrthographicCamera();

    //Create the player
    BodyDef bdef = new BodyDef();
    bdef.type = BodyDef.BodyType.DynamicBody;

    //Sets the body position to the center of the screen
    bdef.position.set(Gdx.graphics.getWidth() / 2, Gdx.graphics.getHeight() / 2);

    player = world.createBody(bdef);
    CircleShape shape = new CircleShape();
    shape.setRadius(2f);
    player.createFixture(shape, 1f);
}

@Override
public void render () {
    world.step(1f/60f, 6, 2);

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    b2dr.render(world, cam.combined);
}

```

I am not seeing the player on the center of the screen, just a black void.

But if I add cam.setToOrtho(false); I see the player! Why is that?

setToOrtho sets the camera to Orthographic projection WHY?

The camera is Orthographic what oder projection can it have?? Isn't the orthographic projection obvious?

# Answer
> 2 votes
`setToOrtho` does not set the projection type of the camera. An `OrthographicCamera` will always have an orthographic frustrum.

Looking at the source, it seems to me that `setToOrtho` is a convenience method to set the viewport size to the screen size and center the camera on the viewport. `setToOrtho(false)` is showing your character is because your character is within this default viewport that `setToOrtho` creates.

The reason why you can't see your character without this call, is you never give your camera a viewport size and you never update the camera. Try

```
cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

```

And then every time you change any parameters of your camera, you must call `cam.update();` before any draw calls. I usually end up changing the camera so often that I call this every frame.

---
Tags: java, libgdx, camera, projection, projection-matrix
---


# Question
Title: Using a script to draw an icon next to (i.e. inline with) a text label in Unity
Suppose `mystring` is a string variable (whose value changes over time) and that `myIcon` is a texture or sprite of known dimension, say 32x32.

Is it possible to write a Unity script that draws `myIcon` alongside `myString`like this example (where `myString` is "TURTLE" in this case):

In particular, I have the following challenges:

* I would like the whole construction (icon + string) to be horizontally centered on the screen).
* The spacing between the icon and the text should be some fixed number of pixels.
* Since the pixel width of the string changes when the value of the string changes, the appropriate horizontal positioning of the icon and the text will also change and can't be easily calculated in advance.

So, my question is: **how can I draw and center such a GUI element using a Unity script**?

---

The obvious way to do this would be to have `myIcon` inline in the text label, but I read that this isn't possible with unity's current GUI implementation.

It also looked like this might be possible using a horizontal layout group, but I couldn't find a clear guide on how to implement that in a script.

# Answer
Use manual anchoring instead of using layout groups if it's not a must.

Keep both logo and text UI objects in an empty UI object. Manually anchor both objects as your intended layout. They are children of an empty parent so you can move, scale, rotate parent as you want and place the anchors manually for parent. This way icon and text layout won't change as they are children, unless you change display orientation.

Get the UI text object with `iconName = gameObject.GetComponent<Text>();` and update with `iconName.text = "string";` as you need from script. Use suitable setup for text UI object such as `Best Fit`, `Alignment` etc.
> 2 votes

---
Tags: unity, gui, scripting, text
---


# Question
Title: How to rotate an image in pygame without losing quality or increasing size or moving position
I am trying to make a game in which I place a spaceship (its an image I downloaded) in the center and then rotate it **on its place**. However, when I use *pygame.transform.rotate()*, it rotates the image and changes its location and keeps on increasing its size. I have tried *pygame.transform.rotozoom* but even when I used scale 1, it didn't show any difference. And also when it rotates and blits the image onto the screen the image severely loses its quality. Pleaseee helpp!!

# Answer
> 2 votes
## Maintaining quality

When you're rotating the image using `pygame.transform.rotate()`, pygame creates a new Surface with your rotated image on. By doing this your image lose some information and therefore some quality. That's why it's always practical to rotate the original image and **not** a rotated copy. In code it'll look something like this:

```
class Player(pygame.sprite.Sprite):

    def __init__(self, pos=(0, 0)):
        super(Player, self).__init__()
        self.original_image = pygame.image.load("My_image.png").convert()
        self.image = self.original_image  # This will reference our rotated image.
        self.rect = self.image.get_rect().move(pos)
        self.angle = 0

    def update(self):
        self.image = pygame.transform.rotate(self.original_image, self.angle)
        self.angle += 1 % 360  # Value will reapeat after 359. This prevents angle to overflow.

```

---

## Why the image changes size

Surfaces in pygame can't actually be rotated; they have a horizontal width and a vertical height. When you load your image pygame creates a Surface which has a horizontal width and a vertical height equal to your image. When you rotate your image 45 degrees pygame have to create a new Surface where your original image fits. The new Surface's horizontal width and vertical height has to be the images hypothenuse to be able to fit the image.

As you see, the Surface is the biggest when the hypothenuse (the turquoise line) is vertical (or horizontal). This is supposed to be, otherwise your image wouldn't fit. If the problem you're having is about collision detection I'd recommend you to try other forms of collision detection like circular, or keep using rectangular but minimize it's size.

---

## Keep the image on the same position

To prevent the image from moving I usually position the image by its center. So after each rotation I move its new center to its previous center.

```
def update(self):
    self.image = pygame.transform.rotate(self.original_image, self.angle)
    self.angle += 1 % 360  # Value will reapeat after 359. This prevents angle to overflow.
    x, y = self.rect.center  # Save its current center.
    self.rect = self.image.get_rect()  # Replace old rect with new rect.
    self.rect.center = (x, y)  # Put the new rect's center at old center.

```

---

## Full code

```
import pygame

class Player(pygame.sprite.Sprite):

    def __init__(self, pos=(0, 0), size=(200, 200)):
        super(Player, self).__init__()
        self.original_image = pygame.Surface(size)
        pygame.draw.line(self.original_image, (255, 0, 255), (size[0] / 2, 0), (size[0] / 2, size[1]), 3)
        pygame.draw.line(self.original_image, (0, 255, 255), (size[1], 0), (0, size[1]), 3)
        self.image = self.original_image
        self.rect = self.image.get_rect()
        self.rect.center = pos
        self.angle = 0

    def update(self):
        self.image = pygame.transform.rotate(self.original_image, self.angle)
        self.angle += 1 % 360  # Value will reapeat after 359. This prevents angle to overflow.
        x, y = self.rect.center  # Save its current center.
        self.rect = self.image.get_rect()  # Replace old rect with new rect.
        self.rect.center = (x, y)  # Put the new rect's center at old center.

def main():
    player = Player(pos=(200, 200))
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                raise SystemExit

        player.update()
        screen.fill((255, 255, 255))
        screen.blit(player.image, player.rect)
        pygame.display.update()

if __name__ == '__main__':
    pygame.init()
    screen = pygame.display.set_mode((400, 400))
    main()

```

# Answer
> 1 votes
*I don't know pygame, but here are some ways to fix some of your issues.*

---

> However, when I use pygame.transform.rotate(), it rotates the image and changes its location and keeps on increasing its size.

This is typically caused because you have other transformations that are applied, i.e. if you have a scale applied before you do the rotation.

Also, reading the documentation:

> Unless rotating by 90 degree increments, **the image will be padded larger to hold the new size**. If the image has pixel alphas, the padded area will be transparent. Otherwise pygame will pick a color that matches the Surface colorkey or the topleft pixel value.

---

Ultimately, if you can't achieve what you want with the tools offered by the engine, you could create a spritesheet with the image rotated. This would be done in a program like photoshop, and you would change the sprite instead of rotating it in the game. This would give you a better control on the final quality.

---
Tags: pygame
---


title: How to make enemies in Game maker?

text:
# Question
Title: How to make enemies in Game maker?
how do i make enemies in game maker? its kinda hard since the enemies are falling from the sky I want the cats with the bombs to do more damage than the regular ones

# Answer
> 2 votes
An enemy is just an object whose actions -or interaction with- may lead to a *game over*. For enemies to work here, you need a *lose condition* and a way to enforce the lose condition. There is no other concept for *enemy* you need right now. The way you will implement the enemy is by dealing damage to the player upon collision.

You must create:

1. A parent object which you will call `obj_base_cat`. It will have no sprite. Declare a create behavior setting something like `vspeed = 5; damage = 0;`. The damage variable is just to have it as defined.
2. A player object.
3. A child object of `obj_base_cat`, with the regular cat sprite. When creating, invoke `super` (the parent behavior), and also `damage = 3;`.
4. A child object of `obj_base_cat`, with the bomb-having cat sprite. When creating, invoke `super` (the parent behavior), and also `damage = 3;`.
5. The player, when receiving the collision of an `obj_base_cat` (children will trigger this condition as well!) will be hit given the `.damage` property of the cat. Then you must handle the criterion for damage reception, life loss, and eventual game over. If you don't do that beforehand, the whole concept of enemy is meaningless.

---
Tags: game-mechanics
---


# Question
Title: How to convert and handle (controlling) OOP game objects via ECS?
I'm having hard time converting OOP game objects to Ashley ECS framework. I have a character, gun & a bullet class. The character uses the gun as weapon, the gun class has a fire method that handles the creation of bullet. In the below code, is my current `WeaponSystem` that serves as a generic system for any weapon like `Gun` class.

```
public interface Weapon {
     void use();
}

public class WeaponComponent implements Component {
     Weapon weapon;
}

public class WeaponSystem extends IteratingSystem {

    ... // Constructor

    ... // Process Entity

    public void use(Entity weapon) {
         WeaponComponent weaponComponent = Components.getWeapon(weapon);
         weaponComponent.use();
         ...
    }

}

```

The character system..

```
public class CharacterSystem extends IteratingSytem {

    ... // Constuctor

    ... // Process Entity

    public void attack(Entity character) {
        getEngine().getSystem(WeaponSystem.class).use(character);
        // also can be use like this
        // CharacterComponent characterComponent = ...
        // it seems that, it was redundant
        // characterComponent.weapon.use();
    }

}

```

And the user controlled system ...

```
public class UserControlledSystem extends IteratingSystem {
     ...

     public void move(Entity character) {
          ... Set character directions

          InputComponent input ...
          input.key == arrow key, etc...

          getEngine().getSystem(CharacterSystem.class).move(character, direction);
     }

     public void attack(Entity character) {
          getEngine().getSystem(CharacterSystem.class).attack(character);
     }
}

```

Based on this article, they are using event dispatcher. But do I really need to use dispatcher? Is that possible to not to use dispatcher, just purely ECS? Anyways let's back to the main question(*How to convert and handle (controlling) OOP game objects via ECS?*). Currently, the Ashley ECS Entity has an access to engine and systems. Like in the above code example, do you think it is the proper way of handling the system?

# Answer
> 1 votes
I'm not too familiar with Ashley's ECS system. The reason they are using the dispatcher is to share information across multiple objects. This is usually to reduce coupling in classes, which makes things easier to manage in practice, but not easier to design. Typically this method is MOSTLY used for event based systems.

Say a scripted game event, servers, or in stackless python.

For overly complex and large scale games where you have thousands of different objects that need to be managed by a single computer or something. Truthfully I'd be using the dispatch system,

You can use the ECS system without the need for broadcasting messages. But you'll find that as your project grows in complexity, the pure ECS system becomes a pain in the ass to convert to anyways.

Basically you'd do one or two things. You'd call update on the entity, and update it's components all at once. or you run through each system and update components. But sometime's you find that your systems requires data from other systems, this is where the dispatcher would shine best.

# Answer
> 1 votes
Both dispatcher and calling systems directly from systems breaks the architecture. A system should never be called directly to update, if anything, only call methods to set some flag or data to be handled when it's time for that system.

If the CharacterSystem knows about the WeaponSystem, then if you change the WeaponSystem to behave in a different way you might run into trouble. Same for UserControlledSystem: does it really have to know how to call the system to move it, and call it out of order?

A good way to solve this is to simply write down what you would need to do pass information for a system, a message, and make a component out of it, that could be destroyed or just reused, in an object pool or never even removed from the entity. Let's take a look at the UserControlled class. What if we just set the velocity instead of calling the system? If I press right, then I just set the velocity.x = 1f for example. Then, when the MovementSystem iterates, it tries to add that velocity to the character, and adjust position accordingly. But can we do this better? We can create a component that is UserControlsComponent, that has a few boolean flags to represent if a direction is being pressed. Then we create a UserControlsSystem, that checks these flags and acts. What is the advantage? Well, to start, suddendly we just take care of handling input, and setting some flags, which means we don't care about the end result, we just express the player wants to do something, for example, move right. Now the system in charge of transforming these flags into actions would read the flags, do actions accordingly, and set flags to false, to indicate they are consumed. What happens next is that suddendly, even if you are using different controllers, you could even create a System to handle that type of controller without duplicating code.

It does create a bit more code, but not necessarily complexity, because in the end, if the code is broken down into smaller, more easy to handle, readable chunks, you benefit from it, and you get more flexibility.

---
Tags: libgdx, entity-system, entity-component, entity
---


# Question
Title: How to decide which GameObject should handle the collision?
In any collision, there are two GameObjects involved right? What I want to know is, How do I decide which object should contain my `OnCollision*`?

As an example, let's suppose I have a Player object and a Spike object. My first thought is to put a script on the player that contains some code like this:

```
OnCollisionEnter(Collision coll) {
    if (coll.gameObject.compareTag("Spike")) {
        Destroy(gameObject);
    }
}

```

Of course, the exact same functionality can be achieved by instead having a script on the Spike object that contains code like this:

```
OnCollisionEnter(Collision coll) {
    if (coll.gameObject.compareTag("Player")) {
        Destroy(coll.gameObject);
    }
}

```

Whilst both are valid, it made more sense to me to have the script on the *Player* because, in this case, when the collision happens, an action is being performed on the *Player*.

However, what's making me doubt this is that in future you may want to add more objects that will kill the Player on collision, such as an Enemy, Lava, Laser Beam, etc. These objects will likely have different tags. So then the script on the Player would become:

```
OnCollisionEnter(Collision coll) {
    GameObject other = coll.gameObject;
    if (other.compareTag("Spike") || other.compareTag("Lava") || other.compareTag("Enemy")) {
        Destroy(gameObject);
    }
}

```

Whereas, in the case where the script was on the Spike, all you would have to do is add that same script to all the other objects that can kill the Player and name the script something like `KillPlayerOnContact`.

Also, if you have a a collision between the Player and an Enemy, then you likely want to perform an action on **both**. So in that case, which object should handle the collision? Or should both handle the collision and perform different actions?

I have never built a game of any reasonable size before and I'm wondering if the code can become messy and difficult to maintain as it grows if you get this sort of thing wrong in the beginning. Or maybe all ways are valid and it doesn't really matter?

---

Any insight is much appreciated! Thank you for your time :)

# Answer
I personally prefer to architect systems such that *neither* object involved in a collision handles it, and instead some collision-handling proxy gets to handle it with a callback like `HandleCollisionBetween(GameObject A, GameObject B)`. That way I don't have to think about what logic should be where.

If that's not an option, such when you're not in control of the collision-response architecture, things get a bit fuzzy. Generally the answer is "it depends."

Since both objects will get collision callbacks, I'd put code in both, but only code that is relevant to *that object's role in the game world*, while also trying to maintain extensibility as much as possible. This means if some logic makes equal sense in either object, prefer to put it in the object that will likely lead to fewer code changes in the long run as new functionality is added.

Put another way, between any two object types that can collide, one of those object types generally has the same effect on more object types than the other. Putting code for that effect in the type that affects more other types means less maintenance in the long run.

For example, a player object and a bullet object. Arguably, "taking damage on collision with bullets" makes logical sense as part of the player. "Applying damage to the thing it hits" makes logical sense as part of the bullet. However, a bullet is likely to apply damage to more different types of objects than a player (in most games). A player won't suffer damage from terrain blocks or NPCs, but a bullet still might apply damage to those. So I'd prefer to put the collision handling for imparting damage into the bullet, in that case.
> 47 votes

# Answer
**TL;DR** The best place to put the collision detector is the place where you consider it is the *active* element in the collision, instead of the *passive* element in the collision, because perhaps you'll need additional behavior to be executed in such active logic (and, following good OOP guidelines like SOLID, is the responsibility of the *active* element).

**Detailed**:

Let's see ...

My approach when I have the same doubt, *regardless the game engine*, is to determine which behavior is *active* and which behavior is *passive* with respect to the action I want to trigger on collection.

*Please note: I use different behaviors as abstractions of the different parts of our logic to define the damage and -as another example- the inventory. Both are separate behaviors I'd add later to a Player, and not clutter my custom Player with separate responsibilities which would be harder to maintain. Using annotations like RequireComponent, i'd ensure my Player behavior had, also, the behaviors I am defining now.*

*This is just my opinion: avoid executing logic depending on the tag, but instead use different behaviors and values like enums to choose among*.

Imagine this behaviors:

1. Behavior to specify an object as being a stack on the ground. RPG games use this for items in the ground able to be picked up.

```
public class Treasure : MonoBehaviour {
    public InventoryObject inventoryObject = null;
    public uint amount = 1;
}

```
2. Behavior to specify an object capable of producing damage. This could be lava, acid, any toxic substance, or a flying projectile.

```
public class DamageDealer : MonoBehaviour {
    public Faction facton; //let's use it as well..
    public DamageType damageType = DamageType.BLUNT;
    public uint damage = 1;
}

```

To this extent, consider `DamageType` and `InventoryObject` as enums.

These behaviors are not *active*, in the way that by being on the ground or flying around they do not act by themselves. They do nothing. E.g. if you have a fireball flying in an empty space, it is not ready to do damage (perhaps others behaviors should be considered active in a fireball, like the fireball consuming his power while travelling and diminishing its damage power in the process, but even when a potential `FuelingOut` behavior could be developed, it is stil another behavior, and not the same DamageProducer behavior), and if you see an object in the ground, it is not checking the whole users and thinking *can they pick me?*

We need *active* behaviors for that. The counterparts would be:

1. One behavior to take damage (It would require a behavior to handle life and death, since lowering life and receiving damage are usually separate behaviors, and because I want to keep this examples as simple as possible) and perhaps *resist* damage.

```
public class DamageReceiver : MonoBehaviour {
    public DamageType[] weakness;
    public DamageType[] halfResistance;
    public DamageType[] fullResistance;
    public Faction facton; //let's use it as well..

    private List<DamageDealer> dealers = new List<Da mageDealer>();

    public void OnCollisionEnter(Collision col) {
        DamageDealer dealer = col.gameObject.GetComponent<DamageDealer>();
        if (dealer != null && !this.dealers.Contains(dealer)) {
            this.dealers.Add(dealer);
        }
    }

    public void OnCollisionLeave(Collision col) {
        DamageDealer dealer = col.gameObject.GetComponent<DamageDealer>();
        if (dealer != null && this.dealers.Contains(dealer)) {
            this.dealers.Remove(dealer);
        }
    }

    public void Update() {
        // actually, this should not run on EVERY iteration, but this is just an example
        foreach (DamageDealer element in this.dealers)
        {
            if (this.faction != element.faction) {
                if (this.weakness.Contains(element)) {
                    this.SubtractLives(2 * element.damage);
                } else if (this.halfResistance.Contains(element)) {
                    this.SubtractLives(0.5 * element.damage);
                } else if (!this.fullResistance.Contains(element)) {
                    this.SubtractLives(element.damage);
                }
            }
        }
    }

    private void SubtractLives(uint lives) {
        // implement it later
    }
}

```

*This code is untested and should work as a concept*. What's the purpose? Damage is something someone *feels*, and is relative to the object (or living form) being damaged, as you consider. This is an example: in regular RPG games, *a sword damages you*, while in other RPGs implementing it (e.g. *Summon Night Swordcraft Story I and II*), *a sword can also receive damage by hitting a hard part or blocking armor, and could need repairs*. So, since the damage logic is relative to the receiver and not to the sender, we only put relevant data in the sender, and the logic in the receiver.
2. The same applies to an inventory holder (another required behavior would be one related to the object being on the ground, and the ability to remove it from there). Perhaps this is the appropriate behavior:

```
public class Inventory : MonoBehaviour {
    private Dictionary<InventoryObject, uint> = new Dictionary<InventoryObject, uint>();
    private List<Treasure> pickables = new List<Treasure>();

    public void OnCollisionEnter(Collision col) {
        Treasure treasure = col.gameObject.GetComponent<Treasure>();
        if (treasure != null && !this.pickables.Contains(treasure)) {
            this.pickables.Add(treasure);
        }
    }

    public void OnCollisionLeave(Collision col) {
        Treasure treasure = col.gameObject.GetComponent<Treasure>();
        if (treasure != null && this.pickables.Contains(treasure)) {
            this.pickables.Remove(treasure);
        }
    }

    public void Update() {
        // when certain key is pressed, pick all the objects in the pickables list, and add them to the inventory if you have a free slot for them. also remove them from the ground.
    }
}

```
> 12 votes

# Answer
As you can see from the variety of answers here, there's a fair degree of personal style involved in these decisions, and judgement based on the needs of your particular game - no one absolute best approach.

My recommendation is to **think of it in terms of how your approach will scale as you grow your game**, adding and iterating on features. Will putting the collision handling logic in one place lead to more complex code later? Or does it support more modular behaviour?

So, you have spikes that damage the player. Ask yourself:

* Are there things other than the player that spikes might want to damage?
* Are there things other than spikes that the player should take damage from on collision?
* Will every level with a player have spikes? Will every level with spikes have a player?
* Might you have variations on the spikes that need to do different things? (eg. different damage amounts / damage types?)

Obviously, we don't want to get carried away with this and build an over-engineered system that can handle a million cases instead of just the one case we need. But if it's equal work either way (ie. put these 4 lines in class A vs class B) but one scales better, it's a good rule of thumb for making the decision.

For this example, in Unity specifically, I'd lean toward putting the *damage-dealing* logic **in the spikes**, in the form of something like a `CollisionHazard` component, which upon collision calls a *damage-taking* method in a `Damageable` component. Here's why:

* You don't need to set aside a tag for every different collision participant you want to distinguish.
* As you add more varieties of collidable interactions (eg. lava, bullets, springs, powerups...) your player class (or Damageable component) doesn't accumulate a giant set of if/else/switch cases to handle each one.
* If half your levels end up having no spikes in them, you're not wasting time in the player collision handler checking whether a spike was involved. They only cost you when they're involved in the collision.
* If you later decide that spikes should kill enemies & props too, you don't need to duplicate code out of a player-specific class, just stick the `Damageable` component on them (if you need some to be immune to spikes only, you can add damage types & let the `Damageable` component handle immunities)
* If you're working on a team, the person who needs to change the spike behaviour and checks out the hazard class/assets isn't blocking everyone who needs to update interactions with the player. It's also intuitive to a new team member (especially level designers) which script they need to look at to change the spike behaviours - it's the one attached to the spikes!
> 9 votes

# Answer
It really doesn't matter who handles the collision, but be consistent with whose job it is.

In my games, I try to choose the `GameObject` that is "doing" something to the other object as the one who controls the collision. I.E. Spike damages the player so it handles the collision. When both objects "do" something to each other, have them each handle their action on the other object.

Also, I would suggest trying to design your collisions so that the collisions are handled by the object that reacts to collisions with fewer things. A spike will only need to know about collisions with the player, making the collision code in the Spike script nice and compact. The player object can collide with many more things which will make a bloated collision script.

Lastly, try to make your collision handlers more abstract. A Spike doesn't need to know that it collided with a player, it just needs to know that it collided with something that it needs to deal damage to. Lets say you have a script:

```
public abstract class DamageController
{
    public Faction faction; //GOOD or BAD
    public abstract void ApplyDamage(float damage);
}

```

You can subclass `DamageController` in your player GameObject to handle the damage, then in `Spike`'s collision code

```
OnCollisionEnter(Collision coll) {
    DamageController controller = coll.gameObject.GetComponent<DamageController>();
    if(controller){
        if(controller.faction == Faction.GOOD){
          controller.ApplyDamage(spikeDamage);
        }
    }
}

```
> 2 votes

# Answer
I had the same Problem when I started out so here it goes: In this particular case use the Enemy. You usually want the Collision handled by the Object that performs the action (in this case - the enemy, but if your player had a weapon, then the weapon should handle the collision), because if you want to tweak attributes (for example the damage of the enemy) you definitely want to change it in the enemyscript and not in the playerscript (especially if you have multiple Players). Likewise if you want to change the damage of any weapon the Player uses you definitely don't want to change it in every enemy of your game.
> 2 votes

# Answer
Both objects would handle the collision.

Some objects would be immediately deformed, broken, or destroyed by the collision. (bullets, arrows, water balloons)

Others would just bounce off and roll to the side. (rocks) These could still take damage if the thing they hit was hard enough. Rocks don't take damage from a human hitting them, but they might from a sledge hammer.

Some squishy objects like humans would take damage.

Others would be bound to each other. (magnets)

Both collisions would be placed on an event handling queue for an actor acting on an object at a particular time and place (and velocity). Just remember that the handler should only deal with the what happens to the object. It is even possible for a handler to place another handler on the queue to handle additional effects of the collision based on the properties of the actor or the object being acted on. (Bomb blew up and the resulting explosion now has to test for collisions with other objects.)

When scripting, use tags with properties that would be translated into interface implementations by your code. Then reference the interfaces in your handling code.

For instance, a sword might have a tag for Melee which translates to an interface named Melee which might extend a DamageGiving interface which has properties for damage type and a damage amount defined using either a fixed value or ranges, etc. And a bomb might have an Explosive tag whose Explosive interface also extends the DamageGiving interface which has an additional property for radius and possibly how quickly the damage diffuses.

Your game engine would then code against the interfaces, not specific object types.
> 2 votes

---
Tags: collision-detection
---


# Question
Title: PYGAME: When I release two directional keys together the player keep moving
I did the code this way to avoid the player to stop if a press two directional keys together making the movement more smooth. It works well but when I release two keys or more together the player keep moving in one of the directions of the key. I can't figure out how to solve this issue.

Here is my code:

```
def input(self, event, pygame):
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_LEFT:
            self.left_is_down = True
            self.speed_x = -self.velocity
        if event.key == pygame.K_RIGHT:
            self.right_is_down = True
            self.speed_x = self.velocity
        if event.key == pygame.K_UP:
            self.up_is_down = True
            self.speed_y = -self.velocity
        if event.key == pygame.K_DOWN:
            self.down_is_down = True
            self.speed_y = self.velocity

    if event.type == pygame.KEYUP:
        if event.key == pygame.K_LEFT:
            self.left_is_down = False
            if self.right_is_down:
                self.speed_x = self.velocity
            else:
                self.speed_x = 0
        if event.key == pygame.K_RIGHT:
            self.right_is_down = False
            if self.left_is_down:
                self.speed_x = -self.velocity
            else:
                self.speed_x = 0
        if event.key == pygame.K_UP:
            self.up_is_down = False
            if self.down_is_down:
                self.speed_y = self.velocity
            else:
                self.speed_y = 0
        if event.key == pygame.K_DOWN:
            self.down_is_down = False
            if self.up_is_down:
                self.speed_y = -self.velocity
            else:
                self.speed_y = 0

def update(self):

    self.x += self.speed_x
    self.y += self.speed_y

```

# Answer
> 3 votes
In pygame (and many other frameworks like it), events are received in an **event queue**. Multiple events can arrive per frame, for example when you press or release two buttons together. You need to **consume the event queue** before proceeding. Typically that looks like this:

```
while True:
    for event in pygame.event.get():
        if event == pygame.KEYDOWN:
            # handle key pressed
        elif event == pygame.KEYUP:
            # handle key released
        # handle other events
    # update
    # render

```

You haven't shown how your `input()` is called, but I suspect you're not looping over `pygame.event.get()`, which explains why some key events are missing.

But a simpler solution for your problem is to forget about key events, and simply **get the state of all keys pressed**, via `pygame.key.get_pressed()`, like in your proposed solution, but that's all you need. Leave the `KEYDOWN`/`KEYUP` events for when you need to know when a key is first pressed, or released. Then it's just:

```
while True:
    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]:
        # Go left
    if pressed[pygame.K_UP]:
        # Go up
    # Or handle diagonals, like pressed[pygame.K_LEFT] and pressed[pygame.K_UP]

```

# Answer
> 0 votes
If you remove the part bellow, maybe it can work. I do this in the JavaScript game and worked, try it:

```
if event.type == pygame.KEYUP:
    if event.key == pygame.K_LEFT:
        self.left_is_down = False
        if self.right_is_down:
            self.speed_x = self.velocity
        else:
            self.speed_x = 0
    if event.key == pygame.K_RIGHT:
        self.right_is_down = False
        if self.left_is_down:
            self.speed_x = -self.velocity
        else:
            self.speed_x = 0
    if event.key == pygame.K_UP:
        self.up_is_down = False
        if self.down_is_down:
            self.speed_y = self.velocity
        else:
            self.speed_y = 0
    if event.key == pygame.K_DOWN:
        self.down_is_down = False
        if self.up_is_down:
            self.speed_y = -self.velocity
        else:
            self.speed_y = 0

```

# Answer
> 0 votes
I'm a beginer in pygame and python so i'm having some troubles hahahahah.

I figured ou what my problem was. Pygame does not reognize two keys being pressed or released at the same time.

So for example, when i press the down button, and the right button the program states that self.down\_is\_down = True and self.right\_is\_down = True so the player gain a positive vertical speed and a positive horizontal speed.

But if i release two of then together pygame just recognize one being released so only one of self.down\_is\_down and self.right\_is\_down will be set False and the player will keep moving to one of the directions.

to solve this i add in the end if event.type == pygame.KEYUP block the following code:

```
      if not pygame.key.get_pressed()[pygame.K_LEFT] and not pygame.key.get_pressed()[pygame.K_RIGHT]:
        self.speed_x = 0
        self.left_is_down = False
        self.right_is_down = False
    if not pygame.key.get_pressed()[pygame.K_UP] and not pygame.key.get_pressed()[pygame.K_DOWN]:
        self.speed_y = 0
        self.down_is_down = False
        self.up_is_down = False

```

wich checks if the keys are still being pressed. I don't think it's the better way to solve that problem but it works for now

# Answer
> 0 votes
I've tried out a smooth way to move around a player that works pretty well. It basically keeps track of the key presses in a list and moves the player based on the last key pressed. When you press a key it'll add a speed variable at the first position in the list, and when you release the key it'll remove that variable. In the update method you'll add the first speed variable of the list to corresponding x and y value.

```
import pygame
pygame.init()

screen = pygame.display.set_mode((720, 480))

class Player(pygame.sprite.Sprite):

    def __init__(self):
        super(Player, self).__init__()
        self.rect = pygame.Rect((0, 0), (32, 32))
        self.image = pygame.Surface((32, 32))
        self.image.fill((255, 255, 255))
        self.velocity = [0, 0]  # It's current velocity.
        self.speed = 4  # The speed the player will move.
        self.dx = []  # Keeps track of the horizontal movement.
        self.dy = []  # Keeps track of the vertical movement.

    def update(self):
        try:
            self.rect.x += self.dx[0]  # Index error if the list is empty.
        except IndexError:
            self.rect.x += 0
        try:
            self.rect.y += self.dy[0]  # Index error if the list is empty.
        except IndexError:
            self.rect.y += 0

player = Player()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                player.dx.insert(0, -player.speed)
            elif event.key == pygame.K_d:
                player.dx.insert(0, player.speed)
            elif event.key == pygame.K_w:
                player.dy.insert(0, -player.speed)
            elif event.key == pygame.K_s:
                player.dy.insert(0, player.speed)
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                player.dx.remove(-player.speed)
            elif event.key == pygame.K_d:
                player.dx.remove(player.speed)
            elif event.key == pygame.K_w:
                player.dy.remove(-player.speed)
            elif event.key == pygame.K_s:
                player.dy.remove(player.speed)

    player.update()
    screen.fill((0, 0, 0))
    screen.blit(player.image, player.rect)
    pygame.display.update()

    # print player.dx, player.dy  # Uncomment to see what's happening in action!

```

---
Tags: 2d, movement, python, pygame
---


# Question
Title: Does it matter who does the collision detection?
I gave an answer to How to decide which GameObject should handle the collision?, and received a lot of negative feedback on it, claiming that it does not matter who does the collision detection. I am not understanding that stance.

For example:

There are 100 bullets and 1 player on the screen. Let's assume brute force collision detection and no optimization such as layers or references.

If the collision detection is done by the bullet, each bullet must detect for collision on 100 different objects. That's 100 x 100 detections, for 10000 detections total.

If the player does the detection, that's 100 detections total, one for each bullet.

Am I mistaken? If so, what am I missing?

# Answer
It does not matter *in general*.

Your examples aren't exactly fair. Your "player does collision" check looks like this:

```
for each player:
  for each bullet:
    if player.intersects(bullet), report it

```

Your "bullet does collision" check looks like this:

```
for each bullet:
  for each other object in the world:
    if bullet.intersects(object), report it

```

Yes, in that case, the first example is definitely better. It will execute 100 times, whereas the second example executes 10,000 times. A more fair example would be `for each bullet, for each player` for the second case, which will also loop 100 times. If the first example is allowed to take advantage of the fact that system has individual lists of types and that bullets don't need to test against other bullets, why is the second not?

Most general-purpose collision systems don't operate like that because they don't have the foreknowledge of the system required by your first example, and because to build it out could be expensive in terms of memory, and not always a computational win. Doing so means you need to store collision properties in separate arrays for each type of object that can interact, or otherwise similarly manage and configure different blocks of collision data and iterate them possibly several times at different times in the update loop and it can quickly become a cumbersome and potentially cache-unfriendly mess. There *are* scenarios where such a specialized collision handling structure could be advantageous over other methods. But they are specialized scenarios.

In general collision handling works by looking at N objects and (modulo various optimizations for spatial organization, preventing duplicate checks in a given frame, et cetera), tests them all against each other, blindly firing out notifications to any interested party that "these two things hit each other, do something about it if you want."
> 3 votes

# Answer
*Disclaimer: I just saw the answer you gave and I don't think it is a downvotes-deserving one to thaaaaat extent, although is just an opinion perhaps implementation-dependent*

Your answer made focus on the iterations, perhaps assuming bruteforce and ignoring the pairs, which are usually made by the preexisting framework. The question seemed to be framework-agnostic and just asked in terms of software design.

To this extent, I'd like to add:

* If you use a preexisting framework, most of the times you don't know which mechanism it will be using.
* You did not focus on the just-created collision pairs, but instead focused on the amount of potential code execution. Said this, it is still irrelevant when to put the code based on that argument. Assume this:

1. Your code for handling the collision is `DETECTED(foo:Foo, bar:Bar)`.
    2. First scenario: you want `Foo` to trigger it when any `bar:Bar` hits the `foo:Foo`. There are 10 `Foo`s and they hit `bar:Bar` at the same time. 55 collision pairs will be made, while only 10 will matter. `DETECTED` will be called 10 times. Does not matter if the `foo` called it each of the 10 times, or if each `bar` called it once.
    3. Second scenario: you want `Bar` to trigger it when any `foo:Foo` hits the `bar:Bar`. There are 10 `Bar`s and they hit `foo:Foo` at the same time. 55 collision pairs will be made, while only 10 will matter. `DETECTED` will be called 10 times. Does not matter if the `bar` called it each of the 10 times, or if each `foo` called it once.
    4. Your approach puts several constraints on the level designs when more objects appear in the level.

So you acted as if the OP wanted to build a game from the very scratch, like also having to create their own particular framework (e.g. collision iteration mechanism). It is most likely not the case.

Again: Perhaps focusing on the software architecture aspect instead of the iteration internals was what the OP asked for.
> 0 votes

---
Tags: collision-detection, optimization, collision-prediction
---


# Question
Title: Instantiate Prefab From Script Inside A Canvas
I am trying to instantiate a `Prefab` inside a `Canvas`. Right now, it keeps appearing behind the canvas. I was reading online and it said to set the parent of the `GameObject` you are trying to instantiate. However, I can't figure out how to get the `Canvas` component.

My hierarchy looks like this:

My `EnemyFormation` object has this script attached to it:

```
public class EnemySpawner : MonoBehaviour {

    public GameObject enemyPrefab;

    void Start () {
        Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
        Debug.Log("Spawning enemy");
    }
}

```

I attach the prefab inside Unity editor. I tried adding this line under `Instantiate()`:

```
enemyPrefab.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas"), false);

```

However, I get an error saying it can't convert from `Unity.GameObject` to `Unity.Transform`.

How do I make the prefab appear inside the `Canvas` instead of behind it? Thanks in advance!

This is what it looks like when it creates it in-game: `Enemy_Orange3(Clone)` is created outside of the canvas and at the bottom left instead of the center. My camera is in the same position and is the same size of the canvas.

# Answer
`SetParent` like below. You have to use a another `GameObject` to instantiate and set the parent.

```
GameObject enemy = Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
enemy.transform.SetParent (GameObject.FindGameObjectWithTag("Canvas").transform, false);

```

Setting parent is done with transforms of two objects.
> 1 votes

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


title: Big maps with deep zoom and pan

text:
# Question
Title: Big maps with deep zoom and pan
I have a world map of 14048x7134, the game starts with the zoom completely out and during the operation it zoom in and zoom out and pan in all directions, it can get really near the surface, at almost a 1:1 ratio between the screen and the map information. It is going to be draw in a 1024x768 screen.

Scale a 14048x7134 to fit 1024x768 in each frame it's way far from efficient, so I am wondering... What strategies there are to solve this problem? Is there any tool or library to help in this process?

# Answer
> 5 votes
If you have access to shaders, you can invert the drawing logic. Normally you *loop through tiles* and draw each one. When you're zoomed out there are a lot of tiles to draw. Zooming out is slower. Inverting the logic, you can *loop through pixels* and figure out which tile that pixel is on, and that tells you which sprite to draw, and then you look up a color in the sprite. This is weird but it means that no matter what zoom level, you have the same number of draw calls (just one quad), and the same amount of work to do, at least for the tiles. The objects on top of the map don't work with this trick so you'll still have to draw them separately.

To make it work you put the game map into a texture. The texture *color* tells you which *tile* to use. You also have the tile sprites in another texture. For example if you have 32x32 pixel tiles, and 16x16 of them, you can put that into a 512x512 texture. If the game map is 200x200 you can put that into a 200x200 texture, where each color is {red = 0.0 for column 0 to red = 1.0 for column 15, green = 0.0 for row 0 to 1.0 to row 15}.

If the tile to draw is in column 3, row 9, then you'd store {red = 3/15, green=9/15} as the color. The shader then looks up the tile coordinates first. It would see that it needs to look in the *spritesheet* at column 3 (which starts at pixel x=3\*32) and row 9 (which starts at pixel y=9\*32). It then calculates which pixel of the sprite it needs to draw, and looks that color up in the spritesheet.

I had tried this out a long time ago with this flash demo, and then I tried to find other people who had the same idea and found this javascript demo and a blog post about the technique. Some of the comments on that blog post suggest that it may not actually be that efficient of a shader, so if you're going to try this it's worth measuring the performance.

# Answer
> 3 votes
You can create something like level of details for this. There are three ways you can handle this:

I. Create tiles that will cover the same amount of screen but have smaller resolution. You stay with same number of draw calls but with less data per draw.

II. Create tiles that are bigger so you get less draw calls.

III. Merge this two methods and create bigger tiles but also with less data per tile of normal size.

Third option is the best in my opinion. When you zoom out there will be lack of details so there is no reason to render tiles with all data.

Of course this will take more memory and you will need to calculate which tile render depend on distance from camera.

Also if this is one big image and you can write shader for rendering you can just change vertices uv's in shader. With this you can render just one quad (2 triangles) and I think this is the best solution ;)

---
Tags: 2d, tilemap, maps, scrolling
---


# Question
Title: Issues with character controller (unity 4 project in unity 5)
I'm having the weirdest issues with a game me and a mate have been working on. They came up immediately after moving from the last version of Unity 4 to Unity 5.

The two objects (player and enemy) return an error "**Character Controller Settings are invalid**" both on starting and stopping the game.

The enemy settings are:

```
Slope Limit:        50
Step Offset:        60
Skin Width:         0.003
Min Move Distance:  0
Center:            (0, 0, 0)
Radius:             0.01
Height:             0.01

```

some of the values have had to be scaled down to accommodate for the scale of the actual model.

Then, whenever the "Move" function calls (which use to have the enemy move towards the player), I get

**CharacterController.Move called on inactive controller**

which I have located to come from this code:

`_controller.Move(moveDirection * Time.deltaTime);`

where moveDirection is just a Vector3 co-ordinate of where to move too.

as I said, this was all working before I converted to the new version of Unity. I have checked and confirmed that the Character Controller is both correctly linked and enabled. I have not found anything useful looking up problems others have had with a similar error, and it's pretty much got me stumped.

# Answer
I have since identified that this may have been corruption resulting from an upgrade of Unity versions mid-project.

As I have had many other weird problems as a result of updating Unity, since, this is the best I have come up with. I will consider any future answer that goes to better effort to explain why it was happening, and would advise anybody facing a similar issue to greatly consider waiting until after project completion before performing updates to Unity.
> 0 votes

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


# Question
Title: How does one go about offering a mobile game, or offering all in-app purchases to backers?
I am planning on trying to get my android game kickstarted. Of course, it's too early in development, and I will wait on until 60% done to do the kickstarter.

Some of the rewards I am hoping to give my backers are:

1. The android game without having to pay
2. All in-app purchases unlocked for them

Since the google Play store (or other market places) would be where I would put my game up, how would I be able to reward my backers?

I could give them an apk, but I would want them to enjoy the freedom of downloading from play store, getting automatic updates, re-installing whenever they want etc.

I am hoping some of you have done something similar and can shed some light on how one goes about this?

Thank you.

# Answer
> 3 votes
I haven't released any games, but why not make it so your backers have to put in an email with a special code you send them? Your game will be attached to their accounts somehow and you will be able to achieve everything you just mentioned.

# Answer
> 0 votes
If you game is not out yet, check out itch.io. set your indie game up there, mobile users can download from itch.io. From creating a dev account on that site, you can send people product keys. You create a product key for each backer, and send the key to the person. they then activate this key and download from itch.io(Its free to upload to itch.io, as some mobile marketplaces it is not.But you can sell on itch.io as well, so use it to gain a fan-base, make some profits etc. Thats my advice) but if your going to splash the cash and upload it to Mobile Marketplaces, i can tell you from my experience that giving people codes is easier on android, but its still not a massive task on I-store(Cant for the love of me remember the correct name).

*summary*

Id advise you go on itch.io to upload as its a good starting platform for indie games both pc and mobile. If you do go with a store like Google play store etc then its still going to be easy, just recommending something to save you money :) Hope i helped.

---
Tags: android, game-maker, monetization, fund-raising
---


# Question
Title: What algorithm can I use for handling two types of HP, one of which may be undefined?
In my game, each unit has two types of HP: Hard and Soft. Soft represents the human part of the unit, while hard represents anything mechanical. For example, a regular rifleman would have 100 softHP, and 0 hardHP. Another example would be the Tank which has 100 soft and 1000 hard (subject to balancing).

Now, the problem I'm facing is the fact that it should be enough for one of these types of HPs to be =\< 0 for the unit to die - a Tank can't work without its driver, and it needs its gears, nuts, and bolts to function properly.

At first I was thinking of setting the soft and hard values for a unit, but leave, for example infantry, with an undefined value for hard HP, but this becomes an issue when a weapon hurts a unit: A weapon can hurt both hard and soft. A check for undefined value also becomes an issue, as many other things can affect HP as well, thus necessitating this check to be done many places, which to me seems very redundant. Another thing I was thinking of would be to set the hard HP for infantry abnormally high, to the point where it would "never" reach 0, but this is bound to bite me at a later point, I'm sure. I could easily overcome this hurdle some other way, but I would love some fresh eyes on this, in case there are any obvious solutions that I'm missing.

Any suggestions? Pseudo-code would be appreciated.

# Answer
> 3 votes
The solution by congusbongus is good, but I would suggest a solution which is scalable to even more HP types. The advantage of this method is that you can easily add more damage types later without editing any of the old units which aren't supposed to have them, like for example EMP damage which only affects high-tech units or PSI damage which only affects psionic units.

Implement the HP values of a unit as an associative array (also called "Dictionary" in some programming languages) with key `HpType` and value `int`. The array can have any number of entries (including none, which would be a completely invulnerable unit). The definition files could look like this:

```
units = [
    {   name: "Rifleman",
        HP: { soft: 100 },
    },
    {   name: "Psyker",
        HP: { soft: 80
              psi: 100 }
    },
    {   name: "Tank",
        HP: { soft: 100
              hard: 1000 },
    },
    {   name: "Anti-Grav Laser Tank",
        HP: { soft: 100
              hard: 1500
              emp: 50 }
    },
    {   name: "Psi Cyber Mecha Bot 3000",
        HP: { soft: 80
              hard: 3000
              emp: 100
              psi: 100 }
    }
]

```

The method to reduce the amount of HP of a unit takes two arguments, `HpType` and `value`. The method first checks if the unit actually has an entry in the `HP` associative array for that damage type. When it doesn't find one, it does nothing. When it does find a corresponding entry, the value is decremented, and when less-or-equal zero afterwards the unit is destroyed:

```
function reduceHpIfApplicable(HpType type, int amount) {
     if (this.HP[type] != null) {
          this.HP[type] -= amount;
          if (this.HP[type] <= 0) {
               this.isAlive = false;
          }
     }
}

```

**tl;dr:** This is a variant of the "undefined" solution.

# Answer
> 4 votes
Going with an "undefined", or "special" value for HP is the way to go, but you don't have to worry about having to check for it in many places as long as you abstract it well.

There are many ways to do it, but depending on your language one of the more abstract ways to do it is to use a different strategy for it, and use it to handle all the things you want out of a HP object, and don't worry about how it's actually represented - numeric or else. In your example, you may want to `damage()`, or ask it `isDead()`. So focus on those interfaces:

```
class HP {
    // private; don't worry about this if you're not the HP class
    int value;

    // used for things like the UI
    func getString() { return value; }

    func damage(amount) { value -= amount; }

    func isDead() { return value <= 0; }
}

```

And then you have a special class for "undefined" HP:

```
class UndefinedHP : HP {
    // in your UI you may want to handle this like display a grayed-out bar
    func getString() { return "undefined"; }

    // does nothing
    func damage(amount) { }

    // always alive
    func isDead() { return false; }
}

```

And then your units might look like:

```
units = [
    {name: "rifleman", softHP: HP(100), hardHP: UndefinedHP()},
    {name: "tank", softHP: HP(100), hardHP: HP(100)}
]

```

Then you deal hard/soft damage to these units and things will just work - the rifleman will never die from hard damage, and so on.

---
Tags: algorithm, game-mechanics
---


title: Sprite sizing for my game

text:
# Question
Title: Sprite sizing for my game
I have recently started a new project with my SO (Significant other)and she is doing the art for my game (Pixel art) now i have always gone with 32x32, 64x64 and so on (Using 16x scale) but she thinks we should only have world objects tiled at that scale i.e the floors and walls etc, but the character and crafted items, weapons etc as whatever other scale, as it wont affect it. Am i correct in thinking this could lead to collision issues, scaling issues etc if we used, say a 50x16 character scale? I know this may be opinion based (Although im not sure) i just want to know if it will affect things like collision and other mechanic's if the sprites don't all follow the same size scale.

# Answer
> 2 votes
so i tested this by using 32x32 floor tile, with a 50x40 box as the player and no problem persists, so thank you to everyone who commented and helped.

---
Tags: game-design, game-mechanics, platformer, game-maker
---


# Question
Title: How do videogames store information offscreen?
I'm trying to make a videogame from scratch, but I'm really new to this and keep running into basic issues. Most importantly, how do videogames store offscreen information? What I mean is, how does the program know what to display next onto the screen? Or even, if the player changes the environment, how does this change remain for the next time it loads onto the screen?

For example, in New Super Mario Bros, if you hit a ? block and then go off screen, and come back, it still remains hit. How is this information kept and then executed the next time the player loads the block? Why doesn't it just reset?

# Answer
> 58 votes
Usually you should separate the logical state of your game environment from the visual representation.

The player might only see a small part of it on their screen, but you still keep the state of the whole level in memory and usually also calculate the game mechanics for the whole level. When your world is so huge that this would require too much ram and/or cpu, you can suspend further away areas to hard drive.

Your rendering subroutine checks which parts of the level are currently on the screen and then only draws those. Whatever is off-screen isn't drawn, but that doesn't mean it isn't updated.

# Answer
> 37 votes
You are going at it backwards.

You start with the logical state of your game and model that. The whole logical state of the entire world will almost certainly be too much to be held in memory at once, so you break it down in smaller parts that can be loaded and saved independently. These parts are often referred to as *chunks*. These chunks can form a continuous world, but they can also be separate levels/instances. Terminology varies wildly depending on genre and which technique you want to use.

Then you load those parts that are of interest -- that is, chunks that are in the vicinity of the player. Chunks that are too far away are saved to disk/permanent storage and unloaded from memory.

And then, as last step, you determine what is actually visible and create the *visual representation* of the current game state and render it on the screen.

Of course you would try not to rebuild the entire visual representation every time but cache it and re-use it if you have parts that are already constructed, but that is the main principle.

---

This holds true for any program that has output. If you write a program with a normal GUI, like a text editor, you would likely model the document, and then the GUI would determine the state and visible parts of the document and render it to screen. Or fill form fields appropriately, or else.

The main gist is: Think about where and how you store the data first (probably alongside with how to represent it). Almost every program has to deal with data storage. There is only very few cases in which you don't store any data.

# Answer
> 6 votes
As others have said, you keep a map (e.g. in an array) and draw the visible part of it to the screen, and don't read back from the screen.

But in some older systems you would literally keep data offscreen. There would be, say, 400x300 pixels of video memory for a 320x200 display, and you would define a viewport into that ("start at X=10 Y=30"). So you could scroll the screen by just adjusting a register. You wouldn't have to spend the hundred thousand cycles required to move the bytes around, you just change where the video hardware starts reading them.

The NES has this, combined with a tile-based system: http://wiki.nesdev.com/w/index.php/PPU\_scrolling

The NES never constructs the full image in memory, because it doesn't have enough RAM. Instead, there's a RAM array that defines a two-screen-wide set of tiles. One byte per kind of tile. The video hardware looks up the tile and X/Y offset coordinates in order to decide what pixel should appear at any point.

# Answer
> 1 votes
Well, if you are asking this kind of question you are going to have a long road to get to the point where you can make a game. But, getting to the heart of your question, the program can save the state of many different things in variables which are in the back end of your program. Let's look at a couple of examples.

Mario Brothers (or similar) saves the state of the level you are in. that might include how far you have gone before you died, if a block was hit or not. In some a more object oriented sense, the game just says "be a block here" and the block exists. then when you hit the block, the block changes its own internal state to say "I was hit". Data like that can be stored in a variety of ways.

Your word processor saves its data in a data structure. Now there are lots of these and many ways they can be implemented, but probably it uses some form of a tree. In a tree you have at least one node. Anything added before it goes to the left. Anything added after it, goes to the right. After you add three nodes you have two of them hanging off the middle node. And the tree can grow even larger with new pieces being added anywhere and the tree will rebuild itself.  Or think about shooter games where your enemy wanders around. Each of them has variables which tracks their location, life, etc. so that when you wound one, it will remember that it was hurt.

All of these things require a knowledge of data structures. It goes way beyond what you see on the screen. I would suggest reading about arrays, lists, hashes (sometimes called dictionaries or maps) and then coming back to your problem.

Here are some good starting materials:

# Answer
> 0 votes
To an extent, this is a function of how 3D is rendered. For example, OpenGL will automatically cull geometry outside of the -1.0, +1.0 range in X-Y screen space (Z is more complex but similar). Culled geometry never generates fragments (approximately pixels) and thus is never turned into actual imagery, despite being sent to the system to render. In any case, it's impossible to write to space outside the render window (if everything is working as it should).

In some contexts, it's enough to rely on this behavior as an optimization. However, you still have to pass all your game data through at least one rendering stage (vertex shaders) before the video card can know what is visible. In something like, say, Skyrim, that would be impractical. Not only do you have to send every vertex in the world through the rendering pipeline, but you have to *load* every vertex into system/video memory. That's inefficient, if even possible.

So, many games will make use of CPU-based culling. They will typically implement some sort of LOD (level of detail) system, where the quality and existence of assets are impacted by how important they are assessed to be in a given context. A pyramidal mesh might be an acceptable approximation for a mountain if you're 50 miles away from it. If you can't see it at all (like it's blocked by other mountains), there's no need to even load it. There are a number of more complex methods for doing this that are topics I don't feel are directly relevant to the depth requested by this question, but look at tessellation for one of the most common examples.

The real gist of this is that the visuals are only the product of the game. The actual data has nothing directly to do with what you are seeing or not seeing most of the time, and the data is filtered by various stages to remove extraneous information before hitting the point where a picture is written to the screen. Depending on the engine design, visuals can be extremely decoupled from the actual game logic, so far as something like having a 2D and 3D interface to the same game is a possibility. It's even possible for many game engines to run with no output what-so-ever; sometimes this is used to test game AI.

That's where things can get complicated, though. In something simple like a Mario game, it is not too prohibitive to calculate the movement of all enemies in the level, even if they are not visible. In modern contexts, what is *happening* off-screen is an actual question of serious consideration. If there are multiple entire cities of NPCs, how do you handle how they behave when they are completely culled - like when the player is in a different city? Do you really want to be computing hundreds of NPCs' decisions all the way across the map? The answer is usually no, but the exact approach to accomplish not doing so can vary, and it can have some impacts upon the game.

It's important to note that this is how things work *now*. The old Mario games themselves were likely programmed in very different ways (I can't speak to the exact ways), given the extreme hardware limitations at the time. The concept of 3D did not exist back then; yet today almost all games, even ones which are entirely 2D, use 3D rendering in some form, even if they don't know they do. Modern video hardware is 3D first, and 2D rendering (at least when it makes use of the hardware properly) merely ignores the 3rd dimension.

# Answer
> 0 votes
To answer your question: video games keep the state of the game world in some abstract data structure that has nothing to do with the screen. This is then rendered to the screen as needed (i.e., depending on where the player is).

Games that use the video RAM directly for state purposes were around in the '80s in the 8-bit, maybe even in the 16-bit era, but unless you are developing for that platform or for some µC which counds its RAM in KB instead of GB, forget about it.

That said, you seem to be very new to everything related to programming, or the question would not have come up. I suggest going at it step by step, programming very easy things first; maybe something that has only textual input/output (simple prompts and all that). To be honest, the time when I did that is around 30 years past, so I have no really good resources for you, but your local library *might* just be better than the internet to give you a really good start in programming.

---
Tags: game-design, architecture, software-engineering, game-mechanics
---