title: OpenGL ES 2 jittery camera movement

text:
# Question
Title: OpenGL ES 2 jittery camera movement
First of all, I am aware that there's no camera in OpenGL (ES 2), but from my understanding proper manipulation of the projection matrix can simulate the concept of a camera.

What I'm trying to do is make my camera follow my character. My game is 2D, btw. I think the principle is the following (take Super Mario Bros or Doodle Jump as reference - actually I'm trying to replicate the mechanics of the latter): when the caracter goes beyond the center of the screen (in the positive axis/direction), update the camera to be centred on the character. Else keep the camera still. I did accomplish that, however the camera movement is noticeably jittery and I ran out of ideas how to make it smoother.

First of all, my game loop (following this article):

```
private int TICKS_PER_SECOND = 30;
private int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
private int MAX_FRAMESKIP = 5;

@Override
public void run() {
    loops = 0;

    if(firstLoop) {
        nextGameTick = SystemClock.elapsedRealtime();
        firstLoop = false;
    }

    while(SystemClock.elapsedRealtime() > nextGameTick && loops < MAX_FRAMESKIP) {
        step();
        nextGameTick += SKIP_TICKS;
        loops++;
    }

    interpolation = ( SystemClock.elapsedRealtime() + SKIP_TICKS - nextGameTick ) / (float)SKIP_TICKS;

    draw();
}

```

And the following code deals with moving the camera. I was unsure whether to place it in `step()` or `draw()`, but it doesn't make a difference to my problem at the moment, as I tried both and neither seemed to fix it. `center` just represents the `y` coordinate of the centre of the screen at any time. Initially it is `0`. The camera object is my own custom "camera" which basically is a class that just manipulates the view and projection matrices.

```
if(character.getVerticalSpeed() >= 0) { //only update camera if going up
        float[] projectionMatrix = camera.getProjectionMatrix();

        if( character.getY() > center) {

            center += character.getVerticalSpeed();

            cameraBottom = center + camera.getBottom();
            cameraTop = center + camera.getTop();

            Matrix.orthoM(projectionMatrix, 0, camera.getLeft(), camera.getRight(), center + camera.getBottom(), center + camera.getTop(), camera.getNear(), camera.getFar());
        }
    }

```

Any thought about what I should try or what I am doing wrong?

**Update 1:** I think I updated every value you can see on screen to check whether the jittery movement is affected by that, but nothing changed, so something must be fundamentally flawed with my approach/calculations.

# Answer
> 1 votes
First I agree with the other answer about camera location code. On your display loop I would draw everything first, then update everything after that, then repeat.

Second, I have a game I'm working on right now that has a character (space ship) that can travel anywhere in a 2d world (3d game with a flat map). I use something like this to change the camera's position:

```
        // set camera targets to the ship's x,y - T is TargetX and TargetY
        cameraTX = myShip.currentPos.x;
        cameraTY = myShip.currentPos.y;

        // V is velocity
        GLfloat cameraVXT = (cameraTX - cameraX) * 4.0; // magic numbers that work for my game
        GLfloat cameraVYT = (cameraTY - cameraY) * 4.0;
        GLfloat cameraVZT = (cameraTZ - cameraZ) * 8.0;

        //but velocity can't change that fast due to inertia.  So move towards that velocity over time
        cameraVX +=  (cameraVXT - cameraVX) * 3.0 * deltaTimeThisRound;
        cameraVY +=  (cameraVYT - cameraVY) * 6.0 * deltaTimeThisRound;

        cameraX += cameraVX * 4.0 * deltaTimeThisRound;
        cameraY += cameraVY * 4.0 * deltaTimeThisRound;
        cameraZ += (cameraTZ - cameraZ) * 6.0 * deltaTimeThisRound;

```

The target x and y of the camera is set according to the ships last known position. The z doesn't usually change but is set in another function. Then I take the distance between the current location of the camera and the target location of the camera and create a target velocity. Then move the velocity towards the target velocity over time. Then apply that velocity to the camera over time.

All the different numbers like `* 4.0` and `* 8.0` were found over trial and error to dampen or speed up the camera's following of the ship. Too big and looks jerky and follows too tight. Too small and it lags too much and makes you motion sick. So you have to mess with these to get it to feel right for your game. Maybe you don't even need one of the steps and you just add a simple rubber banding to the characters position without using a target velocity.

After all of this I call a bindCamera method that sets my view matrix.

# Answer
> 0 votes
About the place of the camera location code: If you are not using the camera in the `step()` function (which your probably don't), it might get updated multiple times per frame, but only get used once in the `draw()` function. So to prevent a waste of calculations, I'd place it in the latter.

Related to the jittery camera: there is no good reason for using a projection matrix for camera movement. The projection matrix is generally only generated once in the initialization, and a view matrix is used to determine the rotations and translations of the camera. You can use the `Matrix.translateM()` function to create a view matrix that does nothing more than translate the camera. Then, before you render, use the combined `view * projection` matrix. (You can combine them using the `Matrix.multiplyMM()` function)

For more information about the topic of view/projection matrices, have a look at the following resources:

**Update 1:** In your code, you are using two different variables (`character.getY()` for the check, `character.getVerticalSpeed()` for the update).

Although the code

```
center += character.getVerticalSpeed();

```

and

```
center = character.getY();

```

should virtually do the same, could you give that second one a try? (The actual values might differ due to things such as floating point roundoffs).

---
Tags: java, android, opengl-es2
---


# Question
Title: Offset a camera/render without changing perspective
I need to offset a render so that the perspective / vanishing point doesn't change. Or another way to look at it is that I need to adjust the vanishing point in my view so that instead of being at 0,0 xy it's where ever I want it to be.

Imagine a tall iPhone screen with some extruded 3d text at the top of the view. You would see the bottom sides of the extrusion because the camera is below the object. But now move the object to the bottom of the view. Now you see the top sides of the extrusion because the camera is above the object. Same if you move the camera instead of the object. The vanishing point is at 0,0 in the window.

Now let's say I wanted to draw the 3d text as it would look at the top of the screen but I want to draw it at the bottom of the screen. Forget about the cheat of rendering it to a texture and drawing that texture somewhere else. How do I shift everything up or down without changing the perspective? Is there an easy way?

In practice I only need to move the vanishing point up a little in my game. Perspective is key to being able to play. Basically when the ad banner is at the top of the screen the view is smaller height wise. That moves the vanishing point down by half the size of the ad banner, and screws up the game play.

I'm using the standard camera look at matrix function and projection matrix function that is based on the fov...

```
lookAtMatrix(cameraPos, camLookAt, camUpVector, mView);
matrixPerspective(cameraFOV, near, far,  aspect, mProjection);

```

I'm assuming that I need to change my mProjection somehow.

# Answer
> 4 votes
Wow that was fast. It's crazy how sometimes just writing out the question helps you figure out how to approach a solution.

Here is my matrixPerspective function:

```
void matrixPerspective(float angle, float near, float far, float aspect, mat4 m)
{
    //float size = near * tanf(angle / 360.0 * M_PI);
    float size = near * tanf(degreesToRadians(angle) / 2.0);
    float left = -size, right = size, bottom = -size / aspect, top = size / aspect;

    // Unused values in perspective formula.
    m[1] = m[2] = m[3] = m[4] = 0;
    m[6] = m[7] = m[12] = m[13] = m[15] = 0;

    // Perspective formula.
    m[0] = 2 * near / (right - left);
    m[5] = 2 * near / (top - bottom);
    m[8] = (right + left) / (right - left);     // 0 - THIS
    m[9] = (top + bottom) / (top - bottom);     // 0 - AND THIS
    m[10] = -(far + near) / (far - near);
    m[11] = -1;
    m[14] = -(2 * far * near) / (far - near);

```

}

`m[8]` and `m[9]` will offset the vanishing point in view space. So -1 to 1 in either of these to adjust it to a point inside the view. For example a -1 in `m[9]` will make the vanishing point be the very top of the view.

And I can make a companion function that inputs the vanishing point offset.

For my particular problem of needing to offset by the amount of the banner ad. I know the pixel size of the banner ad and the pixel height of the screen. And 2/height is one "pixel". So I just moved the vanishing point by half the pixel height of the ad. Boom goes the dynamite.

Edit: Here's the function I made for it:

```
void offsetProjectionCenter(float xOffset, float xTotalSize, float yOffset, float yTotalSize, mat4 m)
{
    // each axis has the scale of -1 to 1 with default at zero.
    // offsetting an axis by 1/TotalPixelSize would be 1/2 pixel.  So 2/Size is a full pixel.
    // or totalSize/2 is just from center to the edge.  So 1/halfPixelSize is a full pixel
    // the offset/(totalSize/2) or 2*offset/totalSize - is the answer
     m[8] = 2.0 * xOffset / xTotalSize;
     m[9] = -2.0 * yOffset / yTotalSize;         // the y axis is reversed with -1 at the top
}

```

---
Tags: ios, matrix, opengl-es2, projection-matrix
---


# Question
Title: how to store game state for a multiplayer board game eg. poker
**First Approach**: Store the state in database and play with database queries. Could a database handle the load, as poker is quite fast paced, and I have to query/update database for each player move.

**Second Approach**: Store the state in memory. What kind of architecture/implementation is needed to achieve this?

What are the pros/cons of each approach, what other options do I have?

What is the best fit for poker, and/or chess?

# Answer
> 5 votes
From a performance standpoint, having data in memory is orders of magnitudes faster than having it in a database. There are two reasons to put data into a database instead of storing it in memory:

1. You have more data than fits into memory
2. You want to make sure no data is lost in case of a (intentional or unintentional) server shutdown

As you already said, poker can be quite fast. To keep response times low, handling each game in memory would be beneficial. However, you might want to estimate how many games you intend to handle simultaneously and how much data you will have per game. When you realize that this will occupy more RAM than your server(s) will have, persisting the whole game state to the database after each move and retrieving it again when the next player makes their move might be necessary. I didn't do the math (I can't, because I don't know your requirements) but eyeballing it I would find it unlikely that this would be required.

However, I would recommend to persist the current state to the database as soon as a round is over, so the chip balance of each player is persisted and no progress is lost in case of a sudden server crash. Having to rollback the current round which wasn't even decided yet would likely be acceptable for most players, but rolling back a high-stakes game several rounds in could make those who already won a lot quite angry.

---
Tags: architecture, javascript, multiplayer, databases, state
---


# Question
Title: Selection with region (when rendering with shaders and VAO)
I am currently render my geometry using "Modern OpenGL" approach (with shaders and buffers). I have already implemented picking of single primitives using `glReadPixels`. Now I am faced with problem how to implement selection of multiple objects. I cannot use `glReadPixels` because maximum (and it seems meaningful for me) number of objects that I could select with `10x10` box is `100`. But it is really necessary for my purposes to have ability to select thousands of objects in small selection area.

I already read answer to similar question where was recommended to test each point against selection rectangle. But it gives new problems: all my vertices are already stored in buffers and it looks like huge performance to test each point on CPU.

Could someone help with such issue?

# Answer
> 1 votes
One option is to take the screen coordinates for the rectangles corner points, convert them to rays in world space and then use these to define a box to do 3D collision detection with. The maximum length of the box should be the distance between the camera's near and far clipping plane.

---
Tags: opengl, selection
---


# Question
Title: Crafty - How to get the id of the collision element?
As the topic says, I want to know how to get the ID of an active colliding entity.

My Player Entity is called with

```
Crafty.e("Player")

```

Please notice, that I **do not want** the ID of my **Player Entity**. I want the ID of the **Collision element**

# Answer
Do you want the id of the entity your player collided with?

```
var mobs = this.hit('Mob');
if (mobs) {
    // mobs is an array, could be more than one
    var collidingMob = mobs[0].obj;

    // if you still want the crafty id of this entity
    var mobId = collidingMob[0];
}

```
> 1 votes

---
Tags: collision-detection, crafty, entities
---


title: animating a spritesheet using crafty.js

text:
# Question
Title: animating a spritesheet using crafty.js
this is my jsfiddle : http://jsfiddle.net/seekpunk/ek6ub4u5/1/

i don't understand what i am missing it's been three days now working and trying to do the animation but i am stuck

```
 Crafty.sprite(128, "https://0.s3.envato.com/files/42440549/1_Ninja.jpg", {
               idle: [1, 0]
           });

```

i've loaded the spriteseet image and declare `idle`

```
 Crafty.c("animation", {
               init: function () {
                   this.requires("SpriteAnimation");
                   this.animate("run", 1, 1, 4);
                   this.bind("enterframe", function () {
                       if (!this.isPlaying("run")) {
                           this.animate("run", 20);
                       }
                   });
               }
           });

```

then i have declared the animation component and the `bindframe` function

```
var player = Crafty.e("2D,Canvas,idle, animation")
                        .attr({ x: 0, y: ch - 128, w: 128, h: 128 });

```

then i've declared the player ,but sadly the animation is not working .. can anyone tell me what i am missing please

# Answer
There are a few problems here. First, SpriteAnimation has changed. You now need to define an animation reel.

```
//this.animate("run", 1, 1, 4);
this.reel("run", 1000, 1, 1, 4);

```

Second, names in javascript and Crafty are case sensitive.

```
//this.bind("enterframe", function () {
this.bind("EnterFrame", function () {

```

Third, I fixed a few small problems with your jsfiddle so it will run. http://jsfiddle.net/hso6cmvp/
> 1 votes

---
Tags: javascript, html5, crafty
---


# Question
Title: Are Tilesets more efficient than single pictures?
i want to program a 2D game and as i did lots of tutorials and read books about creating simple 2D games, nearly always tilesets were used for the graphics. But are tilesets really more efficient compared to loading not from one but from several pictures?

Thanks

# Answer
> 5 votes
Yes, they are more efficient. Depending on your specific hardware and driver, massively so.

The basic idea is that you want to minimize *state changes*. Changing the active texture is a state change. In many cases the GPU can only handle rendering with a single state at at time. If you think of all the dozens/hundreds/thousands of shader cores that a GPU can have, if you're rendering only one single sprite at a time you're massively under-utilizing the hardware. By using a texture atlas / sprite sheet (and batching every other piece of state you can) you will allow the GPU to work on drawing many sprites simultaneously.

For the modern gaming world, the actual draw speed is probably less important than the power consumption of your game. If you're being inefficient then the CPU/GPU have to remain in their active power-sucking states for longer, greatly reducing battery life. If you're efficient and "race to sleep" (do all of your work as fast as you possibly can so that the device can go back into its low-power state until its time to draw the next frame) then mobile users (phones, tablets, laptop PCs, etc.) will be much happier. The only two real states you have are "everything is idle and low-power" or "something is running and we're high-power." Modern devices have some intermediate states and additional complexities but you can and should ignore those details: either do everything the absolute most efficient way you can manage or make sure your game is completely idle (no polling a timer or anything; make a call to explicitly wait for the next vsync event and let the OS put your game to sleep until it happens).

There's nothing quite so "amusing" as firing up a fancy 3D game on your phone and being able to play for several hours and then trying some silly little 2D game that drains your battery in 40 minutes.

And again, even as a PC game developer, laptops and convertibles are hugely popular and battery powered so being a PC developer doesn't excuse you from being considerate about users' battery lifetime.

That said, while I deeply disagree with @wondra that the efficiency isn't important, it is good advice *if these are your first game development experiments* to not worry about it just yet. But keep texture atlases high on your list of things to learn how to make and use after you get all the basics down.

# Answer
> 2 votes
This is one of "truths of old days" and no longer important (that much important). While using one texture is definitely more efficient(switching texture, as every operation, introduces some overhead), on today's hardware is not *that* big difference and the extra performance is generally *not needed*.
If you have hardware capable of rendering millions textured triangles and you need few tens of sprites, do you *really* need any extra performance? On the other hand premature optimization, that is what really hurts every beginner game programmer efficiency - why spend a week building something that will increase your fps from 1000 to 1020?
**tl;dr:** Using texture atlases is a good practice and it is a bit more efficient, but there often more important things to spend your time with. If you do not like them, go ahead and ignore them in your first games.

# Answer
> 2 votes
Yes, using texture atlases is more efficient than using individual images.

It largely boils down to two things:

1. The images have to be transferred onto the GPU in order to be drawn to the screen. Sending one large image is going to generally be faster than sending a ton of small images.
2. State changes on the GPU are expensive, and switching textures is a state change. So for a lot of little images, that's a lot of state changes. Whereas using a texture atlas will allow the GPU to not have to change states quite so much.

---
Tags: 2d, game-design, tilesets
---


title: glm direction vector rotation

text:
# Question
Title: glm direction vector rotation
I'm working on a flight simulator, but I'm stuck with my airplane orientation. I tried some things but noone worked correctly. This is what I have :

To be able to move it and roll it around himself, I need two vectors, forward and up, and use them to create quaternions I need for the rotation :

```
void Plane::Update()
{
    m_position += ( m_forward * m_speed );

    mat4 translation = translate( mat4( 1.0f ), m_position );

    float angle = dot( vec3( 1.0f, 0.0f, 0.0f ), m_forward );
    quat direction = angleAxis( acos( angle ), cross( vec3( 1.0f, 0.0f, 0.0f ), m_forward ) );

    m_matrix = translation * mat4_cast( direction );
}

```

vec3( 1.0f, 0.0f, 0.0f ) is my model orientation. Note that in this code, I don't have quaternion for rolling the plane, because I first want to have a correct direction.

This works great, what doesn't work is when I want to make him taking off. To do that, I first get the right vector, then use it to create my quaternion with the angle I need, and I apply the rotation to the forward and up vector.

```
void Plane::FlyUp()
{
    vec3 right = cross( m_forward, m_up );

    quat temp = angleAxis( radians( 1.0f ), right );

    m_up = temp * m_up;
    m_up = normalize( m_up );

    m_forward = temp * m_forward;
    m_forward = normalize( m_forward );
}

```

Using debugger and an online vector visualizer, It seems to give me the good vectors, but the plane is rotating weirdly ( in fact, that's not even only rotating, he's scaled too for some reasons... ).

What am I doing/understanding wrong?

Edit :

To be more precise, here is screenshoots of what I have :

And what I'm trying to have, whatever the m\_forward vector is pointing to :

# Answer
> 1 votes
The bug quite likely comes from `angleAxis` requiring a normalized vector (see `quaternion.inl` in the source code). You need to call `normalize()` on the cross product result.

(you might be interested in my article about creating a quaternion from two vectors without using trigonometry functions)

---
Tags: opengl, c++, quaternion, glm
---


# Question
Title: How to avoid subpixel values in a resolution independent 2D game with orthographic projection?
I'm trying to do resolution independent rendering of moving sprites in a 2D game. My plan is work in a fixed coordinate system in my world (for example 960x540) and use orthographic projection to scale that up or down to fit the viewport. I do letterboxing to handle different aspect ratios.

According to most tutorials, I am free to use whatever dimensions I like for the view frustum, but I found that in many cases that leads to the problem that I end up using subpixel values on the viewport. For example a vertex at (62,62) in a coordinate system of 960 x 540 ends up at (51.6666667,51.6666667) on a viewport with the dimensions 800 x 450.

I noticed two kinds of problems with that:

* the texture sampling changes all the time for objects that are in motion depending on where the vertices are in relation to a pixels center
* my objects get stretched horizontally or vertically by a pixel from time to time due to rounding

What is the best practice to avoid this (while maintaining resolution independence in terms of movement speeds and so on)? And where would be the best place to do address this? Before passing the vertices to the shaders or inside the vertex shader?

# Answer
> 1 votes
To get to your main question, whether or not to influence the vertices before or during the shader, using a shader is preferred. If you know how to write a routine that can take into account the viewport and coordinate system, using a shader is preferred as it allows many sprites to be adjusted in parallel. Also, it ensures the "cosmetic" coordinates stay separate from in-game coordinates in the CPU code so one doesn't influence the other.

You can do this either in the vertex OR pixel shader. In the pixel shader it is possible to shift texels to lock them to the pixels on the display.

In DirectX9 I needed to do this with HLSL in order get around the quirk that texel corners were located at 0.5, 0.5 relative to the pixel, making crisp textures look semi-blurry. Correcting this changes the physical location of the texels without moving the vertices.

In your case, the offset will vary from frame to frame, so pass the true coordinates of the sprite to the shader to calculate the decimal offset. Remember to CLAMP the texture sampling to avoid wrapping in the textures.

# Answer
> 3 votes
I think I would store two sets of coordinates.

1. One used for drawing your objects `DISPLAY POSITION` and
2. a second used for keeping a `TRUE POSITION`.

This way you can draw sprites with rounded coordinates to eliminate the distortion caused by fixed size of your view area.

But this also allows you to keep the exact location without influencing any of your game logic. because of the nature of sub-pixels I also think you will not even notice any discrepancies between the view and the game logic.

---
Tags: opengl, 2d, opengl-es2
---


title: Entity Component System for HUD and GUI

text:
# Question
Title: Entity Component System for HUD and GUI
This is a very rough sketch of how I currently have things designed. It should, at least, give an idea of how my ECS is currently designed.

If you notice in that diagram, I have basically split the HUD out of the ECS. They have their own set of things (HudLayer, HudComponent, etc) and are handled differently. This is where I'm struggling, though.

There are many different instances in which the HUD will need to know about entities. Not just data changing (I have an event dispatcher for that), but the actual entity and all it encompasses. There are also situations where entities will need to be able to query the HUD for data. Let's take a couple examples:

* First, my equipment screen. On here I can change the equipment on a character (Entity). In order for this to happen, I need to know about the entity. At least I think I do? How can I handle this?
* The second scenario involves my Systems needing to query a HudComponent for data. A specific example would be my battle system. Each "team" is given a 3x3 grid they can move around in. See here:

Skills target these cells, and not the player, so I would need a way for my systems to determine which cells are occupied and which are not. Basically I need a way for two way communication between Systems and my HUD. I know it's recommended (by some people, anyways) to take your HUD out of the ECS. Is that appropriate in my case?

# Answer
It seems to me that you're mixing the visual representation with the logical representation of what you're trying to create. Lets discuss your two scenarios.

**Equipment Screen**

In this situation, I would simply have the Equipment UI be capable of querying the inventory system for the current player. This allows the inventory system and it's management to remain inside your ECS framework and you are simply allowing the UI system a means to ask the inventory system what it's contents are and visually represent the data for the user. When users move items around in their bags, the bags simply call methods on the inventory system that manipulate the components accordingly. This way, the Equipment UI screen really knows nothing about the ECS. It simply has a reference to a class that implements an Inventory System interface and through that instance, it can obtain the information it needs to draw itself.

**Battle Screen**

I believe this scenario again follows a similar premise. You can easily abstract the component, entity, and logic aspects of the battle system into a `BattleSystem` that is part of your ECS. This system again implements a specific interface that defines the contract between the UI and the system. Now, when a user performs a UI action, the UI simply calls the appropriate method in the `BattleSystem` and whatever interactions must occur between it, entities, and components happen.

One thing I would strive to do in either of these cases, is any information that feels as though it's leaking from the subsystem abstraction to the UI should be pushed into the system. The UI should be designed in such a way that perhaps these values could be tweaked in the system and the UI adapts accordingly. For example, the `BattleSystem` maybe has a method that tells you the grid size is 3x3 but in a later release you decide it should be 4x4 or 5x5. By allowing this to be data-driven, the UI no longer cares necessarily about it and just adapts, really allowing the UI to be as decoupled as possible from the system's logic and implementation.

The key take away is don't be hesitant to design a system or systems at one layer and then wrap those system(s) up into a larger system at a higher level until you reach the level of abstraction and generalization you need to keep things decoupled at their respective levels, but cohesive enough across layer boundaries without impairing design.
> 2 votes

# Answer
Your `HudLayer` could contain a System `HUDSystem` where your entities eventually register their components. The `HUDSystem` can then track changes from the registered entities.
> 0 votes

# Answer
You are on the right track about keeping the HUD out of the ECS. HUDs and game screens in general benefit greatly from inheritance, as the flow of gameplay is essentially one tree where you can branch out in different paths or backtrack in a manner that makes sense to the player. I use a variation of state pattern, where

However, the HudLayer and GameScene can be condensed (in the programmatic sense) into the same type of object. I consider HUDs to be GameScenes too, in that they can contain entities and a update-\>display loop that may await user input. Entities in HUDs are the background, icons and text, in a similar way that characters and backgrounds on the battle screen are entities composed of graphics and locations. While this means HUDs contain elements that are part of the ECS, the HUD screens themselves are not in the ECS.

Going back to inheritance, if the battle screen is considered the primary GameScene that is active, all the on-screen HUDs and menus can be children screens of the battle screen. When you open the inventory screen from the battle screen, the battle screen stops taking input and creates the inventory screen. The battle screen keeps track of the active character and what cell it is on, and any character-specific menus are loaded with this information. After making a selection and closing the menu, a value based on the selection is returned back to its parent, the battle screen, and the ECS would take care of making the character entity respond appropriately.
> 0 votes

---
Tags: architecture, entity-system, component-based, hud
---


title: Wandering motion in Unity

text:
# Question
Title: Wandering motion in Unity
I am trying to come up with a smooth wandering motion for my game-object using Unity. What I currently doing is rotate the object by some random angle calculated every 1.5 second delay. But I am aiming getting a smooth rotation whenever it transitions to a different randomly generated angle.

Below is my script attached to my character.

```
 void Update () {
     if (canWander && (currTime + delay < Time.time)){
        changeAngle();
        currTime = Time.time;
     }
     if(canWander){
        Wander();
     }
}

private void changeAngle(){
    float prevPosY = transform.position.y;
    Vector3 waypoint = Random.insideUnitSphere + new Vector3(10,prevPosY,10);  //waypoints are generated based on random unit sphere + ( bounds of the plane they are on )
    Vector3 relative = transform.InverseTransformPoint (waypoint);
    float angle = Mathf.Atan2 (relative.x, relative.z) * Mathf.Rad2Deg;
    transform.Rotate (0, angle, 0);
}

private void Wander(){
    transform.position += transform.forward * Time.deltaTime * acceleration;
    if (acceleration < maxSpeed) {
        acceleration += 0.5f;
    }
}

```

So the character wanders with newly generated random angles every time but its not a smooth transition. It suddenly transitions to the new angle and it does not feel realistic at all. What could I possibly change with my current code to make it more smooth and realistic?

# Answer
When you set the new angle that you want to rotate to, use that as a *target* rotation, and then in `Update()` you can continually interpolate the character's current rotation to the target rotation using `Mathf.LerpAngle`. The rotation speed variable will be an arbitrary float that controls how quickly the character moves to the target angle.

```
void Update() {
    // ...
    transform.eulerAngles = new Vector3(0, Mathf.LerpAngle(transform.eulerAngles.y, targetAngle, Time.deltaTime * rotationSpeed), 0);
}

```
> 3 votes

---
Tags: unity, physics
---


title: Find shortest path to gather items

text:
# Question
Title: Find shortest path to gather items
I have a rectangular grid with obstacles and food items on certain tiles. There are also a few storage bins. Each food item gives 10 food. How can I find the shortest path that will allow me to collect 30 food and bring it back to any storage bin ?

I don't think I can use Dijksra class of algorithms because it does not account for a state (food carried) during the pathfinding.

# Answer
There is an approximation for the traveling salesman that will fit your needs very good. It is Cristofides algorithm. Here is how it works:

From your current position calculate a minimum spanning tree to the food items. Stop the calculation when the tree will contain 30 food. Calculate a hamiltonian path from the tree by appending non-visited elements when walking the tree in preorder.

The results created by this approximation are at most 2 times the optimum path. Further details can be found here for example

The runtime complexity is lower than with using floyd warshall, since constructing the minimum spanning tree is of lower complexity. This is especially true for your case as your a using a grid where the triangle inequality applies and no obstacles are on the gird. When there are obstacles, it path-finding needs to be applied. But again, floyd warshal is not necessary. For the minimum spanning tree construction, you only need the nearest neighbor for the tree, which is still of much lower cost.

Just one restriction is that using this method is bound to symmetric path distances between positions, because each branch of the tree may be walked in both directions and therefore they should have the same distance.
> 5 votes

# Answer
The solution is easy implemented but very very computionally heavy - I would not be suprised if this was NP-complete problem, similar to the travelling salesman.
The solution has two steps:

1. compute distance between all points (food locations and your location), you can do that with Floyd-Warshall algorithm in n^3 complexity
2. from then, you need to find the shortest combination such as its first edge connect you to food location and the last one connects to basket, there is roughly V(k,n) such variations(!).

Because of that, I suggest you use greedy/look ahead algorithm, finding not optimal solution but some "good" solution instead.
For greedy you just always pick closest location, for look-ahead you look at the length of next one too (and if you looked more and more ahead, it would turn into near-bruteforce described above, so better to limit it).
> 5 votes

# Answer
"Each food item gives 10 food. How can I find the shortest path that will allow me to collect 30 food",
so you need to collect 3 food items.
This is small enough that you shouldn't need to give up optimality.

1. Compute shortest paths and distances from the starting location to each food location,
between each pair of food locations, and from each food location to each bin location.
The Floyd-Warshall algorithm can do that, but using Dijkstra's algorithm once with the starting
location as the initial node and once with each food tile as the initial node will probably
be faster, since your graph is sparse and all other pairwise information is not important.
2. Use the algorithm described by the following pseudo-code.

.

```
maxdist = 0
for tile0 in tiles:
    for tile1 in tiles:
        maxdist = max(maddest,distance(tile0,tile1))
dtobin = maxdist+1
for bin in bintiles:
    if distance(startingtile,bin) < dtobin:
        dtobin = distance(startingtile,bin)
        closestbin = bin
if dtobin == maxdist+1:
    print("There are no reachable bins!")
    return []
path = shortestpath(startingtile,closestbin)
L = distance(startingtile,closestbin)
midpoint = path[round(L/2)]
dtofood = maxdist+1
for food in foodtiles:
    if distance(midpoint,food) < dtofood:
        dtofood = distance(waypoint,food)
        food2 = food
if dtofood == maxdist+1:
    print("There is no reachable food!")
    return []
partofpath = shortestpath(startingtile,food2)
L = distance(startingtile,food2)
waypoint = path[round(L/2)]
dtofood = maxdist+1
for food in foodtiles:
    if distance(waypoint,food) < dtofood and food != food2:
        dtofood = distance(waypoint,food)
        food1 = food
if dtofood == maxdist+1:
    print("There is only one reachable food item!")
    return []
partofpath = shortestpath(food2,closestbin)
L = distnace(food2,closestbin)
waypoint = path[round(L/2)]
dtofood = maxdist+1
for food in foodtiles:
    if distance(waypoint,food) < dtofood and food != food2 and food != food1:
        dtofood = distance(waypoint,food)
        food3 = food
if dtofood == maxdist+1:
    print("There are only two reachable food items!")
    return []
bestsofar = distance(startingtile,food1)+distance(food1,food2)+distance(food2,food3)+distance(food3,closestbin)
waypointlists = []
for bin in bintiles:
    if bestsofar < distance(startingtile,bin):
        continue
    for food2 in foodtiles:
        if bestsofar < distance(startingtile,food2)+distance(food2,bin):
            continue
        for food1 in foodtiles:
            partial = distance(startingtile,food1)+distance(food1,food2)
            if bestsofar < partial+distance(food2,bin) or food2 == food1:
                continue
            for food3 in foodtiles:
                if bestsofar < partial+distance(food2,food3)+distance(food3,bin) or food3 == food2 or food3 == food1:
                    continue
                currentpathlength = partial+distance(food2,food3)+distance(food3,bin)
                if currentpathlength < bestsofar:
                    bestsofar = currentpathlength
                    waypointlists = [[food1,food2,food3,bin]]
                else:
                    waypointlists.append([food1,food2,food3,bin])
return waypointlists

```

(The `continue` syntax is described here.)

3. If `waypointlists` has more than one list, then choose
one of them according to whatever preference you have.
4. String together shortest paths \[between `startingtile` and the initial waypoint\]
and between consecutive waypoints. (Those shortest paths were found in step 1.)

If memory use is not a problem, then that algorithm can almost certainly be sped-up by
making lists of what tiles could possibly help and only trying those. If memory use is not a
problem, then that algorithm can probably be sped-up by trying things in a better order,
so that it will `continue` more often in the four final for loops, especially the outer loops.
Also, depending on cache behavior (something I have no clue about) and how often it `continue`s
two lines afterward, computing `partial` might actually be slower than not doing so.
> 1 votes

---
Tags: ai, path-finding
---


title: Game Lagging due to too much details

text:
# Question
Title: Game Lagging due to too much details
I'm making a car racing game where you drive around hills.

The game has some performance issues. At some point it starts lagging badly. After one day spent on this, I realized that when the car drives through detailed areas with lots of objects, the game starts to lag. It works fine with a simple scenery (eg. just a plane).

# Answer
If you know the problem is a too detailed environment then you should be able to fix it by toning down the details.

You don't need to model every leaf of every tree, instead use a few intersecting textured transparent planes to create the illusion of volume.

You don't need to model the window sills of the buildings you are whizzing past, just use a simple box and and bump-mapping to create the illusion of depth.

You can set the shadows statically with textures so you can disable receiving shadows on those objects. Only the road surface and your car will need to be able to have a shadow cast on it.
> 1 votes

---
Tags: unity
---


# Question
Title: OpenGL - Drawing multiple meshes at once using VBOs and IBOs
I have been learning OpenGL 2.1 but using shaders, VBOs, IBOs, etc. I have gotten a rendering engine that can load and draw meshes, materials, forward lighting (no shadows yet), SceneNodes, and NodeComponents. There are no optimizations yet (for obvious reasons) such as occlusion culling, only Face culling at the moment.

A mesh (simplified) class looks like this:

```
struct Mesh
{
    GLuint vbo;
    GLuint ibo;
    GLuint size;

    void draw(Program* shaderProgram) const
    {
        glEnableVertexAttribArray(shaderProgram->attrib("vertPos"));
        glEnableVertexAttribArray(shaderProgram->attrib("vertTexCoord"));
        ...

        glBindBuffer(GL_ARRAY_BUFFER, vbo);

        glVertexAttribPointer(shaderProgram->attrib("vertPos"), 3, GL_FLOAT, false,
                              sizeof(Vertex), (const GLvoid*)(0 * sizeof(float)));
        ...

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
        glDrawElements(GL_TRIANGLES, size, GL_UNSIGNED_INT, 0);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

        glDisableVertexAttribArray(shaderProgram->attrib("vertPos"));
        ...
    }
}

```

When I have been drawing multiple objects with the same mesh (or multiple meshes), I notice a frame drop compared to a single mesh with the same number of triangles.

```
Stanford Models were used.
(1 Face = Triangle)
| Model  | Num Models  | Total Faces | With Lighting | Without Lighting |
| -      | -           | -           | ms / frame    | ms / frame       |
|--------|-------------|-------------|---------------|------------------|
|        | 0 (control) |        0    |  0.47         |  0.41            |
| bunny  | 1           |    69630    |  1.2          |  0.64            |
| bunny  | 14          |   974820    | 12.4          |  3.50            |
| buddha | 1           |  1087474    |  7.87         |  2.89            |
| buddha | 10          | 10874740    | 71.4          | 23.8             |

```

I does look like that time/frame is ~O(n). However, drawing one vbo with 12% more faces, the frame time is decreased by 37%.

**So my questions are:**

* Is drawing multiple VBOs actually worse than drawing one big one?
* How would I combine these VBOs and IBOs into one big one if this is true?

# Answer
Yes, doing several draw calls is slower than one. This is why state changes are expensive. There are techniques (like instancing) that fight this, but they're still more expensive than simply doing a single draw call.

To combine several VBOs into one, they must have the same state (i.e, same shader, same textures, etc), and they must be static (i.e, not moving independently). Then simply transform the vertex data into the same space (for instance world space, or possibly the object space of a reference object) and handle the result as a single object.

The first question you have to ask, however, is whether all of this is worth it. First make it work, then make it fast.
> 5 votes

---
Tags: opengl, c++, performance, vbo
---


# Question
Title: Objects don't instantiate at mouse position
I'm trying to get the player to shoot a projectile at the mouse position, however the projectile is shot in weird directions (http://gfycat.com/BothFluidHoneyeater).

Here is relevant part of my code:

```
var shotSpeed = 1000;
var projectile : Rigidbody;

function Update () {
    var clone : Rigidbody;
    if(Input.GetKeyDown(KeyCode.Mouse0)){
        clone = Instantiate(projectile, transform.position, transform.rotation);
    }
    clone.rigidbody.AddForce(Vector3.forward * shotSpeed);
}

```

What am I doing wrong?

# Answer
First off, you should only be applying forces to rigid bodies inside the `FixedUpdate` method. You'll get more consistent results.

If you want objects to move in the direction another object is facing, you need to use `transform.forward`, not `Vector3.forward`. Alternatively you can multiply `Vector3.forward` by the quaternion of the rotation you want to use, like `transform.rotation * Vector3.forward`, this will output a Vector3 that's been rotated to face the same direction as the rotation you supplied.

The last thing to check is that your projectiles aren't colliding with the parent body that's spawning them. Since you're spawning the projectiles inside the parent body, you need to ensure they're not colliding, as that would produce strange results.
> 1 votes

---
Tags: unity, javascript
---


title: 2D RGBA texture is gray in GLSL shader

text:
# Question
Title: 2D RGBA texture is gray in GLSL shader
I have a shader to perform LUT coloring of a texture and a c++/c# programs that call it which work perfectly when i use a 1D texture.
Since i need to support computers that don't support the 1D texture in the shader i thought the easiest would be to convert the 1D texture to a 2D texture with the height==1.
After the conversion (1D -\> 2D) when i run the program it seems that the LUT 2D texture is received gray in the shader. I render the exact same texture in another place (not using a shader) in the program and the texture looks fine (same as it did when i used a 1D texture).
The shader code:

```
uniform sampler2D FluorImage;
uniform sampler2D FluorColorLutRGBA;

void main(void)
{
  vec3 FluorPix = texture2D(FluorImage, gl_TexCoord[0].st).rgb;
  vec2 Coord = vec2(FluorPix.g, 0.0);
  vec4 NewColorFluor = texture2D(FluorColorLutRGBA, Coord).rgba;
  gl_FragColor.rgb  = NewColorFluor.rgb;
}

```

The texture creation code

```
glGenTextures(1, &m_FluorShadersParams[fpsFused].m_LutTexture);
glBindTexture(GL_TEXTURE_2D, m_FluorShadersParams[fpsFused].m_LutTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 256, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);

glActiveTexture(FluorTextureIndexes[fpsFused]);
glBindTexture(GL_TEXTURE_2D, m_FluorShadersParams[fpsFused].m_LutTexture);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);

```

Filling the texture with data

```
glActiveTexture(a_FluorTextureIndexes[fpsFused]);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, i, 256, 1, GL_RGBA, GL_UNSIGNED_BYTE, pLUT);
glActiveTexture(GL_TEXTURE0);

```

Calling the shader

```
glUseProgram(m_progObj[fsFluorFused]);

glActiveTexture(FluorTextureIndexes[fpsFused]);
glBindTexture(GL_TEXTURE_2D, FluorTextureIndexesNum[fpsFused]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, inputTextures[eftIR]); // Fluor image

glBindFramebuffer(GL_FRAMEBUFFER,outputFBO.m_FBO[eftFused]);

uniformLoc = glGetUniformLocation(m_progObj[fsFluorFused], "FluorImage");
if (uniformLoc != -1)
{
  glUniform1i(uniformLoc, 1);
}

uniformLoc = glGetUniformLocation(m_progObj[fsFluorFused], "FluorColorLutRGBA");
if (uniformLoc != -1)
{
  glUniform1i(uniformLoc, FluorTextureIndexesNum[fpsFused]);
}

glClear(GL_COLOR_BUFFER_BIT);

glBegin(GL_QUADS);
 glTexCoord2f(0,    fTextureRatioY);
 glVertex2f(0,      fTextureRatioY);
 glTexCoord2f(fTextureRatioX,   fTextureRatioY);
 glVertex2f(fTextureRatioX,     fTextureRatioY);
 glTexCoord2f(fTextureRatioX,   0);
 glVertex2f(fTextureRatioX,     0);
 glTexCoord2f(0,        0);
 glVertex2f(0,          0);
glEnd();

glUseProgram(0);
glActiveTexture(GL_TEXTURE0);

glBindFramebuffer(GL_FRAMEBUFFER,0);
glBindTexture(GL_TEXTURE_2D,0);

```

The strange thing is that if i change all the places in the code back from Texture2D into Texture1D and the sampler in the shader to 1D everything works great.
Anyone has any idea where the issue can be?

# Answer
Try using this instead:

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 256, 1, 0, GL_BGRA, GL_UNSIGNED_BYTE, pLUT);

```
> 1 votes

---
Tags: textures, fragment-shader
---


title: Shared Material

text:
# Question
Title: Shared Material
I have this simple script, so the user touch one of the cubes all cubes with same material will change color.

One of this cubes must have the name of the color on it, only one, so the user touch the cube written RED and all cubes related to material RED will change color to RED.

I can't figure out how to write the name of the color in this unique cube. :( need help....

```
using UnityEngine;
using System.Collections;

public class allCubes : MonoBehaviour {

    public Color defaultColor;
    public Color selectedColor;
    private Material mat;

    void Start(){
        mat = renderer.sharedMaterial;
        mat.color = defaultColor;
    }

    void OnTouchDown () {
        mat.color = selectedColor;
    }

    void OnTouchUp () {
        mat.color = defaultColor;
    }

    void OnTouchStay () {
        mat.color = selectedColor;
    }

    void OnTouchExit () {
        mat.color = defaultColor;
    }
}

```

# Answer
Your issue most likely is caused by your sentence in the start

> mat = renderer.sharedMaterial;

Once you assign a shared material to objects you will change the material/appearance settings for each of the shared material instances. For more info check out the unity docs

To prevent this you should try using renderer.material instead.
> 1 votes

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


# Question
Title: Alert Dialog Box font color in AndEngine
I am developing an app using AndEngine and I am using my own custom theme to use white background theme. My styles.xml file looks like this:

```
<resources>

<color name="white_opaque">#FFFFFF</color>
<color name="pitch_black">#000000</color>

<style name="AppTheme" parent="android:Theme.Light">
  <item name="android:background">@color/white_opaque</item>
  <item name="android:windowBackground">@color/white_opaque</item>
  <item name="android:colorBackground">@color/white_opaque</item>

</style>
</resources>

```

Everything is working fine except in the dialog box the font color is white and it looks like this:

How can I change the font color to black for the text?

# Answer
So far you only specified the background colors in your style. You also need to define the foreground / font colors for your style:

```
<item name="android:textColor">@color/pitch_black</item>

```

Reference: android:textColor
> 0 votes

---
Tags: android, andengine
---


# Question
Title: Is this way of making an XNA game window borderless safe to use for various Windows PCs?
I have found a way to simply make an XNA 4.0 game's window borderless. Here is the code from the article:

```
IntPtr hWnd = this.Window.Handle;
var control = System.Windows.Forms.Control.FromHandle( hWnd );
var form = control.FindForm();
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form.WindowState = System.Windows.Forms.FormWindowState.Maximized;

```

You add it to the Game's constructor and it works perfectly. I tested it on several Windows PCs and it's great: the game runs seemingly in full screen, even if you set the game's resolution lower/higher than your desktop one. The only issue I had with it is the fact that you need to provide positions for XNA's SpriteBatch methods (Draw and DrawString) in desktop resolution, not in game's resolution, while retrieving width/height from GraphicsDevice gives you the latter.

At the same time, DOTA 2 has borderless window option, but the game scales the window down, if your requested in-game resolution is lower than your desktop one. I wonder if they have a good reason for doing this?

I wanted to ask if this approach is safe to use on PC or can it be buggy occasionally? I would especially like to know if it will work with Windows XP as I don't have a pc with this system to test it.

# Answer
```
form.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
form.WindowState = System.Windows.Forms.FormWindowState.Maximized;

```

The MSDN documentation does a good job of listing the platforms supported for each function.

## form.FormBorderStyle MSDN Documentation

> Platforms
>
> Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

## form.WindowState MSDN Documentation

> Platforms
>
> Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
> 1 votes

# Answer
Since this is a basic function, it should be safe, but you should look into setting up a VM or finding a friend with an XP machine so that you can specifically test for it.
> 1 votes

# Answer
This functionality is pretty basic for Win32 API, you are pretty safe to use it on XP (and even below).

The OS support for `FormBorderStyle` enumeration (on .NET 3.5), for example:

> Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

same goes for `FormWindowState`. I hope that edit makes answer more useful.
> 0 votes

---
Tags: xna, window-management
---


title: DX11 Reusing Command Lists

text:
# Question
Title: DX11 Reusing Command Lists
My team is working on an engine implementation and we are trying to add multithreaded scene traversal for updating and rendering our components... The question has come up as to whether or not we can create command list for a subscene once and reuse it across multiple frames. Current code recreates the subscene command list for each frame but we would like to track renderables being added or removed from the subscene and only regenerate the command list as needed.

Google searches have revealed that it is OK to reuse the device context for a new cycle after FinishCommandList is called, but there is nothing definitive about reusing the the command list from frame to frame once it is created.

# Answer
> 2 votes
You can submit command lists multiple times across frames, but the current design makes it less than ideal for "display list" style rendering because you can't change modify or inherit state once the command list is created. You can modify resources (constant buffers, textures, shaders, etc.).

The DirectX 11 command list model is really intended for multi-threaded submission. See the MultithreadedRendering11 sample.

See this blog post for some presentation links.

---
Tags: directx11, multithreading
---


# Question
Title: Balancing Player vs. Monsters: Level-Up Curves
I've written a fair number of games that have RPG-like "levelling up," where the player gains experience for killing monsters/enemies, and eventually, reaches a new level, where their stats increase.

**How do you find a balance between player growth, monster strength, and difficulty?** The extreme ends of this spectrum are:

* Player levels up really fast and blows away monsters without much effort
* Monsters are incredibly strong and even at low levels, are very difficult to beat

I've also tried a strange situation of making enemies relative to players, i.e. an enemy will always be at 50% or 100% or 150% of player stats (thus requiring the player to use other techniques instead of brute strength to succeeed).

But where's the balance, and how do you find it?

**Edit:** For example, I am expecting to hear things like:

* Balance high instead of balance low (200 HP and 20 str is easier to balance than 20 HP and 2 str)
* Look at easiest vs. hardest monsters, and see what you have in terms of a range

# Answer
> 32 votes
Playtest. No, really, just playtest your balance until you get it right, or rather mostly right (there's no such thing as perfect balance).

Write automated tests and run them hundreds of times. Even very simple automated tests, like "level 2 player always hits with shortsword, goblin always hits with club, player should win" can really help, if you run these tests often (generally, whenever you change anything). Also, test balance by playing. Whenever you find some new potentially balance-changing tactic, write an automated test for it.

# Answer
> 24 votes
One problem with making enemies strength relative to players is that it can make the player feel like they aren't making progress. *"What's the point of getting stronger if all the monsters also get stronger at the same rate?"*

I tend to prefer that enemies have static strength instead of being relative to the player for the following reasons:

* Players will notice the effect of getting stronger (and believe they have progressed).
* Players will be defeated by strong monsters, and this will give them something to aspire to and achieve.

Of course there are negatives also:

* Areas containing weak monsters can become redundant
* Some players may find that the time they need to invest to beat a particular monster is too long

> Player levels up really fast and blows away monsters without much effort

You can prevent this by decreasing the exp received from a monster the higher the players level is over the monsters level - in essence removing the motivation that player has to fight easily blown away monsters.

> Monsters are incredibly strong and even at low levels, are very difficult to beat

This should never happen due to play-testing.

See also: How to implement an experience system?

# Answer
> 6 votes
To a certain extent, you can use math to manage this process. This is the approach Wizards of the Coast used with D&D 3.x and 4. Figure out how many battles you want between levels, and base how much XP battles give you based on that. Do you want it to be easy to level by fighting lower-level monsters? Then choose a flatter XP curve to make that a feasible strategy. On the other hand, you can discourage grinding by making lower-level monsters give much less XP than the player needs to level.

If you've got random encounters, make sure to take into account the average frequency of battles. You don't want to force players to grind for hours to progress the main storyline. Conversely, if your encounters are all manually placed, make sure there are enough of them to level the PC(s) appropriately.

I second the dislike of auto-leveling monsters to match the player level. You want to give the player a feeling of progress, which means they should always be able to see monsters too powerful for them and monsters too low-level to be challenging. As an aside, try and make it so that higher-level monsters have something special and advanced about them that goes beyond sheer statistical advantage. There's no difference between fighting a plain 100hp monster and a plain 1000hp monster if your attacks at the time do 10 damage and 100 damage respectively.

# Answer
> 4 votes
Experience curve balance is a game design choice. Only you know the way you want your combat system to work, the amount of time you want someone to spend on one level, the number of combats you expect a player to take between levels, the proportion of battles a player is expected to win, the magnitude of the numbers you want to display to a player, whether you want the experience-per-level to go up each time or not, whether any or all of these factors should change over the course of play (and in which direction), etc. Choose the experience you want, then do the mathematics to work out how to get that.

# Answer
> 3 votes
Group monster difficulty by region. Allow the player to select the region.

E.g.: Level 10-12 monsters go in zone A, level 12-15 monsters go in zone B, level 15-18 monsters go in zone C. The player is level 11. Lock zone C away from the player. If the player tries zone B and it is too difficult, allow the player to leave zone B and try zone A instead.

Player strength and player skill both affect how difficult the monsters are for the player to kill. By allowing the player to implicitly choose which monsters to fight, you take both into account.

If your game is linear (the player cannot choose a path or physical region), then spawn weaker monsters up to some lower bound if the player is killing the monsters more slowly than you expect.

# Answer
> 2 votes
Difficulty is perceived as a combination of time, risk, and meaningful choice. RPGs usually start off with small encounters that are very quick, have little risk, and little meaningful choice. This continues while the player is learning the game and the character they are playing. As new abilities are introduced, more meaningful choice is introduced. *Do you use poison at the start of the fight or just go for direct attack*. Along with this comes longer fights and more risk. If a player can kill a creature in 2 basic attacks or 2 special attacks, there isn't much choice. You need more granularity to have more meaningful choices.

To get to this sort of growth, you need to control the length of encounters. In large scale development, this is done with formulas, which are much later fine tuned after extensive play-testing.

Formulas are written only after requirements are established, and are generally used as a baseline for fights. You can create variations of the baseline after you have established the baseline.

Answer some basic questions such as

* What are the level ranges you are dealing with
* How long should a fight last (seconds for an action game, rounds for turn based)
* What comparative range of enemy levels should be considered a normal encounter
* Should this balance change at higher levels?

Lets take a simple example using only damage and health, with a level cap of 20. The base enemy has 10+5/level health and the average damage per round of the player is 8+2/level. You can put those equations into Excel and you come out with something like this:

```
 LVL    HP  DMG TTK
    1   15  8   1.9
    2   20  9   2.2
    3   25  10  2.5
    4   30  11  2.7
    5   35  12  2.9
    6   40  13  3.1
    7   45  14  3.2
    8   50  15  3.3
    9   55  16  3.4
    10  60  17  3.5
    11  65  18  3.6
    12  70  19  3.7
    13  75  20  3.8
    14  80  21  3.8
    15  85  22  3.9
    16  90  23  3.9
    17  95  24  4.0
    18  100 25  4.0
    19  105 26  4.0
    20  110 27  4.1

```

If you want to increase the time to kill (TTK) for later levels, you could either increase enemy health scaling or decrease player damage scaling.

Of course this is only one dimension of the combat. You would have to create another set of formulas for player health and enemy damage. The TTK for the creature vs the player should be higher (it should take longer for a creature to kill the player than visa versa), but the closer you get to 20, the closer the numbers should get, for increasing difficulty.

Add in avoidance and mitigation requires you to combine the damage formulas with the mitigation % or miss chance to determine the actual average expected damage. The damage values above would be the target numbers for each level that you try to balance around.

Once you have squared away your baseline creature, then you can create variations, such as glass cannons that do high damage but have lower health. If you put in the work at the start to build a good baseline enemy for all level ranges, then creating new enemies that are near balanced is actually fairly simple.

# Answer
> 1 votes
The absolute best balance is to combine the two standard methods used in most games for determining monster strength. That is essentially a level range is selected for perhaps a region, or a monster type, and then the system attempts to auto balance using the relative strength of the player.

The benefit to this is that it allows you or your designers in the future to retain some form of control over where the player should find the best rewards for the difficulty put in, while still not being as easily gamed by simple grinding, though obviously it should be mentioned that setting the possible level ranges should be refined through playtesting to find an appropriate range.

The only other thing that is very important when using a system like this, that generates monster difficulty on the fly, is that you save those difficulty settings once they are generated. This is very important, or otherwise you end up with a situation like Bethesda ran into with Oblivion. That game used an almost entirely systematic approach to monster difficulty, and as a result a number of players expressed concerns that they did not feel like they were leveling up at all, since every time they visited a new area (or even returned to an old area previously explored in which they knew how difficult the monsters were when they were there the first time) they found that the encounters were of very similar if not identical difficulty.

Finally the last thing to remember, there is no "best balance". If you want to make your game incredibly difficult, then feel free to increase the average monster strength, if you want it to be easier smooth out the player leveling curve. The exact balance of your games difficulty is not nearly as important as it's consistency, nothing is more frustrating than a game with a difficulty curve that flies all over the landscape.

# Answer
> 1 votes
Your percentage idea looks great to me, let your player choose if 40% or 180%. This way more people will like your game, casual player and pro, everyone will find his 'ideal' difficulty.
Of course, score, bonuses and other difficulty related values should be based on this percentage.

# Answer
> 0 votes
My game balance is as follows:

I reduce points to simple offensive/defensive points (instead of a slew of attributes - STR, INT, DEX, etc... that only cause game devs headaches trying to balance throughout the game experience -- not everything has to be D&D peeps!) and add a Proficiency Modifier that increases proficiency (per character level) of the offensive "weapon" / defensive "shield" that the player chooses to mostly use based on the personality of the character they wish to play (keeping ROLE-PLAYING king, keeping game balance intact).

This means that no matter what weapons/armor a PC wishes to use at the start of their new level, they ALL have the same effect, averaging out damage per turn (therefore the choice is simply a role-playing aesthetic), until you actually use one more often than the other.

However, the more damage done by a certain weapon choice, or the more defense done by a certain defensive, will receive behind the scenes Proficiency Points that increase their favorite weapon/defense's proficiency during that character level.

At each level, the character can choose to abandon their particular off/def strategy, or keep it in tact. This is, again, a role-playing choice, with NO advantage/disadvantage upon arriving at the new level until the player decides to use one tactic (OFF vs. DEF) over another, at which point they will accumulate (behind the scenes) Proficiency Points for using their favorite weapon/defense.

The caveat here is that once you level up, your now under-levelled weapons and defense still hit as hard/protect as much as your level demands, but they also become less effective (until they don't work at all -- weapons/shields break, magic loses it's off/def oomph), on an exponentially descending scale, forcing the player to reevaluate it's use of under-levelled weapons/defense tactics, over upgrading their favs to the current level (for a price, of course), or finding weapons they would rather have that's copacetic with their current level.

This allows for players to upgrade their favorite weapons/defensive measures (for a price) to their current level or journey (quest or explore) to find better weapons that suit their current level (once again, keeping the game balance intact).

The overriding point is, Role-Playing should not be forced into classes, My toga wearing, staff-wielding monk should be able to do as much damage per level as a steel-armoring wearing, sword-slashing tank. (this whole idea, btw is relegated to a single player CRPG so that comparisons between what IS and what COULD BE is eliminated). You simply play AS YOU WISH TO PLAY, and no harm is done by choosing a "class" over another "class" based on a bevy of stats.

It all falls apart, I think, when playing pen-and-paper. :)

---
Tags: rpg, balance, roguelikes, progression
---


# Question
Title: How to draw a rectangle or curve between two co-ordinates in libGDX
I am new to libGDX.I just want a Rectangle or a small curve drawn between the object and the clicked position .I know libGDX has RECTANGLE class.

I just want to draw a rectangle or a curved line to be drawn between the object and the clicked position like this \>\>\>

1. click can occur anywhere inside the circle region(above red object or below the red object).
2. green cross represents the click position.
3. red one represents the object.

Problem is if i use `shapeRenderer.rect(x, y, width, height);` it will give me straight horizontal rectangle like the gray rectangle shown in the image. Therefore i will have to use `shapeRenderer.rect(x, y, width, height, originX, originY, rotation);` . I gave `0` for both `originX` and `originY` but what will be the rotation value ? I am stuck up in calculating the rotation value .

Currently i can think of two ways to do it :-

1. By using Rectangle \>\>\> `shapeRenderer.rect(x, y, width, height, originX, originY, rotation);`
2. By using sprite image \>\>\> `batcher.draw(region, x, y, originX, originY, width, height, scaleX, scaleY, rotation, clockwise);`

But in both the cases as u see i need the rotation value .How to calculate that ?
Or is there any other way we can achieve the same results maybe by using some sprite image or something ?

# Answer
> 3 votes
I finally got it !!

```
package com.Main;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;

public class vectorTest implements Screen {

    MainClass main;

    public vectorTest(MainClass main) {
        this.main = main;
    }

    Vector2 touchPos = new Vector2(); //touch position
    Vector2 pos = new Vector2(); // position

    Sprite sprite, touchPosDot;
    Texture txt;

    SpriteBatch batch;
    OrthographicCamera cam; // a camera

    float width;
    float angle;

    @Override
    public void show() {
        cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2, 0);
        batch = new SpriteBatch();
        touchPos = new Vector2();
        pos = new Vector2(0, 0);
        touchPos.set(211,312); // I took casual coordinates

        txt = new Texture ("img/UI/square.png");
        sprite = new Sprite (txt);   // our "rectangular"
        sprite.setPosition(pos.x, pos.y);
        sprite.setColor(Color.RED);

        touchPosDot = new Sprite (txt); // green point
        touchPosDot.setColor(Color.GREEN);
        touchPosDot.setSize(10, 10);
        touchPosDot.setPosition(touchPos.x - touchPosDot.getWidth()/2, touchPos.y - touchPosDot.getHeight()/2);

        width = (float) Math.sqrt(Math.pow(touchPos.y - pos.y, 2) + Math.pow(touchPos.x - pos.x, 2)); // find the distance between the two points using Pythagorean theorem
        angle = (float) Math.asin((touchPos.y - pos.y)/width); // fint the angle in radians
        angle = (float) Math.toDegrees(angle); // convert to degrees
        sprite.setSize(width, 2);
        sprite.setOrigin(pos.x, pos.y); // IMPORTANT set the origins
        sprite.rotate(angle); // and finally, rotates the sprite to the right angle

    }

    @Override
    public void render(float delta) {
        GLCommon gl = Gdx.gl;   // clear the screen
        gl.glClearColor(1, 1, 1, 1);
        gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        cam.update();
        batch.setProjectionMatrix(cam.combined);
        batch.begin();
            sprite.draw(batch);
            touchPosDot.draw(batch);
        batch.end();

    }
      ( ... )
}

```

# Answer
> 2 votes
Actually it's already present in Vector2 class.

You can use something like this:

```
    Vector2 touchPoint = new Vector2(211,312); // random touch position
    Vector2 center = new Vector2(world.getWorldWidth() / 2, world.getWorldHeight() / 2); // center of the world
    float width = touchPoint.sub(center).len(); // length of resultant vector
    float angle = touchPoint.angle(); // and angle what you are looking for

```

# Answer
> 0 votes
This code makes you draw a **shape (line)** whenever a touch-event is registred.

```
 package com.Main;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;

public class vectorTest implements Screen {

    MainClass main;

    public vectorTest(MainClass main) {
        this.main = main;
    }

    Vector3 touchPos; //touch position
    Vector2 position; // object A position

    SpriteBatch batch;
    ShapeRenderer renderer; // it's required for drawing the shape (line)
    OrthographicCamera cam; // a camera

    @Override
    public void show() {
        renderer = new ShapeRenderer();
        cam = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        cam.position.set(Gdx.graphics.getWidth()/2, Gdx.graphics.getHeight()/2, 0);
        batch = new SpriteBatch();
        touchPos = new Vector3();
        position = new Vector2(1, 1);

    }

    @Override
    public void render(float delta) {
        GLCommon gl = Gdx.gl;   // clear the screen
        gl.glClearColor(1, 1, 1, 1);
        gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        cam.update();
        batch.setProjectionMatrix(cam.combined);

        batch.begin();
        cam.update();
        renderer.setProjectionMatrix(cam.combined);

        if (Gdx.input.isTouched()) {
            touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
            cam.unproject(touchPos);
             renderer.begin(ShapeType.Line); // shape type
             renderer.setColor(1, 0.5F, 0.5F, 1); // line's color
             renderer.line(position.x, position.y, touchPos.x, touchPos.y);  // shape's set of coordinates (x1,y1,x2,y2)
             renderer.end();
        }
      batch.end();
    }

    (...)
}

Make me know if this method is ok ;)

```

---
Tags: java, libgdx
---


# Question
Title: Need guidelines for quest xp and reward balancing
Where would I look to get guidelines for how much XP and gold/items to give as rewards for quests? The following is the algorithm I'm using to determine the XP needed for each level:

```
/** This starts at level 1. If you're at level 1, to get to level 2 you call getXpForLevel(1). */
public static long getXpForLevel(long level) {
    return 40 * level * level + 360 * level;
}

```

If I know roughly how long it'll take the player to complete a quest, how much xp should I award for that quest? How much should difficulty factor into the xp for the quest?

How do I balance the amount of gold you get for completing a quest vs the cost of items that can be purchased?

Do people just go by their gut feelings and then try to balance the values through playtesting or are there good rules to follow?

# Answer
> 3 votes
Game Balance Concepts likely has everything you need to know about that.

# Answer
> 0 votes
There are multiple ways to come at the question, depending on what you have already decided.

If you already have your content made, then you need to determine the points at which you want players to level, and use the amount of XP needed to get them to that level to determine what quests should give.

If you are still making your content, then it is better to determine how long you want it to take to level. If each quest takes 10 minutes, and you expect a player to take an hour to level, then it should take 6 quests to level. Of course, take into account the other XP sources. Killing creatures probably contributes, so subtract out the amount of XP they are expected to gain in an hour of questing before you divide it up.

To use your case for an example, I did these columns in Excel from left to right, in order

* Lvl - Character level from 1 to 20
* LvlXP - using your formula: 40 * level * level + 360 * level
* TTL - Time to level, I arbitrarily decided I wanted a exponential curve that leveled off, so I chose this equation: level^0.5-0.5
* Quests - This is a derived column. You get it by multiplying the TTL by the number of quests per hour (6).
* This is a derived column. You get it by dividing the XP per level by the amount of quests done in that level (this assumes xp per level is the amount you want to come from quests, everything else is subracted out already).

---

This is your baseline. Quests that take 50% longer should generally get a 50% boost in XP. You might make Hard/Medium/Easy quest difficulties that get 150%/100%/50% XP respectively.

```
Lvl LvlXP   TTL     Quests  QuestXP
1   0400    0.50    3.00    133
2   0880    0.91    5.49    160
3   1440    1.23    7.39    195
4   2080    1.50    9.00    231
5   2800    1.74    10.42   269
6   3600    1.95    11.70   308
7   4480    2.15    12.87   348
8   5440    2.33    13.97   389
9   6480    2.50    15.00   432
10  7600    2.66    15.97   476
11  8800    2.82    16.90   521
12  10080   2.96    17.78   567
13  11440   3.11    18.63   614
14  12880   3.24    19.45   662
15  14400   3.37    20.24   712
16  16000   3.50    21.00   762
17  17680   3.62    21.74   813
18  19440   3.74    22.46   866
19  21280   3.86    23.15   919
20  23200   3.97    23.83   973

```

---

After you have established how long a player is expected to be in a level, you can decide how much money they should gain in that level. Generally the amount of money gained should grow FASTER than the TTL. So if your TTL increases by 20% between levels, your money gained should increase by MORE than 20% between levels. Otherwise it becomes more efficient to grind money by dropping to lower levels, and you don't want to reward tedious behavior.

Use the Excel table from before and just add a column for Gold Per Hour. Come up with a formula for that with a slight exponential growth. Once you have established the GPH gained at each level, you can then use that to calculate the total gold gained in a given level. From that you can determine the curve of the cost of buying items of a given level, depending on the pace at which you want players to replace their items.

* Lvl - I brought this from the other table
* TTL - Time to Level, from the other table
* GPH - I arbitrarily created a formula for Gold Per Hour (GPH). I started at 5% increase per level and decided it was too small, and ended at 20% increase per level: 40+200\*level^1.2
* GPL - Gold per Level is calculated by multiplying GPH times Time to Level (TTL). This is how much gold the player is expected to make during this level: GPH * TTL
* ItemCost - For this, I assumed that we want the player to replace 1 item per level and for it to use 20% of the gold earned: GPL * .2
* Training - Lets assume you the player to use another 40% of their money on training, for example: GPL * .4

---

```
Lvl TTL     GPH     GPL     ItemCost    Training
1   0.50    240.0   120.0   24          48
2   0.91    499.5   456.6   91          183
3   1.23    787.4   970.2   194         388
4   1.50    1095.6  1643.4  329         657
5   1.74    1419.7  2464.7  493         986
6   1.95    1757.2  3425.6  685         1370
7   2.15    2106.1  4519.1  904         1808
8   2.33    2465.1  5739.9  1148        2296
9   2.50    2833.3  7083.3  1417        2833
10  2.66    3209.8  8545.3  1709        3418
11  2.82    3593.9  10122.6 2025        4049
12  2.96    3985.0  11812.0 2362        4725
13  3.11    4382.7  13610.8 2722        5444
14  3.24    4786.6  15516.6 3103        6207
15  3.37    5196.3  17527.1 3505        7011
16  3.50    5611.5  19640.3 3928        7856
17  3.62    6032.0  21854.4 4371        8742
18  3.74    6457.4  24167.6 4834        9667
19  3.86    6887.5  26578.3 5316        10631
20  3.97    7322.3  29085.0 5817        11634

```

---

This process of filling out can be extended all across the creation of the RPG. All numbers are interdependent. Examples:

* How much a creature drops: Multiply the GPH * percent of money you want to come from creatures times the creature kills per hour.
* How much money a quest gives: muliply the GPH * percent of money you want to come from quests * quests per hour.

---
Tags: rpg, balance
---


title: Moving a tiled map in a jframe

text:
# Question
Title: Moving a tiled map in a jframe
I rendered a tiled map, with the help of slick2d, in my JFrame in Java. I can move my main character, but it is just that the character itself moves. I would like to do it that, if the player moves, the map moves and the player himself stays in middle of the frame. Do you have any suggestions on how to do that ?

# Answer
> 1 votes
Don't use `JFrame`, instead use `BasicGame` subclass and `AppGameContainer` (it's much better than `JFrame`).

And to your problem, you have to create a `Camera` class. That's all already covered here.

---
Tags: java, movement, tilemap, slick, jframe
---


# Question
Title: Applying transformations in Geometry Shader
So, I am trying to program in opengl (3.3) a kind of robot. The idea is that I have some simple blocks that represent his body (4 rectangles for his arms, one for the torso and the last one representing the head). To simplify a made a bad picture of my idea.

So now what I want to do is to make him move his arms depending on keyboard commands. Doing that would be just rotating each arm the amount that you want (translating too). But I am stuck because the only way I found to make striped rectangles (just the borders) is using the geometry shader. From the little I know about opengl, transformations are applied in the vertex shader, which would not work for my idea. Would be inefficient to apply the transformations on the geometry shader? (It is from what I know). If so, is there an easier way of drawing those rectangles?

EDIT: Ok, I can simplify a lot this question. The thing is that I want to draw those "skeletal" rectangles, but the only way I know how to do it is using the geometry shader. But with this comes the problem of the transformations, so I would want to avoid doing that. There is another way to draw those skeletal shapes?

# Answer
Looks like you don't have a clear understanding of what you can do in each type shader. You don't need a geometry shader to do this, a vertex shader is enough.

I suggest you to have a look at this tutorial that shows how to draw triangles in modern OpenGL. Once you understand how you can draw, play with the function `void CGLRenderer::SetData()`, which is where you set the actual vertex positions of your primitives. What you probably want to do is modify the Vertex Buffer Object content depending on the key that you press, this will change the position/orientation/size of your shapes.

Perhaps **this is another good tutorial** for you. It shows how to create a spinning triangle in WebGL using fragment and vertex shaders. See the result **here**.
> 1 votes

---
Tags: opengl, shaders
---


title: Orthogonal projections question

text:
# Question
Title: Orthogonal projections question
I'm very VERY new into the game development world and I had just some slight trouble wrapping my head around something. We were told between classes just to think about how scaling matrices can perform simple orthogonal projections on a cardinal axis or plane.

What I know is orthogonal projections are 3D objects minus the z-coordinates in most cases. Scaling matrices are a matter of altering x,y,z coordinates to adjust the shape of an object. So, the only way for scaling to actually make a orthogonal projection is for the x,y,or z to be scaled by a factor of zero. Am I kinda getting it so far or is there still a lot going over my head?

# Answer
An orthographic projection is better described as a kind of parallel projection, because if you were to draw lines between the points in "world space" (ie 3d) to "projected space" (ie 2d) they would be parallel to each other.

All projections map one space to another, though for the most part when we're talking about orthographic projections we're transforming a cloud to be coincident to a plane (the screen).

You could open a 3d modelling program and then simulate orthographic projection for any angle by first rotating a mesh into position, then scaling it by zero along the z axis. The vertices of the model will end up being coincident to the xy plane. There's a little more to it in practice, of course, since any triangles with normals parallel to the -z axis line would end up z-fighting.
> 1 votes

---
Tags: matrix, projection
---


# Question
Title: I can load new tiles but how do I load new chunks?
I have successfully been able to add new tiles and place random trees on a 2d map grid however I haven't used chunks. I just load a new tile when the player moves and save it to the map array. But I have had some issues with the forests. And I'm thinking chunks would solve my problem. The problem is my forest just appears on the map when the player moves left or up. But I want to focus on how to handle the chunks because I know if I get that right I'll be able to solve the other symptoms to the main problem. Here is a link to the game.

https://76295db93db3812642fa5ba984c042fa81ffc37c.googledrive.com/host/0B6H3TRExU5M9eEkyd2FreHhiNlU/

Here is how I generate new tiles. This runs every game loop and not sure if that is the best way to do it. Does this cause lag? The bottom of the function checks if the tiles need to be updated to forest graphics. I know this is probably the wrong way to do it but I maybe if I get the chunk thing figured out I won't have these issues.

```
map.update = function() {
    for(var x = Math.floor(player.x - map.width / 2); x < Math.floor(player.x - map.width / 2) + map.width + 2; x++){
        for(var y = Math.floor(player.y - map.height / 2); y < Math.floor(player.y - map.height / 2) + map.height + 2; y++){
            //Surrounding tiles
            var tiles = [];
            //Check if tile needs to be generated
            var check = function(x, y) {
                if(typeof map.data[x] === 'undefined') {
                    map.data[x] = [];
                }
                if(typeof map.data[x][y] === 'undefined') {
                    map.data[x][y] = new Tile(x, y, map.generate.groundLayer(), map.generate.playerLayer(x, y), map.generate.aboveLayer(), map.generate.event());
                }
                //Add tile to collection
                tiles.push(map.data[x][y]);
            };
            //Center
            check(x, y);
            //Top
            check(x, y - 1);
            //Top Right
            check(x + 1, y - 1);
            //Right
            check(x + 1, y);
            //Bottom Right
            check(x + 1, y + 1);
            //Bottom
            check(x, y + 1);
            //Bottom Left
            check(x - 1, y + 1);
            //Left
            check(x - 1, y);
            //Top Left
            check(x - 1, y - 1);

            //Check if there is a forest
            /*
            if(map.data[x][y].playerLayer === sprite.forest.topLeftCorner) {
                tiles[3].playerLayer = sprite.forest.topRightCorner;
                tiles[4].playerLayer = sprite.forest.bottomRightCorner;
                tiles[5].playerLayer = sprite.forest.bottomLeftCorner;
            }
            */

        }
    }
};

```

# Answer
Your best bet is to not generate tiles but generate and manage chunks which contain tiles. If you think about chunks as a fundamental part of the design then the issue may go away.

I faced a similar issue in 3d with building my voxel engine.

You likely want to do something like ...

```
class Map {
   public Size Size { get { ... } }
   public List<Chunk> { get; set; }
   public Tile GetTileAt(int x, int y) { ... }
   public Tile SetTileAt(int x, int y, Tile newValue) { ... }
}

class Chunk {
   Tile[] Tiles { get; set; }
   public Size Size { get { ... } }
   public Tile GetTileAt(int x, int y) { ... }
   public Tile SetTileAt(int x, int y, Tile newValue) { ... }
}

```

Then map just figures out the chunk on get and set calls and calls the same method on the chunk. The chunk looks at a subset of the map so should be faster when performing lookups on tiles. The common scenario I guess will be things like ...

Player moves over a chunk boundary so map / some parent goes and adds new chunks and fills them with tiles. This also allows you to "pick portions" of the map for rendering calls to help optimise the engine a bit more.

And by tracking the current chunk the player is stood on you can make any player interaction with the map much faster too :)

You will however need to address the problem of chunk bounds if you only look at data on a chunk by chunk basis so be aware of that.
> 2 votes

---
Tags: 2d, javascript, procedural-generation, tilemap, automation
---


title: Creating refraction map problem

text:
# Question
Title: Creating refraction map problem
I'm reading riemers tutorial on how to make a water effect and trying to translate it from xna 3 to xna 4. So far I figured out I have to create a shader in order to clip the planes for my refraction map. I'm new to hlsl and how to implement custom shaders into my program, so I am wondering what I am doing wrong here.

```
  float4x4 World;
  float4x4 View;
  float4x4 Projection;

  float4 ClipPlane0;

  void vs(inout float4 position : POSITION0, out float4 clipDistances : TEXCOORD0)
  {

clipDistances.y = 0;
clipDistances.z = 0;
clipDistances.w = 0;

position = mul(mul(mul(position, World), View), Projection);

    clipDistances.x = dot(position, ClipPlane0);
  }

  float4 ps(float4 clipDistances : TEXCOORD0) : COLOR0
  {
clip(clipDistances);

return float4(0, 0, 0, 0); // TODO: whatever other shading logic you want
  }

  technique
 {
pass
{
    VertexShader = compile vs_2_0 vs();
    PixelShader = compile ps_2_0 ps();
}
  }

```

This is the fx file that I found on an xna forum just for reference.

Major edit:

I was able to get the program running successfully but when I viewed the saved screenshot of the refraction map, nothing was clipped.

```
    public void DrawRefractionMap(Effect clipEffect, Camera camera, GraphicsDevice device)
    {
        Plane refractionPlane = CreatePlane(waterHeight + 1.5f, new Vector3(0, -1, 0), camera, false);
        clipEffect.Parameters["ClipPlane0"].SetValue(new Vector4(refractionPlane.Normal, refractionPlane.D));

        device.SetRenderTarget(refractionRenderTarget);

        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1, 0);

        foreach (EffectPass pass in clipEffect.CurrentTechnique.Passes)
        {
            pass.Apply();

            DrawTerrain(clipEffect, camera, device);
        }

        device.SetRenderTarget(null);
        refractionTexture = (Texture2D)refractionRenderTarget;

        FileStream stream = File.OpenWrite("Screenshot33.png");

        refractionTexture.SaveAsJpeg(stream, refractionTexture.Width, refractionTexture.Height);
    }

```

# Answer
You seem to be only setting the clip distance.x value also where is this clip function defined maybe that can lend some light on the subject?

If memory serves, reimers approach was to use a plane and effectively reflect / refract the scene off that.

Then combining the reflection and reflection and refraction maps with some peturbation results in water.

The shader code shouldn't need updating at all since you can still use them as they are (its perfectly valid to use an older shader model with newer cpu code which it looks like your rewrite is doing anyway).
> 1 votes

---
Tags: xna
---


title: Rendering multiple meshes in directx11

text:
# Question
Title: Rendering multiple meshes in directx11
Recently I have tried adding rendering with multiple meshes in my program. This did not go too well. The attempt I currently have goes like this

```
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(VERTEX)* nVertices.at(i);
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = 0;
    bd.MiscFlags = 0;
    bd.StructureByteStride = 0;

    vertexData.pSysMem = vertices.at(i);
    vertexData.SysMemPitch = 0;
    vertexData.SysMemSlicePitch = 0;

    dev->CreateBuffer(&bd, &vertexData, &pVBuffer);

```

looping through the meshes and doing like wise for the index buffer. Similar to this, the render code loops through the mesh data as well:

```
        UINT stride = sizeof(VERTEX);
        UINT offset = 0;
        devcon->IASetVertexBuffers(0, 1, &pVBuffer, &stride, &offset);
        devcon->IASetIndexBuffer(pIBuffer, DXGI_FORMAT_R32_UINT, 0);

        devcon->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

        devcon->DrawIndexed(nIndices.at(i), 0, 0);

```

But all of this only ends up rendering one of the meshes. Does anyone know what I need to change to fix this or whether I need to have a completely different approach? Thanks in advance!

# Answer
> 1 votes
ok im not a c++ developer but i do this all the time in c#.

Essentially you need to wrap up a vbo and a ibo in to some container like this ...

```
class Mesh {
   public VertexBuffer Vertices;
   public IndexBuffer  Indices;
}

```

Then run your code generate a bunch of mesh objects ...

```
List<Mesh> Meshes = GetMeLotsOfMeshes();

```

Then you do something like ...

Apply Shader state to context foreach mesh { Set vert and index buffer call draw indexed }

My c# code for this works something like this ...

I have a material class which basically wraps up the creation and management of a shader stack in which i do something like this once before i begin dealing with any meshes ...

```
public void Apply(DeviceContext context, Matrix world)
{
    if (LastMaterial == null || LastMaterial != ClassName)
    {
        //apply material and buffers to device context
        context.InputAssembler.PrimitiveTopology = Topology;
        context.InputAssembler.InputLayout = layout;
        context.VertexShader.Set(vertexShader);
        context.PixelShader.Set(pixelShader);
        if (sampler != null) context.PixelShader.SetSampler(0, sampler);
        LastMaterial = ClassName;
    }
    ApplyConstants(context, world);
}

```

After thats been done once I begin looping through my meshes first i apply the shader constants for the buffers im about to render (world matrix for the object) then I go in to the mesh class and call draw which sets the right buffers and then calls draw on them ...

```
protected override void ApplyConstants(DeviceContext context, Matrix world)
{
    context.PixelShader.SetShaderResource(0, textureView);
    wvp = world * camera.ViewProjection;
    wvp.Transpose();
    context.VertexShader.SetConstantBuffer(0, constantBuffer);
    context.UpdateSubresource(ref wvp, constantBuffer);
}

public void DrawTo(DeviceContext context)
{
    context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(VertexBuffer, Utilities.SizeOf<T>(), 0));
    context.InputAssembler.SetIndexBuffer(IndexBuffer, Format.R32_UInt, 0);
    context.DrawIndexed(Indices.Count, 0, 0);
}

```

---
Tags: c++, directx11
---