# Question
Title: Pygame surface rotation, rect rotation or sprite rotation?
i seem to have a conceptual misunderstanding of the surface and rect object in pygame.

I currently observe these objects this way:

**Surface**

* Just the loaded image

**rect**

* the 'hard' representation of the ingame object (sprite). Used for simplifying object moment and collision detection

**sprite**

* rect and surface grouped together

What i want to do is rotate my sprite. The only available method i found for rotation is *pygame.transform.rotate*.

How do i rotate the rectangle, or even better, the whole sprite?

Below is the image of how i visualize this problem.

# Answer
> 12 votes
Conceptually you've got it, just think of the rectangle as a helper for you to deal with position and collision detection of your image. To implement it you could use:

```
  mySprite.image = pygame.transform.rotate(Surface, angle)

```

This will give you a rotated Surface (image), then you can use:

```
mySprite.rect = mySprite.image.get_rect()

```

To give you your new rectangle; this won't be a rotated rectangle, it will be a orthogonal one that is big enough to fit your image in, i.e. its sides will remain vertical and horizontal. This should serve most purposes, and be satisfactory for most collision detection, if it's not some people shrink the rectangle a bit, doing it pixel perfect is a lot more complexed and cpu hungry and often not worth it.

NB:keep a copy of your original image (with no rotation) and do all your rotations from that one, otherwise there is potential for your rectangle to keep getting bigger and bigger.

# Answer
> 0 votes
Just noticed something which made me almost insane during this whole day of experimenting.

**The rect of the image is not the rectangle of the sprite!**

In case of this code:

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

    def __init__(self, xy):
        # initialize the pygame sprite part
        pygame.sprite.Sprite.__init__(self)
        # set image and rect
        self.image = pygame.image.load(os.path.join('images','gusjenica.jpg'))
        self.original_image = pygame.image.load(os.path.join('images','gusjenica.jpg'))
        self.rect = self.image.get_rect()

```

the self.rect is a rect for its on, not a reference of to the surface rect. That means that we have s situation like this.

This brings up another important thing i noticed.

**The image.get\_rect() location is relative to the Sprite rect!**

The image explains it better. Gray are the locations of the sprite rect, red is the position of image.get\_rect()

Please correct me if I'm wrong, this is just an empirical proof based on a single experience.

# Answer
> 0 votes
I realize this is an old post, but I wanted to chime in with some things that I've found helpful.

Any time you have a sprite image that you're drawing to a rect, you can set the properties of the sprite's rect during the `Surface.get_rect()` call.

For example, if we have a game object with attributes for its rect and its image, and we can reasonably assume that the image can be consistently centered around the object's `rect.center` without making it display weirdly, the following is something I've found to be helpful.

```
for object in things_to_draw:
    drawn_image = altered_image(object.image) # altered_image() is whatever changes you're making to the image before it's drawn
    image_location = drawn_image.get_rect(center=object.rect.center) #returns the Surface's rect with rect.center set to the center of the object
    myDisplay.blit(drawn_image, image_location)

```

Additionally, you may want to take a look at using the `bounding_rect` of the image after doing a lot of work with said image. The `bounding_rect` is the resized rect that a rotated image fits into; if your image is significantly taller than it is wide (or vice versa) this might be more useful for collision detection than a static rect that is set once. One can get this by using `Surface.get_bounding_rect()`; however, for whatever reason **this method cannot be passed the same setters** as the previous one, so you'll have to set new values after this rect is created.

```
image_rect = object.image.get_bounding_rect() #does not take the same args! can't set rect.center until the next line...
image_rect.center = (some_x, some_y) #sets the bounding_rect's center to whatever X/Y you're using

```

Like I said, I know it's an older post, but this stuff was driving me up a wall at first as well.

---
Tags: rotation, pygame
---


# Question
Title: Implement an upper FPS limit in the gameloop
I implemented my game-loop as described in deWiTTER's article, using the last approach with an unlimited FPS and a constant game-speed.

My problem is, that the unlimited FPS cranks up my CPU usage to *nearly* 100%. I understand that this is desired (as the hardware does as much as it can), but for my game, it's not really necessary (it's pretty simple). So I'd like to limit the FPS to some upper bound.

Consider my game-loop:

```
private static final int UPDATES_PER_SECOND = 25;
private static final int WAIT_TICKS = 1000 / UPDATES_PER_SECOND;
private static final int MAX_FRAMESKIP = 5;

long next_update = System.currentTimeMillis();
int frames_skipped;
float interpolation;

// Start the loop:
while (isRunning){
    // Update game:
    frames_skipped = 0;
    while (System.currentTimeMillis() > next_update
            && frames_skipped < MAX_FRAMESKIP){
        // Update input, move objects, do collision detection...
        // Schedule next update:
        next_update += WAIT_TICKS;
        frames_skipped++;
    }
    // Calculate interpolation for smooth animation between states:
    interpolation = ((float)(System.currentTimeMillis() + WAIT_TICKS - next_update)) / ((float)WAIT_TICKS);
    // Render-events:
    repaint(interpolation);
}

```

How would I implement a maximum FPS?

If i implement the repaint the way I implemented the update (or use a sleep instead of "do-nothing-cycles"), then the FPS is **locked**, *right?* That is **not** what I want. I want the game to be able to work with lower FPS (just as it does now), but limit the FPS to a maximum of, say 250.

# Answer
Store the last time you rendered a frame, and if it hasn't been *enough* time, Sleep().

Note that Sleep() can sometimes result in your program not waking up when it should, giving you a framerate stutter - test it pretty carefully. In my experience most modern OSes will timeslice frequently enough that this won't be an issue except in fast-paced first-person-shooters.

```
private static final int UPDATES_PER_SECOND = 25;
private static final int WAIT_TICKS = 1000 / UPDATES_PER_SECOND;
private static final int MAX_FRAMESKIP = 5;

long next_update = System.currentTimeMillis();

/////// NEW CODE BEGIN
private static final int MAX_UPDATES_PER_SECOND = 60;
private static final int MIN_WAIT_TICKS = 1000 / MAX_UPDATES_PER_SECOND;

long last_update = System.currentTimeMillis();
/////// NEW CODE END

int frames_skipped;
float interpolation;

// Start the loop:
while (isRunning){
    /////// NEW CODE BEGIN
    // Delay if needed
    while (System.currentTimeMillis() < last_update + MIN_WAIT_TICKS){
        System.Sleep(0); // I don't know C# so this is a guess, but there will be some equivalent function somewhere
    }
    last_update = System.currentTimeMillis();
    /////// NEW CODE END

    // Update game:
    frames_skipped = 0;
    while (System.currentTimeMillis() > next_update
            && frames_skipped < MAX_FRAMESKIP){
        // Update input, move objects, do collision detection...
        // Schedule next update:
        next_update += WAIT_TICKS;
        frames_skipped++;
    }

    // Calculate interpolation for smooth animation between states:
    interpolation = ((float)(System.currentTimeMillis() + WAIT_TICKS - next_update)) /     ((float)WAIT_TICKS);

    // Render-events:
    repaint(interpolation);
}

```
> 3 votes

---
Tags: game-loop
---


# Question
Title: What steps should I take to learn level design/programming?
I'm still in high school, and I've been playing games for 12 years, and I've always wanted to eventually learn level development and design, and programming. However I'm no good at art and as of now have absolutely no education what-so-ever about either of these things.

I was wondering which fields of study should I branch into in order to learn these things? Is it even reasonable to attempt to learn level creation if I'm no good at art anyway?

# Answer
I would pick up an Art class at school if possible, or online to learn the basics of design, and then practice a ton. Many people that are good at art is because they have been practicing ever since they were a kid. Drawing all the time. For level design I agree with Nick, start looking into the modding community, Valve has some great downloads for modifying your levels (have only used the left 4 dead one). Any game that allows you to alter the level, or create your own will help. Here is Valve's "Making a Mod"

For programming, Math is pretty important, it makes things a lot easier, and see if your school offers any programming classes as well

Other than that, pick a language/program and try to stick with it for a little while. Learning a certain language won't matter all that much, as soon as you master one Object Oriented language, the others are easy to learn. C#, Java, Actionscript were easy for me.

When you begin learning programming,it probably won't relate to game programming, but stick with it, as these are stepping blocks that are needed down the road.
> 5 votes

# Answer
Be sure to learn a lot of advanced math. Math is the most important thing in games. Also, learn some programming languages such as **Java**, **C++**, or **C#**.
Personally, I like Java because it is very flexible.
But the most important thing is interest. If you're interested, you will do well.
You can find free textures and images online.
> 0 votes

---
Tags: graphics-programming, education
---


title: What is the definition of "tiles?"

text:
# Question
Title: What is the definition of "tiles?"
When we talk of tiles, are we strictly talking about images or the underlying data structures?

For example, I read an article which explains that tiles are a *data structure* that holds your game data. Then I read this article which explains that tiles are *images* that fit together.

Which is correct? Should I infer that "tile-based games" use both systems concurrently?

# Answer
> 2 votes
You've over-thinking this. The answer to your question: "Which is correct?" is... **Both**.

There are a million different ways to structure a game which uses visual tiles and you're making a **false assumption that there can be only one true way, but there's not**.

The only uncontested description of what a tiled game is is that visually a tiled game is made up of... tiles. **Bits and pieces stuck together in a regular grid** to make maps, just like a bathroom floor and ceramic tiles.

Inside a game can be **anything** from old style RPGs (e.g. Chrono Trigger) where you hop from tile to tile to free roaming movement (e.g. Diablo).

# Answer
> 6 votes
There are no *strict* definitions. It's true that the term tiles can apply to both data structure and visual representation. When people say "Tiles", they are just breaking the game into a regular grid, either logically (data structure) or visually (tiled images).

It's probably more appropriate to only refer to tiles as the visual aspect (like real life tiles), and use the term *grid* to define the underlying data structure (like a mathematical structure).

Grids are commonly square or hexagon shaped and any tiles being used will likely be shaped to match.

# Answer
> 1 votes
From the gameplay point of view, a tile is the minimun unit of movement for a game object in lots of games.

E.g: You press left key, the player move one tile to the left.

# Answer
> 0 votes
"Tile" is a general definition for a grid item. Whether that grid represents a data object, image object, or something else is up to you.

---
Tags: tiles, tilemap
---


title: Fighting Game and input buffering

text:
# Question
Title: Fighting Game and input buffering
In fighting game, there is an important thing called input buffering. When your character is doing an action, you can input the next action that will activate as soon as possible (the buffer is 5-10 frames).

Has anyone already implemented, or knows the most efficient way to do this?

I thought of things like this:

```
Enum list moves (a list of all my moves)
if (moves = fireball)
{
    if (Mycharacterisidle)
    {
         Do the fireball
    }
    else if (MycharacterisMoving)
    {
         if (lastspriteisnotfinished)
         {
             InputBuffer++;
         }
         else if(spriteisfinished && InputBuffer < 5)
         {
             Do the fireball
         }
    }
}

```

Any better ideas? Thx.

# Answer
How about you use a `Queue<T>`?

There are 4 significant members of `Queue<T>` you can use:

1. `Queue.Enqueue(T item)` \- put your item at the end of the queue.
2. `T Queue.Peek()` \- look at the first item without removing it.
3. `T Queue.Dequeue()` \- get and remove the first item.
4. `Queue.Count` \- check how many items are in queue.

---

## Sample usage

Here's what could be a **class representing moves**:

```
public enum MoveType
{
    Fireball, Jump, Block
}

public class Move
{
    public MoveType MoveType { get; private set; }
    public double Duration { get; private set; }
    //...

    public Move(MoveType moveType)
    {
        this.MoveType = moveType;
        switch (moveType)
        {
            case MoveType.Fireball:
                this.Duration = 1.0;
                break;
            case MoveType.Block:
                this.Duration = 0.5;
                break;
            case MoveType.Jump:
                this.Duration = 0.8;
                break;
        }
    }
}

```

Your update **checks to see if moves are elapsed**:

```
Queue<Move> _moveQueue = new Queue<Move>();
double _elapsedMoveTime = 0;

public override void Update(GameTime gameTime)
{
    if (_moveQueue.Count > 0)
    {
        _elapsedMoveTime += gameTime.ElapsedGameTime.TotalSeconds;
        Move current = _moveQueue.Peek();
        if (_elapsedMoveTime > current.Duration)
        {
            _elapsedMoveTime -= current.Duration;
            _moveQueue.Dequeue();
        }
    }
    else
    {
        _elapsedMoveTime = 0;
    }
}

```

To add a move to the queue, simply call

```
_moveQueue.Enqueue(new Move(MoveType.Fireball));

```

To get the current move, simply

```
Move currentMove = _moveQueue.Peek();
if(currentMove.MoveType == MoveType.Fireball)
   //...

```

Also - don't count the duration in frames, count it in seconds (or milliseconds if you must).
> 10 votes

# Answer
I have a really simple method of detecting special move sequences for my game Fearless Night.
It just stores the last 60 frames of input, but you can make it any length. I implemented a simple method for checking if a sequence has been executed. It's written in Lua, but I'll do my best to write it in C# for you.

We use integer values to represent directions based on a keyboard's number pad, but you can use anything that's comparable as a replacement for the input state. I simplified some things here, such as not accounting for a character's direction flipping when crossing over an opponent. Normally this would flip the forward and back directions for a special move input.

The algorithm simply checks each input state from the `CurrentTick` offset inside the input buffer back until `maxDuration`. This assumes that the `buffer` array is circular.

```
public class Input {
    int bufferSize = 60;
    int[] buffer = new int[60];

    // Offset for the current input in the buffer.
    int CurrentTick = 0;
    ...
    // maxDuration must be <= bufferSize
    public bool CheckSequence(int[] sequence, int maxDuration) {
        int w = sequence.Length-1;

        for(int i=0; i<maxDuration; ++i) {
            int direction = buffer[(CurrentTick-i+bufferSize) % bufferSize];

            if(direction == sequence[w])
                --w;
            if(w == -1)
                return true;
        }

        return false;
    }
}

```

You can use it like such

```
// Somewhere at the start of the "match"
Input input;
...
// 2=down, 3 = down-forward, 6=forward
int[] qcf = new array[] {2, 3, 6};

// Where you check for move transitions
if(input.CheckSequence(qcf, 16)) {
    ExecuteMove("Fireball");
}

```
> 3 votes

---
Tags: c#, xna, input, fighting-game
---


# Question
Title: Calculation: Is a sphere/square/plane visible from a certain point?
I'm searching for a way to detect if a form (shape can be changed if algorithm requires it) is visible from a single point in a 3D tile-based world. This should be used as some kind of wall-hack protection to hide players from the client if they are fully covered behind a wall.

This does not have to be extremely precise. The only condition is that the algorithm never returns a false-negative. Therefore I thought it might be the easiest choice to create a rather large sphere around each other player and peform visibly operations from the viewpoint to that that imaginary sphere. I'm planning to use this on larger maps and only if players are far away from each other. It wouldn't be a problem if you could see players that a behind a wall right next to you.

Since I have no clue how the solution may look like I'm searching for a very abstract description of how such an algorithm works.

I found this very similiar question: Precomputing Visibility But I think this led me into the wrong direction since my main aspect ist speed rather than accurancy.

# Answer
> 2 votes
A system which never has any false-negatives is going to need to rely on some variant of graphics occlusion query. Ray casts and other physics-based measures will not work.

You can use a GPU Occlusion Query for the easiest solution. Render your static geometry (just solid geometry, no need for colors or textures or other surface effects; you don't even need a color output buffer, all you are doing is building a depth buffer and testing against it). Then under a depth-pass query render the player. The query will tell you if any fragment of the player geometry passed the depth test, meaning it was in front of some static geometry and not clipped/culled. Again, the render is just vertex positions (and skeletal animation data) and nothing else and no need for a color buffer; very similar to a shadow map except you never need to read from the generated depth buffer.

I haven't done any performance tests myself and haven't seen any number from recent hardware, but in the past it has been faster to do this in the CPU with a software triangle rasterizer. Part of the reason is that the GPU may be fully utilized rendering the game. The bigger part of the reason is that it takes a lot of time to send the render commands to the GPU, have it render everything, and then return a result. A low-resolution depth-only render of simple geometry is not difficult to do on the CPU, can be easily multi-threaded and vectorized, and *might* be more efficient (though even if it is, you may not *need* that extra performance; not every game is a massive AAA affair).

Note again that you can do all these occlusion tests in low resolution. Just because your game is rendering at 1920x1080 doesn't mean the occlusion queries need to happen at that size. It's typical to use some smaller size with multi-sampling disabled, possibly not even the same aspect ration. If it's too small you'll start getting noticeable false-negatives. With any size reduction you may get some *very minor* false negatives (say, if only a couple pixels of the player is visible, not something other humans would actually notice). If you really, *really* need zero false-negatives (you don't) you'd want to do occlusion queries at full resolution with the same multi-sampling setup, but that will hit performance pretty hard.

# Answer
> 1 votes
It seems like you need an occlusion query algorithm.

Roughly speaking in order to check if certain object is visible from a certain point of view, one way is to use a ray casting algorithm:

1. Cast a ray from the viewer point of view to the object.
2. If the ray hits any other object in its way before hitting the target object then you can set the target object as partially invisible.
3. This is usually not enough and you need to ray cast multiple rays.

Even if you are ray casting bounding volumes and not actual triangle meshes, this will more likely be very slow (unless you have a very small scene), because the objects are not spatially sorted so you will end up checking every object, even if they are unlikely or even far away from the ray's path.

In order to solve this problem you need to use some kind of spatial partitioning like grid, octree, or even bsp trees. This way you will be able to only test objects that are more likely be in the way.

I also answered a similar question here. And covered multiple types of visibility determination algorithms here.

---
Tags: algorithm, line-of-sight, occlusion, visibility-determination
---


title: Keep rasterized pixel amount constant

text:
# Question
Title: Keep rasterized pixel amount constant
I have a scene that is rendered from the point of view of the light using an orthographic projection matrix.

For an arbitrarily shaped and oriented object that doesn't change its shape or size in any way, the amount of pixels that get rasterized change with its position. I guess it's better to explain this with an images:

The depth of the quads (their y coordinates) are constant. Their x and z coordinates are slightly different. However, since it's an orthographic projection matrix, their "world space" floating point sizes are the same as seen from the camera. Just in one case, one additional lines of pixels is rasterized (I drew the two white lines with mspaint to illustrate their size difference).

This is highly undesirable for my application. Is there a way to keep the amount of rasterized pixels consistent? How would I go about implementing it using OpenGL?

# Answer
Snap the quad sizes to integer multiples of the light's-eye-view camera's pixel size.

What's happening is the bottom vertices in the right quad have just barely crossed the y-threshold of the bottom row of pixels, so that row gets included in the rasterized quad.

If the height is exactly an integer number of pixels, then this will only happen when the top vertices have slipped out of the top row at the same time, so the total rows covered remains the same.

As long as the quad is strictly between n and n+1 pixels tall, there will be some positions where it will rasterize to n rows and some positions where it will rasterize to n+1 rows.
> 2 votes

---
Tags: opengl, rendering, rasterization
---


# Question
Title: Apply a texture on a Box - jMonkeyEngine
How can i wrap a texture (for ex a 4x4 pixels) on a box (1x1x1) in such a way that the texture is repeated and not enlarged to cover all the surface.

```
 Geometry box = new Geometry("Box", new Box(1f,1f,1f));

```

# Answer
Try this:

```
Geometry box = new Geometry("Box", new Box(1f, 1f, 1f));
Material woodMat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md"); //create a simple material
Texture tex = assetManager.loadTexture(new TextureKey("Models/guide.png", false));
tex.setWrap(Texture.WrapMode.Repeat); //This should set the texture to repeat.
woodMat.setTexture("ColorMap", assetManager.loadTexture(tex)); // with Unshaded.j3md
woodGeom.setMaterial(woodMat);                   // set the cube's material

```

Let me know if it works :)

(Note, I'm new to jMonkeyEngine myself, so this might not work. Good luck!)

NOTE: You might have to tinker with using:

```
box.scaleTextureCoordinates(new Vector2f(0.5f, 0.5f));

```

This will scale the texture to your liking.
> 1 votes

---
Tags: textures, graphics, jmonkeyengine
---


title: Straighter SLERP/LERP

text:
# Question
Title: Straighter SLERP/LERP
I am debugging my Lerping to see how it works. It is rotating a card and it looks good. However the lerping contains way beyind the card is visually done rotating. I understand it has to do with the mathematics. Is thera a way i can fix it? Is it unavoidable with Lerp/Slerp? Basically what i want is the function to be done when the card has rotated enough so that steps are no longer visible.

```
public IEnumerator LerpRotationY (float durationSeconds, FlipsSide flipSide)
    {
            int targetAngle = FlipSideEnumToDegrees (flipSide);

            //float flipSpeed = 3F;
            var flipRotation = Quaternion.Euler (0, targetAngle, 0);
            float t = Time.deltaTime;
            var cardRotation = cardSides.rotation;
            var timePassed = Time.time;
            print ("SLERPING! ");
            while (t < durationSeconds) {

                    cardSides.rotation = Quaternion.Slerp (cardSides.rotation, flipRotation, t);

                    yield return null;
                    t += Time.deltaTime;
            }
            print ("SLERPING FINISHED: " + (Time.time - timePassed).ToString ());}

```

# Answer
I'm having trouble visualizing the problem you are describing, however I can see two issues with the implementation posted.

The first issue is that you are using the updated rotation as the first parameter of the lerp function. Doing this will produce a movement that will start off quickly but then slow down towards the end. This effect is great for camera movement but would look a little off for rotating a card.

Another issue is that you are using `t` (elapsed time) as the third parameter for lerp, this will produce varying (and possibly unexpected) results for those occasions where `durationSeconds` is not equal to 1. The solution is to use `t / durationSeconds` as this will smoothly travel from 0 to nearly 1. At the end of the loop you can then force the final rotation to ensure a predictable final state.

A smooth and complete lerp requires stable `start` and `end` parameters and a `t` parameter that ranges between 0 and 1.

Please try this version with these changes applied:

```
public IEnumerator LerpRotationY (float durationSeconds, FlipsSide flipSide) {
        int targetAngle = FlipSideEnumToDegrees(flipSide);
        var flipRotation = Quaternion.Euler(0, targetAngle, 0);
        // store starting rotation:
        var startingRotation = cardSides.rotation;
        float t = Time.deltaTime;

        while (t < durationSeconds) {
                // First parameter changed to startingRotation
                // Third parameter changed to t / durationSeconds
                cardSides.rotation = Quaternion.Slerp(startingRotation, flipRotation, t / durationSeconds);
                yield return null;
                t += Time.deltaTime;
        }
        // force final rotation:
        cardSides.rotation = flipRotation;
}

```
> 3 votes

---
Tags: mathematics, lerp
---


# Question
Title: How to handle platform collisions in a 2D game?
If I have a map in my platformer game and I want my character be able to jump on some platform, for example. Is there an easy way to tell the game where the platforms are and where the player can jump to and start jumping from?

Also, for games like Super Mario Bros and such, are the maps made in .txt files ? I watched a tutorial for maps and he said all professional game developers make a .txt file for the map and write numbers for example using...

```
111111111111111111111
111111111111111111111
111111111111111111111
111111111111111111111
222222222222222222222

```

...to create a map. Is this correct or how did the developers do the maps in the Super Mario Bros or MegaMan games?

What I am wondering is, if I want my player to be able to jump up on some platform or something, how do I do it?

# Answer
> 1 votes
I can't really say if there is an easy way to do collisions without knowing everything about your game :) Anyway, it depends on your definition of word "easy". It looks like you knowledge about collisions is rather limited, so chances are that it won't be very easy.

If I guessed right and you're aiming at a simplest form of collision, 2D rectangle tile collision, then there is a simple and quite complete tutorial series. There you will feel how basic things are done with tile-based collisions, jumping and platforms included. No need to code it yourself in Flash, just read it and remember terms for Googling later.

Onto the next question, I highly doubt that MegaMan and SuperMario used .txt map file format considering the fact that games back then were often written in assembly language and had limited memory, so they were probably just storing tile arrangement in some segment of the ROM. Game developers use any map format they want within platform limitations, I've seen bitmap file formats where pixel colors represented tile types, but it's usually some kind of a binary format.

Seriously though, investigate topic of collisions by reading that tutorial link and using help of mighty Google, think and let it sink for a while, come back with specific questions later. For a map file either save/load your data manually into/from any format you want or use serialization.

# Answer
> 0 votes
You're asking at least two questions here so I'm a little thrown off. Your primary question *seems* to be asking about how 2D tiled levels are stored but your subject line and tags are more directed toward collision detection. Can you clarify your question(s)?

There are myriad ways to represent level data and I certainly wouldn't say that all pro game developers store 2D tiled level data as .txt files. However, for a simple project, a .txt file that's read into a two-dimensional array is certainly a good fit—just not necessarily the only fit.

Over on Stack Overflow, I've posted the same generalized pseudocode for 2D, tile-based collision detection/resolution. Check that out and see if it helps answer your collision question.

# Answer
> -2 votes
i see that this thread is a bit old but maybe i can help anyone. I had the same problem with a super mario game in c++.

Here is the piece of code:

```
float oldX = m_x;
float oldY = m_y;

moveX(seconds);
moveY(seconds);

float top = m_y,bottom = m_y + m_height,left = m_x,right = m_x + m_width;

//Check collisions with map
if(top >= 0.f && left >= 0.f && bottom / Tile::m_height m_rows && right / Tile::m_width m_cols)
{
    //Check new x value with old y
    top = oldY+0.1f;
    bottom = oldY + m_height-0.1f;
    left += 0.1f;
    right -= 0.1f;

    if(     (map->getDesign(left/Tile::m_width,top/Tile::m_height) && map->getTile(left/Tile::m_width,top/Tile::m_height).m_solid)
        ||  (map->getDesign(left/Tile::m_width,bottom/Tile::m_height) && map->getTile(left/Tile::m_width,bottom/Tile::m_height).m_solid)
        ||  (map->getDesign(right/Tile::m_width,top/Tile::m_height) && map->getTile(right/Tile::m_width,top/Tile::m_height).m_solid)
        ||  (map->getDesign(right/Tile::m_width,bottom/Tile::m_height) && map->getTile(right/Tile::m_width,bottom/Tile::m_height).m_solid)  )
    {
        m_x = oldX;
    }

    //Check new y value with old x
    top = m_y+0.1f;
    bottom = m_y + m_height-0.1f;
    left = oldX+0.1f;
    right = oldX + m_width-0.1f;

    if(     (map->getDesign(left/Tile::m_width,top/Tile::m_height) && map->getTile(left/Tile::m_width,top/Tile::m_height).m_solid)
        ||  (map->getDesign(left/Tile::m_width,bottom/Tile::m_height) && map->getTile(left/Tile::m_width,bottom/Tile::m_height).m_solid)
        ||  (map->getDesign(right/Tile::m_width,top/Tile::m_height) && map->getTile(right/Tile::m_width,top/Tile::m_height).m_solid)
        ||  (map->getDesign(right/Tile::m_width,bottom/Tile::m_height) && map->getTile(right/Tile::m_width,bottom/Tile::m_height).m_solid)  )
    {
        m_verticalAcceleration = 0.f;
        if(m_y > oldY)
        {
            if(!m_ground)m_ground = true;
            m_y = ((int)m_y / Tile::m_height) * Tile::m_height;
        }
        else
        {
            m_y = ((int)m_y / Tile::m_height+1) * Tile::m_height;
        }
    }
}
else
{
    m_x = oldX;
    m_y = oldY;
}

```

---
Tags: 2d, collision-detection, software-engineering
---


title: Collision detection for sloping tiles

text:
# Question
Title: Collision detection for sloping tiles
I've been looking into adding 'sloping' tiles into my platform game and my first attempt at collision detection with these tiles has produced some promising results (considering it's a first attempt), however, there is something that I just can't work out.

First, some **background**.

My tiles (on my dev device which is a Google Nexus 10 tablet) are 102 pixels wide by 100 pixels tall (this was done on purpose so they fit better to the screen).

So, my 'slope tile' looks something like this:

Not being a perfect square, the slope isn't quite 45 degrees but that shouldn't really matter I don't think.

Now, in order to find out the vertical 'centre' for collision purposes, I'm doing the following:

* Find out where the sprite is in relation to the X Coordinate of the tile. (So, if the tile is at 100 and the sprite is at 110, then I am 10 in from the X of the tile.
* I then multiply that by my slope (slope being height/width or 100/102 in my case)
* I then divide by 2 to get the centre
* Finally, I subtract that result from the height of the tile (to invert it)

This gives me the vertical center which I can compare with the centre of my sprite to check for collision.

So, my code looks like this:

VertTileCentre=Math.round(tileYCoord\]+tile.quadHeight-((slope\*(spriteX-tileX))/2));

**Results**

When I run this, although my sprite can slide up and down the slope it doesn't follow the (visible) path of my tile so I get something like this:

So when moving down the slope it moves in a jagged line and when trying to move up, it moves up the slope until it hits the next tile along, then gets stuck

Would appreciate if someone could point out why my sprite path is not following the slope correctly or anything else I may be doing incorrectly.

**Edit 1 - results from further experimenting**

I've noticed that the sprite when at the top-left of a slope tile sinks into the tile slightly, this is why the sprite was 'getting stuck' when moving up - because it was hitting solid blocks behind (which have their own collision detection)

Strangely, I've also noticed that if I remove the 'divide by 2' from my above calculations the path of the sprite is pretty much OK although the sprite itself still sinks into the tile slightly (But now throughout the whole slope) - therefore if I remove the solid blocks, it works OK.

So I have no idea why *not* dividing by 2 makes sense and also why my sprite is not correctly sitting on the slope!!

# Answer
> 2 votes
I found the answer and it actually lay in my collision routine. During normal collision detection (between 2 rectangles) I take half the width/height of both objects and compare their sum to the distance between the 2 object's centres at any given time.

Up until now, my objects (for collision purposes) have always been a constant 102 x 100 so the sum of 2 object's half-size has always been the same (100 for height and 102 for width) - however, I failed to take into account the vertical size of the slope is effectively changing every time my character moves so I need to dynamically update it based on the characters position.

I've done that and now it seems to be working - there are some other issues I have for which I will post another question if required. :-)

---
Tags: collision-detection, sprites, tiles, collision-resolution
---


# Question
Title: Getting the rightmost point of gameobject
How do i determin the point on a gameobject that is most to the right (highest x value).

# Answer
> 3 votes
This was a bad question, i admit it. But for who ever that comes along later i solved the 2nd quesiton like this.

```
var bounds = gameObject.renderer.bounds.max.x;

```

---
Tags: unity, pixel
---


title: Perlin Noise Help

text:
# Question
Title: Perlin Noise Help
Okay so I have been trying to make perlin noise, fractal noise to be specific, with mixed success. What I do is I fill 5 arrays with white noise, basically just floating point values. Each array is four times as big as the last array. Then what I do is add each of these arrays together. What I have gathered from my extensive research is that putting this into a picture with a gray-scale should produce something like Pic One, but what i'm getting out is Pic Two. I really have no understanding of what i'm doing wrong, and I would appreciate some clarity and explanation on the subject.

Some sites I'v read through.

Libnoise

Perlin Noise Demo

Edit:

I know for sure it has nothing to do with the how i'm rendering the noise. I'm also fairly sure that how I add the noise is not an issue.

Edit 2:

I have one more question. In some implementations I see that they interpolate between 4 gradients, and I understand how to get the value using dot product and whatnot. (Talking about 2 dimensional noise). My question is what would the difference be between using gradient vectors at each point or using a value representing height? Is there one that is better than the other? Thanks.

# Answer
> 2 votes
*Extensive?* Extensive.

imagine totally white noise (audio). Then add 4 more times of white noise to it. Would you get any sort of pattern emerging? Statistics say white noise + white noise=more white noise.

Perlin noise isn't truly random. It's pseudorandom. What it is is pseudorandom values spaced out **on a grid**, then the values in between the grid points are *interpolated* so the noise appears smooth.

```
*----*
|n3  |n4
|    |
*----*
n1   n2

```

So here, n1, n2, n3 and n4 would have actual noise values defined for them. but all the -- points between n1..n2 etc would be *interpolated*.

Don't implement Perlin noise yourself.. it's really just reinventing the wheel.

The best implementation I've found so far is Stefan Gustafson's DSONoises.zip. Download it and check out the functions.

# Answer
> 3 votes
Fractal noise is usually produced by summing up Perlin noise taken at varying frequencies. You can't really generate it by adding up arrays of white noise... Classic Perlin noise can be found here: http://mrl.nyu.edu/~perlin/noise/ you can then produce "fractal noise" through simple fractional Brownian motion:

```
float fbm(in vec3 v, in int octaves){

      float frequency = 0.6;
      float persistence = 0.6;
      float lacunarity = 2.0;
      float sum = 0.0;
      float noise = 0.0;
      float pers = 1.0;
      v *= frequency;

      for (int i = 0; i<octaves; i++)
      {
         noise = noise(v);
         sum += noise * pers;
         v *= lacunarity;
         pers *= persistence;
    }
    return  sum;
}

```

If you want to keep your one array of white noise you can use it to create "smooth noise" as one of those websites describe. This means that you simply interpolate across the random values in the array and then take the values in the array and sum them up at different frequencies (see above algorithm). I don't believe that method is actually Perlin noise but a variant known as "value noise".

Edit: I forgot to include this: http://webstaff.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf It's the best summary of Perlin noise I've seen.

---
Tags: procedural-generation, terrain, lua, perlin-noise
---


title: Game maker, issues with an equation

text:
# Question
Title: Game maker, issues with an equation
Hello I am having an issue getting this equation to work, even with manually entering values replacing the variables. I cannot seem to get it to work, I have tested that the variables are being updated and working correctly and simpler equations are working and are able to be drawn, but when i try this all i am getting is "0.00"

yes this is working out profit made from bitcoin mining.

The original equation i am trying to get to work is dailyprofit = 24/(d\*2^32/(h\*10^6)/60/60)\*c

```
global.profit =(24/(global.difficulty * power(2,32)/(global.hashrate * power(10,6))/60/60)*global.reward);

```

any help or ideas would be greatly appreciated.

# Answer
> 0 votes
Thank you all for you help, and sorry. The error I found to be the cause was not to do with the equation itself. Game maker does not automatically draw more than 2 decimal places and this issue was resolved as below.

```
x=string_format(global.profit,0,6)

```

Then drawing X instead.

Thank you all again for your time.

# Answer
> 1 votes
You may have accidentally done integer division, which is division that returns an integer - the number that you expected from the division is truncated (which in this context effectively means rounded down) thus yielding 0.0 as the result of the equation.

To fix this, replace all of the "24"s in the equation with "24.0"s.

I'm not sure how GM handles this kind of thing, so it may not be the problem, but it's my best guess as to what's going on, Python does this kind of thing when you don't use a .x in a division.

---
Tags: mathematics, game-maker
---


# Question
Title: What's wrong with using a static class to load and expose all of my assets?
What are the pitfalls associated with loading and storing all references to all of your content/assets within a single static class?

I've been trying to ask myself why I would want to instantiate an assets bank and can not think of a good reason to do so.

I have made a static class which enumerates through my game assets and adds each one to a dictionary which I can access (safely exposed, of course) anywhere like so:

```
var tex = Assets.Image("folder\\easyaspie");
spriteBatch.DrawString(Assets.Font("font2"), new Vector2(100, 100), Color.White);

```

... you get the picture.

I appreciate that this gets much more complicated when you have so many assets that having them all loaded at once is not a good idea. However, there is nothing to stop you from including selective loading of assets in your static class, as well as having static methods to change the contents of the 'reference banks'.

What do you think?

**Edit:**

*My examples are pretty shallow, I recognise it's not a good idea to attempt to grab the reference of an asset mid-draw and is much better stored locally.*

# Answer
> 8 votes
I would strongly recommend you do *not* do this.

Static classes are fine for things that lack state or data, especially in languages like C# where you cannot otherwise have free-standing (non-member) functions. Once a class has any kind of state or data, however, you should seriously re-evaluate the decision to make it static. A good rule of thumb is to prefer instance to static; it greatly improves the long-term quality and maintainability of your code if you do.

For a case like this, an asset bank, I don't think a static class is a good idea:

* There's only one asset bank. That means you forgo the possibility of multiple banks of assets (for example, allowing you to load an unload assets as they are needed to conserve memory, or for unit testing). Once you start building this "selective loading" into a single static bank as a way to bypass this problem, you're just engineering a shoddy mockery of what you could have done more simply as an instance class.
* Because there's only one, you have to either engineer to the lowest-common-denominator in terms of access control and safety (think cross-thread access issues), or throw such issues to the wind and demand that client code write and thread-safety wrappers needed. This results in poorly-performing code in many cases for the former option, and the latter option often leads to code duplication and the resulting bugs.
* Being able to easily access the resources *anywhere* is usually a disadvantage, not an advantage. It might seem the opposite at first, but unconstrained ubiquitous access means you either already have or will be easily able to create a mess of poorly-scoped dependencies on the assets. It's the same general principle behind why globals are generally undesirable constructs.

Instead, build your asset bank as a regular class, and create a single instance of it when the game loads. Pass references to that interface to methods or other interfaces that have a need to load or otherwise access assets.

This gives you the flexibility easily support multiple banks in the future, *without* constraining you a design that can be very hard to recover from. Making the class static is simple enough, but if you ever need to change *that* you may find yourself having to clean up a mess of dependencies in client code that assumed there would only ever been a single bank, rather than just working with the bank provided.

Further, this method makes it obvious when you start to introduce dependency creep: when you find that you need to pass the asset bank reference to *everything* in your game, that is what tells you that your game's subsystems are not well separable and you should consider redesign their API boundaries.

I don't really see any *concrete* benefits to using a static class for this sort of thing except, perhaps, in an *extremely simple* bit of tech demo code. Most of the things that appear to be advantages to the static class decision relate to "simplicity" but usually are anything but, in the long run (and simplicity at the expense of quality is not an advantage).

# Answer
> 1 votes
I actually don't have a problem with something like this:

```
spriteBatch.DrawString(StaticAssets.DefaultFont, new Vector2(100, 100), Color.White);

```

It's a fairly reasonable simplifying assumption to say that there is only one instance of the default font per program. The kind of scenarios where this breaks down are uncommon, complicated, and difficult to plan for in advance. YAGNI.

You wouldn't want to do this in a library for 3rd-party consumption. But for a small-to-medium-sized game, where you can easily modify your own code, it's not a problem. Make your code flexible. Do things that save development time.

When you **break the rules** like this, it's important to do it **deliberately**, and to have an easy "out". In the above case, you can right click `DefaultFont`, do a "Find All References" and change how it works in a matter of minutes.

The problem with the original code, doing a dictionary lookup by string like this:

```
spriteBatch.DrawString(Assets.Font("font2"), new Vector2(100, 100), Color.White);

```

Is that you can't as easily discover all the places where the rules are being broken to reliably fix them when and if the need arises.

---

To put it another way - **you really don't want a static asset manager** (and I think Josh Petrie did a good job of explaining why). **But many times you *do* want static assets!**

Usually such assets will be static to a particular class, not global. So instead of having a `Draw` method like this:

```
spriteBatch.Draw(Assets.Image("playerSprite"), position, Color.White);

```

Or this:

```
spriteBatch.Draw(StaticAssets.PlayerSprite, position, Color.White);

```

You should probably do something like this:

```
class Player
{
    private static Texture2d playerSprite;

    public static void LoadContent(ContentManager content)
    {
        playerSprite = content.Load<Texture2d>("playerSprite");
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(playerSprite, position, Color.White);
    }
}

```

And then call each class's static `LoadContent` method in your game's `LoadContent` method. It's perfectly reasonable to assume that there will only ever be one instance of your `Game` class to be calling `LoadContent`.

---
Tags: xna, c#, assets
---


# Question
Title: What is difference between AndEngine's three Cameras
I am new to game development. After observing some AndEngine code snippets, I am trying to figure out which camera would be best suitable for my 2D game. Either it's **BoundCamera, SmoothCamera or ZoomCamera**?

I just know that these three classes inherit *Camera* and *bound Camera* is used to limit camera area it can follow player.

Can someone tell what's the difference between these three cameras and when should I use one? It would be great if you can give some example. Thanks.

# Answer
The camera hierarchy goes like this:

SmoothCamera extends -\> ZoomCamera extends -\> BoundCamera - Zoom cameras adopt Bound camera properties/methods. Smooth cameras adopt Zoom camera and Bound camera properties/methods

Choosing a SmoothCamera you'll have all the functionality from the others.

The difference between them is that they simply gain functionality depending on which you pick.

**BoundCamera** can be free moving, the position can be set manually by yourself or can be bound to a particular sprite or object to follow the x,y coordinates of that object constantly.

**ZoomCamera** is like BoundCamera, it can be freemoving, or follow an object but this time you can dynamically set the zoom level and make handlers to zoom in or out on the scene (You could add pinch to zoom functionality with this camera).

**SmoothCamera** can zoom, free-move, follow and additionally have a speed setting that allows it to tween from one position to the next. So when following an object it will move smoothly from point a to b, not snap to the object constantly. These parameters are generally set in the constructor.

I hope that makes it easier to understand.
> 4 votes

---
Tags: 2d, camera, andengine
---


# Question
Title: How can obtain the relative orientation between two quaternions?
How do I obtain the relative orientation given two orientations (represented by quaternions `q0` and `q1`)?

# Answer
The relative orientation is obtained simply by division:

```
q = q0 / q1

```

Or, if division is not available:

```
q = q0 * inverse(q1)

```

Note that since the quaternions used to represent rotations are unit quaternions, the inverse of `q1` is simply its conjugate `q1*`, and is obtained by flipping the sign of `x`, `y`, `z` but not `w`.
> 4 votes

# Answer
Quaternion is another representation of axis angle. The solution is to create a new quaternion from the original quaternion that only has the needed components.

An axis angle representation can be converted to a quaternion using the following formula

```
q[0] = cos(R/2);
q[1] = sin(R/2)*x;
q[2] = sin(R/2)*y;
q[3] = sin(R/2)*z;

```

Where `R` is the angle in radians, and `(x,y,z)` represents the axis, and quaternion is (R,x,y,z).

So in order to create a new quaternion with only the pitch component you just zero out the other components and normalize the quaternion:

```
Quaternion q; // this is your original quaternion
q.x = 0.0;
q.z = 0.0;
q.Normalize();

```

Edit based on your update:

Sensors AFAIK calculate orientation relative to gravity, in other words Y (or Z) is the direction of the gravity. You need take that into consideration. And I think you don't need to multiply it with the inverse *initial* orientation.
> 2 votes

---
Tags: rotation, quaternion
---


# Question
Title: how to make a onMouseEnter events in xna
I have been trying different things all day to get the answer. What I need is a sound to play one time when I enter a given rectangle I need the sound to fire one time and never fire again until I exit the rectangle.It is easy for me to find out if the mouse is over the rect by using the contains() method but the problem comes when the sound gets played it just keeps looping.I added a check to see if the sound state is not playing and that stops it from just making random noise but it still loops help me obi wan.

# Answer
In a polling-based system like XNA's you must store the previous input state as well as the current one, in order to detect state transitions.

So just as you would use code like this to detect a click:

```
var mouseState = Mouse.GetState(); // <- top of Update method

bool mouseDown = lastMouseState.LeftButton == ButtonState.Released
                 && mouseState.LeftButton == ButtonState.Pressed;

if(mouseDown)
    DoSomething();

lastMouseState = mouseState; // <- bottom of Update method

```

You would use code like this to detect the mouse entering:

```
bool mouseEnter = !rect.Contains(lastMouseState.X, lastMouseState.Y)
                  && rect.Contains(mouseState.X, mouseState.Y);

if(mouseEnter)
    PlaySound();

```

(And so on for mouse leaving, mouse button up, etc.)
> 1 votes

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


title: AndEngine Font Issue

text:
# Question
Title: AndEngine Font Issue
I am learning AndEngine. I am displaying Hello world using this code:

```
public class myactivity extends SimpleBaseGameActivity
{

 private final int CAMERA_WIDTH = 320;
 private final int CAMERA_HEIGHT = 480;

 private Camera  m_Camera;
 private Scene  m_Scene;

 private Font  font;
 private Text  text;

 @Override
 public EngineOptions onCreateEngineOptions()
 {
  m_Camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  EngineOptions en = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(
    CAMERA_WIDTH, CAMERA_HEIGHT), m_Camera);

  return en;
 }

 @Override
 protected void onCreateResources()
 {
    //determine the density
 WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
 Display display = windowManager.getDefaultDisplay();
 DisplayMetrics displayMetrics = new DisplayMetrics();
 display.getMetrics(displayMetrics);
 int density = (int)(displayMetrics.density);

 //scale desired size 25 by density
     int fontSize = (int) (25 * density);
  font = FontFactory.createFromAsset(this.getFontManager(), this.getTextureManager(), 1024, 1024, this.getAssets(),
    "times.ttf", fontSize, true, android.graphics.Color.BLACK);
  font.load();

//Texture fontTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
//font = new Font(fontTexture, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), fontSize, true, Color.WHITE);
//mEngine.getTextureManager().loadTexture(fontTexture);
//mEngine.getFontManager().loadFont(font);

 }

 @Override
 protected Scene onCreateScene()
 {
  m_Scene = new Scene();
  m_Scene.setBackground(new Background(Color.WHITE));

  text = new Text(0, 0, font, "Hello Android", this.getVertexBufferObjectManager());
  m_Scene.attachChild(text);

  text.setPosition(CAMERA_WIDTH/2 - (text.getWidth()/2), CAMERA_HEIGHT/2 - (text.getHeight()/2));
  return m_Scene;
 }

}

```

It is displaying the font like this:

As you can see that pixels are stretching and font is looking ugly with too much pixelation. How do I display proper font text with no pixelation or add anti-aliasing to the font?

# Answer
It actually looks like you are already on the right track with your comments.

Try changing your font initialisation to this:

```
//scale desired size 25 by density
int fontSize = (int) (25 * density);
//define texture for font with BILINEAR scaling
final ITexture fontTexture = new BitmapTextureAtlas(this.getTextureManager(), 1024, 1024, TextureOptions.BILINEAR);
font = FontFactory.createFromAsset(this.getFontManager(), fontTexture, this.getAssets(),
     "times.ttf", fontSize, true, android.graphics.Color.BLACK);
font.load();

```

Try it out and let us know the results.
> 2 votes

---
Tags: android, andengine, fonts, antialiasing
---


# Question
Title: margin of error trying to check if a point lays on line
Working with floating point values it is as easy as breathing to run on approximation errors by comparing quantities which should be the same. I want to know if there is a way built in some MSDN (or even external) library for c# to ignore the problem.

An example could be: more than comparing 2 float values like this

```
if(myVector3.X == anotherVector3.X)

```

I would appreciate something like this

```
if(myVector3.X.isInTheNeighbourhood(anotherVector3.X))

```

This is not well-written, I know. That is just to simplify the explaination. What I am exactly doing is checking if a point (`Vector3`) lays on line segment. So basically the calculations I make are nothing more than

```
(x - x1)/(x2 - x1) = (y - y1)/(y2 - y1) = (z - z1)/(z2 - z1)

```

But these values won't be always the same, so I need to write down some code which includes a sort of tolerance a sort of Neighbourhood mathematical concept to accept values close enought to the line.

Hope that I made myself clear. Has anyone a solution for this?

# Answer
> 2 votes
In order to take into consideration the floating point error you need to do the following:

```
\#define ERR 1e-9
if( fabs (myVector3.X - anotherVector3.X)  <= ERR )

```

Keep in mind that this kind of approximation changes the geometrical properties of the shape, for instance this can generate fat planes/lines. a case where a line or a plane no more has zero width. But as far as you don't need exact calculations such as those needed in geometry analysis it's fine for a game. Here is a link where it explains the problem in using floating points in geometry.

There are other methods to solve the error problem and get exact results, but they are far too complex or far too slow. So non of them from my experience with geometry fit the requirements of the real time video games.

# Answer
> 0 votes
It sounds me to me like you need a Ray-Sphere Intersection test.

Your sphere would be defined by the point and the radius as your margin of error.

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


title: Can I Use SetLOD with D3D9Ex?

text:
# Question
Title: Can I Use SetLOD with D3D9Ex?
I need to limit the mipmap level loaded onto the device for certain textures, but I'm using a D3D9Ex-based engine, so I can only use `D3DPOOL_DEFAULT`, *not* `D3DPOOL_MANAGED`.

Microsoft's documentation says that I can use `SetLOD`

> for a managed texture.

Does that mean that I cannot use `SetLOD` in D3D9Ex?

# Answer
> 2 votes
I believe the answer is no, you cannot use `SetLOD`. As the documentation says, the texture must be managed which means `D3DPOOL_MANAGED` and which does not exist in Direct3D 9Ex.

I have a sample app which uses Direct3D 9Ex, and tried calling `SetLOD`, and I got a return of `0` which means it failed according to the documentation which states

> This method returns 0 on nonmanaged textures

---
Tags: directx9, level-of-detail, mipmaps
---


# Question
Title: Import Blender files to SharpGL (openGL for c#)
please i have problem with import 3D models to SharpGL (openGL in c#). Have you got pls any project where is this problem solved? I need create any models in for example blender, and then import to sharpGL. I try this 4 days, and without result. Please can you post me any project with loading (obj,3ds,...) files with texturing? I do big school project and without this i never completed this project. Thank you for answer.

Sorry for my english.

# Answer
You can take a look at my own 3d .obj importer written in Java:

https://github.com/lukasz1985/Simple3dEngine/tree/shaders/src/io

look at classess: "ObjLoader" and "ObjParser" which is used by the former.

It should be pretty easy to adapt the code to C#.
> 1 votes

---
Tags: opengl, c#, blender
---


# Question
Title: Top-Down Tilemap Rendering and Collisions in Libgdx
I'm sorry if this question has been previously answered, but I was unable to find an answer here or through google. I'm trying to make a simple roguelike-like that would feature a top-down tile map, a player, AI controlled enemies, and various items. I'm having trouble understanding how I can properly have the tilemap interact with the player and enemies through both collision detection and rendering.

It seems that the two main options for collision detection are 1)to specify if a tile is collidable in Tiled Map Editor, and then check tile by tile in the game code to see if the player's position overlaps that of a nearby collidable tile, or 2)integrate the tilemap with box2d physics. Admittedly, I do not understand any part of using tilemaps with box2d.

Additionally, I am unsure of how to properly draw the tilemap in reference to the player and enemies. Say I had a tree tile that I would like to always draw on top of/in front of the player. What is the best practice for accomplishing this in libgdx? I was thinking assign such tiles a certain ID and then render them after the player is rendered.

# Answer
You can put the tiles you want to render in front of the player in its own tile layer, then you can draw that layer after you've drawn the player. The tiled map renderers in libgdx can take an int array as an argument that specifies what layers to render.

```
//create the int arrays
int[] background = {0};
int[] foreground = {1};

//in the rendering method
map.render(background);
//drawing the player here
map.render(foreground);

```

For collision detection you can take a look at this video and see if it answers your question: click me
> 1 votes

---
Tags: collision-detection, libgdx, tilemap
---


# Question
Title: Should I store ads in the background or recreate them every time I need them?
I am developing an XNA game for Windows Phone 7 and 8. The game is level-based. After finishing each level a screen comes up with a bit of stats summary. I wish to embed an ad in this screen, on which I expect users to only spend a few seconds on after each level.

The ads I am using are Microsoft's pubCenter ads and AdDuplex as a backup.

Should persist instances of these ads throughout the game's operation and only make them visible on level completion? Or should I create new instances every time they are needed and destroy them once I don't want them anymore for each level?

My worry is that starting up an ad on a screen which is intermediate and lasts for a short while might not be enough time for an ad to download. On the other hand, having one or more ads running continuously in the background might not be a good thing for battery or performance.

# Answer
I'd recreate them every time they are needed.

You are right to be concerned about the downsides of both choices, but in the end, you should err on the side of being *less user-hostile*. Having the ad constantly active in the background (assuming that the ad cannot be downloaded and then "suspended" until needed) will cause unnecessary processing during your games runtime, and the potential impact on performance and the user's battery life is almost certainly going to be worse in the long run for you than the potential impact of an ad not downloading fast enough and consequently not displaying long enough for the user to comprehend it (or see it at all).

If your levels are linear enough you can start to pre-load the ads as the user nears the end, if such capability is provided by the API and does not violate any usage terms you may have agreed to.
> 1 votes

---
Tags: xna, performance, mobile, advertisements
---


# Question
Title: How can I find the location of OpenGL object after rotation?
I have a rotating object, a cube, which I rotate in OpenGL as follows:

```
gl.glPushMatrix();
gl.glTranslatef(400.0f, 300.0f, 1300.0f);
gl.glRotatef(m_x, 4.0f, 0.0f, 0.0f);
gl.glRotatef(m_y, 0.0f, 4.0f, 0.0f);
gl.glRotatef(m_z, 0.0f, 0.0f, 42.0f);
gl.glCallList(++shapeNumber); // cube 2
gl.glPopMatrix();

```

(`m_x`, `m_y`, and `m_z` are the change in the rotation each frame.)

I want to detect a collision between the camera and that rotating object, and to do that I need to get the coordinates of the rotated object in real time. How can I accomplish that?

# Answer
OpenGL's `glTranslate` and `glRotate` methods don't *actually* perform translation or rotations on any objects. Instead, they compute transformation matrices and apply those matrices to OpenGL's matrix stack, which in turn yields a final transformation matrix that is applied to the object vertices by the GPU when a frame is actually rendered.

In order to compute the coordinates of an object after the application of any transformation, then, you're going to have to do it yourself on the CPU. This involves the construction of an equivalent transformation matrix for your combined rotation/translation operation on the CPU (most game libraries and frameworks have "matrix" classes, such as this one from LWJGL, or you can roll your own; the math behind the various matrix operations is well-documented).

Once you have the matrix, multiply it by all the original vertices of your object to yield the transformed vertices and perform your collision detection on that resulting object (in general one simplifies this process to only transform the bounding cube or similar low-resolution collision mesh, but since you are already using cubes in your specific example you can continue to use them directly).
> 2 votes

---
Tags: opengl, java, 3d, graphics, jogl
---


title: How do I make someone walk in Skyrim?

text:
# Question
Title: How do I make someone walk in Skyrim?
I'm coding a mod for Skyrim with Papyrus and the Creation Kit. I can't seem to get an Actor to move from point A to point B. I know there's a function to teleport an actor, but how can I make them walk or run using Papyrus?

# Answer
If you just want the actor to wander around, give him a sandbox package such as `DefaultSandboxHomeowner`. This will cause the actor to mill about his or her home. If you have other packages assigned to the actor, you generally will want this sandbox package to be lower than them in the package stack so that it has the least priority.

If you want the actor instead to walk between specific points, give him or her a new package based on the `Patrol` template or perhaps the `Travel` one instead. The former will require you associate a path with the package, so you'll want to have that set up first. The latter only requires a location but does not have facility for repetition, so the actor will move to the specified location and then stop.

You'd have to set up additional behavior to have the actor move *back* (you could probably do this in a quick-and-dirty fashion by giving the actor many travel packages, with schedule limitations that account for the time it should take the actor to make the trips, but at this point a patrol package would be cleaner... unless perhaps you need the actor to move across cells).
> 1 votes

---
Tags: scripting, modding, skyrim-modding
---


# Question
Title: Where is linked_portal_door in the Source SDK?
I just made a new mod in the Source SDK. I saw online that there is an entity that allows portals to be created (`linked_portal_door`). However, I cannot find or create this entity.

Is it included in the base SDK or do you have to have an add-on. If it is not included, is there an alternative?

I am using Source Engine 2007.

# Answer
> 2 votes
Per the documentation, `linked_portal_door` was added with Portal 2.

It sounds like your version of the SDK and toolset is too old to have it, and there is no alternative that I am aware of (the releated `prop_linked_portal_door` is also only available in Portal 2).

---
Tags: source-engine
---


title: Using Box2D / Physics with Tiles?

text:
# Question
Title: Using Box2D / Physics with Tiles?
Here is my issue.

I currently have Box2D setup and working. But, it works with my Entity system. So I can create static objects and dynamic moving ones, and they simulate fine.

However, my world is made up of tiles.

I have very easy ways of determining which Tiles a Body is intersecting, but I'm not sure how to tell this to Box2D.

I could obviously turn each tile into a Body but that would waste a lot of ram because I have 10s of thousands of tiles.

The tiles also form some cool patterns and can be converted to an empty tile at will.

My thought was to do something like this:

-Iterate the bodies, find which tiles they are touching, add these as static bodies into the world. Step the world. Remove the bodies.

This seems like a bit of a hack though and I am wondering if anyone can think of a better way.

Thanks

# Answer
> 3 votes
I've done the same thing a few years ago.

The solution was to initialize a Pool of Body Objects, and then position them all off screen. The idea is to create a set amount of bodies, and then move them around when required. I managed to locate my old code, here is the initialization code from my old project:

```
private void InitializeBodyPool()
{
    Bodies = new Pool<LandBody>(50);
    foreach (Pool<LandBody>.Node node in Bodies.AllNodes)
    {
        node.Item.Init(World);

        node.Item.BodyType = BodyType.Static;
        node.Item.Position = new Vector2(-9999999999, -9999999999);   //init offscreen

        PolygonShape box = new PolygonShape(1);
        box.SetAsBox(2.5f, 2.5f, Vector2.Zero, 0);
        node.Item.CreateFixture(box);

        node.Item.FixtureList[0].Friction = 1000;
        node.Item.FixtureList[0].Restitution = 0;
        node.Item.FixtureList[0].CollisionGroup = -1;
    }
}

```

When you need to set a body, simply grab one from the pool, and set its position.

This may not be the proper way of handling this but it worked for me.

I took a animated gif to demonstrate how the bodies are swapped into position:

---
Tags: c++, box2d, physics
---


# Question
Title: How do I export my Blender model to OGRE XML format for jMonkeyEngine 3?
I'm an amateur software engineer with several simple 2D-game projects under my belt. I'v recently turned my attention towards creating a basic 3D game, nothing too fancy, just to get a grip on things.

I used jMonkeyEngine 3 (RC 2) because I'm interested in Java, and open-sourced games. Unfortunately, being an independent project, jME3 is not as complete as other Game Engines, and its community is not as large.

I've followed most of their basic how-to tutorials to get me started on jME3, but one area always escapes me; the use of models in a game. jME3 recommends Blender, and also recommends exporting the models as OGRE XML files.

In my experience, jME3 can import .blend files directly, but at the loss of anything other than the very basic model itself. No bones, no animation, and so far, my attempts at giving it a solid color failed as well.

I'm only interested in using and seeing my model in game, with bones, if at all possible. Animations an come later. I've followed their tutorials on how to import models here:

http://jmonkeyengine.org/wiki/doku.php/jme3:beginner:hello\_asset

But I get stuck on "Open the menu File \> Export \> OgreXML Exporter to open the exporter dialog."

For one, there IS no Export to OgreXML (in Blender). I've fiddled around in the preferences and still found nothing. I've installed the required 'stuff' by going through jME3 and clicking 'install OGRE plug-ins.'

I've also tried to download a converter from Ogre itself, but all I get are some command line parameters that open CMD and close it way too fast for me to do anything.

Am I missing something?

My experience with Blender and modelling is even more limited than my experience in programming, so I don't really understand scripts, and python and whatever it is I found on the net in my research.

I used:

* Blender 2.65
* JMonkeyEngine 3.0 RC 2
* Windows 8 (ick)

# Answer
> 5 votes
Install the blender2ogre add-on in Blender and you can select what you want to export. You just need to place the python script in the scripts/addons folder where you have Blender installed. Once you are ready to export, go to File-\>Export-\>Ogre3D (.scene and .mesh).

# Answer
> 3 votes
I just import the Blender file with Spatial spatial = assetManager.loadModel("Models/sample.blend"); For me that works great. (Dont forget to remove the belnder light and camera :) )

# Answer
> 1 votes
I had to manually enable Ogre3D in blender user preferences \> add ons \> Import-Export also the direct .blend import does support animations

---
Tags: java, blender, ogre, jmonkeyengine
---


title: Libgdx sprite rotation (image quality)

text:
# Question
Title: Libgdx sprite rotation (image quality)
This one is probably really simple but I didn't find a solution.

I'm trying to create a widget (speedometer) with libgdx. For the arrows I'm using the `setRotation()` function. But when the image is rotated, the quality drops.

The result looks like this:

How can I improve the quality of the arrows?

# Answer
> 7 votes
Roy T. suggested to fix this changing the texture filtering settings, On LibGDX this can be found on `Texture.setFilter` or changing the `Texture Params` if you are using the `AssetLoader`. Set the filter params to `TextureFilter.Linear` and the problem should be fixed.

For more on the matter, take a look at http://www.learnopengles.com/android-lesson-six-an-introduction-to-texture-filtering/

---
Tags: libgdx, rotation, spritebatch
---


# Question
Title: How can I compute the average color of a texture?
I'm making a mini-map system for my tile based game, and I thought the best way to accomplish this would be the following:

At the beginning of the game, I calculate the predominant color of every block (tile type), and store it somewhere. Then, to create the mini-map, I just run through the block matrix and paint a single pixel for each block, instead of it's full 16x16 image.

To do this, I need to be able to get the pixel color of a given position in the texture (to compute the average color). The way I was doing it was using `getTextureData()`.

This method, however, seems to be buggy and very poorly-documented. It returns a single array with all the data in what I thought was RGBA order. Thus, the code to get the average color of a rectangle starting at `x` and `y` with dimensions `w` and `h` from the texture `t` would be:

```
int r = 0, g = 0, b = 0;
byte[] bytes = t.getTextureData();
for (int i = 0; i < h; i++) {
    for (int j = 0; j < w; j++) {
        r += bytes[4*((y + i)*t.getImageWidth() + x + j)];
        g += bytes[4*((y + i)*t.getImageWidth() + x + j) + 1];
        b += bytes[4*((y + i)*t.getImageWidth() + x + j) + 2];
    }
}

r /= bytes.length / 4;
g /= bytes.length / 4;
b /= bytes.length / 4;

```

However, this does not seem to work. It produces incorrect (often negative) values for each pixel. Is my approach correct or should be I handling the problem differently?

# Answer
> 2 votes
Your approach is sound (`getTextureData` is the right basic idea).

However, you aren't checking the texture's `hasAlpha` method to see if the texture has alpha, in which case each pixel would be three bytes and not four. Also, you assume that the texture is in RGBA format and that's not always necessarily going to be true (depending on where the underlying texture object is getting its data from).

Furthermore, in your loop you are trying to access a byte of a pixel via the computation

```
bytes[4 * ((y + i) * t.getImageWidth() + x + j)]

```

however, your loops (with `i` and `j`) are over the width and height of the source rectangle *in pixels*. For an input of (0,0), this works out fine. But for an input of (0, 1) (assuming `x` and `y` are both 0), you end up trying to access `bytes[1]`, which is not what you want (you want to access `bytes[4]`).

I'd write the loop thusly:

```
int pixelSize = t.hasAlpha() ? 4 : 3;
for (int row = y; row < y + h; ++row) {
  for (int column = x; column < x + w; ++column) {
    // Compute the pixel index.
    int pixelIndex= row * t.getTextureWidth() + column;

    // The byte index can be obtained by multiplying the pixel index
    // by the size of each pixel; that will refer to the first component
    // of the pixel.
    int byteIndex = pixelSize * pixelIndex;

    // Simple offsets can reach the remaining components of the pixel.
    r += bytes[byteIndex];
    g += bytes[byteIndex + 1];
    b += bytes[byteIndex + 2]
  }
}

```

(Note that this does *not* attempt to handle non-RGB-ordered textures, but it does suggest a way to deal with textures missing alpha).

Finally, once you have summed up each component, you only need to divide by the number of pixels that were in the subrectangle you measured to get the alpha:

```
int pixelCount = w * h;
r /= pixelCount;
g /= pixelCount;
b /= pixelCount;

```

(Previously, you were dividing by the number of pixels in the entire texture, which is not always the same size as the area you actually measured.)

---
Tags: textures, lwjgl, slick
---


# Question
Title: In an XNA game object, what should I use to represent a texture for serialization?
While trying to save to a file a list of objects needed to run my game, I noticed that `Texture2D` is not serializable. Why? What was the purpose?

The object I want to serialize looks like this:

```
[Serializable]
public class GameObject
{
    private Vector2 position_ = Vector2.Zero;
    private float rotation_ = 0.0f;
    private Vector2 scale_ = Vector2.One;
    private float depth_ = 0.0f;

    private Texture2D texture_;

    private bool is_passable_ = true;

    private GameObject(
        Vector2 starting_position,
        string filepath,
        ContentManager content)
    {
        this.position_ = starting_position;
        this.texture_ = Content.Load<Texture2D>(filepath);
    }

    //Properties
    //Update/Draw
}

```

So, what should I serialized since `Texture2D` isn't made to be used that way?

# Answer
> 1 votes
You should serialize a *reference to* the texture (such as its file name), not the texture itself. That way when you load the serialized game object later, you know which texture to look up and associate with the object.

You don't want to serialize the entire texture with the object, because that would be a huge waste of space when objects started to share textures (when serialized, they'd each have a complete copy of the texture bytes). That's why the `Texture2D` object itself isn't marked as serializable. It's trying to protect you from yourself.

This is related to why it's generally a good idea to separate game logic state from rendering and visual presentation state.

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


# Question
Title: 2.5d with box2d - approaches from the top and bottom
So, I'm using box2d for my 2.5d game (think double dragon, tmnt arcade, castle crashers) where you can move around on the z-axis (faked as y-axis movement). Basically, I have box2d only doing collision if 2 entities have the same z coordinate or a z-coordinate within the depth. All is fine, except when I approach an entity from the top or bottom.

So yeah, approaching any box2d entity from the top or bottom within the correct x will make the player bounce back once the z becomes the same as the entity - which makes sense because then it starts detecting collision, and it detects a box inside a box. How could I circumvent this? Thanks.

# Answer
This blog post covers pseudo 3D collisions and discusses an interesting solution to your problem. I'll give an overview of the post but you should check it out as it does a thorough job of explaining the solution (with pictures too!)

Their entities are essentially represented by three parts: a box for the body, a box for the footprint and a box representing the attack area. You can think of the body box as representing the width and height of the entity and the footprint as representing the depth. The footprint is used to determine z-order for drawing and whether or not entities are capable of colliding with one another. So, when the player is just moving (not attacking) only the footprint is used to determine whether it's colliding with another entity.

In Box2D terms an entity could be represented by a Body with three Fixtures for the body, footprint and attack. Each Fixture would be a sensor so you get begin/end callbacks for collision detection but the Fixtures don't actually physically collide. In other words, just use Box2D for collision detection not physics simulation.
> 2 votes

# Answer
You shouldn't treat your objects as boxes with the same height the entity have. Your objects should have a collidable fixture only on the FOOT, and the head+limb+legs should be a sensor fixture, where you only use it to detect if a player has fell on top of another, etc.
> 0 votes

---
Tags: java, 2d, box2d, libgdx
---


# Question
Title: Why am I getting a mirrored mesh out of my data structure?
I'm in the beginning stages of an RTS game in Unity. I have a procedurally generated terrain with a Perlin noise height map, as well as a function to generate a river. The problem is that the graphical creation of the map is taking the data structure of the map and rotating it by 180 degrees.

I noticed this problem when I was creating my rivers. I would set the river's height to flat, and noticed that the actual tiles that were flat in the graphical representation were flipped and mirrored.

Here are some screenshots of the map from different angles:

As you can see, if you flipped (graphically) the river by 180 degrees on the Z axis, it would fit where the terrain is flattened. I have a suspicion it is being caused by a misunderstanding on my part of how vertices work.

This code here creates a new array of `Tile` objects, which hold the information for each tile, including its type, coordinate, height, and it's vertices:

```
public DTileMap (int size_x, int size_y)
{
    this.size_x = size_x;
    this.size_y = size_y;
    //Initialize Map_Data Array of Tile Objects
    map_data = new Tile[size_x, size_y];
    for (int j = 0; j < size_y; j++) {
        for (int i = 0; i < size_x; i++) {
            map_data [i, j] = new Tile ();
            map_data[i,j].coordinate.x = (int)i;
            map_data[i,j].coordinate.y = (int)j;

            map_data[i,j].vertices[0] = new Vector3 (i * GTileMap.TileMap.tileSize, map_data[i,j].Height, -j * GTileMap.TileMap.tileSize);
            map_data[i,j].vertices[1] = new Vector3 ((i+1) * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j) * GTileMap.TileMap.tileSize);
            map_data[i,j].vertices[2] = new Vector3 (i * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j-1) * GTileMap.TileMap.tileSize);
            map_data[i,j].vertices[3] = new Vector3 ((i+1) * GTileMap.TileMap.tileSize, map_data[i,j].Height, -(j-1) * GTileMap.TileMap.tileSize);
        }
    }

```

}

This code sets the river tiles to height 0:

```
foreach (Tile t in map_data)
{
    if (t.realType == "Water")
    {
        t.vertices[0].y = 0f;
        t.vertices[1].y = 0f;
        t.vertices[2].y = 0f;
        t.vertices[3].y = 0f;
    }
}

```

Finally, below is the code to generate the actual graphics from the data:

```
public void BuildMesh ()
{
    DTileMap.DTileMap map = new DTileMap.DTileMap (size_x, size_z);
    int numTiles = size_x * size_z;
    int numTris = numTiles * 2;

    int vsize_x = size_x + 1;
    int vsize_z = size_z + 1;
    int numVerts = vsize_x * vsize_z;

    // Generate the mesh data
    Vector3[] vertices = new Vector3[ numVerts ];
    Vector3[] normals = new Vector3[numVerts];
    Vector2[] uv = new Vector2[numVerts];

    int[] triangles = new int[ numTris * 3 ];

    int x, z;
    for (z=0; z < vsize_z; z++) {
        for (x=0; x < vsize_x; x++) {
            normals [z * vsize_x + x] = Vector3.up;
            uv [z * vsize_x + x] = new Vector2 ((float)x / size_x, 1f - (float)z / size_z);
        }
    }
    for (z=0; z < vsize_z; z+=1) {
        for (x=0; x < vsize_x; x+=1) {
            if (x == vsize_x - 1 && z == vsize_z - 1) {
                vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x - 1, z - 1].vertices [3];
            } else if (z == vsize_z - 1) {
                vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x, z - 1].vertices [2];
            } else if (x == vsize_x - 1) {
                vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x - 1, z].vertices [1];
            } else {
                vertices [z * vsize_x + x] = DTileMap.DTileMap.map_data [x, z].vertices [0];
                vertices [z * vsize_x + x+1] = DTileMap.DTileMap.map_data [x, z].vertices [1];
                vertices [(z+1) * vsize_x + x] = DTileMap.DTileMap.map_data [x, z].vertices [2];
                vertices [(z+1) * vsize_x + x+1] = DTileMap.DTileMap.map_data [x, z].vertices [3];

            }

        }
    }

    for (z=0; z < size_z; z++) {
        for (x=0; x < size_x; x++) {
            int squareIndex = z * size_x + x;
            int triOffset = squareIndex * 6;
            triangles [triOffset + 0] = z * vsize_x + x + 0;
            triangles [triOffset + 2] = z * vsize_x + x + vsize_x + 0;
            triangles [triOffset + 1] = z * vsize_x + x + vsize_x + 1;

            triangles [triOffset + 3] = z * vsize_x + x + 0;
            triangles [triOffset + 5] = z * vsize_x + x + vsize_x + 1;
            triangles [triOffset + 4] = z * vsize_x + x + 1;
        }
    }

    // Create a new Mesh and populate with the data
    Mesh mesh = new Mesh ();
    mesh.vertices = vertices;
    mesh.triangles = triangles;
    mesh.normals = normals;
    mesh.uv = uv;

    // Assign our mesh to our filter/renderer/collider
    MeshFilter mesh_filter = GetComponent<MeshFilter> ();
    MeshCollider mesh_collider = GetComponent<MeshCollider> ();

    mesh_filter.mesh = mesh;
    mesh_collider.sharedMesh = mesh;

    calculateMeshTangents (mesh);
    BuildTexture (map);
}

```

# Answer
> 2 votes
As discussed in the comments, it appears that your texture coordinates were mirrored and not your terrain. When building the mesh from your data structure, it's a good idea to build the the texture coordinates at the same time. This makes the code a bit more readable and helps prevent issues like this.

---
Tags: c#, unity, terrain-rendering
---


# Question
Title: Why would I lose the D3D device during an HLSL unroll?
I have a pixel shader that downsamples a texture from one size to another. The downsample shader uses a nested 'for' loop to traverse the uv coordinates. When the for loop executes more than four times( \[unroll(8)\] for example ) the graphics device is lost and all hell brakes loose...Here is shader code:

```
void DownsamplePass_Pixel_Shader( in float4 Position : POSITION0,
           in float4 PositionSS : VPOS, out float4 vEnergy : COLOR0 )
{
    float width = LastMipInfo.x;
    float height = LastMipInfo.y;
    float mip = LastMipInfo.z;
    float mult = LastMipInfo.w;
    float4 vPos = PositionSS;
    float4 vColor = 0;
    int ncPixels = 0;

    // depending on the size of the visibility buffer( texture to downsample )
    //      it may be necessary to sample more than a 2x2 block of pixels( if the size is greater than twice the target )
    //      this is only necessary for the first pass
    if( bFirstDownsamplePass )
    {
        [unroll(8)]
        for( int y = 0; y < mult; ++y )
        {
            [unroll(8)]
            for( int x = 0; x < mult; ++x )
            {
                float2 vCoord = float2( ( vPos.x * 2 * mult ) / width + x * ( 1 / width ), ( vPos.y * 2 * mult ) / height + y * ( 1 / height ) );
                float4 vTexel = tex2Dlod( g_SamplerMip, float4( vCoord, 0, mip ) );
                if( all( vTexel.rgb == 0 ) )
                    continue;

                vColor.rgb += vTexel.rgb * tex2D( g_SamplerMultiplier, vCoord ).rgb;
                ncPixels++;
            }
        }
    }
    else
    {
        float2 vCoords[ 4 ];
        vCoords[ 0 ] = float2( ( vPos.x * 2 ) / width, ( vPos.y * 2 ) / height );
        vCoords[ 1 ] = float2( vCoords[ 0 ].x + ( 1 / width ), vCoords[ 0 ].y );
        vCoords[ 2 ] = float2( vCoords[ 0 ].x, vCoords[ 0 ].y + ( 1 / height ) );
        vCoords[ 3 ] = float2( vCoords[ 1 ].x, vCoords[ 2 ].y );

        // calc average energy
        float4 vColor = 0;
        int ncPixels = 0;
        for( int i = 0; i < 4; ++i )
        {
            float4 vTexel = tex2Dlod( g_SamplerMip, float4( vCoords[ i ], 0, mip ) );
            if( all( vTexel.rgb == 0 ) )
                continue;

            vColor.rgb += vTexel.rgb;

            ncPixels++;
        }
    }

    vEnergy = float4( vColor.rgb / max( ncPixels, 1 ), 1 );
}

```

I could just define each uv coordinate but I'm interested in knowing why this problem occurs!

# Answer
> 2 votes
I can think of two obvious possibilities:

1. You've hit the TDR timeout because the shader is taking ages to run. You can work round this locally by adjusting the timeout in the registry. You probably shouldn't adjust that setting for other people though - the general solution is to break the draw call up into multiple smaller draw calls - resizing is usually quicker when done in multiple intermediate steps instead of all in one go anyway.
2. You've found some sort of driver bug. If adjusting the timeout didn't help then try it on a different graphics card, or the Reference Rasterizer. It might also help if you could post a shader that can be compiled by someone else.

As a side note efficient downsampling shaders use the hardware bilinear filter to do a quarter as many texture reads as the obvious algorithm.

---
Tags: c++, hlsl, directx9, fragment-shader
---


title: Value of the Game Institute Courses

text:
# Question
Title: Value of the Game Institute Courses
I'm considering purchasing courses from Game Institute, specifically, the Foundation Studies Package. Has anyone here taken their courses? If so, do you feel they are a good value? If you can, please be specific as to what you benefited from them, and their strengths and weaknesses.

Though I am most interested in reinforcing computer science fundamentals with respect to game development, I would also like to know if the material is relevant to today's technologies.

I'm especially interested in responses from working professionals who have taken their courses or reviewed their materials.

Background: My work week is spent mostly with SQL Server ETL and some C# web forms development. I have ideas for 2D and 3D platformers, but I don't have the skills to build them to completion yet.

TIA!

# Answer
> 6 votes
I'll give my input since I've used their package before (and no, I'm in no way affiliated with them). You may have noticed that they're currently having a sale where for 99$ you get access to most of their content across a lot of different topics. For instance:

* C++ Programming for Game Developers - Module I and II
* Graphics Programming with DirectX 9 - Module I and II
* Game Mathematics and Math Primer
* Artificial Intelligence for Game Developers
* Introduction to Robotics
* Video Game Console Design

I honestly believe that for that price, that's one of the best deals of this kind I've ever come across.

I haven't completed all of the courses yet, but from what I've seen so far, the amount of content and detail packed into each of them is *at least* as high as most books you could buy for each individual topic. For instance, just the textbook/workbook for the first DX9 Module is over 1000 pages long, and that's not including the actual presentations which also have a full voice recording.

I've also found the content to be very complete and useful. For instance, about 3 years ago, right after working through the first few lessons (including the workbook chapter) of the graphics programming module, I stepped away for a moment and implemented my first basic 3D graphics pipeline from scratch (on an old 2D Javascript Canvas) with the things I had learnt. I think that was probably the first time matrices and transformations really started making sense to me.

To put it shortly, I believe that the value in this case (for the 99$ deal) is *ridiculously high* for the amount of content you'll get. I've built up quite a large library of game developments books over the course of the past few years, and this package still ranks up there on the list as one of the best investments I've made.

The only drawback I see is that the courses (at least the ones I have) are mostly aimed at beginners, and are a bit outdated in terms of dealing with some more recent techniques. But that's usually the sort of thing you will only learn after reaching a more advanced level anyway, so the courses serve as an excellent starting point from beginner to intermediate level. Although more recent techniques are being researched every day, the basics still apply so in my opinion all of these courses are still very relevant.

**Edit**

I just noticed the following disclaimer on the site:

> Advanced Graphics Programming with DirectX course content (coming 2012)

So I think that will probably address the concerns on my last paragraph.

# Answer
> 5 votes
I haven't taken their courses, nor am I a professional game developer, so take this as it is. I'll try to keep this concise.

Basically, these courses focus on specifics, like graphics, etc. Like my comment mentions, game dev is a whole bunch of stuff -- how to design a game, polish it, play-test it, etc. etc. and you won't learn that from any course.

I'm a believer in trial by fire, i.e. learn by making it; that's the best way to learn all this "other" stuff.

But then again, if you have a specific learning need (like GPU graphics in C++), and you find a course on that, great.

# Answer
> 5 votes
I wouldn't place much emphasis on these courses, I've done them all. It's WAY more beneficial buying the highest rated text books off Amazon or ask for more recommendations and starting to code a game yourself in whatever manner you wish.

Simply put, the courses aren't bad themselves, but they aren't worth the money either.

# Answer
> 0 votes
I have registered before two day's in 30/12/2013.

The course is incredible, full materials, they have more then 70 project in every level. Who can give you offer like this. I tried many courses. If you want to purchase a book you need a lot of helping, the book is good but the book can't give you the whole picture about the game design and development, however they also have exams and quizzes. Exams help you test your knowledge and they offer forums to ask question and you can email the instructors to contact them.

If you are looking around you can find other websites give the same course in different price you can learn c++ for 100$ and you need another course for 3D and other course for unity

So what you waiting for, go and get an account right now :)

---
Tags: c++, directx, books, education, platformer
---


# Question
Title: Is setting the render target back to backbuffer supposed to take long?
I am creating a game in Monogame (XNA extension). I draw to a render target to display menu items for my game. Everything works fine, however... Whenever I set the render target back to the back buffer of my graphics device

```
graphicsDevice.SetRenderTarget(null);

```

it takes a long time (more than a second). This would be fine if I just needed my menu items at the beginning of the game. However if the game resets due to player input I have to re-initialize some of the menu items using the render target this lengthy process gets annoying.

Before I try to debug this, has anyone else experienced time delay with setting the render target back to the graphics back buffer? It works just fine when I set the render target to a created render target.

```
graphicsDevice.SetRenderTarget( new RenderTarget2D( device, width, height) );

```

That works just fine.

Edit:

I tried debugging this (C# is not my greatest language), and reached the line GL.BindFramebuffer( GLFramebuffer, this.glFramebuffer); inside ApplyRenderTargets inside GraphicDevice.cs of the Monogame Framework (Not my code).

The delay is occuring when you are trying to bind a framebuffer to a specified frame buffer target inside the OpenTK library. Debugging further requires I get OpenTK. I have to go out right now, but when I get back I'm going to test this on an XNA project (I have tested this in another monogame project with the same results) and attempt to debug further.

Edit 2:

The problem Setting the Render target back to the device back buffer after drawing to a large render target ( 8000 X 8000 ) causes the delay. I don't know the reason why I thought the buffers just swapped out.

Edit 3:

I am going to have to look into how setting render targets actually works. For now the time delay is fine, since I will have loading screens / asynchronous loading as the player progresses in the game to deal with these delays. In the end the the render target swapping the render target from a very large one causes a small delay, this seems to be expected behaviour.

Edit 4: Looking into a better solution than using a large render target.

Edit 5: Check answer

# Answer
Thanks to Adam and Sean for helping find the most likely cause of the slow load being large frame buffers and the regular buffer can't both sit in video memory, so when the buffers switch the large buffer probably has to be copied into main memory and the device back buffer copied from main memory back to video memory.
> 0 votes

---
Tags: xna, 2d, monogame, rendertargets
---