# Question
Title: Is the viewport meant to be an absolute representation of where the underlying device is drawing?
I know this may sound like an odd question but I just wanted to confirm which way it is.

Currently I am using XNA within Windows Forms (MDI) and I am just wondering about the viewport, as I have multiple forms with their own graphics device to draw with.

Now originally I just assumed the viewport was meant to be a basically a wrapper for the screen size (i.e., width and height), however I noticed it contains an X and Y. So then I was unsure if it was meant to directly represent the drawing region of the device.

Take for example the below scenario:

I have a forms with a panel which is docked within a group box, its relative position in the form is `{ X: 100, Y: 100, Width: 320, Height: 280 }` however its absolute position on the screen would be lets say `{ X: 400, Y: 320, Width: 320, Height: 280 }`. Then if I were to use it like I was originally assuming the panel itself which hosts the underlying handle for Xna to draw to it would be `{ X: 0, Y: 0, Width: 320, Height: 280 }`.

So if you imagine I then start dragging the window around a bit, the relative positions do not change, but obviously the absolute one would, as you could technically drag the panel off screen.

So basically the question is, do I need to use absolute positions for my viewport and update them every time the graphics device is about to be drawn, or do I use relative positions and only update when the area is resizing? and if so is it relative to the form, or is it always going to be 0,0 for the x/y in this scenario?

# Answer
> 7 votes
No.

The **viewport** is a rectangular region on the **backbuffer** that determines the area in which the rasteriser draws pixels. A viewport (X,Y) of (0, 0) is always the top-left corner of the backbuffer (in XNA). You can freely move and resize it *within* the backbuffer.

The **backbuffer** is the underlying surface that the GPU is drawing to. To resize it you have to reset the graphics device. It doesn't have a position of its own - it is drawn on whatever window it is attached to, using that window's position (in this case, a panel counts as a window).

When rendering, the rasteriser takes inputs in **projection space**, converting vertex positions to pixel positions within the **viewport**. The position (-1, -1) in projection space is in the bottom-left of the viewport, and (1, 1) is in the top-right. To transform the 3D vertices in your world into projection space, you use a projection matrix.

(`SpriteBatch`'s default projection matrix lets it take input coordinates in client space within the viewport.)

Here are some references about the various things that determine display size and about projection space.

# Answer
> 3 votes
Taken directly from the Winforms Series samples, here's the relevant bit of code related to your question. There was also a bit of commentary in there that might be useful.

```
void BeginDraw()
{
    // ... other code handling device resetting

    // Many GraphicsDeviceControl instances can be sharing the same
    // GraphicsDevice. The device backbuffer will be resized to fit the
    // largest of these controls. But what if we are currently drawing
    // a smaller control? To avoid unwanted stretching, we set the
    // viewport to only use the top left portion of the full backbuffer.

    Viewport viewport = new Viewport();
    viewport.X = 0;
    viewport.Y = 0;
    viewport.Width = ClientSize.Width;
    viewport.Height = ClientSize.Height;
    viewport.MinDepth = 0;
    viewport.MaxDepth = 1;
    GraphicsDevice.Viewport = viewport;

    // ...
}

```

In short, they never change the `Viewport` X and Y anywhere on the code and it still works in the scenario you described.

---
Tags: xna, windows-forms
---


# Question
Title: How should I connect objects when using the MVC paradigm?
This has been confusing me for the past week as I am trying to make my first actual game. It's only my 2nd year learning Java so I am really trying to learn how to program like a professional organization and how classes interact and whatnot.

I found that the MVC is generally the pattern for professional programs (although there are different ways). I've been trying to code in this pattern and have been confounded by the connections. I don't understand code-wise how to connect them but I understand the concept.

For example, in my game I have a Card class which contains all the logic for the card but I also have a CardDisplay class which contains the paint override and extends JComponent displaying the image of the card and the listeners. Should I consolidate them together or are they suppose to be separate?

Also how do I connect the view to the controller such as my View class containing the JFrame and update methods + GUI elements. Do I create a instance variable of View in my Game class? Do I Create the variable in the Main method?

Basically, I really am just trying to progress past learning the "actual language" and more of the technique and structure behind professional programs. I've been looking at the structure of Notch's Minicraft (not minecraft!) source code if that helps?

# Answer
MVC, like all paradigms, is a tool. It has it uses and its problems. The high-caliber professional engineer does not dogmatically adopt MVC but takes from it what he or she needs and discards the rest. The focus should be on building a readable, maintainable piece of software, not on following MVC to the letter.

> I have a Card class which contains all the logic for the card but I also have a CardDisplay class which contains the paint override and extends JComponent displaying the image of the card and the listeners. Should I consolidate them together or are they suppose to be separate?

It is generally a good idea to keep game logic (`Card`) and render logic (`CardDisplay`) distinct, regardless of whether or not you are trying to employ MVC or not. Consequently I would say this is a good approach.

> Also how do I connect the view to the controller such as my View class containing the JFrame and update methods + GUI elements. Do I create a instance variable of View in my Game class? Do I Create the variable in the Main method?

The controller object generally knows about (and thus contains some reference to) the view and model objects so as to facilitate the communication between them. The controller is usually the really vaguely-defined aspect of any particular MVC scenario, especially in games, where most of the controlling comes from a singular input layer that feeds its updates directly into the game logic code. You rarely actually need a distinct controller type for every logic or render type (for example, you should not really need `CardController`).

The bits of your code responsible for turning user input into commands probably lives somewhere in your game loop and those commands translate to operations on the set of `Card` objects currently in play. Your card render objects can contain a reference to the corresponding `Card` object (or be given one immediately to render) such that they always draw the most up-to-date rendition of the card's logical state.

You will probably want to simply create an instance of your overall view (which presumably owns all the `CardDisplay`s and other GUI elements and such, in your game class. You probably will have one instance of your game class created somewhere in your Main function or entry point.
> 5 votes

---
Tags: java, gui, mvc
---


# Question
Title: Which is worst: Too many VertexShader instructions, or FragmentShader instructions?
I want to have a better understanding of how to create shaders with optimal performance and realize where some bottlenecks can occur.

Is it usually favorable (when possible) to delegate most of the work to the VertexShader since in certain situations it may only need to process a few vertices vs. having the Fragment process the same thing potentially on thousands of pixels?

For example, if I have scrolling UV values for a texture, is it best that I pass this scroll amount in the Vertex-Shader so that it adjusts the start UV + scroll UV to a Variant register for the Fragment to read, or to just use a Fragment Constant with the scroll UV amount stored in it which will be added with the start UV's read from a Variant register?

Is passing values to one kind of Constant register (Vertex vs. Fragment) faster than the other?

# Answer
This is going to be one of those "it depends" answers, so let's get that over with first: "it depends".

The objective here is not to reduce workload in one stage but to balance workload across all stages. That's what keeps your pipeline pumping nicely without each stage needing to go idle while waiting on the previous stage to complete.

So - with specific reference to your question - if your fragment shader is currently fairly lightweight but your vertex shader is already doing a lot of work, you would put the extra work in your fragment shader. Conversely the opposite is also the case.

A further consideration is that sometimes putting work in the vertex shader is just not acceptable on quality grounds. An example would be a sine wave or a sqrt calculation - the results of these will not linearly interpolate well, so if your output is dependent on them you want to put them in your fragment shader.

Regarding constants, sometimes the vertex shader can be faster and sometimes it makes no difference at all. Updating fragment shader constants can sometimes cause a full pipeline flush if the update requires a new shader to be uploaded (see http://tomsdxfaq.blogspot.com/2006\_04\_01\_archive.html#114482755569486635 for a discussion around this) but this shouldn't really be the case with modern hardware.

As always the correct answer is - profile, determine if it's a bottleneck, then address it, but not before.
> 6 votes

# Answer
Of course, this highly depends where your bottlenecks are. If your application is geometry-limited, offloading work to the fragment shader (or doing additional work at effectively no cost) might be a good idea, if it is fill-limited offloading work to the vertex shader is a good idea. If it is CPU-limited, it might even be an idea to move some work from CPU into shaders.

That said, nowadays most applications are usually fill-limited (if not CPU-limited). This is on the one hand due to the usually much more complicated effects done in the fragment shader than in the vertex shader and the fragment shader's dependence on steadily increasing screen resolutions. And on the other hand due to the fact, that you usually simply have fewer vertices than fragments and a triangle should usually cover more than three pixels. So in general it is usually a good idea to make the vertex shader help out the fragment shader as good as it can, in the same way as it is usually a good idea to precompute per-object data as much as possible and make it uniforms instead of doing things for every vertex (if possible, of course).

And to your last question: It shouldn't make a difference, in fact vertex and fragment shader (and all the others) share their uniforms/constants.
> 2 votes

---
Tags: shaders, performance, optimization, gpu, agal
---


title: Ray Triangle Intersection issue

text:
# Question
Title: Ray Triangle Intersection issue
I'm trying to perform ray triangle intersection on a mesh made of triangles. The below code seems to work fine but only about 50% of the time. The ray often gets into positions where no intersection is detected when there definitely should be. Is there something wrong in my function that isn't checking for intersection under all circumstances.

```
bool rayTriangleIntersect(Vector3 rayOrigin,
                          Vector3 rayDirection,
                          Vector3 vert0,
                          Vector3 vert1,
                          Vector3 vert2,
                          ref Vector3 intersectionPosition)
{
    // this originally comes from http://www.graphics.cornell.edu/pubs/1997/MT97.pdf

     float u, v, t, det, inv_det;
     Vector3 edge1, edge2, pvec, tvec, qvec;

    Vector3 direction = rayDirection;
    direction.Normalize();
    t = v = u = 0f;
    edge1 = vert1 - vert0;
    edge2 = vert2 - vert0;
    pvec = Vector3.Cross(direction, edge2);
    det = Vector3.Dot(edge1, pvec);

    if (det > -0.00001f)
        return false;

    inv_det = 1.0f / det;
    tvec = rayOrigin - vert0;
    u = Vector3.Dot(tvec, pvec) * inv_det;

    if (u < -0.001f || u > 1.001f)
        return false;

    qvec = Vector3.Cross(tvec, edge1);
    v = Vector3.Dot(direction, qvec) * inv_det;

    if (v < -0.001f || u + v > 1.001f)
        return false;

    t = Vector3.Dot(edge2, qvec) * inv_det;

    float rayMagnitude = rayDirection.magnitude;

    if (t <= 0f || t >= rayMagnitude)
        return false;

    intersectionPosition = rayOrigin + (rayDirection * (t / rayMagnitude)); // percent along ray

    return true;
}

```

and im calling it with

```
for (z = 0; z < LENGTH - 1; z++)
{
     for (x = 0; x < WIDTH - 1; x++)
     {
           v0 = verts[(z * WIDTH) + x];
           v1 = verts[((z + 1) * WIDTH) + x];
           v2 = verts[(z * WIDTH) + x + 1];
           v3 = verts[((z + 1) * WIDTH) + x + 1];

           if(rayTriangleIntersect(rayOrigin, rayDirection, v0, v1, v2, ref intersectPosition) ||
              rayTriangleIntersect(rayOrigin, rayDirection, v1, v2, v3, ref intersectPosition))
           {
                 Debug.log(Intersection found at : " intersectPosition);
           }
    }
}

```

I'm really stuck on this one so any guidance would really be appreciated.

Edit

The triangle are defined like this:

```
 for (z = 0; z < LENGTH - 1; z++)
   {
        for (x = 0; x < WIDTH - 1; x++)
        {
            triangles[index++] = (z * WIDTH) + x;
            triangles[index++] = ((z + 1) * WIDTH) + x;
            triangles[index++] = (z * WIDTH) + x + 1;

            triangles[index++] = ((z + 1) * WIDTH) + x;
            triangles[index++] = ((z + 1) * WIDTH) + x + 1;
            triangles[index++] = (z * WIDTH) + x + 1;
        }
    }

```

# Answer
Try changing

```
 if (det > -0.00001f)
        return false;

```

to,

```
 if (det > -0.00001f && det < 0.00001f)
        return false;

```

Currently, your code only checks one side of the triangle
> 3 votes

# Answer
Your code seems to use quads and it seems that you don't use the two triangles from the quad but two overlapping ones (say the second one is wrong), try this instead (see the "v2, v3, v0" part) :

```
          if(rayTriangleIntersect(rayOrigin, rayDirection, v0, v1, v2, ref intersectPosition) ||
          rayTriangleIntersect(rayOrigin, rayDirection, v2, v3, v0, ref intersectPosition))

```

If that doesn't work, you could try v0,v3,v1 or v1,v3,v2 or check out how your quads are actually built and figure it out.
> 4 votes

# Answer
I don't know what's the problem with your implementation, but I have used the method below (taken directly from this sample) on a raytracer and it worked correctly and performed well too. So you might consider swapping to this implementation:

```
/// <summary>
/// Checks whether a ray intersects a triangle. This uses the algorithm
/// developed by Tomas Moller and Ben Trumbore, which was published in the
/// Journal of Graphics Tools, volume 2, "Fast, Minimum Storage Ray-Triangle
/// Intersection".
///
/// This method is implemented using the pass-by-reference versions of the
/// XNA math functions. Using these overloads is generally not recommended,
/// because they make the code less readable than the normal pass-by-value
/// versions. This method can be called very frequently in a tight inner loop,
/// however, so in this particular case the performance benefits from passing
/// everything by reference outweigh the loss of readability.
/// </summary>
static void RayIntersectsTriangle(ref Ray ray,
                                  ref Vector3 vertex1,
                                  ref Vector3 vertex2,
                                  ref Vector3 vertex3, out float? result)
{
    // Compute vectors along two edges of the triangle.
    Vector3 edge1, edge2;

    Vector3.Subtract(ref vertex2, ref vertex1, out edge1);
    Vector3.Subtract(ref vertex3, ref vertex1, out edge2);

    // Compute the determinant.
    Vector3 directionCrossEdge2;
    Vector3.Cross(ref ray.Direction, ref edge2, out directionCrossEdge2);

    float determinant;
    Vector3.Dot(ref edge1, ref directionCrossEdge2, out determinant);

    // If the ray is parallel to the triangle plane, there is no collision.
    if (determinant > -float.Epsilon && determinant < float.Epsilon)
    {
        result = null;
        return;
    }

    float inverseDeterminant = 1.0f / determinant;

    // Calculate the U parameter of the intersection point.
    Vector3 distanceVector;
    Vector3.Subtract(ref ray.Position, ref vertex1, out distanceVector);

    float triangleU;
    Vector3.Dot(ref distanceVector, ref directionCrossEdge2, out triangleU);
    triangleU *= inverseDeterminant;

    // Make sure it is inside the triangle.
    if (triangleU < 0 || triangleU > 1)
    {
        result = null;
        return;
    }

    // Calculate the V parameter of the intersection point.
    Vector3 distanceCrossEdge1;
    Vector3.Cross(ref distanceVector, ref edge1, out distanceCrossEdge1);

    float triangleV;
    Vector3.Dot(ref ray.Direction, ref distanceCrossEdge1, out triangleV);
    triangleV *= inverseDeterminant;

    // Make sure it is inside the triangle.
    if (triangleV < 0 || triangleU + triangleV > 1)
    {
        result = null;
        return;
    }

    // Compute the distance along the ray to the triangle.
    float rayDistance;
    Vector3.Dot(ref edge2, ref distanceCrossEdge1, out rayDistance);
    rayDistance *= inverseDeterminant;

    // Is the triangle behind the ray origin?
    if (rayDistance < 0)
    {
        result = null;
        return;
    }

    result = rayDistance;
}

```
> 4 votes

# Answer
Without looking at the code in much detail, I'm going to take a guess that your triangle intersection routine only works from one side of the triangle, but your triangle "mesh" describes triangles with opposite "handedness" (if v0,v1,v2 is clockwise, then v1,v2,v3 is anticlockwise as seen by a ray from the same direction). This could be confirmed by e.g permuting the order of the latter to v1,v3,v2 and seeing if all or none of the tests succeed. If that is indeed the problem, and it's desired to have an intersection test succeed from either side of the triangle (rather than "back face culling"), then you probably need to handle the case of a negative "det" better.
> 1 votes

---
Tags: 3d, raycasting, intersection
---


# Question
Title: Pro's and Con's of Various 3D Game Engines
I normally code my admittedly simple games by hand in either Assembly or C but I'm looking to go a little more high level. I also want to build more modern skills so I'm looking at UDK. What are the pro's and cons of it for indie 3D development. I plan to use graphics, control and physics from the engine so I'm wondering if I should also consider source engine or anything else?

# Answer
> 20 votes
UDK is a proven SDK, used in many AAA titles. But as with any other professional tools, it has a quite steep learning curve. The 25% royalty term in the Commercial Licensing is also kind of painful. We evaluated it when we were planning to build a game for presentation purposes in our company.

There are other good alternatives :

* Unity, mature, cross-platform (Windows, Mac, Web, iPhone, iPad, and even Android), it also has a free version. I think this would suit your needs better, this is what we finally end up with.
* Torque Game Engine, IMHO not as polished as Unity, but worth a look.

There is also another good, lower-level library that you might be interested to check out:

* Ogre3D, open-source 3D rendering engine. It is a mature, stable rendering engine that has a very large user base. We used it in our projects. It is easily integrated with OIS for input, has bindings for Newton, PhysX, ODE & Bullet physics engines.

# Answer
> 6 votes
I also recommend Unity. The free version provides about 80% of the features of the paid version, and there is a large, active online support community.

# Answer
> 1 votes
jMonkeyEngine is a very good, general purpose, open source game engine.

There's a long feature list you can use to see if it covers your needs but in my experience it has pretty much everything you are likely to want for an indie game.

It runs on the JVM so you can get all the higher-level advantages of the managed Java runtime environment (proper garbage collection, multi-threading, cross platform etc.). Coding is normally in Java but you can also use other JVM langauges relatively easily (Scala, Clojure etc.)

# Answer
> 1 votes
Try 001. It's mediocre for experienced game designers, but really nice for people new to the game designing world.

# Answer
> 0 votes
Good JavaScript 3d engine (here you will have 3d engine in any browser - that is really cross-platform): http://github.com/mrdoob/three.js/

---
Tags: 3d
---


title: Constant size geometries

text:
# Question
Title: Constant size geometries
How can I display objects in a 3D perspective projection that look like as if their size does not change, despite of the camera's position? I am using DirectX 9.0. I know of PositionTransformed declaration usage, but I was thinking of scaling the objects in every frame as the camera zooms in/out to achieve this. Is there a way to know the "scale" of a perspective projection?

An example usage would be to show lines with constant width. E.g. roads on a map.

**Update, I've found the solution**

check the accepted answer.

# Answer
> 4 votes
Suppose we want an object to appear that it has constant size, regardless of the camera's position, in a 3D perspective projection. The solution is to scale the object in every frame, to increase/reduce it's size. Suppose we want the object to be 1/4 of the size of the viewport. This can be calculated as follows :

```
const double fov = Math.PI / 4.0;  //suppose 45 degrees FOV
float cameraObjectDistance = Vector3.Distance(Camera.Position, Object.Position);
float worldSize = (2 * Math.Tan(fov / 2.0)) * cameraObjectDistance;
float size = 0.25f * worldSize;

```

I hope this will be useful to others as well.

# Answer
> 0 votes
I haven't tried this but theoretically you could create the matrix without the 1/D projection transform. http://msdn.microsoft.com/en-us/library/bb147302.aspx to render these and you'd still get them settled properly into the 3D scene.

# Answer
> 0 votes
Just thinking out loud here:

Depending on if you zoom by changing camera position or changing FOV, apply this concept to the view matrix for the former, the projection matrix for the latter.

If you want some objects in the scene to follow normal size changes during zoom, but others to not change... You could use two view (or projection) matrices. One for everything in the scene that changes normally, and one for the object you are trying to keep uniform size. Simply keep it's position (or FOV) a constant distance (or value) but in alignment and orientation with the other normally zooming matrix.

---
Tags: directx9, perspective
---


title: Using the AssetManager in LibGDX

text:
# Question
Title: Using the AssetManager in LibGDX
I am trying to use the `AssetManager` class in LibGDX and I understand how it works but I am trying to implement a loading screen. I have followed the `AssetManagerTest.java` file here, but I am having a hard time trying to figure out how to get it to work correctly. Can someone point me in the right direction? My goal is to load the assets (textures, sounds, fonts, ... etc) and update a bar with the percentage complete on the screen. I don't understand the `ResolutionFileResolver` and the `Resolution[]` in the link I provided. What are they for? My goal is to support a static class that can give me access to all of the assets I need in my game from any screen. Is there a preferred method to do this? Thanks.

# Answer
> 3 votes
To create a Loading screen you may want to follow the approach explained in the thread "How should I manage resources in a professional project" of LibGDX forum.

ResolutionFileResolver is used to load different assets depending the resolution of the device. For example, you define a file extension ".480800" for devices of 480x800 then the AssetManager loads one or the other asset based on the resolver.

Hope it helps.

---
Tags: android, java, libgdx, loading
---


# Question
Title: How to add energy ball which disappears when touched by player in UDK?
I am new to UDK and learning game development. I want to know about how to add a ball to the game world with the following effects/actions:

* Glowing effect
* Physics-like object (just having gravity)
* Particles when touched by player-avatar
* Disappears in 1-2 seconds after touch
* Score updates based on different colors of ball

I know little about this can be done by kismet, cascade and content creation, but do not know where to start. Please tell me the steps for this. I am trying this weekend in depth.

# Answer
> 1 votes
The first four thing you want to achieve can be done pretty easily from within UDK without having to use any UnrealCode. The ball will have to be a UTRigidBody, which can be added from the list of actors in the content browser. You can detect when the player is touching it with Kismet using an OnTouch event created with your UTRigidBody(the ball). Same goes for removing it and the particles, fairly simple through basic Kismet nodes.

If you don't know what any of what I just said means, all the information is gone through step by step in much greater detail than I could here in the official video tutorials. If you're just getting started with Unreal, I suggest you start there.

---
Tags: graphic-effects, udk
---


# Question
Title: How to resize an image loaded using ContentManager in XNA
I am new to XNA programming and I loaded the background image using ContentManager as a Texture2D object.

The background image which I have is of size 480\*320. I have kept the minimum game window size as 640\*480. My question is how would i resize the background image to the size of the game window.

Thanks in advance!

# Answer
Whatever size the destination rectangle is for any of the top 3 SpriteBatch.Draw functions is how large your image will appear on screen.

So try the below to automatically draw an image full screen.

```
SpriteBatch.Draw(background_texture, GraphicsDevice.Viewport.Bounds, Color.White);

```

Note this doesn't actually change the size of you image it just scales it to the specified size when rendered.
> 4 votes

---
Tags: xna-4.0
---


# Question
Title: Next-gen technologies to anticipate for development?
From the point of view of pure game design and planning, what are the technologies of the next-gen (post-360, PS3, and wii) consoles that I can anticipate for my design? In designing a new game, I want to leave it open-ended enough to incorporate the new technologies and start planning for future gameplay. Depending on the technologies, I might also want to change the style of gameplay.

# Answer
> 1 votes
A lot of your question depends on the type of game you are making. Recently, the big 3 game consoles have put a lot of effort into motion control based systems, and personally I expect that trend to continue.

However, there are 2 distinctly different approaches at this time. The Wii / PS3 approach involves handheld controllers combined with motion. The 360's Kinect eliminates the controller entirely and relies on pure player movement. Both have been relatively successful, so it is hard to anticipate which approach will be more adopted in the future.

---
Tags: game-design, planning
---


title: Pygame import error

text:
# Question
Title: Pygame import error
When I installed pygame and tried to run import pygame, I got this error:

```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 95, in <module>
    from pygame.base import *
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so, 2): no suitable image found.  Did find:
    /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/base.so: no matching architecture in universal wrapper

```

Any idea on how to fix it?

# Answer
I'm assuming you're on a Mac? The last bit of that error message: "no matching architecture in universal wrapper" is a clue that there is a 32-bit vs. 64-bit conflict.

I'll refer you to this post from not that long ago. That person had the exact same problem as you. One of the answerers was able to fix it.
> 2 votes

---
Tags: python, pygame
---


# Question
Title: Flash Professional vs FlashBuilder 4.6 for mobile app development
From the marketing materials I see online, it seems to me that FlashBuilder 4.6 is a subset of the functionality available in Flash Professional. If I understand correctly, mobile app development target iOS and Android started as a plugin for Flash Pro and has since been made a separate product.

But can Flash Pro still do all the multi-platform targeting that FlashBuilder 4.6 can do? What other considerations are there between the two applications that are critical to understand for mobile app development?

Thanks!

# Answer
Adobe pulled mobile support from Flash, so Flash Professional would not work for mobile development; however, I believe you can use Adobe AIR to package Flash for mobile. As for which is better for mobile development, it is easier to test mobile applications with Flash Builder.

Other than that, it just depends what you are trying to do. Flash Professional is good for animations. Flash Builder is better for code-heavy projects. I assume you are planning on making games, so Flash Builder would be best.
> 3 votes

---
Tags: android, flash, ios
---


# Question
Title: Pre game loading time vs. in game loading time
I'm developing a game in which a **random** maze is included.
There are some AI creatures, lurking the maze. And I want them to go in some path according to the mazes shape.

Now there are two possibilities for me to implement that, the first way (which I used) is by calculating several wanted lurking paths once the maze is created.
The second, is by calculating a path once needed to be calculated, when a creature starts lurking it.

My main concern is loading times. If I calculate many paths at the creating of the maze, the pre loading time is a bit long, so I thought about calculating them when needed.
At the moment the game is not 'heavy' so calculating paths in mid game is not noticeable, but I'm afraid it will once it will get more complicated.

Any suggestions, comments, opinions, will be of help.

**Edit:**

As for now, let `p` be the number of pre-calculated paths, a creatures has the probability of `1/p` to take a *new* path (which means a path calculation) instead of an existing one.
A creature does not start its patrol until the path is fully calculated of course, so no need to worry about him getting killed in the process.

# Answer
> 6 votes
BerickCook has expressed the idea correctly. Leave the calculations where they are if they work properly now.

If you can do the calculation before and you are sure you will not need them mid-game, then do it before. Else do it after loading. If the calculation during the game is unnoticeable you could do it there. If at some point the complexity evolves and the calculations become too heavy start optimizing.

But one thing: if your calculations are implemented to run mid game you can always force them to be performed during loading anyway.

There are numerous solutions:

* calculate/load the paths during level creation/loading
* use a second thread to calculate the paths
* optimize your algorithms
* use an interruptible system if you have no access to threading.

I have seen and used the last option in a mass market game. Simply make sure you properly save all the data needed for the calculation to resume, and check regularly for remaining time/operations during the calculation.

Depending on your case, the interruptible system could give preliminary and partial solutions that can be used event before the calculation has ended.

---

**Edit**: answering @Keeper

The "interruptible algorithm" was useful only because of the constraints we had. Basically we palliated to the lack of multithreading.

At one point we had a game where the AI had to compute large amounts of moves based on multiple dictionaries. During this calculation all animations would stop because the dictionaries were expanded with more data and the dataset holding the data was changed and less efficient when the game was adapted for multiplayer (where the AI had to interact even for the player's moves). We had only one thread available for the game loop (the imperative being the multi-platform code must run on all supported platforms). At this point it was decided to break the calculation algorithm so we could interrupt it. Therefore we couldn't just use the recursive system that was in place as variables could not be saved. The functions were replaced with objects which simply held all the necessary variables and pointers to parent and child objects. I don't remember the full implementation but each object had a way to:

* save the status of its current computations
* interrupt either at the end of a loop or during a loop (when a child object interrupts)
* exit when time's out
* resume where it stopped either restarting a loop at the right index or calling the child object currently being at the top of its children stack.
* clean everything if the computation is interrupted
* give the best partial result.

Only the most expensive operations were broken into separate objects and it took some time to find the right places where we could stop the calculations, but in the end it works very well.

We lost performance, but perceived performance was much better for the user as animations ran smoothly on all platforms, all platforms could then use the larger dictionaries without suffering from choppy animations or freezes. Also this allowed us to run multiple instances in parallel when we needed it later.

Of course now on the iPhone and iPad the game doesn't need this, using a second thread would be ideal. But I suspect the code is still there.

# Answer
> 8 votes
For now, since calculating the paths mid-game is unnoticeable, that is the ideal approach. If / when it gets to the point where gameplay is interrupted by the calculations, then switch it over to per-calculating the paths before the level is loaded.

Longer initial loading times are forgivable, but random FPS fluctuations during play generally aren't.

# Answer
> 2 votes
One possibility if you need it is to move the calculations to a second thread as almost every PC has more than one CPU core these days.

The basic process would be:

* When a creature requests a path add the request to a thread safe request queue and signal the thread.
* Creature stands idle while waiting for the thread to pop the entry off that queue, process it, and put it on a completed list.
* Each frame check the completed list from the main thread and assign completed paths to creatures.

You have to watch out for a few extra edge cases too (e.g. what if the creature dies before the request is processed).

---
Tags: loading, maze
---


# Question
Title: Game with static scene and bouncing balls. How to?
How to make a game with a static scene and balls that can bounce on it? What is used for this, generally? Physics engines? Even if this is a simplistic example?

# Answer
The easiest way would to be use a physics engine. Box2D has been ported to nearly every popular language. However, its impossible to make a more specific suggestion as you provide no contextual information.
> 2 votes

# Answer
The simplest way would be good if the static scene only has straight walls and flat ground. All you would have to do is multiply one of its components speeds by -1. If it collides with a wall, this would be the x component. If it is the ceiling or floor, this would be the y component. If you want to add in friction, multiply instead by -.7 or something similar.
> 0 votes

---
Tags: physics-engine
---


# Question
Title: Server-side physic simulations with hundreds of players
I’m currently working on a singleplayer physics-orientated game where I would like the physics to be simulated server-side. This because the game will have leadersboards, persistant player progression, etcetera and I want to prevent any type of cheating – basically a pure client-server architecture, the client is “dumb” and only displays what the server wants you to display.

The problem however is that the game will most likely be played by hundreds (maybe thousands) of people at the same time. This concerns me, as it will most likely kill server-processing power if I have to do and maintain hundreds of states at the same time.

I would have no problems moving all of the physics simulations to the client-side, but then I would really need a way to validate if the result of a client simulation is valid. However, I can't figure out how.

I have thought about running the simulation server-side once in a while to validate if the client is still playing fair, but I really want the server to have as less strain as possible.

Physics will become about as complex as the GDC 2011 demo by Glenn Fiedler, maybe even simpler. However, a lot more always-colliding rigid-bodies will be in a single scene and they will all be visible at once.

I have a hard time getting an answer to this particular case, as most resources on the web - again, Glenn Fiedlers site being a great one - speak about small-scale networked physics (eg. a FPS with 30 players, like Halo).

Any advice, websites, papers or the like on the subject will be very appreciated.

A recap of the questions I would like an answer to:

* How feasible is a client-server model? Is my server-processing power concern legit and grounded?
* Is it possible to reliably validate a physic simulation run by the client on the server? If so, how?

# Answer
You can validate client-side the submissions of other users, and have the client report to the server if a submission looks invalid.

Then you can take action (either ban the cheater, or ban who forged the false report). To check yourself if that submission is really invalid or not you can use a special client or whatever.
> 5 votes

# Answer
Your game is singleplayer, the only 'interaction' with the other players is a leaderbord. You could spawn an instance to check a simulation on your server for each submission, you don't need all the tricks of making sure physics are the same over 30 clients, so I don't think you need more resources than you have already since the physics are already working :).

Checking every result is gonna be a bit overkill, you could send the simulation compressed to the server whenever someone sends a score to the leaderbord, then only check the top 5% scores on your own server, or maybe even the top 1% or even smarter only check new highscores and assume everyone not better than #1 probably has a non-cheated simulation.

I don't know if your simulation is like, set up and don't interact (easy to check) or if players can interact with the sim while it is running, but be sure to do your physics in such a way that different floating point representations don't mess stuff up and make a valid run look invalid .
> 1 votes

# Answer
Don't do it, I can assure you that simulating physics solely on the server is a very bad idea. The main problem isn't server load, but responsiveness. The responsiveness on the client will be incredibly poor. The player will hit a button, then you'll have to make a round trip to the server before you get the results of the simulation. I've done variations of this in the past (mostly just button presses), and the results aren't pretty and should solely be done for very slow games which have any chances of getting away with it (and even in those cases the perceived lack of responsiveness is a huge issue).

A better scheme which I've been intending to try the next time this type of scenario presents itself is to pick players a very small subset of your playerbase, then you simulate for them server side for a short while and compare your results to theirs, without their knowledge. If they're deviating by to much (you have to expect some degrees of divergence), then you classify them as potential cheaters, and continue to simulate them for a while longer to confirm. What you'll get is some sort of curve by how much a legit player diverges compared to the server, influenced by network conditions etc, and you'll quickly see that the cheaters are outside of this curve. This system has the following benefits:

* Automated
* You don't sacrifice responsiveness
* As you just simulate a very small subset of your playerbase the load will be manageable, and even scalable (perhaps you pick fewer players to simulate if the load is high)
* Applicable to every game I can think of, so highly reusable
> 1 votes

# Answer
As Daniel stated, the big issue here is going to be programs which perform the action for the player; no in-game physics skewing would be necessary if the player was robotic arm with precision normally resolved for neurosurgery.
> 1 votes

---
Tags: physics, networking, multiplayer, simulations, validation
---


# Question
Title: How to get the texture coordinate of a neighbouring pixel for a blur shader?
I'm still having some trouble to get my head around fragment shaders and doing some image processing on textures. The context is a 2D sprite: a simple texture painted on a quad. All done with **OpenGL ES 2.0**.

My very basic goal is a simple blur filter using a 3x3 Kernel with average weights: every pixel used is weighed 1/9th and summed up.

Besides many ways to improve the performance of the fragment shader(code below) so far I'm still having some difficulties to find the right texture coordinate for the kernel.

My approach so far is to use the actual size of the quad on the screen on which the texture is painted and pass those two values to the shader. This is done **outside** the shader and **passed as a uniform** to the shader program.

```
glUniform2f(_offset, 1 / spriteWidth, 1 / spriteHeight);

```

This should result in the step in both directions to calculate a texture coordinate in the 0 to 1 space.

The result is kind of looking good. BUT I am still struggling if this is something that could be done within the shader. Is there a way to get the size of the texture within the fragment shader? If we would be only doing this on a bitmap, I'll just go from pixel to pixel and read the color of the surrounding pixels. I am wondering if my understanding of a fragment shader is quite right: It's run per rendered pixel on the screen. I found some examples for the GLSL to do this but I wasn't able to port it to OpenGL ES, so I had to start from scratch.

For the sake of readability I write a bit more code in hope it's easier to understand the fragment shader:

```
varying vec2 v_texCoord;
uniform vec2 u_offset;
uniform sampler2D u_texture;

const int size = 3;
const int KernelSize = size * size;

void main()
{
    int i, j;

    vec4 sum = vec4(0.0);
    vec4 intensityOfPixel;
    vec2 texCoordForKernel;

    for (i = 0; i < size; i++)
    {
        for (j = 0; j < size; j++)
        {
            texCoordForKernel = vec2(v_texCoord.x + (float(i) - 1.0) * u_offset.x,
                                     v_texCoord.y + (float(j) - 1.0) * u_offset.y);

            intensityOfPixel = texture2D(u_texture, texCoordForKernel);

            sum += intensityOfPixel * 1.0 / float(KernelSize);
        }
    }

    gl_FragColor = sum;
}

```

Thanks alot in advance!

# Answer
Yes, there is no way for the fragment shader to know what is the size of the bound texture.

Your best approach is to pass the pixel size already calculated instead of the texture bounds, since you are sparing two divisions that would be calculated once per fragment, adding unnecessary overhead.
> 6 votes

---
Tags: shaders, opengl-es
---


# Question
Title: Parallax Scrolling - Layers not preserving their relational positions
I've created a little 2D game engine with parallax scrolling and something has been bugging me for some time.

**Layers / objects set at a different depths / z orders don't preserve their position relative to each other. The position of each layer after substaintial camera movement seems to decay and become inaccurate over time**.

I have 3 layers / objects, each set at a different Z co-ordinate / layer depth. The higher the Z co-ordinate, the slower the layer moves; basically the more distant the layer is to the camera. Each layer being 1 level deeper than the next. For example:

```
layer1.z = 4;
layer2.z = 3;
layer3.z = 2;

```

Then, when rendering out all the layer positions every update. I use the following algorithm; let's use the first layer as an example:

```
layer1.x += (layer1.moveX -= cameraTarget.moveX) / layer1.moveZ;

```

moveX being the layer's / object's potentional movement modifier. So this should take into account not only the cameras movement, but the layers movement (if any) as well. This should allow dynamic bodies to work within the parallax scrolling paradigm.

For simplicities sake, even if I assume there are no dynamic bodies and just want to render background elements, I can simplify the above and do this instead:

```
layer1.x += (cameraTarget.moveX / layer1.moveZ) * -1;

```

I ASSUME this is the very core and basic math to doing parallax scrolling. Yet if I move the camera around enough, each layer seems to slightly offeset more and more. To test this, I even created a grid-like puzzle that fits together when all 3 layers match. It starts matching by default, and matches fine during the first initial movements, but after signifcant movements, it is unable to match perfectly again. Basically by moving the camera and tweaking it's position, I can't get the puzzle to match.

**What am I doing wrong?** I would think if everything passes through this algorithm, it should at least be consistant. Well, in saying that, to a casual observer it looks great, but on closer scrutiny it's flawed (I think). **Is parallax scrolling natually decaying / desctructive to objects relational postioning to each other?**

I am using Flash / ActionScript 3.0. One possibility I thought of was perhaps Flash's renderer could be doing something funky to my calculations when I assign these numbers to the x and y property of a DisplayObject. I've tried rounding too, in some naive attempt to make it more precise and perhaps have movement only to 1 sub-pixel.

**UPDATE**

My current setup is this, I have 3 layers, each of equal dimension layed out on the stage. So that at the start, the layers are where I want them, but they must just respond to camera movements.

```
layer1.z = 4;
layer1.x = 80;
layer1.y = 60;

layer2.z = 3;
layer2.x = 80;
layer2.y = 60;

layer2.z = 2;
layer2.x = 80;
layer2.y = 60;

// Place the player at the center of the screen, the camera directly follows / mimics the player's position
player.x = (stage.stageWidth / 2) - (player.width / 2);
player.y = (stage.stageHeight / 2) - (player.height / 2);

```

Then, in my render function that updates every frame:

```
// Capture camera movement
camera.x += cameraTarget.moveX; // cameraTarget being the player
camera.y += cameraTarget.moveY;

// Move all the layers
layer1.x = (camera.x + layer1.x) / layer1.moveZ;
layer1.y = (camera.y + layer1.y) / layer1.moveZ;

layer2.x = (camera.x + layer2.x) / layer2.moveZ;
layer2.y = (camera.y + layer2.y) / layer2.moveZ;

layer3.x = (camera.x + layer3.x) / layer3.moveZ;
layer3.y = (camera.y + layer3.y) / layer3.moveZ;

```

I've removed a few things my code has that would just confuse matters, but this is essentially what it does. For example, I have a loop that loops through an array of layers and then applies the transforms. Here, I'm only hardcoding it.

I also was using a Matrix to capture the rotation, scale etc... of the cameraTarget, which was nice.

# Answer
> 6 votes
Whenever you do a float operation, some rounding errors are bound to occur. Because you are adding each specific layer's position change on every frame, eventually these errors add up and become noticeable.

Say you have a max error `e` in each multiply operation, then with your algorithm the frame 1 position is:

```
   layer1.x(1) += cameraTarget.moveX * layer1.z;
=> layer1.x(1) = layer1.x(0) + cameraTarget.moveX * layer1.z;
=> layer1.x(1) = layer1.x(0) + layer1.moveX + O(e);

```

Then on frame 2 you get (assuming the same camera movement):

```
   layer1.x(2) += cameraTarget.moveX * layer1.z;
=> layer1.x(2) = layer1.x(1) + layer1.moveX + O(e);
=> layer1.x(2) = layer1.x(0) + 2*layer1.moveX + O(2*e);

```

As you can see, after N frames you'll have `O(N*e)` error in each layer's position, so the differences between layers may become noticeable.

The best way to avoid that is to calculate all layer positions from a single parameter, for example, using the camera position instead of camera movement:

```
layer1.x = cameraTarget.x * layer1Scale;
layer2.x = cameraTarget.x * layer2Scale;
layer3.x = cameraTarget.x * layer3Scale;

```

This way any error from previous calculations is wiped-out on every frame - even if cameraTarget has an error, it will be the same constant error for all layers.

---
Tags: 2d, flash, actionscript-3, parallax-scrolling
---


# Question
Title: How do I set a single pixel of an image in Slick2D?
I would like to set an individual pixel in Slick (i.e `Image.setPixel(x, y, r, b, g)`) but I can't figure out how.

There is an `Image.setPixel` function but it doesn't take x and y coordinates. Any ideas?

# Answer
> 4 votes
You're in luck.

In Slick2D, Image has a function called getGraphics, which will return you a Slick2D graphics context.

While the graphics context does not have a setPixel function, it does have a fillRect function that you can use to set a single pixel.

```
Graphics g = img.getGraphics();
g.setColor(color);
g.fillRect(x,y,1,1);
g.flush();//IMPORTANT!!!

```

I just tried this out myself, which is how I discovered the importance of the flush call. Also check out the example ImageGraphcisTest.java in the Slick2D src folder.

# Answer
> 2 votes
If you really want to make this from an `Image` object then you must:

* Get the texture with `img.getTexture()`
* Retrieve the inherent pixel data with `texture.getTextureData()`
* Parse the byte-array until you reach the pixel (x, y)
* Change the RGB value of this pixel

---
Tags: java, image, slick
---


title: merge textures 2D , in Xna

text:
# Question
Title: merge textures 2D , in Xna
i try to learn Xna, but now i have problem:

In my simple 2D game i have tile engine, using

```
    SpriteBatch.Draw(Texture2D, Rectangle, Nullable<Rectangle>, Color, Single, Vector2, SpriteEffects, Single)

```

to extract tiles from TileSet (1 big texture). This works nice.

But then i wanted to merge all displayed tiles into one big texture, instead of many small tiles (something like THIS). Problem is that, i cant use SpriteBatch.Draw() with 2 different overloads at same time.

So, is there any way to use GPU for (1.) extracting tiles from tileSet and (2.) merge tiles together (and render them as 1 texture) ?

thanks for ideas

# Answer
> 6 votes
Are you sure you really need to store the result into a *separate* texture? Normally you'd just iterate over each individual visible tile in your map and draw them one at a time inside the same `SpriteBatch` block. Since you're using the same texture in all the calls, the `SpriteBatch` class will automatically group all calls into a single dynamic vertex buffer and submit it to the GPU *all at once*.

But if you really need to render it to a texture, you can do it using the `RenderTarget2D` class which looks like a regular `Texture2D` but lets you set up the `GraphicsDevice` so that it draws directly to the texture instead of drawing to the screen.

Here's an (untested) example that should give you a general idea how to use it. First create an instance of `RenderTarget2D`:

```
RenderTarget2D renderTarget2D = new RenderTarget2D(GraphicsDevice, textureWidth, textureHeight);

```

Then call something like the following code *once* in order to render your merged tiles into the texture. Note: The way I draw my tiles is just an example, use whatever you're already using. The important part is setting and unsetting the render target:

```
// Set render target
GraphicsDevice.SetRenderTarget(renderTarget2D);

// Render your tiles as usual, this is just an example
spriteBatch.Begin();
for(int x=0; x<width; ++x)
    for(int y=0; y<height; ++y)
       spriteBatch.Draw(tileset, new Vector2(x*tileWidth, y*tileHeight), CalculateRectangleForTile(map[x,y]), Color.White);
spriteBatch.End();

// Unset render target
GraphicsDevice.SetRenderTarget(null);

```

And finally on your `Draw` method use the render target as a normal texture:

```
// On draw you can use your render target as any other texture
spriteBatch.Begin();
spriteBatch.Draw(renderTarget2D, Vector2.Zero, Color.White);
spriteBatch.End();

```

# Answer
> 0 votes
That tutorial works well for tiling an image across the viewport but is incomparable with an image map. What the author is doing is scrolling the sampling location on the texture and when the source rectangle extends past the borders of the Texture2D its wrapping around to select from the other side.

To render a tile map you are going to have to make as many draw calls as there are visible tiles.

Assuming that your tiles are in an 2 dimensional array this is easy

The left most visible tile is

```
var minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0);

```

The right most visible tile is

```
var maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width);

```

The top most visible tile is

```
var minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0);

```

The bottom most visible tile is

```
var maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height);

```

One you know this all you need to do is loop though the visible tiles and render them. Below is an example of how I have done this.

```
public void Draw(SpriteBatch spriteBatch, Rectangle worldArea) {

    //Init the holder
    _holder = new Rectangle(0, 0, TileWidth, TileHeight);

    //Figure out the min and max tile indices to draw
    var minX = Math.Max((int)Math.Floor((float)worldArea.Left / TileWidth), 0);
    var maxX = Math.Min((int)Math.Ceiling((float)worldArea.Right / TileWidth), Width);

    var minY = Math.Max((int)Math.Floor((float)worldArea.Top / TileHeight), 0);
    var maxY = Math.Min((int)Math.Ceiling((float)worldArea.Bottom / TileHeight), Height);

    for (var y = minY; y < maxY; y++) {
        for (var x = minX; x < maxX; x++) {

            _holder.X = x * TileWidth;
            _holder.Y = y * TileHeight;

            var t = tileLayer[y * Width + x];
            spriteBatch.Draw(
                t.Texture,
                _holder,
                t.SourceRectangle,
                Color.White,
                0,
                Vector2.Zero,
                t.SpriteEffects,
                0);
        }
    }
}

```

---
Tags: xna, textures
---


# Question
Title: How do I create a game design that can adapt to new platform environments?
I'm trying to design a game that can be considered versatile enough to be adapted to different platforms and control schemes without too much difficulty. I asked this question to try to get a handle on what to expect as far as what technologies to try and plan for, but it was closed (justifiably, I agree) for basically asking others to predict what the future technologies were.

So my question now is, instead of trying to plan a game to suit specific technologies and control methods, **what should I consider in my planning if i want to design a game that can easily adapt to new platform environments?**

# Answer
> 5 votes
I'm not sure game design should be forward looking.

Take a look at games designed 20 or 30 years ago. From topscrollers to platformers to racing to dungeon-crawl, they are still just as fun to play and the genres are as alive today as they were back then. Bolting Kinect controls or 3D vision or touch screens onto Galaga or Mario doesn't necessarily make them better.

I guess the corollary is that games that take advantage of unique features of a particular platform probably don't carry over to different platforms with different features. For instance, Scribblenauts would be cumbersome on a Kinect.

# Answer
> 4 votes
You're right, it is difficult to predict what the future gaming technologies will be. In fact, unless you're working for the companies developing the new technologies, you will probably not have access to SDKs until a while after the technology comes around.

Bearing this in mind, I would suggest designing your game in order to push the boundaries of what we consider viable input schemes or platforms for games, rather than designing for what might be or what already is. The great part of designing games is that you get to put the full power of your imagination to work.

When it comes to implementation, it's very hard if not impossible to have your code structure easily portable between two different platforms. This is why console ports of games require a full team to create. As Tetrad said, just make sure that you will be able to implement all your mechanics on all of your target platforms.

# Answer
> 1 votes
Porting to current platforms is already hard enough - making it easy to port to platforms that don't even exist yet seems like asking for too much.

To take a specific example. Almost nobody could have predicted the rise of consumer 3D acceleration back in 1996 or thereabouts. Sure, it could have been predicted to have existed by then (it already did), but going mainstream? There were however a number of relatively coincidental occurrances - falling memory prices pushing them into consumer price-ranges, a killer app (Quake) to suddenly make them highly desirable and the evolution of not one but two widely supported 3D APIs (not to mention a third that had *extremely* high coverage) all at the same time - that suddenly opened the floodgates.

With that all the old rules went out the window. Highly tuned software renderers started becoming marginal, practices that worked well with software didn't necesarily work well with hardware, and things you could do before were suddenly no longer possible (and the converse). Everybody who knew everything about writing a software renderer had to more or less begin learning from scratch all over again. (Where's Ken Silverman now? He was very very good but didn't make the transition.)

Will we see a similar paradigm shift again in our lifetimes? Don't know, nobody knows, but it doesn't even have to be on the same scale. Something that breaks apart the now familiar GPU/CPU model is enough to sufficiently upset things. New storage technology, new comms technology, new input technology, new sound technology - these are all short/medium term feasible and if we get two or more happening at the same time it may be enough to trigger a year-zero reset.

So no - you're not going to be able to achieve this goal. Better to focus on what you can achieve now, and do the best you can with what we've currently got. Don't worry too much about whether it will be obsoleted in 3/4/5 years time, worry about what you're doing now.

# Answer
> 1 votes
Don't design around hardware abilities or even hardware concepts that can't be supported cross platform. Or inversely, design around concepts that aren't device specific. If you have an idea, mentally cycle through a list of current platforms, and ask yourself how you'd implement it on each. If you can't think of how, toss or modify the idea.

Multitouch is pretty neat, but not supportable for a user with just a mouse. If you utilize a keyboard because of its large number of potential inputs, you may find your game very difficult to port to a console controller (fewer inputs). Screen size and screen resolution is another. If you design a game that requires a large amount of information on the screen, you'll have problems on a small tablet.

---
Tags: cross-platform, planning
---


title: OpenGL ES drop shadows for 2D sprites

text:
# Question
Title: OpenGL ES drop shadows for 2D sprites
I've got a an OpenGL scene rendered with a bunch of sprites, and I'd like to automagically add drop shadows to all of them. Here's a picture showing what I mean:

The scene uses orthographic projection, the sprites are textured quads, and I'm using the depth buffer to draw them front to back. I'm working with OpenGL ES 2.0, but thoughts from the iOS or non-ES worlds would be appreciated as well. I've tossed a few ideas around in my head of how I can go about this, and I'd like to find out which has the most promise.

1. Draw each sprite twice, the first normally, the second with some kind of drop shadow shader a bit deeper in the scene. Not sure if this is possible?
2. Draw a sprite, then draw it again, darkened and with some alpha, several times with some random jitter applied to the verticies. This may look silly and not at all like a shadow.
3. Draw the base scene without background to a texture, then blur and darken it to create one large drop shadow. Then draw the base scene over the drop shadow texture, then finally over the background. This would lose the shadows between sprites, though.
4. SSAO in a post-processing pass. Might be the most dynamic and automatic, but could look fuzzy/grainy and really slow things down.
5. At creation time, generate a shadow texture for each sprite. For rendering, draw a sprite and then its shadow texuture a bit deeper in the scene. I think I'd like to avoid this due to the loading time and extra memory requirements, but this may be the fastest and best looking?

I don't want to do any shadow work with external textures, since I use the same sprite textures at varying scales, and pre-baked shadows would scale unnaturally.

So are any of these better than the others? Are there other options I'm not thinking of? Thanks!

# Answer
Your option #5 — generating shadow textures — has a low per-frame cost compared to performing blurs, is readily customizable, does not introduce a lot of complexity in other areas of the rendering process. I recommend trying it out and seeing whether the memory/startup cost is too much before investigating the other options.

Since you are using the depth buffer, you will need to draw the shadows after the opaque sprites and use a subtractive blend function, to avoid drawing-order dependencies.
> 1 votes

---
Tags: opengl, android, graphics, opengl-es
---


# Question
Title: Python/PyGame mixer.music playback of OGG file has intermittent clicking sound - how to proceed?
I have a class within my python + pygame game that handles sound - it worked well until I tried use pygame.mixer.music to switch between streaming .ogg music files. The class switches between them on the pause event.

**The issue I'm having is that the music will play, and even switch between tracks fine, but about half the time I'm getting a quiet, regular clicking noise over the sound track.** I've checked, and the pygame mixer is set to the same bitrate as my .ogg files. I've tried playing with number of channels and tracks, all to no avail. I'm not sure what the root cause of the clicking is - whether I've chosen a poor file encoding / bitrate, or just not initialized/called pygame mixer correctly.

Here is the problimatic code:

`class SoundMgr():`

```
def __init__(self):
       pygame.mixer.init(22050, -8, 4, 4096)
       self.musicFilename = ""
       self.musicPos = 0
       self.musicVolume = .35
       self.musicMuteVolume = .1

def playMusicTrack(self, which):
    pygame.mixer.music.load("data/music/" + which + ".ogg")
    pygame.mixer.music.set_volume(self.musicVolume)
    pygame.mixer.music.play(-1)
    self.musicFilename = which

def dampenMusic(self):
    mark = pygame.mixer.music.get_pos() * 0.001
    self.musicPos += mark
    pygame.mixer.music.load("data/music/" + self.musicFilename + "b.ogg")
    pygame.mixer.music.play(-1, self.musicPos)
    pygame.mixer.music.set_volume(self.musicMuteVolume)

def undampenMusic(self):
    mark = pygame.mixer.music.get_pos() * 0.001
    self.musicPos += mark
    pygame.mixer.music.load("data/music/" + self.musicFilename + ".ogg")
    pygame.mixer.music.play(-1, self.musicPos)
    pygame.mixer.music.set_volume(self.musicVolume)        </code>

```

When I call dampenMusic / undampenMusic the track plays correctly, but about half the time it has a clicking sound over it. The other half of the time it plays perfectly. I've tested, and I can't discover any pattern to when it will / won't have the static.

The clicking noise is about 2 times a second, and is about 50% the volume of the track.

**Anyone who is more experienced with pygame / sound encoding able to give me any tips?**

# Answer
Clicking generally suggests some kind of buffering issue - you're getting a stray sample in there with an incorrect value.

Here's a few things to try:

* Try a much bigger buffer than 4096 samples. Say 65536 or more.
* Go for 2 channels - most music is stereo, although the documentation says the value is clamped anyway.
* Try 16-bit samples at 44100 Hz.
* Stop using the dampen and undampen functions. Sudden volume changes can also cause a click.
> 1 votes

---
Tags: python, sound, pygame, music, ogg-vorbis
---


# Question
Title: How to properly render a Frame Buffer to the BackBuffer in Stage3D / AGAL
After doing a render pass with RenderToTarget (RTT), how do you properly render that texture buffer to the screen while maintaining original scale / proportions so it doesn't stretch or lose quality?

Can an AGAL VertexShader & FragmentShader be written so it's adaptable to any Texture size and Viewport dimensions?

I find I'm getting some "blocky" effects in some of my first attempts at "ping-ponging" between two Texture buffers (to create trailing effects). Perhaps I'm not using the UVs correctly between the rendering-to-target and/or the backbuffer?

Is there a simpler way just to "splash" the texture on the backbuffer, or is a Quad absolutely necessary (4 vertices, 2 triangles)?

If it needs the Quad, should the Texture buffer be fully drawn (0.0 to 1.0 for vertical and horizontal UVs), or only a percentage of it should, like the example below?

* Texture Buffer U: 0.0 to viewport.width/texturebuffer.width;
* Texture Buffer V: 0.0 to viewport.height/texturebuffer.height;

Thanks!

# Answer
You should only render to the area needed as in your example. To speed up rendering, look at using a scissor rectangle.
> 1 votes

---
Tags: flash, textures, rendering, post-processing, agal
---


# Question
Title: Some advice for settling on a map format for a tile game?
I am using XNA 4.0 and am currently working on a simple tile game to pass the time. Basically, I'm using the tried and true method of having numbers refer to tile types, where in 0 would be an empty tile, 1 would be grass, et cetera.

This is all well and good and works fine but I was wondering how to incorporate other assets. For example, a map may have parallax backgrounds, background music, and of course the tileset from which the tile map refers to draw its textures.

Ignoring ambient music and gratuitous scrolling backgrounds, I am still unsure of how to implement just the joining of the tile map (text) and tileset (png image). I see several solutions:

**1)** Embed the texture data for the tileset directly within the map file. This could be extended to other assets as well and would allow for all map files to be together in a single file. Unfortunately, the file sizes quickly become massive as raw texture data is several times larger than compressed images. For this I'm using `GetData` and `WriteBase64`.

**2)** Somehow mention the directory or filename of the tileset from within the text map file. This is how I typically see it done, but because I am using the content loader and not simply loading off the hard drive, this may not be possible. Perhaps the asset name could be stored but this solution seems a bit error-prone.

**3)** Completely separate the textual map data from the tileset image. At runtime, first load the map tiles and then allow any sort of tileset image to be loaded afterwards. This has the advantage of different map files using the same assets without duplicated data and very small file sizes. However, with this solution the width of the tileset would still have to be known before hand in order to correctly offset tile values. Also, map files may become lost and more easily edited by the user.

**4)** Create some sort of ZIP derivative in which all map files are contained in this package. Then, the textual map file can refer to the assets within this container. I'm not exactly sure whether or not this would work with XNA's content loader or how to implement it either, so I'm not sure of the this solution.

How do most developers typically solve this problem with XNA?

# Answer
**5)** Don't roll your own. .NET in general has really great serialization functions, and XNA is no exception: http://msdn.microsoft.com/en-us/library/bb203924.aspx

Edit: As far as *WHERE* to store them, they should be resources in a class library, and however you serialize your data should refer to them using reflection (I typically also have some sort of easier to use string alias as well, because reflection names are ugly).
> 5 votes

# Answer
> Somehow mention the directory or filename of the tileset from within the text map file. This is how I typically see it done, but because I am using the content loader and not simply loading off the hard drive, this may not be possible. Perhaps the asset name could be stored but this solution seems a bit error-prone.

Check out the ExternalReference class. You can load an external Texture2D by its file name relative to the location of the file currently being processed. So as long as the text file that stores the tile data stores the location of the tile map you are good to go.
> 1 votes

# Answer
In my game I have several layers of tiles to achieve the parallax effect. Each layer is a 2D array of a minimal Tile class. If the array element is null, there is no tile there. The tile class stores an enum that refers back to a tile template class, which might be Lava or Wall, or Grass, etc. The template tells me all of the attributes that tiles of that kind share, like what the texture & u,v coordinates are, whether it's walkable by default, what its vertex colors should be. In your case this might also include what music should be playing. The individual tile objects in my layer array can override the template values to do something interesting. All the tiles in a layer use the same texture atlas so rendering them is just one batch but you could just as easily use multiple textures. My layer texture is loaded by the ContentManager and assigned to the layer when my level initializes. When drawing, I interleave the layers with the game objects (characters, monsters doors, chests) that occupy each layer for some simple occlusion.
> 1 votes

# Answer
Unless I misunderstand, you are asking how to make a 2D tile engine. This tutorial will walk you through the process, among other things.

Most developers do not solve this problem. They use an existing tile engine. Several exist for XNA.

If you feel compelled for some reason to make your own, I think the best option would be to have a Tileset object, then have each tile know its tile code, and have the draw method look at each tile, get its code, get that code's tile graphic from the tileset and draw.

As for specifying a tileset, it should be enough for each map to specify a tileset *code*, and the the Tileset object can fetch the relevant tile sheet for that code.

In any event, the thing you appear to ignore is: You should find a map editor you can use, and then code such that you are compatible with it, thereby saving yourself the trouble of writing your own editor later. The way the map editor does will probably immediately suggest simple answers for your questions.
> 0 votes

---
Tags: xna, c#, game-design, xna-4.0, xna-content-pipeline
---


title: Loading textures with SharpDX in Metro

text:
# Question
Title: Loading textures with SharpDX in Metro
I have converted my C# game from OpenTK (OpenGL) to SharpDX (DirectX) and have it up and running from Visual Studio 2010. I also have it up and running from Visual Studio 11 in Metro, in the Windows 8 Developer Preview. However, the Metro build is still lacking textures, so my polygons are simply colored right now. The problem is that the methods used to load images are absent in the Metro DLLs. These methods are all missing from the Texture2D class (inherited from the Resource class) in Metro:

```
SharpDX.Direct3D11.Resource.FromStream
SharpDX.Direct3D11.Resource.FromFile
SharpDX.Direct3D11.Resource.FromMemory

```

Does anyone know if these will eventually be implemented in Metro? Or is there an alternate approach I could be using? Please keep in mind that I never knew a thing about DirectX or SharpDX before this, so I'm still very wet behind the ears with all this.

Finding any kind of help or information for SharpDX is not easy, which is a shame, because it seems to be a great solution for 3D in Metro using C#.

# Answer
Good news! Alexandre Mutel, the author of SharpDX, let me know that Microsoft removed the "helper methods" from Direct3D11. It wasn't an omission by SharpDX. And he also pointed me in the right direction; to use WIC to load my textures. I found sample code here:

http://crazylights.googlecode.com/svn/CLReach/win8/SDX\_CLGC/clgc.cs

I just needed two of the methods: `LoadBitmap()` and `CreateTex2DFromBitmap()`. I had to change the `R8G8B8A8_UNorm_SRgb` to `R8G8B8A8_UNorm`, but ultimately I got it working. And now my game now looks fabulous in Metro with all it's textures in place! :)
> 4 votes

---
Tags: c#, windows, directx11, sharpdx
---


title: Game class and main function

text:
# Question
Title: Game class and main function
I have a Game class with my main game functions and instances of game objects like screen, etc. My game is made using C++ and SDL.

I was wondering, though, should main be a function of my class? Or should I do "Game game;" from "int main();" and have the loop inside main?

My doubt is - if I do it from an outside-main, then most of my stuff will have to be public, and that is kinda bad, isn't it?

Any ideas? Thank you!

# Answer
You could have a *single* public method in your `Game` class to serve as an entry point (e.g. a method called `Run()`). Then the only thing you'd need to do inside `main()` to get everything up and running would be to call that method - nothing more.

The `Run()` method could start by initializing all subsystems and then proceed to enter the main game loop. It should also take care of shutting everything down properly once the loop ends.

Everything else in the class can remain private (or protected if you'd prefer to create a concrete game by inheriting from it) because it will only be needed by your game implementation.

**Example**

Note: Completely bare bones, no timing calculations, extremely simplistic game loop, just an example to get you started. For an actual game it should probably have a lot more complexity than this:

```
class Game
{
public:
    void Run()
    {
        Initialize();
        while(_running)
            Frame();
        Shutdown();
    }

private:
    void Initialize() { /* Initialize subsystems */ }
    void Shutdown() { /* Shutdown subsystems */ }
    void Frame() { /* Update and draw game */ }
    bool _running = true;
}

```

And on your `main()` method:

```
int main()
{
    Game game;
    game.Run();
    return 0;
}

```
> 9 votes

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


# Question
Title: OpenGL es glDrawTexfOES() 2D texture is totaly black no color
First of all I know this is a duplicated question and I check out another questions but didn't helped! I'm trying to convert my android game from canvas system to the GL10. After lots of googling I decided to do that for performans. Anyway I tryed to build a class that loads and draws textures. The problem is textures showing up whole black over my blue screen. I'm not sure If I can draw texture without creating any mesh or something like that but this is what I'm trying to do. I'm only trying to draw 2D texture on their own sizes so I think no mesh needed. Here are my codes:

> onSurfaceCreated

```
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {
        gl.glClearColor(0.0f, 0.0f, 1.0f, 0.2f);
        gl.glClearDepthf(1.0f);
        gl.glViewport(0, 0, 800,  480);

        gl.glShadeModel(GL10.GL_SMOOTH);
        gl.glEnable(GL10.GL_DEPTH_TEST);
        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glDepthFunc(GL10.GL_LEQUAL);
        gl.glMatrixMode(GL10.GL_PROJECTION);
        gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
        //gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
        gl.glLoadIdentity();
        // This is the class where I load and draw my textures.
        textureStorage = new TextureStorage(gl);
        //I'm loading a texture.      **CODE A TEXTURE LOADER**
        bgNightID  = textureStorage.Load(BitmapFactory.decodeResource(context.getResources(),R.drawable.bg_game));
        //This is where I load my units variables. Nothing to do with it.
        RenderingFunctions.InitUnits(this);
    }

```

> onDrawFrame

```
@Override
public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glLoadIdentity();
    //gl.glTranslatef(0, 0, -4);
        **CODE B DRAWING**
        // bgNightID is the ID of texture was loaded.
        textureStorage.DrawTexture(bgNightID, 50,50,0,(short)4000,(short)638);
        // Drawing background right here which is shows up black.
}

```

> CODE A TEXTURE LOADER

```
public int glLoad( Bitmap bitmap ){
    if ( gl == null ){
        Log.e(TAG, "Failed to load resource.  Context/GL is NULL");return -1;
    }
    int textureName = -1;
    gl.glGenTextures(1, TexIDStorage, 0);
    textureName = TexIDStorage[0];

    Log.d(TAG, "Generated texture: " + textureName);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);

    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    //gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
    gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
    gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);

    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);

    int error = gl.glGetError();
    if (error != GL10.GL_NO_ERROR){
        Log.e(TAG, "GL Texture Load Error: " + error);
    }else
        Log.d(TAG, "Loaded texture: " + textureName);
    return textureName;
}

```

> CODE B DRAWING

```
public void DrawTexture(int TexutreID, float X, float Y, float Z, short Width, short Height){
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    //gl.glColor4f(1.0f, 1.0f, 1.0f, 0.5f);
    gl.glBindTexture(GL10.GL_TEXTURE_2D, TexIDStorage[TexutreID]);
    ((GL11Ext) gl).glDrawTexfOES(X, Y, Z, Width, Height);
}

```

I'm totaly new to GL10 and can't figure out what is the problem and what is it I'm missing. So if anyone can help me that would be great. Thank you for givim time!

# Answer
> 2 votes
The problem was my image was not power of 2. like 512x512 or 512x2048. When I did this it worked.

---
Tags: 2d, android, opengl-es
---


# Question
Title: How to calculate shot angle and velocity to hit a moving target?
I am developing a 2D Android game and I am making an aiming algorithm for AI projectiles to hit enemies either following a path, or free moving. At the moment it just calculates where the target will be after a distance and fires a projectile to meet it at that distance. Of course this means varying the projectile speed to meet the target.

Does anyone have any tips for a simple-ish algorithm (optimal-ish) to calculate when the projectile needs to fire and where it needs to aim if it can only travel at a constant velocity? Say the projectile goes twice the speed of the target?

The only way I can think of involves searching and seems quite large.

# Answer
In a tower defence game I made, I used a quadratic equation to predict the intersection and thus aim point. The following aiming code snippet assumes the enemy is traveling at a constant speed and direction. It also assumes the projectile will be traveling at a known constant speed (could be any speeds but must be known to the algorithm).

```
Vector totarget =  target.position - tower.position;

float a = Vector.Dot(target.velocity, target.velocity) - (bullet.velocity * bullet.velocity);
float b = 2 * Vector.Dot(target.velocity, totarget);
float c = Vector.Dot(totarget, totarget);

float p = -b / (2 * a);
float q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

float t1 = p - q;
float t2 = p + q;
float t;

if (t1 > t2 && t2 > 0)
{
    t = t2;
}
else
{
    t = t1;
}

Vector aimSpot = target.position + target.velocity * t;
Vector bulletPath = aimSpot - tower.position;
float timeToImpact = bulletPath.Length() / bullet.speed;//speed must be in units per second

```

Since it also determines time of impact I simply waited until the time pasted to call the impact graphics at the position of the target at that time... no need for any collision detection to determine hits.
> 15 votes

# Answer
The AI, the target's location during the time the projectile is fired, and the target's eventual location at point of death form a triangle.Here is what you should already know:

1. Side length a, which is the projectile speed
2. Side length b, which is the target speed
3. The angle of motion of the target of motion of the target.

You have three parts of the triangle, a SSA case, so solve it like this

1. Find angle B based on the the angle of motion and the location of the AI
2. Use the law of sines to find angle A

Angle A should allow you to determine the angle at which the projectile should be launched.
> 5 votes

---
Tags: 2d, android, mathematics, ai, aiming
---


# Question
Title: Best Method to Create Side Scrolling Levels? - Cocos2D
I am looking to start my first side scroller project using Cocos2D, but I am curious. What is the preferred/best method of creating you levels? For large levels I see hand making it very laborious, is there a more visual way of doing so, as punching in coordinates for everything at a guess seems wrong. Which is why Im here to learn from you guys.

So any help would be much appreciated, thanks.

# Answer
Personally for side scrolling games such as 2D platformers I like to mix a traditional tile map system with hand placed graphics and objects. Using editors such as Tiled and tIDE you can create levels very quickly. By adding a layer of hand placed graphics and objects over the tilemap you can make a map much more interesting and dynamic than you can just with a tilemap alone.

I use tIDE personally and really like it. However, I don't know how easy it would be to integrate with cocos2d since I've never explored its import/export functionality. Tiled is very mature and a quick Google search finds many tutorials to help get you started.

I have an in game editor to hand place objects that are not tiles. However, you could use either Tiled's or tIDE's objects layer and properties to align things for you.
> 1 votes

---
Tags: iphone, cocos2d-iphone, objective-c, side-scroller
---


title: Isometric Optimization in javascript

text:
# Question
Title: Isometric Optimization in javascript
I'm having some issues with my optimization of my game.

I have a simple tile map looped like this in my case the images are 64 by 64 pixels:

```
 for (i=0; i < 50; i++){ //horizontal
    for (j=0; j < 50; j++){ // vertical

    var x = (i-j)*(img[0].height/2) + (canvas.width/2)-(img[0].width/2);
    var y = (i+j)*(img[0].height/4);

    abposx = x + offset_x;
    abposy = y + offset_y;

    total_load++;

    ctx.drawImage(img[0],abposx,abposy);
        }
    }

```

This as you can see is a 50 by 50 map. But i firstly want to do the following optimizations: Work out the max that fits in canvas window (including partial) so it fills the screen.

The problem i have though by imposing the limit the loops will only load that many tiles ( lets say 10 by 10 ) so the map is always 10 by 10 and as i scroll the rest of tiles remain unloaded for obvious reasons.

So i also need to work out how to change the starting position... any ideas =/ ?

# Answer
A few needed variables:

```
var ac = 5; //active column
var ar = 5; //active row
var tr = 0; //top row
var rc = 0; //left column
var br = 10;//bottom row
var rc = 10;//right column

```

Now build the row/column when entered **Note: this is assuming the coordinates for the tile are in the top-left corner.**

```
if(player.x > tile.width*(ac+1)) {
    for(i=0; i<img.length; i++) {
        //draw img[rc+1][i];
        ac++;
    }
}
if(player.x < tile.width*ac) {
    for(i=0; i<img.length; i++) {
        //draw img[lc-1][i];
        ac--;
    }
}
if(player.y < tile.height*ar) {
    for(i=0; i<img[tr].length; i++) {
        //draw img[tr][i];
        ar--;
    }
}
if(player.y > tile.height*(ar+1)) {
    for(i=0; i<img[br-1].length; i++) {
        //draw img[br-1][i];
        ar--;
    }
}

```
> 1 votes

---
Tags: mathematics, javascript, isometric, html-canvas
---


title: Collision detection not working

text:
# Question
Title: Collision detection not working
I realized I put this in the wrong forum, so here it is:

I made a collision detection in the Update() section, and this is the code:

```
    if (player.playerRect.Intersects(turtleRect))
{
    turtleRect.X = turtleRect.X - 60;
}

```

When I run the game, and collide with the turtle, nothing happens. I tried changing the

```
turtleRect.X = turtleRect.X - 60;

```

To

```
turtleRect.X = turtleRect.X - 600;

```

Because I thought I wasn't noticing the change. Still, nothing happened. Then I thought it was just the

```
turtleRect.X = turtleRect.X - 600

```

So I put that in the Update() method, outside of the if statement and it worked. Now I realize that it is the

if (player.playerRect.Intersects(turtleRect)) {

```
}

```

But I cannot figure out what is wrong with that. I have the playerRect in a different class, but I imported it into the main class. I know the Rectangles are moving because of the

```
    turtleRect.X -= 1;

```

in the Update() method. The turtle moves across the screen. I have tested many things, and looked it up and I still can't figure it out. This is the rectangle collision, so could somebody also guide me on how to do the per pixel collision? Here is my Draw() method:

```
protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);

        spriteBatch.Begin();
        spriteBatch.Draw(background, viewPortRect, Color.White);
        spriteBatch.Draw(turtle, turtleRect, Color.White);
        spriteBatch.Draw(turtleSmall, turtleRect2, Color.White);
        spriteBatch.Draw(turtleSmall2, turtleRect3, Color.White);
        spriteBatch.Draw(turtleSmall3, turtleRect4, Color.White);
        player.Draw(spriteBatch);
        spriteBatch.DrawString(font, "Level " + score, new Vector2(20, 10), Color.Blue);
        spriteBatch.End();

        base.Draw(gameTime);
    }

```

Any help is appreciated.

If you need the whole class, here is Game1.cs:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Game1
{

    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D turtle;
        Texture2D turtleSmall;
        Texture2D turtleSmall2;
        Texture2D turtleSmall3;
        Texture2D background;
        Rectangle viewPortRect;
        Rectangle turtleRect;
        Rectangle turtleRect2;
        Rectangle turtleRect3;
        Rectangle turtleRect4;
        public Texture2D texture;
        public Rectangle playerRect;
        public Vector2 position;
        public Vector2 origin;
        public Vector2 velocity;
        SpriteFont font;
        Character player;
        int score = 1;
        public int currentFrame;
        public int frameHeight;
        public int frameWidth;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

        }

        protected override void Initialize()
        {
            player = new Character(Content.Load<Texture2D>("flame"), new Vector2(100, 100), 47, 44);

              base.Initialize();
            }
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            background = Content.Load<Texture2D>("grass");
            turtle = Content.Load<Texture2D>("turtle");
            font = Content.Load<SpriteFont>("SpriteFont1");
            turtleSmall = Content.Load<Texture2D>("turtleSmall");
            turtleSmall2 = Content.Load<Texture2D>("turtleSmall");
            turtleSmall3 = Content.Load<Texture2D>("turtleSmall");
            viewPortRect = new Rectangle(0, 0, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height);
            turtleRect = new Rectangle((GraphicsDevice.Viewport.Width) - (turtle.Width + 200), (GraphicsDevice.Viewport.Height - 66) - (turtle.Height / 2), 100, 75);
            turtleRect2 = new Rectangle((GraphicsDevice.Viewport.Width) - (turtle.Width), (GraphicsDevice.Viewport.Height - 40) - (turtle.Height / 2), 50, 38);
            turtleRect3 = new Rectangle((GraphicsDevice.Viewport.Width) - (turtle.Width -50), (GraphicsDevice.Viewport.Height - 40) - (turtle.Height / 2), 50, 38);
            turtleRect4 = new Rectangle((GraphicsDevice.Viewport.Width) - (turtle.Width - 100), (GraphicsDevice.Viewport.Height - 40) - (turtle.Height / 2), 50, 38);

        }

        protected override void UnloadContent()
        {

        }
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            //Turtle Movement
            turtleRect.X -= 1;
            turtleRect2.X -= 1;
            turtleRect3.X -= 1;
            turtleRect4.X -= 1;
            //Turtle Collision
            if (player.playerRect.Intersects(turtleRect))
            {
                turtleRect.X -= 500;
            }

            player.Update(gameTime);
            base.Update(gameTime);
        }

        private Vector2 CenterTexture(Texture2D turtle)
        {
            return new Vector2((GraphicsDevice.Viewport.Width) - (turtle.Width), (GraphicsDevice.Viewport.Height - 66) - (turtle.Height / 2));
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(background, viewPortRect, Color.White);
            spriteBatch.Draw(turtle, turtleRect, Color.White);
            spriteBatch.Draw(turtleSmall, turtleRect2, Color.White);
            spriteBatch.Draw(turtleSmall2, turtleRect3, Color.White);
            spriteBatch.Draw(turtleSmall3, turtleRect4, Color.White);
            player.Draw(spriteBatch);
            spriteBatch.DrawString(font, "Level " + score, new Vector2(20, 10), Color.Blue);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

```

Here is the Character.cs:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Game1
{
    class Character
    {
        public Texture2D texture;
        public Rectangle playerRect;
        public Vector2 position;
        public Vector2 origin;
        public Vector2 velocity;

        public int currentFrame;
        public int frameHeight;
        public int frameWidth;

        float timer;
        float interval = 75;

        bool hasJumped;

        public Character(Texture2D newTexture, Vector2 NewPosition, int newFrameHeight, int newFrameWidth)
        {
            position = NewPosition;
            texture = newTexture;
            frameHeight = newFrameHeight;
            frameWidth = newFrameWidth;
            hasJumped = true;
        }

        public void Update(GameTime gameTime)
        {
            position += velocity;

            playerRect = new Rectangle(currentFrame * frameWidth, 0, frameWidth, frameHeight);
            origin = new Vector2(playerRect.Width / 2, playerRect.Height / 2);
            position = position + velocity;

            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                velocity.X = 2f;
                AnimateRight(gameTime);
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                velocity.X = -2f;
                AnimateLeft(gameTime);
            }
            else
            {
                velocity.X = 0f;
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Space) && hasJumped == false)
            {
                position.Y -= 3f;
                velocity.Y = -3.5f;
                hasJumped = true;
            }

            if (hasJumped == true)
            {
                float i = 1;
                velocity.Y += 0.15f * i;
            }

            if (position.Y + texture.Height >= 450)
            {
                hasJumped = false;
            }

            if (hasJumped == false)
            {
                velocity.Y = 0f;
            }

        }

        public void AnimateRight(GameTime gameTime)
        {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
            if (timer > interval)
            {
                currentFrame++;
                timer = 0;
                if (currentFrame > 3)
                {
                    currentFrame = 0;
                }
            }
        }

        public void AnimateLeft(GameTime gameTime)
        {
            timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds / 2;
            if (timer > interval)
            {
                currentFrame++;
                timer = 0;
                if (currentFrame > 7 || currentFrame < 4)
                {
                    currentFrame = 4;
                }
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, position, playerRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
        }

    }
}

```

# Answer
The player.playerRect is just a rectangle that represent which portion of the texture to draw. Which is not what you want to use when doing the intersection.

So to get this to work use the playerRect (which is not currently being used) in your Game class to create the bounds of the player:

```
playerRect = new Rectangle(player.position.X, player.position.Y, player.playerRect.Width, player.playerRect.Height);
if (playerRect.Intersects(turtleRect))
{
  turtleRect.X -= 500;
}

```
> 1 votes

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


title: Primitive Animation

text:
# Question
Title: Primitive Animation
I am creating a minecraft-like clone and was wondering what is the best way to go about animating a model, for example implementing the following feature: when the player presses the arrow keys, move both legs in the opposite directions but when the player stops moving retract the legs, slowley. This is what I want to be able to do dynamically, the following is just an example of what I want to acheive and is proberly not the best way of doing so.

So here is an example of what I mean, some thing like:

```
if (player.Velocity != Vector2.Zero)  {
    player.Model.PlayerAnimation("LegsWalk");
} else {
    player.Model.PlayerAnimation("LegsRetract");
}

```

I highly doubt that is a great way about going about animating the legs, but I hope you get the idea. Also, I wondering how would I actually use/create my model class so I can add animations to different objects.

Here is some pesduo code :

```
Animation animation = new Animation("Leg Rotation");
animation.Mesh = playerModel.GetMesh("LLeg");
animaiton.RotationType = RotationType.RotationFromOrigin;
animaiton.Axis = Axis.X;
animation.MaxRotation = MathHelper.ToRadians(25);
animation.MinRotation = MathHelper.ToRadians(-25);
animation.DefaultRotation = MathHelper.ToRadians(0);

model.AddAnimation(animation);

...
if (player.Velocity != Vector2.Zero)  {
    player.Model.PlayAnimation("Leg Rotation");
} else {
    player.Model.PlayAnimation("Leg Retract");
}

```

Altough that is hardly sufficient as you cannot change the speed of the animation based on the speed of the player, and I don't think that is how minecraft does it...

So what I am asking is if anyone has any ideas on how minecraft does/handles animations or any other advice on how I should animite primitive models (in a reusable way) please help me :)

# Answer
> 0 votes
I think you are on the right track. You want to increment animation based on time and in this case the player's velocity. Instead of having a PlayAnimation method being called in the loop, I would have a SetAnimation method that gets called when the player starts walking. The the loop, you call a method that advances or calculates the animations next frame by passing the time passed since the last frame. Now you can multiply the time since last frame with the player's velocity to increase the walking speed.

---
Tags: xna, c#, animation, minecraft-modding, skeletal-animation
---