title: Minecraft - like lighting engine

text:
# Question
Title: Minecraft - like lighting engine
So I was looking on how to create a minecraft - like lighting engine and I found the following post:

How can I implement lighting in a voxel engine?

The answer to it was incredible and perfectly detailed I would love if you the person who wrote it @Byte56 or anyone who knows how @Byte56 achieved the shadow effect that he called "a little more advanced"? If you do know how to achieve it can you please detail the way to create it like he did in his post?

This was the part I found really useful:

> Here are a few things to keep in mind.
>
> We're going to keep a list of cubes that need their lighting values checked Only transparent cubes and light emitting cubes have lighting values The first cube we add is the light source. A source is a special case. It's light value is set accordingly to the light source type (for example torches get a brighter value than lava). If a cube has its light value set above 0, we add all the transparent cubes adjacent to that cube to the list. For each cube on the list, we set its light value to its brightest neighbor minus one. This means that all the transparent cubes (this includes "air") next to the light source get a light value of 15. We continue walking the cubes around the light source, adding cubes that need to be checked and taking lit cubes off the list, util we no longer have any to add. That means that all the latest values set have been set to 0, which means we've reached the end of our light. \- Byte56

This is the effect desired: \[I have already implemented the normal lights\]

EDIT:

I basically want guidelines to implementing the "shadow effect" of the light. As you can see the light being on the bridge casts light onto the ground in-front of the bridge as well even though its "out of the range" of the light. This creates an illusion that there is a shadow underneath the bridge. That is what I am looking to implement. I already have implemented the basic lighting that every block away from the light is the max neighbour minus one. This works great however I would love to implement this "shadow illusion"

# Answer
The shadow effect in that image is created with rays and is somewhat imperfect. When calculating the light for each face, I check to see if the face of that block has line-of-sight to the center of the block containing the torch. The line-of-sight check is performed with a ray cast. If the block does not have line-of-sight, the amount of light is reduced by a significant amount, but not removed entirely. Most of this is explained in the post I linked along with the answer you quoted.

In the image you have in your question, you can see the lighting directly under the light source on the bridge is actually a little bit brighter than the light at the edge of the shadow. This is a defect caused by the light value only being reduced, and not removed entirely.

This can be fixed by not lighting the faces at all if they don't have line-of-sight, but this produces much harder shadows.

All-in-all, the lighting system is not perfect, but it suits the needs of the game well enough.
> 2 votes

---
Tags: lighting, voxels, shadows
---


title: Rotating a square rendered on a Bitmap

text:
# Question
Title: Rotating a square rendered on a Bitmap
I'm writing a Software Renderer for fun/learning. Basically, it's just a giant array of integers which contain hexadecimal values (representing colour) that are rendered to the screen....

```
int screenWidth = 16;
int screenHeight = 16;
int[] pixels = new int[screenWidth * screenHeight];
Arrays.fill(pixels, 0xffff00ff);

```

Something like that, the above should render a pink screen (255, 0, 255). So my problem is I've written a method that will fill a rectangle...

```
public void fillRect(int x0, int y0, int x1, int y1) {
    x0 += xOffs; // apply offset to each vertex
    y0 += yOffs;
    x1 += xOffs;
    y1 += yOffs;

    if (x0 < 0) x0 = 0;
    if (y0 < 0) y0 = 0;
    if (x1 >= width) x1 = width - 1;
    if (y1 >= height) y1 = height - 1;
    for (int y = y0; y <= y1; y++) {
        for (int x = x0; x <= x1; x++) {
            components[x + y * width] = 0xDEADBEEF;
        }
    }
}

```

And it works fine, although I want to try and rotate the quad by 90 degrees, then render it to the bitmap. So I tried this....

```
public void fill(int x0, int y0, int x1, int y1) {
    final int theta = 90;
    x0 = (int) (x0 * Math.cos(theta) - x0 * Math.sin(theta));
    x1 = (int) (x1 * Math.cos(theta) - x1 * Math.sin(theta));
    y0 = (int) (y0 * Math.sin(theta) + y0 * Math.cos(theta));
    y1 = (int) (y1 * Math.sin(theta) + y1 * Math.cos(theta));

    x0 += xOffs; // apply offset to each vertex
    y0 += yOffs;
    x1 += xOffs;
    y1 += yOffs;

    if (x0 < 0) x0 = 0;
    if (y0 < 0) y0 = 0;
    if (x1 >= width) x1 = width - 1;
    if (y1 >= height) y1 = height - 1;
    for (int y = y0; y <= y1; y++) {
        for (int x = x0; x <= x1; x++) {
            components[x + y * width] = hex;
        }
    }
}

```

Although it doesn't work, nothing is shown on the Window. Any ideas? I have a feeling after the rotation, the entire method is wrong. Any help would be great :)

# Answer
> 3 votes
First of all: most computer trigonometric functions takes **radians** as input. Even if the code worked, I am 99% sure it will not rotate by 90 degrees. So if it is that case, try changing it to pi/2.
Secondly, if you would rotate by not-multiply of 90 degrees - the code would still produce axis-aligned rectangle (bounding box), NOT rotated rectangle as you are iterating in axis-aligned loop.
And last: when rotating, you are always rotating around origin point. If you first translated the rectangle - it can very easily end up outside of the screen. The order of transformations matters!
*I imagine you tried it on input like (1,1,4,4), such rectangle is already translated, try the code with pi/2 and input like (-4,-4,4,4) where the rectangle is centered in the origin.*

---
Tags: mathematics, rotation, geometry
---


# Question
Title: What datastructure would you use for a collision-detection in a tilemap?
Currently I save those blocks in my map that could be colliding with the player in a HashMap (Vector2, Block). So the Vector2 represents the coordinates of the blog.

Whenever the player moves I then iterate over all these Blocks (that are in a specific range around the player) and check if a collision happened.

This was my first rough idea on how to implement the collision-detection. Currently if the player moves I put more and more blocks in the HashMap until a specific "upper bound", then I clear it and start over.

I was fully aware that it was not the brightest solution for the problem, but as said, it was a rough first implementation (I'm still learning a lot about game-design and the data-structure).

What data-structure would you use to save the Blocks? I thought about a Queue or even a Stack, but I'm not sure, hence I ask.

# Answer
You should consider using a plain 2d-array or alternatively an array of rooms, where each room is a 2d-array or a grid.

A `grid` would looks something like this:

The player is the yellow dot and the blocks are the green ones. if the player is the light gray square, you only need to check for blocks that around that square area. This saves you the time of repopulating the hash supposedly if I understand you correctly.

You can check if the player is hitting something at `(x = 770, y = 505)` by dividing these values by a block's size and then checking the corresponding spot in the 2d array.

For instance if a block's size `is 50 x 50` you do `770 / 50 = 15` and `505/50 = 10` so you check the array at `array[15][10]`.

If the blocks are very sparse you could consider using a hash where the keys are the positions the blocks would have in the 2d-array.

Do not use a quad-tree unless you are absolutely sure you need it. It is definitely not required for nearly any 2d pc game nowadays.

If you memory demands are so intense that you need to consider loading and clearing data from memory like you suggest, divide the level into a grid and keep only 4 relevant squares of the grid in the memory at a time.

If your blocks are not even, simply create a grid (represented by a 2d array) and add the blocs to each square of the grid they overlap with in advance. Then check the relevant grid squares for elements the player might be colliding with.
> 4 votes

# Answer
For your collision I would merge adjacent colliding tiles together into one big collision box instead of iterating over every single tile and checking their individual collision.

Also I think that a quadtree would work much better than your current approach with a HashMap as it splits your gameworld up in sections and make it easy to delete a section of objects which are far from the player.
> 2 votes

# Answer
You should definitively use a quadtree as Hjorthenify suggest.

see: handling collision detection with a quadtree

At each frame you may reconstruct your quadtree and then for each collideable entity you retrieve the entities contained (or intersected) in the same area (NE, NW, SE, SW).

For exemple :

```
public void checkCollision(Entity e, ArrayList<Entity> entities) {

    QuadTree<Entity> tree = new QuadTree<Entity>(entities);

    ArrayList<Entity> sameAreaEntities = tree.retrieves(e);

    for (Entity collideable : sameAreaEntities) {
        if (collide(e, collideable)) {

            // do something

        }
    }
}

```
> 0 votes

---
Tags: java, collision-detection, libgdx, tilemap, data-structure
---


title: Using depth texture for depth testing

text:
# Question
Title: Using depth texture for depth testing
I was wondering if it is possible to render my scene onto a depth texture then using that texture for depth testing in another pass. I have an idea to that in shaders, but is that possible hardware-side?

# Answer
One way to accomplish this would be to use an FBO (Frame Buffer Object) and multiple depth buffers and/or depth textures. A basic use case is shown on the Wiki at OpenGL.org.

---

Another possible method, maybe applicable to old or very low end hardware could be copying the depth buffer, which you can find an example of using PBOs (Pixel Buffer Objects) here.
> 1 votes

---
Tags: opengl, shaders
---


# Question
Title: How do I make cars on a one-dimensional track avoid collisions?
Using three.js, I use a simple spline to represent a road. Cars can only move forward on the spline. A car should be able to slow-down behind a slow moving car. I know how to calculate the distance between 2 cars, but how to calculate the proper speed in each game update?

At the moment I simply do something like this:

```
this.speed += (this.maxSpeed - this.speed) * 0.02; // linear interpolation to maxSpeed

// the position on the spline (0.0 - 1.0)
this.position += this.speed / this.road.spline.getLength();

```

This works. But how to implement the slow-down part?

```
// transform from floats (0.0 - 1.0) into actual units
var carInFrontPosition = carInFront.position * this.road.spline.getLength();
var myPosition = this.position * this.road.spline.getLength();

var distance = carInFrontPosition - myPosition;

// WHAT TO DO HERE WITH THE DISTANCE?
// HOW TO CALCULATE MY NEW SPEED?

```

Obviously I have to somehow take current speed of the cars into account for calculation.

Besides different maxSpeeds, I want each car to also have a different mass (causing it to accelerate slower/faster). But this mass has to be then also taken into account for braking (slowing down) so they don't crash into each other.

# Answer
> 2 votes
***EDIT***

The current solution has the following problem: The applied braking force is static. That means if we randomly put a car on the road, other cars might be unable to break in time (since we always lower the velocity by a static braking force). I though I could scale the force somehow, but without much success (it causes oscillation).

Now I calculate the needed braking force on the fly.

Stopping distance still calculated the same way:

```
    var distanceToKeep = (CAR_LENGTH * 1.5) * 1.5;
    var stoppingDistance = ((carInFront.lane === this.lane) ? 0 : this.lane.spline.getLength()) + carInFront.position + carInFront.velocity - this.position - distanceToKeep;

```

But then:

```
if (stoppingDistance < 300) {
    // Formula from: http://www.gcsescience.com/pen33-work-energy-calculations.htm
    this.acceleration = -(0.5 * (this.velocity * this.velocity) / stoppingDistance);
}
else {
    this.acceleration = force;
}

```

This will gradually slow us down if the distance is below 300 units. If we spawn a car in front of us only 100 units away, we will brake much harder. In previous solution it would cause a crash.

Still there is a problem left. If we stand still behind a car, and the car in front starts moving, we won't move until the distance is 300 units... So again a static component that causes problems. I solved it by scaling the stoppingDistance based on velocity, which also brings back the reaction time:

```
var effectiveDistance = stoppingDistance * (100 / Math.min(100, Math.max(0.1, this.velocity)));
effectiveDistance *= this.reactionTime; // *= 0.0 - 1.0

if (effectiveDistance <= 300) {
   // the rest is the same, we still divide by stoppingDistance here

```

This works very well. No matter where I spawn cars on a lane, the other cars will always stop in time and will not crash into each other.

***/EDIT***

I solved it now using proper math (thanks to Anko for the hint).

A car's $position property previously was assigned the "point-position" on the spline (0.0 - 1.0). For easier calculation I now use the actual position in units on the spline. For velocity I use units as well. From update method:

```
this.position += this.velocity * dt;
this.velocity += this.acceleration * dt; // we calculate the acceleration below

if (this.velocity < 0) {
    this.velocity = 0;
}
else if (this.velocity > this.maxVelocity) {
    this.velocity = this.maxVelocity;
}

[...]

// Calculate point on lane (0.0 - 1.0)
var pointOnLane = 1 / this.road.spline.getLength() * this.position;
var positionVector = this.road.spline.getPointAt(pointOnLane);

this.mesh.position.set(positionVector.x, 5, positionVector.z);

```

Now for the acceleration calculation:

```
var force = 5;
var reactionTime = 0.5;

if (carInFront !== null) {

        var distanceToKeep = (CAR_LENGTH * 1.5) * 1.5;
        // Formulas from: http://www.seas.upenn.edu/~ese302/lab-content/STOPPING_DISTANCE_DOC.pdf
        var stoppingDistance = carInFront.position + carInFront.velocity - this.position - distanceToKeep;
        var stoppingTime = this.velocity / force;
        var reactionDistance = stoppingDistance * reactionTime;
        var brakingDistance = (0.5 * this.velocity * stoppingTime) + reactionDistance;

        if (stoppingDistance < brakingDistance) {
            this.acceleration = -force / reactionTime;
        }
        else
        {
            this.acceleration = force / reactionTime;
        }

}
else
{
    this.acceleration = force / reactionTime;
}

```

So this already works perfectly. See how they all line up behind the very slow car:

Currently for positive and negative (braking) acceleration I use the same force which results in very long braking times (and looks unrealistic). But it should be easy to fix by calculating braking force or braking reaction time based on distance and/or velocity.

---
Tags: three.js
---


# Question
Title: Set new forward directions based on camera position
I have a 3rd person camera which can rotate around the player.

When I look at the back of the player and press forward, player goes forward. Then I rotate 360 around the player and "forward direction" is tilted for 90 degrees. So every 360 turn there is 90 degrees of direction change.

For example when camera is facing the right side of the player, when I press button to move forward, I want player to turn to the left and make that the "new forward".

I have Player object with Camera as child object. Camera object has Camera script. Inside Camera script there are Player and Camera classes. Player object itself, has Input Controller.

Also I'm making this script for joystick/ controller primarily.

My camera script so far:

```
using UnityEngine;
using System.Collections;

public class CameraScript : MonoBehaviour
{
    public GameObject Target;
    public float RotateSpeed = 10,
    FollowDistance = 20,
    FollowHeight = 10;
    float RotateSpeedPerTime,
    DesiredRotationAngle,
    DesiredHeight,
    CurrentRotationAngle,
    CurrentHeight,
    Yaw,
    Pitch;
    Quaternion CurrentRotation;

    void LateUpdate()
    {
        RotateSpeedPerTime = RotateSpeed * Time.deltaTime;

        DesiredRotationAngle = Target.transform.eulerAngles.y;
        DesiredHeight = Target.transform.position.y + FollowHeight;
        CurrentRotationAngle = transform.eulerAngles.y;
        CurrentHeight = transform.position.y;

        CurrentRotationAngle = Mathf.LerpAngle(CurrentRotationAngle, DesiredRotationAngle, 0);
        CurrentHeight = Mathf.Lerp(CurrentHeight, DesiredHeight, 0);

        CurrentRotation = Quaternion.Euler(0, CurrentRotationAngle, 0);
        transform.position = Target.transform.position;
        transform.position -= CurrentRotation * Vector3.forward * FollowDistance;
        transform.position = new Vector3(transform.position.x, CurrentHeight, transform.position.z);

        Yaw = Input.GetAxis("Right Horizontal") * RotateSpeedPerTime;
        Pitch = Input.GetAxis("Right Vertical") * RotateSpeedPerTime;
        transform.Translate(new Vector3(Yaw, -Pitch, 0));
        transform.position = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        transform.LookAt(Target.transform);
    }
}

```

My player script:

```
using UnityEngine;
using System.Collections;

public class PlayerScript : MonoBehaviour
{
    public float RotateSpeed = 10,
    MoveSpeed = 10;
    float DeltaTime;
    public Transform cameraTransform;

    void Update()
    {
        DeltaTime = Time.deltaTime;
        transform.Rotate(0, Input.GetAxis("Right Horizontal") * RotateSpeed * DeltaTime, 0);
    }
}

```

# Answer
> 0 votes
If the player is looking directly at the camera we can use the following idea to find the direction the player should walk, based on the position of the camera.

We have two vectors C: (camera.Transform.Forward) the direction the camera is looking at and P (player.Transform.Forward) the direction the player is looking at.

By computing the acos of the dot product of these two vectors we can compute the angle between these to vectors.

```
angle = acos(dot(C, P);

```

This angle can be used to rate the player so that it faces the camera (just rotate the player by -angle) and it can be used to transform controller inputs so that no matter where the camera and player is 'left' will always be left as seen from the camera.

This can be done by constructing the left, forward, right, and backward vectors like this.

```
// Assumes the forward vector normally is (0, 0, 1) or
// (cos(pi/2 + 0), 0, sin(pi/2 + 0))
vector3 forward = (cos(pi/2) + angle), 0, sin(pi /2 + angle);

```

If you wish the player to face the forward vector, or another vector you can again compute the acos of the dot product between that vector and the vector that points to where the player is currently facing. Just rotate the player by minus the result of that computation.

There might be small math errors in this answer (offsets wrong by half a pi, a minus that should or shouldn't be there) but I hope the general idea is now quite clear and that you can deduce the other direction vectors yourself.

# Answer
> -1 votes
I shall rephrase, the direction the player is facing is the forward direction, Therefor the camera should face forward (i.e the direction the player is facing), so the camera should be aimed at the player location always (unless you choose it to follow a different object like a vehicle) so there fore the camera facing point is player.location (This isn't code just variables for vectors)

```
     Camera.facing =player.facing; /*this makes the camera face the way the player is facing...therefor camera will always face forward,( i.e the direction the player is facing...)rotating the player 360 degrees should place the camera back where it started (behind the player facing the way the player is facing) rotating it 180 degrees should place the camera still behind the player but but moved on the yaw to face the same way the player is now facing,the idea is not to make a whole new purpose of a "new forward" variable but use a variable that's already there....*/

     Camera.facing=player.location; //*his makes the camera face the location of your player which means the camera might not be facing where the player is facing but more at where he is, this method will allow you too see the front of the player if he is facing the camera, and the back if he is not,or his sides if he is moving that way (this method sounds like the one you need ;) ) */
     Camera.location=player.location.z-4&&player.location.y+2; /*this simply places the camera behind the player at all times (you can change this if you want...)

```

It also sounds like you don't understand this "player.location.x" (this is a vector player.location.x refers to the x piece of the vector where as player.location.y refers to the y piece of the vector and player.location.z refers to the z piece of the vector.... Understanding that should allow you to properly place the camera and view angle correctly, but I do want you to know that rotating 360 degrees should place the camera in the exact place it was... Feel free to ask more questions to me if you don't understand :) Hope this Helps :) Good Luck :)

---
Tags: c#, unity, camera, rotation
---


# Question
Title: Utility of submesh class in a 3d game engine?
I've read somewhere that we use sub mesh for being able to give different materials to one mesh. But why not simply do this with scenegraph ?

I mean you have a car mesh, and instead of using submeshes for windows, wheels etc... We could have one car node which would be composed of child nodes ( wheel, window ) with differents meshes and materials.

What's the utility of submeshes while there is scenegraph ? I've noticed that in Ogre3D there is both scenegraph ( SceneNode class ) and a mesh/submesh system, why ?

# Answer
> 4 votes
Deep within the game engine your mesh is defined by your vertices, your indices (which define how to draw the triangles using the vertices), and its material (which consists of the shader as well as other parameters). Submeshes allow you to define separate lists of indices and materials (depending on the engine) over the same vertex data which is useful not only for applying multiple textures but also to cut down on moving memory around and a few other things.

If you have a car with multiple parts (let's say a few mirrors, a few windows, and the body), there would most likely be some sort of connection where you have vertices shared by the two. Let's say you had these as separate objects in the scene graph as you were saying. To render this the engine would take a path similar to the below in order to render your car

```
>>Render the car
    >>Render the body
    --Load the vertices for the body
    --Load the indices for the body
    --Load the shader for the body
    --Render all of that to the screen (vertex shader, fragment shader, set pixels)
    >>Render the windows
    --Load the vertices for the windows
    --Load the indices for the windows
    --...
    >>Render the mirrors
    --Load the vertices for the mirrors
    --Load the indices for the mirrors
    --...
>>Done rendering car

```

In each step we have to load the vertices for each object from some file (perhaps already in memory) onto the GPU in a vertex buffer which takes time. Now look at the path it would take if we used submeshes which share the same vertex data but have different index data

```
>>Render the car
--Load the vertices for the car
    >>Render the body
    --Load the indices for the body
    --Load the shader for the body
    --Render all of that to the screen (vertex shader, fragment shader, set pixels)
    >>Render the windows
    --Load the indices for the windows
    --...
    >>Render the mirrors
    --Load the indices for the mirrors
    --...
>>Done rendering car

```

Now we only load vertices for the entire car in one go and then apply different lists of indices to get each piece.

Some other things to consider is that with a submesh you also don't generally need the functionality and overhead provided by a full blown game object. I doubt you're going to need to apply velocity separately to the windows versus the car itself or have the windows check for collision independently so why bother, less can go wrong. If you need that functionality then you'd have to end up breaking it up into two separate objects.

It just so happens that some engines will also let you apply a different material to each submesh which can be beneficial in cases here you'd like to keep one mesh sourcing from multiple materials within the same game object (although you need to switch the materials while rendering each submesh which takes time).

---
Tags: 3d, architecture, scene-graph
---


# Question
Title: How do I construct the planes for my camera's frustum?
I'm trying to get a handle on frustum culling, but I'm not quite there yet.

I have a camera in three-dimensional space

```
Camera
    position (cx, cy, cz)
    rotation (tx, ty, tz)
    fieldofview
    near-plane
    far-plane

```

and a quadtree containing my chunks of terrain

```
Quadtree
    Chunk
        bottomleft (x, y)
        width
        length
        heightmap

```

Currently, I am rendering every chunk within the quadtree. However, I would like to cull all chunks outside the six planes of the camera's frustum.

I am unsure how to:

1. Generate these planes given the information in the camera class.
2. Efficiently test for intersection using my quadtree. If one region of the quadtree fails, do all of its children (that seems reasonable, I just want to make sure)? What is the process for running through a quadtree for culling?
3. Perform the intersection test using the planes and my terrain chunks. How do I quickly tell if a piece of terrain (square with varying y values) lies within the 6 camera planes?

# Answer
Field of View and Aspect Ratio define how much the frustum planes diverge, so a little math should let you define the 4 planes of the viewport... but then you are stuck with plane/plane intersection tests

One approach would be to use the inverse of your camera and projection matrix to project the corners of the viewport some defined distance into the environment... the math is the same as used for handling mouse picking of 3D objects.. that will tell you the extents of the frustum planes. Use the same math with a very short (zero) distance to get the close in extents, then make the plane rectangular using the larger edges to expand the smaller.

Since you are only using a quadtree (for terrain I suppose ??) you might be better off just using your camera matrix to project the intersection points of the leaves to viewport space and then test if they are visible... if you get a hit, then the 4 leaves around a the given point are visible, and you can start drilling up/down to find the adjacent sections that are also have visible corners... start with the 4 points for the leaf you are on/above and work from there.
> 1 votes

---
Tags: terrain-rendering, frustum, quadtree, frustum-culling
---


# Question
Title: Using peer to peer for prediction in a client-server network model
By implementing peer to peer connections between clients in a client-server network model I should be able to increase the prediction fidelity as this theoretically would provide the client with other clients commands for a given tick earlier than it would receive the servers game states for the same tick.

One problem I can think of is that clients would have to be able to interpret other clients commands (usually they just have to listen for game states, not commands). This would be a little bit like an RTS model I guess. This should be solvable without any negative effects on gameplay.

Another problem is that clients could cheat by sending fake data to their peers when it is beneficial to them. This can be mitigated by having the client aware of the real commands through the server and have them immediately stop listening to any clients that fed it false data. This should therefore be solvable with different degrees of negative effect on gameplay depending on the design of the game and how impactful a few ticks of wrong command info is at the worst possible moment.

(Unfortunately, you can't have the server punish any client because it has no idea who's lying, it can only help clients themselves understand if they are being lied to by providing them with correct data).

Am I correct in assuming that this would increase prediction fidelity or is there something I'm not accounting for? The idea is that this allows the client access to some information about the other clients faster than in a traditional non peer to peer model where it would base predictions solely on its own commands.

# Answer
> 1 votes
I'm not aware of this ever being used, and I suspect it's because it has very limited benefit for greatly increased complexity and bandwidth use. It might make an interesting experiment, but it seems impractical.

Consider that to support such a scheme, and assuming that most traffic is generated from player actions, you would need to **double the downstream traffic** and **multiply the upstream traffic** for all clients, not to mention opening a large amount of new connections. Double downstream because now you are receiving player commands from the peers as well as the server. Multiple upstream because clients need to send their commands to all peers as well as the server.

But perhaps the biggest cost is that you run into tricky situations when you now have **three points of reference**. With a traditional client-server architecture, there are two: the client and the server (technically the other clients have their own points of reference but the server multiplexes them into a consistent, single one using techniques under the *latency compensation* umbrella). Now you have three (or more): client, server, and peer. Consider this scenario:

* Peer tells you that they shot and killed you
* Server later says that you weren't shot (maybe the peer-\>server shot packet was dropped)

What happens on your client? Do you momentarily die and revive? Do you ignore the peer's input altogether (then what's the point of having p2p)? I'm sure you can come up with many more edge cases like this.

Finally consider the limited benefit of such a scheme. It might be a boon if you and your friends are all geographically close (say, you're all in Nauru) but the nearest hosting server mandated by *Modern FPS 2015* is in US West. You will have a horrible time playing each other, so p2p will make things a lot better and the server turns into a glorified command validator. In practice, such a situation is rare, as most peers will not be significantly closer to you than the server.

---
Tags: networking, client-server, first-person-shooter, peer-to-peer, movement-prediction
---


# Question
Title: How do I render from one render target to another?
I have two render targets:

1. a **fake backbuffer**; a special render target where I do all my rendering.
2. a **light render target**; where I render my light fx.

I'm sure I'm rendering correctly on both.

The problem arises when I overlay the **light render target** onto the **fake backbuffer** by drawing a quad covering it:

```
DxEngine.DrawSprite(0.0f, 0.0f, 0.0f,
    (float)DxEngine.GetWidth(), (float)DxEngine.GetHeight(),
    0xFFFFFFFF, LightSurface->GetTexture());

```

Regardless of what's in the light target, nothing is rendered onto the other target. I tried clearing the light target with full-white or full-black, but still get nothing.

---

Fake backbuffer created with

```
Direct3dDev->CreateTexture(Width, Height, 1, D3DUSAGE_RENDERTARGET,
    D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &Texture, nullptr);

```

Light render target created with

```
Direct3dDev->CreateTexture(Width, Height, 1, D3DUSAGE_RENDERTARGET,
    D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &Texture, nullptr);

```

I also tried to create both with `D3DFMT_A8R8G8B8`, again without difference. Both targets have the same width and height.

Only the fixed pipeline is used

DirectX setup for rendering :

```
Direct3dDev->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR );
Direct3dDev->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR );
Direct3dDev->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE );
Direct3dDev->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP );
Direct3dDev->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP );
Direct3dDev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
Direct3dDev->SetRenderState(D3DRS_LIGHTING, false);
Direct3dDev->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
Direct3dDev->SetRenderState(D3DRS_ZWRITEENABLE,D3DZB_TRUE);
Direct3dDev->SetRenderState(D3DRS_ZFUNC,D3DCMP_LESSEQUAL);

Direct3dDev->SetRenderState(D3DRS_ALPHABLENDENABLE,  true );
Direct3dDev->SetRenderState(D3DRS_ALPHAREF, 0x00000000ul);
Direct3dDev->SetRenderState(D3DRS_ALPHATESTENABLE, true);
Direct3dDev->SetRenderState(D3DRS_ALPHAFUNC,D3DCMP_GREATER);
Direct3dDev->SetRenderState(D3DRS_SRCBLEND,  D3DBLEND_SRCALPHA );
Direct3dDev->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );

Direct3dDev->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
Direct3dDev->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);
Direct3dDev->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE);
Direct3dDev->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
Direct3dDev->SetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE);
Direct3dDev->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);

Direct3dDev->SetTextureStageState(0, D3DTSS_RESULTARG, D3DTA_CURRENT);

Direct3dDev->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_PASSTHRU);

//ensure the first stage is not used for now
Direct3dDev->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE);

```

How can I do this right?

# Answer
> 0 votes
Finally found the culprit, it was a really stupid typo error in my code, the light surface was not the same size as the backbuffer (width and height reversed)....

By the way i was able to pinpoint the problem really fast with PIX, if that can help someone.

---
Tags: c++, directx9, rendertargets
---


# Question
Title: Intelligently move aircraft using curves
I am trying to code a script to move an aircraft entity from point A to point B and at some point in the middle of moving have the aircraft forward vector face Point C (to fire a missile at an enemy entity at C).

I implemented a bezier curve script that takes as input a list of waypoint and tangent handle Vector3 (Tangent handle is angle at point + weight which is represented by the length of the handle) which I plan to use to move the aircraft alone but I have not figured out a good algorithm to determine where to move to and the tangents at those points.

The control points in the img above are the same as my tangent handles.

**The conditions are:**

1. Aircraft must start at A, waypoint 0 is therefore at A
2. Tangent 0 angle must match Aircraft starting forward vector direction
3. Waypoint N (last waypoint) must be at point B (finishing location).
4. At some Waypoint (1 - N) the tangent must be facing the enemy position C
5. The last tangent must be level with the y = 0 plane (aircraft must be parallel with the ground)

**Constraints**

1. A,B,B are on the y=10 plane. This does not mean that waypoints in the middle of the movement need

The aim is to get smooth and somewhat natural looking movement, overly sharp changes of direction are undesirable.

My initial implementation was as follows:

waypointSequence.addPoint(position, tangentHandlePosition)

```
Vector3 middleWaypointPosition =
    new Vector3((aircraftTransform.position.x + movementLocation.x + enemyTransform.position.x) / 3f,
    (aircraftTransform.position.y + movementLocation.y + enemyTransform.position.y) / 3f,
    (aircraftTransform.position.z + movementLocation.z + enemyTransform.position.z) / 3f);
Vector3 finishTangent = middleWaypointPosition + (enemyTransform.position - middleWaypointPosition) / 2;
finishTangent.y = 10;
// Add first point - A position, A forward tangent
waypointSequence.addPoint(aircraftTransform.position, aircraftTransform.position + aircraftTransform.forward * 10);
// Second point - Centroid of A, B, C. Tangent is pointing at C
waypointSequence.addPoint(middleWaypointPosition, finishTangent);
// Last point - position is at B
waypointSequence.addPoint(movementLocation, movementLocation +
    (movementLocation - attackUnit.transform.position).normalized * 10);

```

It works somewhat well in most cases but there are a number of edge cases, for instance A and B being at the same position makes the craft move towards the target then suddenly turn back with a 180 degrees turn towards B. There are a number of cases where I observed strange behavior.

Does anyone have any suggestions on how to design this algorithm?

# Answer
> 4 votes
# Fly along circular arcs

You start at \\$x\_1\\$, moving in the direction \\$v\_1\\$ and want to end up at \\$x\_2\\$ facing in \\$v\_2\\$, then the shortest path (assuming a finite turning radius, which realistically should be proportional to the square of the velocity) takes you along an arc of radius \\$r\_1\\$ around \\$m\_1\\$, followed by a straight line segment and then another arc of radius \\$r\_2\\$ around \\$m\_2\\$

Here is an example path. You start at the bottom, facing either a or b, and want to end up top, facing either A or B, and the possible trajectories resulting from the 4 combinations

The circle centers \\$m\_i\\$ are at \\$x\_i ± r\_in\_i\\$, where \\$n\_i\\$ is the normal vector, orthogonal to the velocity: $$v\_i = (v\_x, v\_y),n\_i = \frac{v\_x, -v\_y}{\sqrt {v\_xv\_x + v\_yv\_y}}$$
From there on its just a little trigonometry and handling degenerate cases with multiple solutions. Those articles on tangent lines might be helpful.

*Disclaimer: This works well for stationary targets like flying through hoops or visualizing the path but its by far not the best solution to shoot moving targets*
Computing the entire path is costly, but if your target is moving, then you will have to update your path at every timestep, discarding all but the first few points from the last computation, so what you effectively doing, is computing where to turn next, or simply the force acting on you, and it depends only on your and your targets current position and velocity.
Searching for 'homing missiles' gets many results on how to do it, for example here.

A simple approach which produces some brutal AI is to use potential fields (Starcraft AI in action using this method)
This is how such a potential threat field could look in your case, based on turning speed and bullet flight time

Now all you need to do is keep the enemy in the white shootable cone, if he is too far away - accelerate to catch up, if he is in your deadzone or behind you - turn to get him back into the white cone. Do the same for all enemies, add their potential fields and move toward the place of least cumulative threat (close by or behind them) to avoid getting shot yourself.

# Answer
> 1 votes
I would add some AI (artificial intelligence) checks. A first thing to do would be to check if the distance to travel, in comparison with the distance to the enemy makes sense to apply the Bezier curves. For example, you could make the weight (i.e.: distance from the end point to the control point of the Bezier curve) depend on the distance travelled and the distance to the enemy. Because right now, the control point "weight" is half the distance to the enemy, which might be way to much in some cases. If the distance to be travelled zero, then don't do anything.

In fact I would even make the AI in that way that it makes sense every time you make a move. Make sure every time you decide the aircraft to move that the move actually would make sense. If the moving depends on a player input, then don't let the player make those senseless moves, by restricting the places where it can fly towards (e.g.: put a restriction on the minimum travelling distance).

Also, something I can think of: make the lengths of the control points vary in that way that they are not to close to each other. If the control points are to close to each other, or the lines (endpoint-control point) intersect with each other, that could cause some strange behaviour in terms of flying: the sharp turns. In general I think it is a good idea to make sure that the line to line distance of these control vectors are not to small. For doing that, take a look here: Shortest distance between two line segments.

After writing this answer, I think that the most interesting restriction is the line to line distance having a minimum value. This would do a great job, except for the ridiculously short traveling distances. This cannot happen in a "normal" way. Moving a tiny bit to the right, without being able to fly sideways, and with the requirement of having to face the same point at the end, is simply impossible to do "normal".

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


# Question
Title: Coordinates issue vertical scroll Libgdx
I'm going crazy with this problem. I'll explain:

I have a camera that falls down (flowing along the y-axis) which displays a TiledMap and declare the whole in this way:

In the create method:

```
map=new TmxMapLoader().load("Map.tmx");
this.renderer=new OrthogonalTiledMapRenderer(map);
this.camera=new OrthographicCamera(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());
this.camera.translate(Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight()/2);
this.camera.update();

```

In the render method:

```
this.renderer.setView(camera);
this.renderer.render();
camera.position.y+=1;
camera.update();

```

Then I have also a sprite drawing by SpriteBatch in the render method:

```
batchM.begin();
sprite.draw(batchM);
batchM.end();

```

In the tiledmap there are MapObject and I have to check if this objects hit to sprite and I do this so in the render method:

```
MapObjects collisionObjects =  map.getLayers().get("objects").getObjects();
        for(MapObject object : collisionObjects) {

               if (object instanceof RectangleMapObject) {
                   RectangleMapObject rect = ((RectangleMapObject) object);
                   Vector3 coo=camera.project(new Vector3(rect.getRectangle().x,rect.getRectangle().y,0));
                    com.badlogic.gdx.math.Rectangle Sprite= sprite.getBoundingRectangle();
                    com.badlogic.gdx.math.Rectangle Map=new com.badlogic.gdx.math.Rectangle(coo.x,coo.y,32,32);
                    //TEST
                   System.out.println("PLAYER X: "+Sprite.x+" Y: "+Sprite.y);
                   System.out.println("Object X: "+Map.x+" Y: "+Map.y);
                   if(Intersector.intersectRectangles(Sprite, Map, Sprite)) System.out.println("HIT");
          } }

```

My problem is that when I do not change the window size(remain the size the starting), collisions are detected fine, but when I change the window size (for example, I enlarge) collisions are not detected and I can not explain why.

Could you help me to fix this bug. Thank you for your time

# Answer
> 0 votes
The SpriteBatch has its own internal camera. Are you also setting the batcher to use the camera's combined projection matrix by calling:

```
       batchM.setProjectionMatrix(camera.combined);

```

The problems you could be experiencing, could perhaps be explained by the fact that collisions only appear to be happening on screen, but actually aren't as the map and the sprites are using two different coordinate systems which have been overlayed over one another. The coordinate systems just happen to correspond when the screen is its initial size, but when resized, diverge from the model. Then again, perhaps not. Without more code, I can't really tell.

---
Tags: java, libgdx, coordinates
---


# Question
Title: Quaternion rotation, translation, scale or 4x3/4x4 matrices for Skeletons?
I'm modding a game that uses 4x3 and 4x4 matrices to make skeletons, but I saw that an skeleton can also be made with a quaternian rotation and vector translation and scaling.

What's the difference between both? The first one has more values, I suppose, but, which is better?

If I have a 4x3/4x4 matrices skeleton, can I transform it in some way to the rotation, translation and scaling?

# Answer
> 1 votes
Smaller data helps a lot with performance which becomes critical when you have dozens or hundreds of characters with multiple blended animations.

There can also be several advantages to using quaternions when interpolating between frames of an animation. Matrices can theoretically fail to represent certain series of transformations (gimbal lock) and linear interpolation of rotational matrices gives you a slightly incorrect values compared to spherical interpolation of quaternions.

In short, use quaternions and offset vectors. You can reconstruct the final transformation matrix easily enough on the GPU during skinning.

This a gets to be a much longer conversation once animation compression and other high-end techniques are tossed in, but you still typically stick with quaternions.

# Answer
> 0 votes
Quaternions are useful for the skeleton representation since animations are often compressed quaternion rotations. So when playing back animations you only need to decompress quaternions for a frame for each joint and multiply the quarernion with the bind pose quaternion of the skeleton. This both preserves memory and is more efficient than using matrices. At the point of rendering though quaternions are often converted to 3x4 matrices and fed to the shader since regular skinning is more efficient with matrices.

---
Tags: matrix, quaternion, skeletal-animation
---


# Question
Title: Impact of object's statistics on the rendering
Consider two 3D objects with n points and n triangles. One of the objects has a smooth surface such as a ball or a box, and the other object is like a fuzzy onion-layered object with large intersecting faces. Is there any difference between the rendering (complexity and time) of these two objects?

I know that regardless of the input, the rendering process has a fixed complexity, but I am wondering whether it is possible to evaluate the impact of objects' (vertex and connectivity) statistics on the rendering (complexity and time).

# Answer
Yes, there are many performance implications to consider even when two objects share the same amount of geometry.

1. Fragments that fail a Z-buffer test will not invoke fragment shaders.
2. The amount of screen-space that the objects occupy will impact performance, as fill-rate is a big deal especially on mobile devices.
3. If you have large triangles that are close to parallel with the camera view direction then filtering textures on them will not be very cache-friendly.

I'm sure there are many more, but the moral of the story is that you need to measure how much impact a specific rendering algorithm has rather than trying to analytically find a solution. The non-determinism of GPUs is going to throw any calculations you make out the window anyway.
> 2 votes

---
Tags: 3d, mathematics, rendering, performance
---


title: Game object position issue in unity3d

text:
# Question
Title: Game object position issue in unity3d
I have a set of objects placed on the same layer where all the objects are invisible except one. When I drag an object into a selected area, the current dragged object gets destroyed, and the object should be loaded in the same position. I have added polygon collider and rigid body (SET FIXED ANGLE) to all the objects. The problem here is: when I drag the object to the selected area, the object gets destroyed, and the next object gets loaded, but the position varies when the object is loaded.

```
public Vector3 ObjectSpawnPosition1;
public GameObject obj1;
void OnCollisionEnter2D(Collision2D col) {
  if (col.gameObject.name == "SemiCircle") {

    if (Input.GetMouseButtonUp(0)) {
      scoreCalculate.currentScore += 10;
      Destroy(gameObject);
      Instantiate(obj1, ObjectSpawnPosition1, Quaternion.identity);
      obj1.renderer.enabled = true;
    }

  }
}

```

# Answer
Try assigning the position of the previous `GameObject` to the spot where you want the new one instantiated before destroying the old object.

```
public Vector3 objectSpawnPosition1;
public GameObject obj1;
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.name == "SemICircle" )
{

        if(Input.GetMouseButtonUp(0))
        {
            scoreCalculate.currentScore+=10 ;
            objectSpawnPosition1 = gameObject.transform.position;
            Destroy(gameObject);
            Instantiate(obj1, objectSpawnPosition1, Quaternion.identity);
            obj1.renderer.enabled = true;
         }

}

```
> 1 votes

---
Tags: unity, collision-detection, gameobject
---


title: CCD IK algorithm going horribly wrong

text:
# Question
Title: CCD IK algorithm going horribly wrong
I'm trying to implement the Cyclic Coordinate Descent algorithm described here:

http://www.cs.cmu.edu/~15464-s13/assignments/assignment2/jlander\_gamedev\_nov98.pdf

So first of all, I'm passing in the starting position bone which the CCD algorithm should stop at and the endPos which is the end-effector bone essentially. So in this instance, startPos could be taken from the **Left\_Clavicle** bone and the endPos could be the **Left\_Hand**. I also pass in the target position and a model object to be able to update the hierarchy.

Here is my attempt at the CCD:

```
void ComputeCCD(Model * model,glm::vec3 target, Bone * startPos, AnimNode * endPos)
{
    glm::vec3 rootPos,curEnd,desiredEnd,targetVector,curVector,crossResult;
    double cosAngle,turnAngle,turnDeg;
    int tries;

    Bone * currentBone = endPos->m_parent;
    tries = 0;

    do
    {
        rootPos = GetPosition(currentBone->m_globalTransform);
        // POSITION OF THE END EFFECTOR
        curEnd = GetPosition(endPos->m_globalTransform);
        // DESIRED END EFFECTOR POSITION
        desiredEnd = target;
        float distSq = DistSquare(curEnd,desiredEnd);
        // SEE IF I AM ALREADY CLOSE ENOUGH
        if (distSq > IK_POS_THRESH)
        {
            // CREATE THE VECTOR TO THE CURRENT EFFECTOR POS
            curVector = curEnd - rootPos;

            // CREATE THE DESIRED EFFECTOR POSITION VECTOR
            targetVector= target - rootPos;

            cosAngle = glm::dot(targetVector,curVector);
            turnAngle = glm::acos((float)cosAngle);
            turnDeg = glm::degrees(turnAngle);
            //Get axis of rotation
            crossResult = glm::cross(targetVector,curVector);

            //currentBone->m_localTransform *= glm::rotate(glm::mat4(1.0f),          (float)turnDeg,crossResult);

            // IF THE DOT PRODUCT RETURNS 1.0, I DON'T NEED TO ROTATE AS IT IS 0 DEGREES
            if (cosAngle < 0.99999)
            {
                if (crossResult.z > 0.0f) // IF THE Z ELEMENT IS POSITIVE, ROTATE CLOCKWISE
                {

                    currentBone->m_localTransform = glm::rotate(currentBone->m_globalTransform,-(float)turnDeg,crossResult);
                }
                else if (crossResult.z < 0.0f) // ROTATE COUNTER CLOCKWISE
                {
                    currentBone->m_localTransform =  glm::rotate(currentBone->m_globalTransform,(float)turnDeg,crossResult);
                }

             }
             if (currentBone->m_name == startPos->m_name)
             {
              currentBone = endPos->m_parent;
              // START OF THE CHAIN, RESTART
             }
             else
             {
                 currentBone = currentBone->m_parent;
             }
               model->UpdateHierarchy(currentBone);
             }

      } while (tries++ < MAX_IK_TRIES && DistSquare(curEnd, desiredEnd) > IK_POS_THRESH);
}

```

So I have a tracker which I can move around and pass into this method. Whenever I try to run it I get the following error. The arm folds in on itself :(

# Answer
Fixed it by replacing

```
 currentBone->m_localTransform = glm::rotate(currentBone->m_globalTransform,-  (float)turnDeg,crossResult);

```

with

```
 glm::mat4 rotation = glm::axisAngleMatrix(crossResult, (float)turnAngle);

 currentBone->m_localTransform *= rotation;

```
> 1 votes

---
Tags: inverse-kinematics
---


# Question
Title: Disabling / Enabling object renderers on click
I am working on unity2d. I have six game objects:

Object1, Object2, Object3 (these are images)

ObjectImage1, ObjectImage2, ObjectImage3 (these are images).

I have arranged the object in the scene as a list one below another

Object1

Object2

Object3

When I click the

Object1 ---\> should change to ObjectImage1

Object2 ---\> should change to ObjectImage2, but the above image of object1(objectImage1) at present should change to Object1

Object3 ---\> should change to ObjectImage3,but the above image on object2(objectImage2) should change to Object2

This is similar to selection. My code is as follows:

```
public GameObject newSprite;
private Vector3 currentSpritePosition;

void Start()
{
    newSprite.renderer.enabled = false; //then make it invisible
    currentSpritePosition = transform.position; //give the new sprite the position of the latter
    renderer.enabled = false; //then make it visible
    newSprite.transform.position = currentSpritePosition;
    newSprite.renderer.enabled = true;
}

void OnMouseExit()
 {
    //just the reverse process
    renderer.enabled = true;
    newSprite.renderer.enabled = false;
 }

```

This is the code used to change the material:

```
public GameObject newSprite;

private Vector3 currentSpritePosition;

void Start(){

    newSprite.renderer.enabled = false;
}

void OnMouseEnter(){
    //getting the current position of the current sprite if ever it can move;
    currentSpritePosition = transform.position;

    //then make it invisible
    renderer.enabled = false;

    //give the new sprite the position of the latter
    newSprite.transform.position = currentSpritePosition;

    //then make it visible
    newSprite.renderer.enabled = true;
}

void OnMouseExit(){
    //just the reverse process
    renderer.enabled = true;
    newSprite.renderer.enabled = false;
}

```

Currently when I click on Object2 it changes to ObjectImage2 but the first object is not changing to Object1 from ObjectImage1.

# Answer
> 2 votes
This is a *selection* functionality but you could easily include your own rules.

First, it's important that you define a tag for the selection group. In case there are more than one selection group in a scene at a time, there should be more than one tag defined for the groups.

**SelectionButton.cs**

```
using UnityEngine;
using System.Collections;

public class SelectionButton : MonoBehaviour
{
    public string selectGroupTag;
    public Sprite spriteDisabled;
    public Sprite spriteEnabled;
    private SpriteRenderer renderer;
    private GameObject[] selectGroup;

    void Start()
    {
        renderer = gameObject.GetComponent<SpriteRenderer>();
        renderer.sprite = spriteDisabled;
        selectGroup = GameObject.FindGameObjectsWithTag(selectGroupTag);
    }

    public void SetEnabled(bool enabled)
    {
        if (enabled)
            renderer.sprite = spriteEnabled;
        else
            renderer.sprite = spriteDisabled;
    }

    void OnMouseUpAsButton()
    {
        foreach (GameObject o in selectGroup)
            o.GetComponent<SelectionButton>().SetEnabled(false);
        SetEnabled(true);
        // TODO
        // add your set of rules here
    }
}

```

It's important that you also add a collider component for the code to work properly, and assign all the public variables.

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


# Question
Title: How would one approach developing an AI for a trading card game
How would one approach developing an AI for a trading card game(e.g. Magic The Gathering, YuGiOh, etc.)?

I'm not sure where to even begin. How would "Easy", "Normal", and "Hard" AI difficulties differ under the hood?

# Answer
> 5 votes
This is my experience from implementing a MTG AI.

If the AI is not considered from the start, adding it later can be challenging.

Your engine needs a way to copy the game state. It also needs a way to to quickly undo a move, so search tree can be generated efficiently.

Every AI thread should operate on its own copy of the game.

When computer makes a move it simulates possible outcomes of the game by simulating the effects of every possible move.

The basic algorithm is:

Create a list of valid moves (spells, abilities, pass ...). Execute each move to generate a new state then create a new list of valid moves. Repeat this until the game ends, or until you reach a certain depth. Remember you simulate the game for both players.

This process will generate a tree. Each path on the tree represents a valid sequence of actions in the game. Assign a score to each leaf node of this tree. This score should be an indicator which player has a greater chance of winning the game. Using minimax algorithm propagate this score to the root of the tree.

Every move from the original list now has a score, pick the best move.

Unfortunately MTG is rather complicated and the basic algorithm will not perform very well...

Things to improve:

* Mana abilities (e.g land tapping) need to be treated differently.
* Do not declare all possible combinations of attackers and blockers, use some 'quick combat' heuristics.
* Spells which require targets will kill the performance, use heuristics to pick only 'good targets'. (Each card which requires targets, should have a ranking algorithm)
* Assigning a timing rules to each card to limit when AI can consider playing it.
* If a card has X, it should know how to calculate a good X value and only try this when it is played.
* If a card can be activated repeatedly, use an algorithm to calculate how many times and do this as one move.
* Force only one option when playing spells that have multiple, based on the game state.

Here is a card implementation which uses some heuristics from above:

```
public class LightningBolt : CardTemplateSource
{
    public override IEnumerable<CardTemplate> GetCards()
    {
      yield return Card
        .Named("Lightning Bolt")
        .ManaCost("{R}")
        .Type("Instant")
        .Text("Lightning Bolt deals 3 damage to target creature or player.")
        .Cast(p =>
          {
            p.Effect = () => new DealDamageToTargets(3);
            p.TargetSelector.AddEffect(trg => trg.Is.CreatureOrPlayer().On.Battlefield());
            p.TargetingRule(new EffectDealDamage(3));
            p.TimingRule(new TargetRemovalTimingRule(removalTag: EffectTag.DealDamage));
          });
    }
}

```

# Answer
> 4 votes
1) **A Value Heuristic**. You need a heuristic that the AI can evaluate how "good" a particular game state is. For example, in MTG, a very simple heuristic could assign 2 points for every card you have in play and 1 point for each point of life the enemy has, so one of the AI's goals would be, all other things being equal, to play as many cards as possible, but it would also be willing to sacrafice any card to do 2 or more damage to the enemy. Note that this heuristic probably depends on the deck in play -- for Mill decks, for example, you'd need to incorporate the opponent's deck size as a primary point source.

2) **Move Lookahead**. The game rules describe all the legal moves available to a player, including drawing/discarding/placing/activating a card. Each move can be rated according to the heuristic you came up with in step 1. However, this is only reading one move. More successful strategies should consider the opponent's subsequent move, and the AI's move after that, and so on. Typically you use a **minimax** strategy.

* One step ahead: for each of your moves, determine the value of the resulting game state and choose the one with the highest points.
* Two steps ahead. for each of your moves and for each of your opponent's responses, determine the highest point value, assuming your opponent picks the optimal response to your first move.
* Three steps ahead. foreach \[your move, opponent move, your move again\], pick the best game state, again, making sure the opponent move is optimal for the opponent.

3) **Further Optimization** Naive move search increases exponentially the further ahead you search.. Using a technique similar to **alpha/beta pruning**, you don't evaluate paths that are really bad. If you can figure out a game state is strictly **dominated** by another game state, you do not have to continue looking down that branch of the move tree. Also, while the heuristic gives a general "sense of direction", the outcome of specific card combinations might not be apparent. Especially when using themed decks, you could keep a list of potent combos, especially gambits that take multiple steps before the heuristic could recognize the value of the combo.

# Answer
> 3 votes
Magic: The Gathering Duels of the Planeswalkers has AI that simulates possible future game states. Different AI difficulties are allowed varying lengths of time to plan advance turns. Additionally, the decks of easier AI opponents are sorted so that rarer cards are more likely to appear near the bottom of the deck.

Here is a detailed article with pictures(!):

http://www.wizards.com/Magic/Magazine/Article.aspx?x=mtg/daily/feature/44

# Answer
> 1 votes
Well, you have to do several things:

1. The AI needs to know rules for the game.
2. Next the AI has to know a strategy, as these card games generally have multiple sections and/or possible types of cards. *example: magic, attack, monsters, abilities, weapons and so on...*
3. For the actual difficulty; the AI should just be a better strategist, so a possible looking ahead algorithm, say an easy AI might plan ahead for an attack, but not a trap, whereas a hard AI shall plan for more types of possibilities, and multiple depths of thinking.
4. The AI should be able to combine techniques, as well as know general strategy for an effective game.

Thats the basics of it. Of course it may vary with how the game is itself.

---
Tags: ai, card-game
---


# Question
Title: Why is H (blinn) used instead of R (phong) in specular shading?
I can't find a good reason for this anywhere. The reflection vector used in phong has a simple basis in physics. But the half vector used in blinn seemingly has no rational basis, and does not constitute a proper reflection. And yet it is used in every so-called "physically based" shading function. If there is a good physical basis for it, I'd like to know.

What I've been able to find are a few reasons:

*It's faster* \- there's mixed information on this, but even so it would have been a great reason... in the year 1998.

*It handles angles higher than 90 degrees better* \- as far as I can tell the only reason for this is because the phong term has been used improperly. The dot product of the reflection and the view gives an angle between -1 and +1. Usually this angle is clamped to 0 to 1, this is the direct cause of the 90 degree problem. Re-normalize the angle instead of clamping it and you get the full 180 degree coverage. I refuse to believe a simple x * 0.5 + 0.5 operation has eluded the graphics world for 40 years.

*it handles edges better* \- The edge "problem" also exists in the blinn solution, just to a lesser degree. The main cause is improper simulation of area lighting at the terminator, which should be essential for any "physically based" shader. But even in simpler situations a sigmoid function can approximate a soft terminator line correctly. Multiplying into a lambert term is incorrect as it attenuates the specular term improperly, this could cancel out a fresnel term and lead to further errors.

*It has long reflections at the edge* \- It seems to me that while anisotropic reflections may be realistic, blinn is not the correct way to implement them, as they only appear at the edge. It is merely a happy coincidence that an error in the H term happens to look realistic.

None of these reasons are satisfactory, I want to sort out this madness.

I want to clarify that I am not talking about blinn and phong *specifically*, but instead about the vector components H and R, which are used as the basis for these shaders as well as others.

# Answer
I have discovered the reason for the H vector to be used. Unfortunately it is not the way it is used in most shading models, which can then be concluded to be incorrect.

For physically based shading reflected light must obey the fresnel equations. (Most "physically based" shaders don't) Microfacets must also obey the fresnel equations, which relies on the angle of incidence for the light as well as the index of refraction of the interface to produce a correct result.

According to the law of reflection the angle of incidence must be mirrored with the angle of reflection along the surface normal. For a ray of light to have hit the camera - which we know it did - it must have been reflected from the light - that we know the direction of. Thus the surface normal must by deduction be the mirror axis for these two directions. This gives us the half vector H which is in between them. Calculated by normalizing the sum of both.

Now by calculating the angle between the light direction L and the half vector H we acquire the angle of incidence for the specular reflection of a microfacet, and can correctly attenuate it using the fresnel term.

Note that the view direction is equal to R for that microfacet, H is not a reflection term. Blinn, Cook, Torrance, and Sparrow can suck it. Phong and Fresnel were right.
> -2 votes

# Answer
For perfectly reflective surfaces Phong-model makes sense. However, where does the n in (R.V)^n of Phong-model for approximating rougher surfaces come from? Where is the theory that you have to raise the result of the dot product to the power except that it just appears to empirically give the proper result?

For Blinn-model there's physically based microfacet theory to support all the components in the equation and there's also empirical evidence that the model approximates real world surfaces more closely (though not perfectly). The half-vector in Blinn model is used as an input to normal distribution function (NDF), which is an approximation how microfacets are distributed about surface normal as the function of the surface roughness. I.e. when H-vector points to the normal direction the value is highest since most microfacets point to that direction, and the probability is decreased accordingly when the angle between normal and H-vector is increased.

Blinn-model isn't perfect by any means though and it doesn't for example take the geometry term of the microfacet model into account (i.e. shadowing and masking of microfacets whose importance increases in grazing angles).
> 25 votes

# Answer
Actually, I think you yourself listed the reasons why Blinn is the default over Phong.

Each reason you listed there is, in fact, an area where Blinn proves superior to Phong.

Taken as a whole, all of these lead to Blinn being a better default than Phong.

Is Blinn perfect? Is it better than Phong?

No.

But it *is* a reasonable default. Feel free to substitute Phong for Blinn in any renderer/shader you write.
> 6 votes

---
Tags: shaders, fragment-shader, shading
---


# Question
Title: Determine percentage of screen covered by an object without using frustum culling
On the CPU-side of an 3D first-person / ego perspective game I need to check whether what the players currently sees on screen is the inside of a box object defined by world space coordinates (the player might be outside of that box but on screen sees only/mostly the inside of the box, or vice-versa, looks from within the box to the outside).

The "casual" way of performing such a check would incorporate frustum culling but such an approach would be hard to achieve with my given set of engine parameters which I'd like to avoid if there is a simpler way.

What I actually have at the point where I would like to do the check (high-level script on CPU, not GPU side):

* Camera world position
* Camera direction
* Camera FOV
* Two Box corner world coordinates (left-bottom-front, right-top-back)

What I do not have right away:

* View frustrum definition (near/far plane or say 6 planes defining frustum)
* Any specific pixel information (uv, view space position, depth or the like)

What I would like to calculate:

* **Percentage of screen "covered" by box.**

Any hints on how to perform such calculation?

# Answer
Here's a rough sketch of an algorithm that might do this.

Use the camera to calculate an inverse view projection matrix. Then transform **all** the cube's vertices using this matrix. You now have all the vertices in screen space (-1~1). Compute the convex hull of all these vertices and then clip this convex hull inside the screen space. You now have a polygon of which you can compute the area. The total area of the screens space is 4 so its easy to compute a percentage and this method is independent on resolutions and aspect ratios.
> 3 votes

# Answer
According to the book Real-Time Cinematography for Games, the fastest but least accurate way to do this is by calculating the projection of an object's bounding sphere onto the viewplane of the camera.

r = f\*r\_w / (**v** . (**p\_w** \- **q**))

Where:

f = focal length

r\_w = bounding sphere radius of the object

**v** = normalized camera direction

**p\_w** = bounding center of object

**q** = camera location

. = dot product

Finally, the area of the object on the screen space is:

a = PI\*r^2

Similarly you can project the 8 corners of the bounding box onto the screen plane and calculate the bounding box area.
> 0 votes

---
Tags: 3d, screen, bounding-boxes, frustum-culling
---


# Question
Title: How does Texture2D.GetData return coloured pixels?
I'm trying to work out how the pixels are stored in the returned array but I'm not having a lot of luck (and thus my calculations don't seem to be working).

I realize that the pixels are stored in one long continuous array but are the pixels grabbed width first or height first? I've tried drawing out the "pixels" of a texture on paper to calculate where the pixels should be based on the single array but I'm not getting expected results.

My assumption is the following:

Assuming I am using `i` to specify rows and `j` to specify columns that any given pixel in a 2D texture can be calculated by the sum of `i * j` or is this incorrect?

# Answer
> 2 votes
The answer to this question here should help explain how to use the GetData function.

Basically, the data is stored in the return array from the GetData call is formed by reading the 2D texture from left to right, top to bottom, transforming it as follows:

```
AAAA
BBBB  => AAAABBBBCCCCDDDD
CCCC
DDDD

```

To determine where a given pixel in the 1D array is, we use the index calculation of `i + (j * width)` should return the correct pixel at any given point.

Your assumptions is almost correct, you are just forgetting to take the width into account. Basically, multiply the Y coord (your j value) by the width of the Texture to select the correct start of the index block containing your pixel, then add the X coord (your i value) to select the correct pixel from that block.

In the sample above, assuming we want the value at (1,2), we have the following equation.

```
v = i + (j * width)
v = 1 + (2 * 4)
v = 1 + 8
v = 9
item at offset 9 = C

```

On 2nd though, that first link probably isn't the best, its just the first one I found with the required math. Here's another one that describes (sortof) how to use it.

---
Tags: xna, 2d, textures, color
---


# Question
Title: What needs to be done to port a Windows Flash game to Android?
My team has developed a game using Flash (with Lua embeded) that targets Windows. And we want to port that game to Android (also iOS in the future).

It's acceptable to rewrite the Flash part of client. And some other team in our company recommended Unity3D to replace the Flash part.

Since we have no experience in Android/iOS development, we would need to learn some new tool/language anyway. So we would like that learning still be useful after the porting and when we starting a new game.

Any thoughts?

**Edits:**

I think it is worth noticing the background of the game : the project is started by a tester and developer, both without knowing much about flex and actionscript. They built the game while learning, so most of the code is hard to maintain. I and other two developers joined the project after a year or so when one has leave (and the other be our manager). The other two developers are just graduates with little experience and little knowledge of flex. I am good at the server part and the c# language.

Based on the fact that the code is hard to maintain (and we do need to change a lot of code to make the game easier to playe in a mobile device), and I am good at c# (and learning). I still tend to do the porting with Unity, which could get better performance and possibly save time.

# Answer
> 2 votes
One of the many advantages of ActionScript 3.0 and Flash is that the content your create can be viewed on any device with little to no work (on porting) needed from the developers. To see your game on mobile devices, follow the instructions and if you get stuck on a certain step, please feel welcome to ask. Learning a whole new framework just to do what Flash is designed to do in another framework is wasteful at best. If you want to learn a new framework cause you wish to expand your horizons, that is not a question covered in the Q&A site.

http://www.gamefromscratch.com/post/2011/08/04/I-want-to-be-a-game-developer.aspx

Taken from FlashDevelop (The instructions are general):

**AIR for Android instructions**

> 1. Configuration:
>
> * edit 'bat\SetupSDK.bat' for paths to Flex SDK and Android SDK (default should be ok)
>     * install your device's USB drivers: http://developer.android.com/sdk/oem-usb.html
>     * enable "USB debugging" on your Android device: Parameters \> Applications \> Development \> USB Debugging
> 2. Creating a self-signed certificate:
>
> * run 'bat\CreateCertificate.bat' to generate your self-signed certificate,
>
> (!) wait a minute before packaging.
> 3. Build from FlashDevelop as usual (F8)
> 4. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter)
> 5. Install AIR runtime on your device:
>
> * run 'bat\InstallAirRuntime.bat'
> 6. Running/debugging the application on the device:
>
> 6.a. Build/Debug directly on device
>
> * edit 'Run.bat' and change the run target 'goto desktop' by 'goto android-debug'
>     * build & run as usual (Ctrl+Enter or F5) to package, install & run the application on your device
>
> 6.b. Debug occasionally on device
>
> * Debug-build from FlashDevelop (F8)
>     * run 'PackageApp.bat' to package and install a debug version of the application
>     * start FlashDevelop debugger: Debug \> Start Remote Session
>     * start the application on device
>     * the application should connect to FlashDevelop interactive debugger as usual
> 7. Packaging for release:
>
> * Release-build from FlashDevelop (F8)
>     * run 'PackageApp.bat' and select Android/normal target
>
> **AIR for iOS instructions**
>
> 1. Configuration:
>
> * edit 'bat\SetupSDK.bat' for path to Flex SDK (defaults should be ok)
> 2. Build from FlashDevelop as usual (F8)
> 3. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter)
> 4. Configure for iOS packaging in 'bat\SetupApplication.bat': Take a deep breath, pay the Apple tax and read extra carefully this tutorial:
>
> * http://www.codeandvisual.com/2011/exporting-for-iphone-using-air-27-and-flashdevelop-part-three-generating-developer-certificates-provisioning-profiles-and-p12-files/ Now this is how to create the p12 key entirely on Windows (steps 1. to 8.):
>     * http://connorullmann.com/2011/04/air-2-6-and-ios/ Then for each project you'll have to go to on Apple's iOS Provisioning Portal:
>     * create a new App ID with: name of the project and ID indicated in 'application.xml',
>     * create a new Provisioning Profile: select App ID & registered devices that will be allowed to install the app. Once you have obtained a .p12 and .mobileprovision file from Apple's Provisioning Portal:
>     * save a copy of your .p12 and .mobileprovision certificates in the 'cert\\' folder in your FlashDevelop project. (make sure to keep an extra copy of these 2 files in a safe place) Finally edit 'bat\SetupApplication.bat' and complete the following lines:
>     * IOS\_DEV\_CERT\_FILE: path to your iOS developer 'p12' key ('cert\\' folder, if you have followed the instructions above)
>     * IOS\_DEV\_CERT\_PASS: developer certificate's password if you don't set it, remove "-storepass %IOS\_DEV\_CERT\_PASS%" from the IOS\_SIGNING\_OPTIONS, you'll be prompted to type it when packaging.
>     * IOS\_PROVISION: path to the project's Provisioning Profile file For example: set IOS\_DIST\_CERT\_FILE=cert\iphone\_dev.p12 set IOS\_DEV\_CERT\_FILE=cert\iphone\_dev.p12 set IOS\_DEV\_CERT\_PASS=YourPassword set IOS\_PROVISION=cert\YourFileName.mobileprovision
> 5. Running/debugging the application on the device: Note: if are testing your application for performance, always package for release (see step 7.)
>
> 6.a. Build/Debug on device
>
> * edit 'Run.bat' and change the run target 'goto desktop' by 'goto ios-debug'
>     * build as usual (Ctrl+Enter or F5) to package
>     * you'll still have to manually upload & run the app on the device
>     * the application should connect to FlashDevelop interactive debugger as usual
>
> 6.b. Debug occasionally on device
>
> * Debug-build from FlashDevelop (F8)
>     * run 'PackageApp.bat' to package and install a debug version of the application
>     * start FlashDevelop debugger: Debug \> Start Remote Session
>     * start the application on device
>     * the application should connect to FlashDevelop interactive debugger as usual
> 6. Packaging for release:
>
> * edit in 'bat\SetupApplication.bat' to add your "distribution" certificate (IOS\_DIST\_CERT\_FILE) Note: you can package ad-hoc IPAs using your developer certificate.
>     * Release-build from FlashDevelop (F8)
>     * run 'PackageApp.bat' and select either iOS/"ad-hoc" for installation on test devices or iOS/App Store for upload in the iOS App Store.
>
> Tips: \- iFunBox: iTunes replacement; installs app faster even if app version doesn't change, \- TestFlightApp: ad-hoc distribution service http://testflightapp.com \- HockeyKit: self hosted ad-hoc distribution https://github.com/TheRealKerni/HockeyKit \- Manual ad-hoc distribution: http://samvermette.com/71

# Answer
> 0 votes
If you choose to use Unity you can also consider using GAF Converter http://www.gafmedia.com/ This tool converts Flash animations into a format that is supported by most development frameworks, including unity. You just need to install a free plug-in and you will be able to convert animations directly in Unity and use them right away.

There is an article on the Unity Forum where you can read the detailed instruction for using this tool.

# Answer
> -1 votes
I would suggest Unity3D as you mentioned. It is without a doubt the most resourceful game development tool on the planet at the moment. (bold but true)

You should be able to remake your client in no time with the resources Unity3D has available.

---
Tags: android, unity, flash
---


title: Enemy spawning problem

text:
# Question
Title: Enemy spawning problem
I've been trying to get my characters to spawn at random points through out the map. I have a camera which is following my main character (2D RPG Style) around the screen, but I want these "enemies" to spawn in random places amongst the map.

I can't seem to get this to work, no enemies are spawning. With my method `summonMonsters(showTime)` statement in 'render', it seems that my characters are spawning relative to where I am on the screen (so not at all).

What I really want is these entities to spawn within the map without the camera being on them or relative to me at all.

The coordinates I'm printing out as to where these enemies should be spawning shows ranges that should appear on the map, which is leading me to think they are spawning relative to the camera (where I am), which I don't want.

This is what I have so far:

```
public class PlatformerGame extends ApplicationAdapter implements ApplicationListener, InputProcessor {

    public static final String TITLE = "ADVENTURE RPG";
    private float time, speed = 160;
    public SpriteBatch batch, ui, showTime;
    private BitmapFont font;
    private float posX;
    private float posY;
    Maps maps;
    Random r;
    Player player;
    GameManager game;
    Monster monster;
    public float width, height;
    ArrayList<Monster> enemyMonster= new ArrayList<Monster>(); //holds the list of enemies as Monster
    boolean summoned = false;

@Override
public void create () {
    width = Gdx.graphics.getWidth();
    height = Gdx.graphics.getHeight();

    r = new Random();

    game = new GameManager();
    player = new Player(200);
    maps = new Maps(); //sets up the initial map
    monster = new Monster(20);
    setUpMonsters(); //sets up monsters

    batch = new SpriteBatch();
    ui = new SpriteBatch();
    showTime = new SpriteBatch();

    Gdx.input.setInputProcessor(this);

    font = new BitmapFont();
    font.setColor(Color.RED);
}

public void dispose(){
    batch.dispose();
}

@Override
public void render () {
    //clear the screens after every refresh
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    player.camera.position.set(player.sprite.getX(), player.sprite.getY(), 0); //camera follows the char around
    player.camera.update(); //update the camera, pass it to tilemaprenderer, then render the map
    maps.tiledMapRenderer.setView(player.camera);
    maps.tiledMapRenderer.render();
    batch.setProjectionMatrix(player.camera.combined);

    handleInput();
    checkCollisions();

    //these update the coordinates every render refresh
    posX = player.sprite.getX();
    posY = player.sprite.getY();

    batch.begin();
    time += Gdx.graphics.getDeltaTime();

    player.sprite.draw(batch); //draw the sprite to the batch

    batch.end();

    ui.begin();
    font.draw(ui, "Time: "+time, 50, 600);
    font.draw(ui,"posX: "+posX, 50, 550);
    font.draw(ui,"posY: "+posY, 50, 525);
    ui.end();

    showTime.begin();
    font.draw(showTime, "Time until next wave: " +game.roundTime, 1000, 650);
    summonMonsters(showTime);//if gametime is equal to zero, summon monsters
    showTime.draw(enemyMonster.get(0).img,posX,posY); //this just tests to draw the image
    System.out.println("GG: " + (20-posX) + ", " + (20-posY));
    showTime.end();
}

//create 5 new monster objects and add them to arraylist
public void setUpMonsters(){
    //int distance = 0;
    for (int i = 0; i < monster.NUMBER_OF_MONSTERS; i++){
        //distance +=5;
        Monster monster = new Monster(20);
        monster.setPositionXY((r.nextInt((int) width)), (r.nextInt((int) height))); //set enemies up in random places on map

        enemyMonster.add(monster); //add monster object to arraylist
    }
}

//draws the monster to screen
    public void summonMonsters(SpriteBatch batch){
        if (game.roundTime == 0){ //if roundtime is zero and it's time for another wave
            if (summoned == false){ //if minions havent been summoned already, summon them and draw to screen
                for (int i = 0; i < monster.NUMBER_OF_MONSTERS; i++){
                    batch.draw(enemyMonster.get(i).img, enemyMonster.get(i).getX(), enemyMonster.get(i).getY());
                    System.out.println(enemyMonster.get(i).getX() + ", " +     enemyMonster.get(i).getY()); //print out positions

                }
            }
            summoned = true; //when all minions are dead, set it back to false.
        }
    }

```

Monsters class:

```
public class Monster extends Entities{

    public Texture img;
    public Sprite sprite;
    private int health;
    public int NUMBER_OF_MONSTERS = 5;
    private int x, y; //x,y coordinate for set position
    Random r = new Random();
    GameManager game;
    PlatformerGame pg;

public Monster(int health){

    game = new GameManager();
    this.health = 20;

    //import img character and then set as a sprite
    img = new Texture(Gdx.files.internal("char/lydiachar.gif"));
    sprite = new Sprite(img);
}

//sets the position of the sprites
public void setPositionXY(int x, int y){
    this.x = x;
    this.y = y;
    sprite.setPosition((float) x, (float) y);
}

@Override
public void moveTo(float playerX, float playerY, float enemyX, float enemyY) {
    // TODO Auto-generated method stub

}

@Override
public float getX() {
    return x;
}

@Override
float getY() {
    return y;
}

```

# Answer
> 1 votes
You're monster locations are based on a random number:

```
monster.setPositionXY((r.nextInt((int) width)), (r.nextInt((int) height)));

```

You initialize width and height with:

```
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();

```

So your monsters will be placed on a random location in **screen coordinates**.

Now I'm not sure about your drawing code but it seems to me that you always only draw the first monster and draw it at the location of the player:

```
posX = player.sprite.getX();
posY = player.sprite.getY();

showTime.draw(enemyMonster.get(0).img,posX,posY);

```

It seems to me there are three bugs here.

1. Monsters should be placed on a location on the map so use map dimenisions
2. When drawing a monster the monster's coordinates should be translated from map coordinates to where that position on the map is on the screen right now.
3. Monsters are currently drawn using the player coordinates, not their own coordinates.

---
Tags: java, libgdx, software-engineering, rpg, eclipse
---


# Question
Title: html5 libgdx project: war to be deployed in a servlet container or only part of the contents to a web server
I am new to compiling games with libgdx to be played on the web and I have some doubts perhaps someone can point me in the right direction:

Using the new gradle setup I wrote a simple game to learn how to deploy a game to be played on the web, but I am not sure what files have to be uploaded to my server.

1) Where is the compiled code I should deploy?: In some places I found that the "war" directory has the files I need to deploy. In other places I found that the "build/dist" (generated running gradle's dist task) has the files.

2) What files should I deploy: The war directory gives me the hint I should deploy everything into a servlet container like Tomcat because, besides of the name, I have a war directory structure (it has a WEB-INF sub-dir). But in the badlogic info I found it says I only need to deploy Assets, html, and the index.html file to a WEBSERVER.

Note: Both ways work, so perhaps the deployment of the full war is to be done under certain conditions. So which would these conditions be?

3) I've read about the SuperDev mode to debug the app. When I run the application I get a SuperDev blue button in the browser. When I compile using GWT (I understand this generates production mode) I stilll get the blue SuperDev button. Do I have to remove it manually, or am I doing something wrong?

Please, can someone put a bit of light on this?

# Answer
> 4 votes
The question is a little stale, but in case it still helps:

After you run `./gradlew html:dist` to generate production code, you want to copy everything inside `./html/build/dist/` to your server. Running that command produces the code in that directory.

The code that's under the `war` directory and that has a Tomcat-like structure, I believe all that is for debugging. I think that is what gets produced from `./gradlew html:superDev`. Running that code from a server will work too, but I think it still has dependencies on java applets or GWT. The production code doesn't have those dependencies--it's just html and javascript running webgl.

And finally, you're right that the issue of SuperDev button is annoying. The HTML template for index.html is in `./html/webapp/index.html`, so you can take out the button there, but it will take it out for both production and debug builds. I don't know of a way to specify different templates for the two builds, so I just manually remove it before pushing to the server. All you have to remove it just that one anchor tag, and everything else works fine.

---
Tags: libgdx, html5, deployment
---


# Question
Title: Informing objects within a particular state of the world state
Following the State pattern, every state in my game is a derived object that reflects a particular segment of the game (MenuState, PlayingState, GameOverState, etc.)

Each of those state objects holds a container of objects pertinent to that world state (eg. menuButtonOBject for MenuState, playerObject/enemyObject for PlayingState, etc.)

For each frame, every object from that particular state makes a call to its update() method:

```
#include "GameState.h"
#include "GameObject.h"

class MenuState : public GameState {

    public:

    // member functions...
    virtual void update() {
        //pseudocode
        foreach (object in objectContainer)
            object->update();
    }

    private:
       std::vector<GameObject*> objectContainer;
}

```

My question being: what is the most common way to make the GameObject's update() method to have access to every other object in the state?

Eg: my veryBadassEnemyObject needs to know if the playerObject is within a particular x0,y0 -\> x1,y1 rectangular area.

The straightest approach I can think of is simply passing the object container to the update function as a parameter, but I have the feeling that there is a much more professional, better way to do it.

# Answer
> 1 votes
If the game design requires that some instances of creatures gain flexible access to certain data through methods or POD, it may be useful to inject this data as optional parameters to the constructor. See dependency injection and/or the Strategy pattern.

For instance `Sight`, `Hearing` and smell could be instances that provide information about visibility of and or the sound other objects are making.

These could be used to compute the needed data of how creatures senses their environment. The advantage is that you can control the state of creatures dynamically.

For instance, to simulate blurred vision, you could hand over a `Sight` instance adds a random vector to the result.

If you always need the same functionality for all creatures, it is not unheard of to simply include it in the class as a static member.

Please note that I am not suggesting access to every other object and rather, to an `ability` object that has access to other objects' data and returns only the needed information. For instance, `ability.whereIsPlayer(); //returns approximate player position` or `ability.whoIsVisible() // returns a collection of visible instances`?

---
Tags: c++, game-loop, oop, game-state
---


title: Problem building a color grading map

text:
# Question
Title: Problem building a color grading map
I am trying to build a default color grading map into a 1024x32 RenderTarget. Here is my shader code:

```
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position,1);

    output.TexCoord = input.TexCoord;
    return output;
}

float4 PixelShaderFunction(float2 TexCoord : TEXCOORD0) : COLOR0
{
    float temp = TexCoord.r*1024;
    float4 result = (float4)0;
    result.a = 1;
    result.r = (temp%32)/32;
    result.g = TexCoord.g;
    result.b = TexCoord.r;

    return result;
}

```

I'm using Catalin Zima's quad renderer to render the color grading map AND to render the contents of the texture back onto the screen. Here is the copy shader:

```
texture Texture;
sampler targetSampler = sampler_state
{
    Texture = (Texture);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = POINT;
    MinFilter = POINT;
    Mipfilter = POINT;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    output.Position = float4(input.Position,1);

    output.TexCoord = input.TexCoord + halfPixel;
    return output;
}

float4 PixelShaderFunction(float2 TexCoord : TEXCOORD0) : COLOR0
{
    return tex2D(targetSampler, TexCoord);
}

```

When I take the resulting image into the Photoshop, the bottom right pixel of the texture always equals (247, 247, 255), even though top left color equals zero.

What could be the problem? I checked the quad renderer class - it is recording texture coordinates exactly 0,1 into the quad's corners. I am aligning pixels to texels with the halfPixel and using point texture sampling. Somewhy the V component of texture coordinates never reaches one. I have no clue where the problem can be. As I plan to use this texture for color grading, the accuracy is crucial.

UPDATE: So far I can only achieve the needed result with the folowing shader code:

```
float4 PixelShaderFunction(float2 TexCoord : TEXCOORD0) : COLOR0
{

    float temp = TexCoord.r*1024;
    float4 result = (float4)0;
    result.a = 1;
    float m = (temp%32);
    result.r = m/32+0.035f*m/32;
    result.g = TexCoord.g+0.035f*TexCoord.g;
    result.b = TexCoord.r;

    return result;
}

```

Which is very wierd.

UPDATE 2: Ok, I had to modulo divide over 33 instead of 32, but I still have to correct the V coordinate.

```
float4 PixelShaderFunction(float2 TexCoord : TEXCOORD0) : COLOR0
{
    float temp = TexCoord.r*1024;
    float4 result = (float4)0;
    result.a = 1;
    float m = (temp%33);
    result.r = m/33;//+0.035f*m/33;
    result.g = TexCoord.g+0.035f*TexCoord.g;
    result.b = TexCoord.r;

    return result;
}

```

# Answer
Where did `0.035f` come from?

I believe your mistake comes from doing `(temp%32)/32`. If you take a look at it closely, you see that you get values in range 0..31, but you divide it by 32, which gives resulting values from 0 to 0.98675 (0 to 247 in RGB)

Correct code would be like so:

```
float4 PixelShaderFunction(float2 TexCoord : TEXCOORD0) : COLOR0
{
    float temp = TexCoord.r*1024;
    float m = temp % 32;   // range is 0..31, repeats 32 times
    result.r = m / 31;     // makes range 0..1 (RGBs from 0 to 255)
    result.g = TexCoord.g; // range 0..1 (RGBs from 0 to 255)
    result.b = TexCoord.r;
    result.a = 1;

    return result;
}

```
> 1 votes

---
Tags: xna, hlsl, color
---