title: Custom lookAt function goes wild

text:
# Question
Title: Custom lookAt function goes wild
I have written a custom lookAt function based on a lot of posts from all over the net, and it works very nice... except when a rotation (which is stored in a quaternion) crosses some 'threshold'. However, it works flawless when the camera's position is on the same horizontal plane as the model I'm lookingAt

On the below GIF, all I do is hold a key to lookAt the model together with a left arrow key to move the camera along the right vector:

My following understanding about how this function should look like (in a brief):

1 .Calculate a quaternion rotation needed to rotate an object from it's facing vector and a target vector.

1.a. Calculate an angle between those vectors by taking their dot product and a perpendicular axis by taking their cross product.

1.b Convert angle-axis info to a quaternion using this formula.

2 .Multiply the main quaternion rotation by the quaternion received above.

If I'm right, I believe that I may have a bug in my code, but I'm not sure. My code below:

```
lookAt: function(vec) {
    if (this.position.isEqual(vec)) {
        return;
    }
    this.rotation.multiply(new Quaternion().twoVecToQuat(this.rotation.getForwardVector(), this.position.sub(vec)));
    MVMatrix.setRotation(this.rotation.quaternionToMatrix());
},

```

// And the twoVecToQuat function based on Ogre3D quaternion library:

```
twoVecToQuat: function(v0, v1) {
    v0.normalize();
    v1.normalize();

    var dot = v0.dot(v1);
    // If dot === 1, vectors are the same
    if (dot >= 1) {
        return this.makeIdentity();
    }
    // If vectors are opposite
    if (dot < (1.0e-06 - 1)) {
        var fallbackAxis = new vec3().make(1, 0, 0);
        fallbackAxis.crossSelf(this);
        // If collinear, pick another vector
        if (Math.areScalarsSimilar(fallbackAxis.length(), 0)) {
            fallbackAxis.make(0, 1, 0);
            fallbackAxis.crossSelf(this);
        }
        fallbackAxis.normalize();
        this.axisToQuaternion(Math.PI, fallbackAxis);
    }
    else {
        var sDot = Math.sqrt((1 + dot) * 2);
        var invSDot = 1 / sDot;
        var tempVec = v0.cross(v1);

        this.x = tempVec.x * invSDot;
        this.y = tempVec.y * invSDot;
        this.z = tempVec.z * invSDot;
        this.w = sDot * 0.5;

        this.normalize();
    }

    return this;
},

```

**UPDATE:** Slin's solutions proved to be working (that one about calculating lookAt matrix), but I still don't know where is the bug in the quaternions library code. Working lookAt function below:

```
lookAt: function(at) {
    if (this.position.isEqual(at)) {
        return;
    }
    var zAxis = this.position.sub(at).normalize();
    var up = upVec(); // World's up vector instead of camera's up vector will unroll the camera
    var xAxis = up.cross(zAxis).normalize();
    var yAxis = zAxis.cross(xAxis);
    MVMatrix.make(
        xAxis.x,            xAxis.y,            xAxis.z,
        yAxis.x,            yAxis.y,            yAxis.z,
        zAxis.x,            zAxis.y,            zAxis.z,
        this.position.x,    this.position.y,    this.position.z);

    this.rotation.matrixToQuaternion(MVMatrix);
    this.copyEulerAngles();
},

```

# Answer
> 0 votes
I am not sure but this does not look like the formula you posted:

```
 var sDot = Math.sqrt((1 + dot) * 2);
 var invSDot = 1 / sDot;
 var tempVec = v0.cross(v1);

 this.x = tempVec.x * invSDot;
 this.y = tempVec.y * invSDot;
 this.z = tempVec.z * invSDot;
 this.w = sDot * 0.5;

 this.normalize();

```

Unless I do not understand some of the sine/cosine relationships or approximations, it should instead be something like this:

```
 var halfCosine = Math.sqrt((1 + dot) * 0.5);
 var halfSine = Math.sqrt(1 - halfCosine*halfCosine);
 var tempVec = v0.cross(v1);

 this.x = tempVec.x * halfSine;
 this.y = tempVec.y * halfSine;
 this.z = tempVec.z * halfSine;
 this.w = halfCosine;

 this.normalize();

```

But you could also just set your quaternion or rotation matrix directly instead of multiplying to it to get the same result. Calculating a look at rotation matrix is actually really simple as all you need is the direction to the target and two orthogonal vectors representing the up and right direction. Check this for more information: https://stackoverflow.com/questions/349050/calculating-a-lookat-matrix

---
Tags: javascript, quaternion, webgl
---


title: Projecting a light onto a quad

text:
# Question
Title: Projecting a light onto a quad
I need to project the light onto the quad and use its value for translating the vertices.

I'm currently having 6 vertices, two quads,
The points are A X C B Y D

Point X, Y are coming from two ray casting downwards.

```
C =  X + RightVector
D =  Y +  RightVector
A =  X - RightVector
B =  Y - RightVector

```

Now I want to translate the vertices based on lightDirectionVector, how would I do that ? I have a directional light, and that mesh of the two quads acting as a shadow quad.

```
    Vector3 lightDir = mDirectionalLight.transform.forward;
    Vector3 normLight = lightDir.normalized;
    normaLight.y = 0;

```

# Answer
> 0 votes
I am not sure if projection is actually the correct word for this, but I hope it is what you are looking for.

First you need the planes normal which is the cross product of the directions from one of your vertices to two of the others, which in case of your image could be C-A and B-A. (the three vertices may not lay in the same line, there is a simple mathematical term for it, but I guess I forgot it :( something with linearity...).

If you got the normal, you can calculate the closest distance of some arbitrary point of which your light direction is the position vector by building the dot product between your light direction and the normal.

Now you can calculate the position of that point within the plane by moving it along the normal towards the plane with the previously calculated distance: newdirection = direction - normal * dot(normal, direction)

But this will only give you the direction to the closest point on your plane to some arbitrary point defined by the light direction and I currently can´t get my head around if it really exactly is what you need or if it is only close.

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


title: LWJGL texture bleeding fix won't work

text:
# Question
Title: LWJGL texture bleeding fix won't work
I tried a lot of things to fix texture bleeding, but nothing works. I don't want to add a transparent border around my textures, because I already got too many and it would take too much time and I can't do it with code because I'm loading textures with slick. My textures are seperate textures and they seem to wrap on the other side (texture bleeding).

Here are the textures that are "bleeding":

The head, body, arm and leg are seperate textures.

Here's the code I'm using to draw a texture:

```
public static void drawTextureN(Texture texture, Vector2f position, Vector2f translation, Vector2f origin,Vector2f scale,float rotation, Color color, FlipState flipState)
    {
        texture.setTextureFilter(GL11.GL_NEAREST);

        color.bind();
        texture.bind();

        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);

        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);

        GL11.glTranslatef((int)position.x, (int)position.y, 0);
        GL11.glTranslatef(-(int)translation.x, -(int)translation.y, 0);
        GL11.glRotated(rotation, 0f, 0f, 1f);

        GL11.glScalef(scale.x, scale.y, 1);

        GL11.glTranslatef(-(int)origin.x, -(int)origin.y, 0);

        float pixelCorrection = 0f;

        GL11.glBegin(GL11.GL_QUADS);
        GL11.glTexCoord2f(0,0);
        GL11.glVertex2f(0,0);
        GL11.glTexCoord2f(1,0);
        GL11.glVertex2f(texture.getTextureWidth(),0);
        GL11.glTexCoord2f(1,1);
        GL11.glVertex2f(texture.getTextureWidth(),texture.getTextureHeight());
        GL11.glTexCoord2f(0,1);
        GL11.glVertex2f(0,texture.getTextureHeight());

        GL11.glEnd();

        GL11.glLoadIdentity();
    }

```

I tried a half pixel correction but it didn't make any sense because GL12.GL\_CLAMP\_TO\_EDGE. I set pixelCorrection to 0, but it still wont work.

# Answer
> 1 votes
Texture must be a square with measurements of an exponent of two (16, 32, 64, 128, etc...), so re-size the file to one of those. I tend to use 1024 X 1024 for item textures. Otherwise LWJGL gets all messed up and the texture 'bleeds.'

# Answer
> 0 votes
Since you are drawing a single texture onto a single quad at a time, shouldn't the texture coordinates of all the vertices be either 0 or 1 (all 4 permutations of that for each of the 4 corners)? Texture coordinates range from 0 and 1, 0 being the start and 1 being the end of the texture in s and t.

Namely:

```
    GL11.glTexCoord2f(0, 0);
    GL11.glVertex2f(0,0);

    GL11.glTexCoord2f(1,0);
    GL11.glVertex2f(texture.getTextureWidth(),0);

   // etc...

```

---
Tags: opengl, java, textures, lwjgl
---


# Question
Title: How can I repeat / scroll a tile which is part of an texture atlas?
I would like to scroll a tile which is part of a texture atlas like it can be done with a single quad and texture wrap mode set to repeat.

Can this be done? I hope it's clear what I would like to achieve.

Here is my shader code which I use to sample tiles from my texture atlas, but I can't figure out how to do the wrapping so that one tile repeats itself over time.

```
uniform float time
void main() {
  float texId = textureId/32.0;
  vec2 tileOffset = vec2(fract(texId)*32.0,floor(texId));
  vec2 offset = invTileCount * tileOffset;
  vec2 texCord = fract(vUv) * invAtlasSize + offset;
  vec4 texelColor = texture2D( uTex, texCord );
}

```

# Answer
> 2 votes
Shouldn´t this already do it? Assuming `vUv` to cover the whole 0-1 range for each tile. The `fract()` will make it wrap and then it is scaled and moved to actually fit your tile.

```
uniform float time
void main()
{
  float texId = textureId/32.0;
  vec2 tileOffset = vec2(fract(texId)*32.0,floor(texId));
  vec2 offset = invTileCount * tileOffset;
  vec2 texCord = fract(vUv+time) * invAtlasSize + offset;
  vec4 texelColor = texture2D( uTex, texCord );
}

```

The problematic part will be to handle the texture interpolation and mipmapping correctly if you need it. `textureGrad()` might be helpful, or you just implement it completely yourself using `texelFetch()`.

---
Tags: glsl
---


# Question
Title: How can I make an AI agent avoid screen edges?
I'm programming an AI agent and I want them to avoid the screen edges. I've been considering using either the *obstacle avoidance* or the *fleeing* behaviour. Do either of these make sense?

How should I approach this?

# Answer
First thing first, creatures should not avoid the "edges of the screen" because that is part of the *View* and not the actual *Game Model*. Game Entities should interact with the *Game Model* and not the *View*. The view is only the way you present the game to your game's players eyes.

Secondly, what you are asking of has little to do with Obstacle Avoidance steering behavior because these techniques were mostly designed to help finding a none-collision path through obstacles or avoiding moving obstacles (see this for more info).

It also should have little to do with fleeing because that is conceptually useful in building distance from moving creatures. If something is trying to get away from the edges of the screen as much as possible, it may just stay in the center of the screen.

## How to avoid the edges of the screen

If the game type is a brawler (beat'em up) or a platformer, you could make it so that if the distance from the camera is greater than `Width / 2` on axis-x or `Height / 2`, on axis-y, the creature will move towards the camera until it is close enough. Alternatively if there are obstacles, the creature could find a path to some spot close enough to the camera and stop once it is near enough.

Normally a creature follows a path. Sometimes the path is generated with a path finding algorithm such as A\*. Other times the path is picked in advance by the games' creators. If the path is picked in advance and the edges of the screen don't move, it could be selected so it doesn't move through obstacles or outside the edges of the screen.

If the path is created by a path finding algorithm, the edges of the screen could be marked as an impassable obstacle and avoided.
> 1 votes

# Answer
How close to an edge do we care about?

For a fairly thin threshold, avoiding the edges is quite closely approximated by finding the *closest point* on the edge and avoiding that:

For a thick threshold, it's a good approximation to just steer toward the center of the screen:
> 1 votes

---
Tags: ai, viewport, steering-behaviors
---


title: In regards to applet games and UDP

text:
# Question
Title: In regards to applet games and UDP
I've got about a year in Java experience, and would like to set up a server and client for an applet game. However, there doesn't appear to be any tutorials out there on anything like I want to use.

I would the server to be able to store an array of x and y coordinates with a player name somehow associated to them, and send them to multiple clients in a short time span. I would like the client implemented in the applet, and be able to request any player's position data.

I'd like to use UDP, because it seems to be the best option for efficient (if less reliable) transmission of data.

If anyone could give me some pointers on how to do such a project, or point me to an appropriate tutorial, I'd certainly appreciate it.

# Answer
The problem in network programming is, that everything you want to send has to be serializable in some kind. So if you have different objects with attributes you have to collect all data in a way you can send them via UDP

So if you have a ball and a box with some kind of coodinates

ball: x:10 y:20 box: x:50 y:50

you should make them parseable that your server can parse them back.

A way of doing this could be putting everything in a string

"ball{x:10;y:20};box{x:50;y:50}" or generating some kind of valid XML (but XML has a lot of overhead just for a nice format)

How to implement a UDP Server/Client you could use the examplecode from http://systembash.com/content/a-simple-java-udp-server-and-udp-client/

You want to use UDP so you cant be sure that all of your packets will reach the clients. Therefore you sould implement some kind of timestep synchronisation, that the server could use to simulate the movements of the players even if he didn't receive any data from a player.

To do this the Server counts its own time and sends it to the clients when they login. From there on the clients count their own time relative to the servers time and sends their relative steps with the data to the server. So the server "knows" what client didn't sent data in the current timeframe (or what data just didn't got to the server)
> 3 votes

# Answer
I actually like Aron\_dc's answer, but i thought I would add an answer to provide additional things to consider.

1) UDP vs TCP - You have to choose a particular protocol and understand the cost and benefits. Picking UDP is quicker, but you have to create your own control code on top of UDP, common problems with UDP : packet loss, firewalls, packets out of order and knowing when the client has disconnected (using timers and "are you alive" packets). With UDP you may have to think about storing packets, numbering them and resending them if they don't get acknowledge. It maybe a bit of a headache for the first time.

2) Multiplayer component design:

* State machine : how many states the client may have : connecting, playing, disconnecting, changing level?
* Components : What are you sending to the client and to the server? Login information, inventory, movement, chat.
* Acks/Nacks : If something happens in the game : like a player dies or wall get destroyed, does every client have to say "yeah i got that information", because if the don't the game state will desynchronize and everyone will be playing their version of the game. (PS: I played a game once with bad multiplayer code and it was kind of funny to know that while I was winning the game on my machine, it was not the case on the other player's machine.)

3) Serialization

You need to have a good handle on understand serialization, as it will also help you write save/load game functionality as well. Essentially it is taking your objects and storing them in a different format. So for example you want to serialize movement message.

```
MovementMessage(int x, int y, int z);

toByte(...)

byteBuffer.write(MOVEMENT_MESSAGE_TYPE); // a unique number that lets you know it is movement message
byteBuffer.write(x)
byteBuffer.write(y)
byteBuffer.write(z)

fromBuffer(...)

messageType = byteBuffer.readInt();

switch(messageType) {
   case: MOVEMENT_MESSAGE_TYPE;
       msg = new MovementMessage()
       msg.x = byteBuffer.getInt();
       msg.y = byteBuffer.getInt();
       msg.z = byteBuffer.getInt();
   break;

```

If you want to send multiple messages in one packet you may add additional details to your protocol, for example

```
[how many messages] [first message] [second message]
02 01 1 2 3 01 2 3 4
two messages, first message is of type 01 with data 1,2,3 and second is also type 01 with data 1,2,3

```

4) Library:

There are two libraries that I am thinking of right off the bat : Google Proto Buffers and Java Netty. I have had a lot of experience with java netty and use it in my projects. It has example for clients and servers. There are probably more.

5) Examples:

When I do multiplayer research, I usually try to find out how the other guys did it. I look up information on Quake, Unreal and other popular titles and read up how they designed their multiplayer component. Once you can understand the design the rest is just picking the right code to do it.
> 0 votes

---
Tags: java, udp
---


title: Calculating ball trajectory in Pong

text:
# Question
Title: Calculating ball trajectory in Pong
I'm making a Pong game and I'm just looking for a simple way to calculate a straight travelling path for the ball based on the angle of the ball. How would I go about implementing something like this? Here is my code right now:

```
public void UpdatePosition()
{
    //For now let's just implement a very primitive movement algorithm
    //TODO: Movement calculation based on angle of the ball
    ball.velocity = (ball.angle < Math.PI / 2) ? 5 : -5;
    ball.Point = new Point(ball.Point.X + ball.velocity, ball.Point.Y + ball.velocity2);

    //Check if the suggested point is beyond the boundaries of the window
    if (ball.Point.X > ball.view.Boundaries.Width || ball.Point.Y > ball.view.Boundaries.Height || ball.Point.X < 0
        || ball.Point.Y < 0)
    {
        ball.Collision(CollisionType.Boundary); // If it does raise collision event
    }

    //Check if the new point collides with the hitbox of a player paddle
    if (ball.gameController.Players[0].Paddle.GetHitbox().Any(point => point.Equals(ball.Point)) ||
        ball.gameController.Players[1].Paddle.GetHitbox().Any(point => point.Equals(ball.Point)))
    {
        ball.Collision(CollisionType.Paddle);
    }
}

```

# Answer
Velocity is a 2-dimensional value, representing the speed in both the X and Y directions. I notice you have `velocity` and `velocity2`; it might make things easier to use a 2D vector for velocity, like you do for position.

To calculate the speed in the X and Y directions, just multiply your total speed by the cos (for the horizontal component) and sin (for the vertical component) of the angle.

```
ball.velocity = new Point(5 * cos(ball.angle), 5 * sin(ball.angle));

```

Then because your velocity is also a 2D vector, you can just do:

```
ball.Point = ball.Point + ball.velocity;

```
> 2 votes

---
Tags: c#, mathematics, pong
---


title: UDP server and large number of users?

text:
# Question
Title: UDP server and large number of users?
My initial research showed the most people prefer to use UDP protocol and build a control code on top of it for multiplayer games. It seems like a good design at first, but I am wondering if it is really the best in the long run.

For example, what happens if your game goes from 64 players to 500, 1000, 20 000

Is the UDP port going to overflow and start dropping incoming packets? Is the overhead that you wrote for UDP-reliability going to be less optimal when you start using more bandwith? (I.e. the server will spend significant cycles managing features that may already be present at the hardware and network level that are built into TCP)

I am considering re-writing a server that initially used UDP+reliablity protocol and splitting it into two cluster servers to handle different regions as well as introducing a load balancer in the middle. The UDP design is starting to look a little more complicated and having a large number of NPCs and state synchronization that may have to take place is making me reconsider UDP.

# Answer
> 3 votes
The UDP port is only going to overflow if your program cannot handle the number of incoming packets at least as fast as they are being sent to your PC. While TCP will lead to your program itself needing to inspect less packets (since you only get reliably ordered packets and the rest are discarded by the networking level) I do not believe that I have ever heard of a programming, or networking interface, to choke because of the number of packets to handle.

As for the complexity of a reliable-UDP based solution this should be solved using abstraction. At the game programming level you should not be able to notice if reliable-UPD or TCP is used. You should even be able to switch between the two without having to change any game code. Basically what you want from your networking interface is just to know for sure that it will arrive (in order).

Why not take a look at the excellent networking library lidgren, its a .NET library but even if you're not using .NET you should be able to learn a lot from it.

In general, make sure you're using the right techniques for the right reasons. Using a technique because everybody else uses it can lead to disaster. You should always try to understand the reason for a technique, only then you can make an informed decision.

---
Tags: networking, mmo, udp
---


# Question
Title: Can I render some vertices as an object instead?
I am generating vertices at runtime that represent terrain.

I've always drawn the vertices as triangles with `GraphicsDevice.DrawUserPrimitives<VertexPositionColor>`, but I'm wondering: Can vertices be converted into a "Model" so I could handle model and terrain rendering in a unified way?

This page is quite similar to what I am searching for.

I want to later port my game to Mono. Would this approach cause problems when using the Content Pipeline to convert the data?

# Answer
> 3 votes
The official answer from Shawn Hargreaves (one of the developers of XNA) is

> The XNA Model class doesn't do any optimization at runtime: that all happens at build time inside the ModelProcessor. This is exactly why it is impossible to create a Model instance at runtime: the Model class depends on the processor to have optimized its data ready for rendering. If you are generating your data procedurally at runtime, there is no place for those optimizations to happen, so you're as well off just using your own standalone class.

Source: http://social.msdn.microsoft.com/Forums/en-US/cd49df6b-21b1-48a5-89ef-77d22cba2e1a/how-to-procedurally-generate-models-at-runtime?forum=xnagamestudioexpress

I do not believe this behaviour has changed. But of course you can create a wrapper class yourselves so that you can handle a series of vertices and Models in a unified way.

---
Tags: 3d, xna-4.0, terrain-rendering
---


# Question
Title: What dimensions should you use for a perspective projection frustum?
What dimensions should you use for a perspective projection frustum? Initially I created a perspective matrix based on the width and height of the screen, with a calculated zNear value based on a 45degree FOV.

```
// OpenGL example
// For height of 800, zNear is calculated to be ~965.
zNear = (height / 2.0f) / tan(Deg2Rad(45.0f) / 2.0));
zFar = 100000.0f;
glFrustum(-width / 2.0f, width / 2.0f, -height / 2.0f, height / 2.0f, zNear, zFar);

```

But then I realised that this isn't a sensible idea and you shouldn't base your frustum on pixels, and you should use logical units instead (else when the window / screen changes size, objects will change position or size).

So now I'm wondering what dimensions I should use for the logical planes of the frustum? How do you choose a zNear value? Is it sensible to base it on the desired FOV? I'm aware that having a small zNear value can mess with the z-buffer, which is why I initially based it on the FOV.

My current thoughts are of using a logical near plane of TopLeft: -10000, -10000 and BottomRight: 10000, 10000. But then that generates a zNear value of ~24142 based on 45degrees FOV, which seems awfully high. What advice do you have? What dimensions should you use for a projection frustum?

# Answer
`zNear` and `zFar` are measured in world space, not in anything to do with pixels. Their scale will depend on the scale of the scene you're rendering and how close/far the camera will be to the geometry. For instance, if your scene is modeled in meters, you might set zNear to 0.1 and zFar to 1000 or so. This would let you get the camera as close as 10 cm from the geometry before it starts clipping, and let you see distances of up to 1 km. You can adjust these values if you have a smaller or larger scene or if you use different units.

For most cases, it's simpler to use `gluPerspective` instead of `glFrustum`. That lets you work in terms of the FOV and aspect ratio, which is more convenient than the width/height of the image on the near plane. If you compare the formulas listed in the docs for `gluPerspective` and `glFrustum` you can see how these functions correspond to each other. They do the same thing, except that `gluPerspective` has more convenient parameters, and doesn't handle off-center frusta (which are uncommon anyway).
> 5 votes

# Answer
zNear is not really related to field of view. FOV specifies the angle of the frustrum, while zNear describes the distance to the nearest clipping plane. As an example, here are two frustrums with the same FOV, but different near clipping planes.

And here is another frustrum with the same zNear as the first, but different FOV.

A good approach to clipping planes is simply to put the zNear as far away as possible and the zFar as near as possible, while still encompassing your world. Putting zNear closer to the camera than any world object will ever sit is a waste of Z-buffer values that will never be used. If your world isn't very large, you don't need to worry about this too much, as you have plenty of Z-buffer to spare. If you're trying to render an insect 1cm from the camera at the same time as mountains 10km away... you'll probably experience some issues with Z-buffer precision!

As the diagrams should hopefully illustrate, it's actually the width and height of the frustrum that really depend on FOV.

And finally, a tip that really helped me: there are helper functions to ease the calculation of frustrums. Check out gluPerspective(). Instead of doing the math yourself, you just pass it FOV, aspect ratio, zNear, and zFar, and it will helpfully calculate the other 4 boundaries of the frustrum for you.
> 3 votes

---
Tags: opengl, 3d, matrix, projection, frustum
---


# Question
Title: How would I apply my isometric art onto isometric CSS with correct Z-indexing
I have been trying to wrap my head around how to apply my isometric art

into an array like so with correct z-indexing

In the long run I want to be able to select a specific tile and depending on what tile it is I can choose a different function via drop down.

I'd appreciate any help. Even links to isometric documentation on putting images onto tiles. Or even how to successfully put an isometric tile onto a div without it being selectable on the transparent parts of the tile.

Sorry if this was hard to understand.

# Answer
> 2 votes
When laying out your tiles you can use their xy-coordinates to determine what z-index to give them. Just add together the x and y values then add one to produce the z value.

Examples:

* `(0, 0) = 0 + 0 + 1 = 1`
* `(0, 1) = 0 + 1 + 1 = 2`
* `(3, 3) = 3 + 3 + 1 = 7`

# Answer
> 0 votes
The simplest solution I think would be to make another array the same size as the one you are using to display things with, perhaps call it the "depth array". You can by-hand fill in the z values into this array, or have some code to do it. This way you can use index for the on screen array as a lookup for z values into the "depth array".

# Answer
> 0 votes
Its 4 am and I am going to bed. But I figure that this might help you.

I found an old script where I did some Isometric stuff.

```
var x_map = x_map_base + (x * (tile_w / 2)) + ((y * tile_w / 2));
var y_map = y_map_base + (x * (tile_h / 2)) - ((y * tile_h / 2));
var x_obj = x_obj_base + (x * (tile_w / 2)) + ((y * tile_w / 2));
var y_obj = y_obj_base + (x * (tile_h / 2)) - ((y * tile_h / 2));

```

I havent tested it for a long time. But it might help you along the way:

index.html

Server - Basically just a 2D array

Grab the files and take a look.

Good Night.

---
Tags: javascript, isometric, css
---


title: Saving resource

text:
# Question
Title: Saving resource
I'm trying to develope a simple platformer on Java, I was wondering if is it better to handle the collissions in a level (player with floor, player with enemy ecc...) by a level handler class which controls all the elements in the level or pass the elements in the level to each elements and then check if collide with itself.

# Answer
This is more of a design decision, since objects are implicitly references in Java, so it really doesn't make much difference to be copying an extra reference. I'd suggest you just do whatever works first and then, if you feel you need to, start to optimise/change things and see if you get a better result. That's the best way to learn.
> 2 votes

---
Tags: java, collision-detection, platformer
---


title: Performing manual clipping in OpenGL

text:
# Question
Title: Performing manual clipping in OpenGL
I'm learning OpenGL and I understand that OpenGL performs clipping as part of the pipeline, but is it a good idea to also perform manual clipping? By manual clipping, I mean not asking the GPU to draw an object if I'm certain it won't be visible on the screen.

The advantage I can think of is that the GPU will not be wasting time on executing the vertex shader only to find out the primitives are to be discarded. On the other hand, performing calculations on the CPU may cause the overall performance to decrease. I believe the world terrain model is loaded once and so it isn't a good idea to perform manual clipping for the terrain and reloading selective parts on the GPU's memory, but maybe doing this for things like trees boost performance.

Thank you!

# Answer
Yes, this is a good idea in general, though it's usually called culling - not clipping.

There are two basic kinds of culling:

1. Frustum culling tries to eliminate objects that aren't in the view frustum, i.e. are behind the camera or too far to the side to be visible on screen. This is commonly done by doing a conservative intersection test of an object's bounding box versus the frustum - for instance, testing if all eight corners of the box are outside the frustum on the same side. This is a fast and easy test that gets rid of the majority of the objects that aren't in the frustum.
2. Occlusion culling tries to eliminate objects that are in the field of view, but not visible because they're hidden behind other objects. This is generally more difficult. There are various methods, and Google can tell you more.

As you say, culling per-vertex on the CPU is overkill since the GPU can do that more effectively. CPU culling is normally done at the per-object level, which allows you to remove the overhead of graphics state changes and draw calls for culled objects.

For large worlds with thousands of objects, it often pays off to have the objects arranged in a hierarchy such as a BVH or octree, which allows culling to be done at a higher level and eliminate many unwanted objects at a time.

Culling is a huge topic and this answer barely scratches the surface of it, but google around a bit and you'll find much more.
> 4 votes

---
Tags: opengl, clipping
---


# Question
Title: Two issues with testing LibGDX on Android
1) When I test my game on desktop it is 100% fine. When I test it on my Nexus 7 physical device, it is the same except the backgrounds have no color. For example my splash screen has a greenish background, On desktop this is visible, on android it's just a white background.

Splash screen:

```
@Override
public void render(float delta) {
    manager.update(delta);
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    backgroud.begin(ShapeType.FilledRectangle);
    backgroud.setColor(147, 112, 219, .4f);
    backgroud.filledRect(0, 0, Gdx.graphics.getWidth(),
            Gdx.graphics.getHeight());

    backgroud.end();
    batch.begin();

    leftLogo.draw(batch);

    batch.end();

}

```

2) When running my game on an Android emulator, it just shows up as a blank black screen on so far 5+ different emulators. What does this usually mean? No errors anywhere.

I also have `cfg.useGL20=true;`

# Answer
Have you tried a newer version of LibGDX? Support for GL 1 was removed a while ago so it seems that you're using an old version. It might fix the problem. If that doesn't work, can you show the rest of your code?

Edit: Oh, and maybe change GL10.GL\_COLOR\_BUFFER\_BIT to GL20.GL\_COLOR\_BUFFER\_BIT

Edit2: Okay, I noticed a few other things you can try. First, I think that the buffer bit part has to go before glClearColor(), not after. Second, when setting the color of backgroud you might try it with an alpha value of 1.0 and not 0.4, not sure why you would want to do that since you clear the screen beforehand so it won't be see through anyway.

Edit3: Last thing: you forgot to set the camera of the batch(es) it seems. Create a class variable "private OrthographicCamera camera;" in your class, and in the create function initialize it with "camera = new OrthographicCamera()". Paste this line afterwards: "camera.setToOrtho(false, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());". What this does is it initializes a camera and sets the bottom left of the screen to (0,0). Now you just have to initialize the batch before calling batch.begin(). Paste this before batch.begin(): "batch.setProjectionMatrix(camera.combined);" Take a look in the docs at the pages about cameras and spritebatches for more information. Also, I think you also have to do this for the backgroud variable, but you can probably figure that out yourself ;-)
> 1 votes

---
Tags: android, libgdx, rendering
---


# Question
Title: irrlicht: drawing two textures with draw2dImage issue
Im just starting out with irrlicht (and c++) for 2d development and I followed the 2d tutorial, so I am able to draw a 2d texture on the screen (With draw2DImage) this seems to work fine.

So I made a seperate class where I draw a ship and also change it's position in the Update function, but here I run into a problem. The ship is drawn twice when I change it's position.

```
void Ship::Draw(irr::video::IVideoDriver * driver, irr::video::ITexture* texture) {
driver->draw2DImage((texture), this->position);
}

void Ship::Update(float gameTime) {
this->position.set(this->position.X += 1, this->position.X += 1);
}

```

The ship is drawn once on its original place (I guess 0,0) but it seems asif the ship is being copied and then that copy is.

in my main.cpp I have this:

```
ship1->Update(1);
ship1->Draw(driver, shipTexture);

```

(Also, the ship's texture is cut off after a while(as seen in the screenshot)).

And also, when I don't 'move' the ship (so I just change it's position once at startup (i.e. this-\>position.X = 100 this-\>position.Y = 100) then it behaves normally, so maybe there is something wrong with the way I set up everything?

# Answer
> 1 votes
I managed to fix it. The problem was indeed my main loop.

What was causing the issue was that I was using the wrong driver when creating my device. My code for creating a device was this :

```
IrrlichtDevice *device = createDevice();

```

But this apparently uses the wrong video card driver, so I had to pass one manually like so:

```
IrrlichtDevice *device = createDevice(video::EDT_OPENGL, core::dimension2d<u32>(1024, 720));

```

This seems to have solved the issue for me!

# Answer
> 0 votes
This seems that the screen buffer is not being cleared.

Make sure you have something like `driver->beginScene(true, true, video::SColor(255,0,0,0));` in your main loop.

---
Tags: c++, 2d, irrlicht
---


# Question
Title: XNA: How to make particles face the camera but not alter the pitch
I'm using the particles sample from create.msdn.com/en-US/education/catalog/sample/particle\_3d which by default, has all the particles look straight at the camera. I'm trying to modify it so that the particles will still look at the camera but won't rotate up and down. I think these are called billboard particles but I'm not really sure.

**Edit:**

This is what I have in the shader now. It seems like its working but the particles are really tiny. What did I do wrong?

```
float4x4 billboardRotation = CreateConstrainedBillboard(output.Position, CameraPosition, float3(0, 1, 0));

output.Position.xy += mul(input.Corner, rotation);
output.Position = mul(output.Position, billboardRotation);
output.Position = mul(mul(output.Position, View), Projection);
output.Position.xy += size * ViewportScale;

```

# Answer
Sprite billboards can be of two types:

* Spherical: they look always at the camera.
* Cylindrical/constrained: you define a constraint axis and they always try to face the camera, but rotating along that axis. This is the kind you are aiming for.

So, instead of using `Matrix.CreateBillboard` when creating the world matrix for your particles, use `Matrix.CreateConstrainedBillboard`. The only difference is that you need to specify the object's rotation axis instead of the camera up vector, and the optional `cameraForwardVector` and `objectForwardVector` to smooth possible deformations when the camera is too close.
> 3 votes

# Answer
I haven't had the time to test this, but after looking through the sample's code I believe you'll need to do a few changes for it to work. Here's what I have in mind, although I'm not sure it will work as it is:

**The Sample**

For starters, the way the particles are being billboarded at the moment doesn't allow for much variation. Each vertex basically carries the particle position and a 2D corner offset such as (-1,-1) or (1,1).

The GPU does all of the particle animation, applies the view and projection matrices to get it into clip space, and then adds the corner offset multiplied by the particle's size to the clip space XY position. Since this sum is done in clip space, the resulting quad will always be facing you. No billboard matrix anywhere.

**The Solution**

You'll need to change your shader in order to apply the billboards in a more traditional way using a matrix. Using the method r2d2rigo mentioned (Matrix.CreateConstrainedBillboard) you'll need to calculate a billboard matrix for each particle and pass it to the shader when drawing.

Then you'll need to change the method in the shader that is currently applying the View and Projection matrices and leave that part out, because you still need to do a few other things before converting to clip space.

With the position still in world space, that's when you will need to apply the corner offset, along with the billboard matrix you created before to make it face the camera.

Finally just apply the View and Projection matrices as it was done originally in the sample.

**Or...**

Start from the billboard sample instead and adapt it to your particle needs. That might turn out to be easier.
> 2 votes

# Answer
I guess it's a little late to post this answer, but, I was struggeling for a few days with the problem as well.

I started from the gpu particle sample from Microsoft and wanted to make it rain. This was one difficult task, But in the end I was surprised that just a few things need to be changed after all.

All I did was changing the CalculateParticlePosition like you did. I just return the plain Position. No View or Projection multiplications involved.

Then I changed some things in the VertexShader and now it runs correctly.

The last Line of the **ComputeParticlePosition**-Line has to look something like this.

```
return float4(position, 1);

```

Here are the changes I made to the VertexShader

```
VSO_Particles VS_Particles(VSI_Particles input)
{
VSO_Particles output;

// Calculate the Particle's age
float lAge = CurrentTime - input.Time;

// Randomize the Age
lAge *= 1 + input.Random.x * DurationRandomness;

// Normalize the Age
float lNormalizedAge = saturate(lAge / Duration);

// Calculate the World Position for this Particle Vertex
output.Position = CalculateParticlePosition(input.Position, input.Velocity, lAge, lNormalizedAge);

// Calculate the Size and rotation for this Particle
float lSize = CalculateParticleSize(input.Random.y, lNormalizedAge);
float2x2 lRotation = CalculateParticleRotation(input.Random.w, lAge);

// These Lines are new, you need to pass the CameraPosition to the shader
float3 ParticleToCamera = output.Position.xyz - CameraPosition;
float3 ParticleUp = float3(0, 1, 0);
float3 ParticleRight = normalize(cross(ParticleToCamera, ParticleUp));

// Apply the Particle's Rotation to the current corner
float2 CurrentCorner = mul(input.Corner, lRotation);

// Then you need to place the Particle's vertices according to their Up and side Vector
output.Position.xyz += ((CurrentCorner.x * lSize * ViewportScale.x) * ParticleRight);
output.Position.xyz += ((CurrentCorner.y * lSize * ViewportScale.y) * ParticleUp);

// and shift to Screen Space
output.Position = mul(mul(output.Position, View), Projection);

output.Color = CalculateParticleColor(output.Position, input.Random.z, lNormalizedAge);
output.UV = (input.Corner + 1) / 2;

// Pass a copy of the ScreenPosition
output.ScreenPosition = output.Position;

return output;
}

```

And that's that. This works for me to get constrained Billboard Particles.

I hope this will help at least somebody who's dealing with the 3D Particle Sample by Microsoft for XNA 4.0.

Cheers Dekurian
> 1 votes

---
Tags: xna-4.0, particles
---


# Question
Title: Entity/Component System and UI "Entities"
I'm still green to entity/component systems. I find that since I have useful components for drawing sprites (or spritesheets) and handling input (mouse/touch clicks), I naturally want to reuse these to create UI components (like buttons, eg. level-select screen).

This strikes me as very odd. I always understood entities as "game model" things like players, enemies, power-ups, etc. On the other hand, from a code-reuse perspective, reusing compnents for UI makes perfect sense.

How (and where) do UI/GUI concerns fit into an entity/component system?

(Note: this question is platform agnostic since it applies to multiple platforms/languages)

# Answer
> 5 votes
After using several entity-component systems, especially CraftyJS, I more or less got the answer to my question: yes, you can reuse components (especially sprites or images and mouse-click handlers in 2D games) for the GUI.

Much of the time, you only have access to the ECS, and not the underlying systems (eg. drawing system). In this case, it's okay to use components, since you have no other choice.

If you do have access to the underlying system (eg. Ruby roguelike with direct access to Curses), you may find that drawing/rendering directly on that system is more effective (less code, less fragile, more natural) than using a bunch of entities and components.

# Answer
> 2 votes
In 2D or 3D, an entity component system (ECS) should at least have access to the GUI system, if it's not part of the same ECS.

Personally, I wouldn't mix the two. The reusability of code for a GUI only really happens at the top level. Responding to the mouse/keyboard, rendering, and so on. The functions that different buttons take, or the information that certain lists display isn't really something that can be made generic enough to reuse.

For example, I would imagine the components for GUI entities would be something like `position`, `render` and `gui`. Where the GUI component would define the type of action the GUI entity takes. However, that action is going to be pretty unique and context specific. This results in the system that handles GUI components being very large and essentially designed to handle each of the GUI functions (load game, save game, find server, etc). Sounds messy.

I'd prefer to do a standard class file for each GUI "screen". Have all the functionality for that screen in one place (with references to a common functionality class). It's a lot neater and easier to manage.

However, as I said, the ECS should have access to the GUI system. It needs to be able to supply information to the GUI based on entities in its systems. For example, hovering over an allied unit would pop up a GUI window with all the information about that unit. Where hovering over a enemy unity would pop up a GUI window with limited information. You likely don't want to program the GUI to know the difference between the two, you want to ask the entity to display its information.

So, entities will still likely have some kind of GUI component, but they'll be "in game" entities, not GUI entities. This component will use the external GUI system to create their GUI interface.

---
Tags: 2d, component-based, gui
---


title: Java application: How to play sound

text:
# Question
Title: Java application: How to play sound
Hello I have a game that has a title menu and I want to play music in the title menu. The game is an application NOT an applet. *(and I'm not changing it)* I saw a video where he uses sun.audio pckage, But when I tried it I got an error when I was writing the code. Access restriction it says. Do I have to download files or what do I need to do.

# Answer
For decent sound support, the standard approach in Java engines is to use OpenAL. Aside from being fuller-featured, this will solve your problems with access restrictions, implicitly.

OpenAL is found in wrappers like LWJGL and engines like JMonkeyEngine and LibGDX. It is the *de facto* standard for sound in games across languages and platforms.
> 2 votes

---
Tags: java
---


# Question
Title: Should I be concerned about assets being accessed by dumping VRAM?
I have heard many people tell me that a user can dump the VRAM on their GPU and get all the images in my game. Including all "Streamed" images. This includes most of my Menu graphics.

How would a user dump their VRAM and get the images? Is there software that does it?

Do I need to be concerned that this is possible and should I protect my game from it?

# Answer
> 13 votes
Yes, it is possible for a user to get the images in GPU memory. It's not likely they'd get them by dumping the entire GPU memory space (though with specialized hardware, drivers or debugging software such a thing is possible -- Visual Studio has a powerful GPU debugger these days). Rather, they can get them from CPU memory, which is much easier. Your game's entire address space is readable, plus they could install API hooks for D3D or OpenGL that intercept the texture upload calls to help figure out where the actual image data is.

Indeed, if somebody is particular unconcerned for the quality of the ripped textures, or your game has 2D ones, it's easy enough to simply extract them from screenshots.

You cannot protect against this from physically happening. As a general rule, anything in a game client is accessible to a user since they fully control the hardware it's running on.

You shouldn't worry about trying to protect your assets this way. Instead, rely on the fact that you are legally protected by intellectual property law.

---
Tags: unity, image, assets, unreal, memory
---


title: Does Unity own my game?

text:
# Question
Title: Does Unity own my game?
I made my first game in unity, and I was wondering if I can sell it without owing anything to unity?

# Answer
> 17 votes
From the Unity FAQ:

> **Are there royalties or a per-title fee?**
>
> No, Unity does not charge on a per title basis and you do not pay royalties or pay revenue share, even for games and applications made with the free version.

and

> **Can we sell games and make money with the free version of Unity?**
>
> Yes you can create and sell a game with the free version of Unity, without paying royalties or any revenue share. However, the free version of Unity may not be licensed by a commercial entity with annual gross revenues (based on fiscal year) in excess of US$100,000, or by an educational, non-profit or government entity with an annual budget of over US$100,000.
>
> Please also be aware that the feature set of the free version is not intended for the production of professional games and interactive content. Lastly, games made with our Pro trial licenses may not be distributed nor used for commercial purposes.

This is also mentioned in the Unity Software License Agreement. Note that *Software* refers to the Unity software. The game or application you are creating is the *Licensee Content* (See section *13. Definitions*). The section quoted in the other answer tells you that you can't distribute the trial or educational versions of their software runtime. With other versions, you may distribute the software bundled with the game you created.

# Answer
> 8 votes
## No, they don't own your game.

But they do own their engine. In Unity's EULA you can find relevant information about how the license between the developer and Unity works out.

> 1. Grant of License
>
> Use Rights. Conditioned upon your compliance with the terms and conditions of this Agreement and payment of all applicable fees, Unity grants you a non-exclusive, non-transferable license: (i) to install and execute the executable form of the Software, solely for internal use by a single person to develop Licensee Content; and (ii) **if you have licensed a version of the Software other than a trial or educational version, to distribute the runtime portion of the Software, on a royalty-free basis, solely as embedded or incorporated into Licensee Content** and solely to third parties to whom you license or sell Licensee Content pursuant to an agreement that is no less protective of Unity and its licensors as this Agreement. You may not sublicense the rights granted under clause (a)(i), but you may sublicense the rights granted under (a)(ii) solely to third parties to whom you license or sell Licensee Content to act as distributors thereof pursuant to an agreement no less protective of Unity and its licensors as this Agreement.

---
Tags: unity
---


# Question
Title: How can I render cloud patterns like in these examples?
I have a quick question.

I see in many games, usually in the menu, some moving "clouds" in the background, apparently additive blended into each other, which does a really nice job immersing the player, in my opinion.

A couple of examples that jump to mind right now are the Far Cry 3 main menu background: https://www.youtube.com/watch?v=B5XcMx3GjPA

and the Plague Inc main menu background: https://www.youtube.com/watch?v=RQv60ywrLxU (the first seconds show it)

These cloudy patterns seem like some kind of noise to me, like Perlin or other. So, how would you proceed to achieve that kind of blurred cloud effect with vivid colors?

More specifically, would you pre-generate sets of clouds and include them in the game package? Or generate them on-the-fly? On the CPU as a regular texture or on-draw in the GPU shader program?

I am interested in mastering this kind of visual effect, and as such any help would be appreciated pointing me in the right way. Thanks.

# Answer
Those kind of clouds are indeed rendered with perlin noise function. They can easily be generated on fly when the game starts, or they can be included in the game textures.

There are ton of great tutorials out there to render perlin noise clouds, this being one of them: Perlin Noise, or this: How to Use Perlin Noise in Your Games You can find more by googling for "perlin noise cloud" or just "perlin noise examples".

One other method could be Simplex noise. A comparison between simplex noise and perlin noise can be found here: Perlin noise versus Simplex noise in Javascript
> 1 votes

---
Tags: rendering, noise, clouds
---


# Question
Title: Point rotation around point, accuracy question
I study OpenGL ES 2.0. But I think it's more a C++ question rather then an OpenGL one.

I am stuck with the following rotation question: It is known, that rotation transformation can be applied using these equations (for simplicity suppose we rotating around (0, 0)):

```
x'=x*cos(theta)-y*sin(theta)
y'=x*sin(theta)+y*cos(theta)

```

But it seems that when I perform this rotation operation several times, the accuracy problem occures. I guess that the core of this problem is in uncertain results of `cos()` function and floating point limitations. As a result I see that my rotating object is getting smaller and smaller and smaller. By the way I am using C++.

1.) What do you think: Is this issue really connected to the accuracy problem?

2.) If so, how can I handle this?

Thanks.

# Answer
This type of accumulated error is usually dealt with by tracking the original point(s) (say, the vertices of a mesh), and their transformation (say, as a matrix or quaternion and scale/translation vectors) separately.

When you transform the object, you don't modify the original points. You just update the transformation data. Then a new set of output points can be generated on demand from the originals and the updated transformation.

Doing it this way lets you police the transformation data for errors. If you maintain the invariant that the transformation data is error-free to within your numerical precision, then any output points you generate will remain accurate within similar bounds.

You can do this in two ways:

1. Generate the transformation from scratch whenever you need it, from more reliable source data (like an angle variable).
2. Update the transformation incrementally, and error-correct it as you go:

A common example is working with a rotation matrix. A matrix that represents a rotation with no scaling/shearing is necessarily **orthonormal** (each row or column of the matrix is a unit vector, perpendicular to each other row or column, respectively). So, you can correct rounding errors that creep into the matrix by orthonormalizing it after making any change. (That is, take one row, scale it to unit length. Take the next row, subtract its projection onto rows considered so far, scale it to unit length. Repeat until you run out of rows)
> 2 votes

---
Tags: c++, opengl-es, floating-point
---


# Question
Title: What are the legal considerations about making a game with a dynamic age restricted content?
What I mean by this is - is it legal to make a game which asks (or proves) your age during install or on initial load, and then dynamically sets the content to the players age.
For example if the players is under-age then all swear word assets are replaced with there PG13 equivalents.
Or the same with blood and gore.

Does this make sense?
Also what are the communities opinions or feelings about this?
(**note** for locality I am referring to UK law but laws and opinions for any other country is encouraged!)

(ps i can't create tags)

# Answer
IANAL but you can certainly ask the player to enter their age and set up some options as a result, or just give the players options for gore & language that they can manually set. Several games do this already allowing you to turn off, or at least tone down blood.

However if you are asking if you can get a lower rating from PEGI/ESRB for this I'm going to make an educated guess of "No". They are going to rate you based on the fully enabled gore/language version of your game. If you look at it from their perspective, even if your game does really tone down elements when given the correct information, there is no way to be sure that players will be honest. So if they put a lower restriction on the title and then little Jimmy says he's an adult and gets full gore, parents will not be happy.
> 6 votes

# Answer
I don't think the ratings board would rate the age down because you set content down. If an underaged person is playing the game, then they should've been aware that the rating is too high.

By all means, add in an option somewhere to tone the content down; could be useful for if a properly aged person is playing in the vicinity of small children.
> 1 votes

# Answer
I agree with wkerslake, but I don't think that should discourage you from doing what you describe.

I would allow the user to be able to change the 'gore' settings manually, but set the defaults based on the age of the user.
> 0 votes

# Answer
I just realized I should have put this in an answer.

Parental controls, especially password-protected ones, do affect a game's rating.

I think WoW is rated Teen, but the user-generated content (chat text, names, etc) is definitely not. But they're subscription based, I believe they may use credit card data to do age verification for subscribers.

Most online games carry that "experience may change during online play" rider, which is a fancy way of saying "other players can and will spew filth endlessly". Seems that players are far more creative when coming up with profanity than profanity filters are in eliminating it in any event.

Certainly you could push the age verification aspects out of the game, distribute it in Locked-to-teen mode, and do something more industry standard for age verification, like sell a separate "Mature" edition, or unlock codes, or leverage some commercial age verification service.
> 0 votes

# Answer
You cannot legally store anyone's age, name, email, address etc. if they are under 13. So just make it so that you cannot join if you are under the age of 13.
> 0 votes

---
Tags: software-engineering, legal, content-rating
---


title: Frustum culling + instancing

text:
# Question
Title: Frustum culling + instancing
I've implemented `instancing` in my app and right now I have an instance buffer holding position data for all instances. But I'd like to also implement `frustum culling` which would cull some of the instances depending on the camera view. Now, how can I render only some of the instances in the buffer but not all? Do I have to rebuild the buffer every frame (so that it only holds visible instances) or is there a way in `DirectX 11` to "tell" API which instances from the buffer I want drawn?

# Answer
> 1 votes
The typical way to do it would be to rebuild the instance buffer each frame, akin to a particle system or other dynamic vertex buffer.

---
Tags: directx11, instancing, frustum-culling
---


# Question
Title: Why does loading a JSON file require the usage of a callback function?
I was wondering why functions that parses JSON files always use callback functions instead of just returning loaded response text? An example here and here. If it is possible, how would I return this value instead of callback'ing it?

# Answer
The functions use AJAX in the form of the `XMLHttpRequest` object (or "XHR" for short). Thus, by definition, they're ***asynchronous***.

Because JavaScript runs in a single UI thread in modern browsers, making such a network call synchronously would lock the browser UI while it waits for the file request to complete, making it unresponsive and causing an extremely undesirable user experience. Thus the asynchronicity.

Because the functions are asynchronous, ***you must have a callback function to handle the asynchronous response when it completes***. You could immediately return a value from an asynchronous function, but that value could never be the result of the file request, since that would basically make the function synchronous again.
> 1 votes

---
Tags: javascript
---


# Question
Title: Find closest point from an origin, in a mesh
I want to do something similar to a raycast. With a raycast, you can set an origin and a destiny, and check where the ray collides with something but only with a line. What I want to do, is given an origin with `x`, `y` and `z` coordinates, check which is the closest point it collides in a mesh. so if I have a box in `0, 0, 0` with width 2, and my origin is on `0, 0.5, 0`, the algorithm/function should return that the closest point it collides is `0, 1, 0`. I hope I am clear enough.

I am using Ogre3D, and bullet physics. I can also use OpenGL.

Thanks.

# Answer
You want to use GJK. The general algorithm finds the closest point between two (convex) meshes, but of course one of your "meshes" can just be a single point in space.

Note that since it only works with convex shapes, you need to break your mesh down into convex pieces (if it's not already convex) in order to apply the algorithm. Find the closest point to each chunk and then keep the closest result.

The algorithm operates by evaluating geometric primitives and refining the primitive under consideration by finding the "next closest" adjoining primitive. You start on each mesh with a point, expand that to a line, then to a triangle, then a tetrahedron, "walking" the adjoning tetrahedrons (or simpler shapes) until you arrive at the point/line/triangle closest to the other shape.

It's easier to visualize than it is for a paragraph or two of prose to explain. Check out Allen Chou's overview or this Molly Rocket video tutorial. The technique extends fairly easily from 2D to 3D.
> 3 votes

# Answer
Finding the closest point on a mesh to a point `P` can be done by **iterating on all primitives** of the mesh’s surface (triangles, quads, *etc.*) and finding the primitive that is closest to `P`. If your mesh is made of triangles, this question has pointers to several methods for distance calculation, especially “Distance from a point to a triangle (3D)” which comes with full source code. Otherwise, you may look at *e.g.* box-point distance.

Once you know which is the closest primitive, you can find the closest point. It’s possible that the distance calculation already provides the information (if you used the source code from geometrictools.com). Sometimes the closest point is a vertex of the mesh, sometimes it’s on an edge, and some other times it lies in the middle of a triangle.

This would be the algorithm:

```
best_primitive = null
best_dist = infinity
for each primitive in mesh:
    new_dist = distance(P, primitive)
    if new_dist < best_dist:
        best_dist = new_dist
        best_primitive = primitive
best_point = closest_point(P, best_primitive)

```

This method is O(n).
> 2 votes

---
Tags: 3d, mathematics, geometry
---


# Question
Title: Is it a good idea to imitate the same name of app to gain number of downloads?
Is there a way in order to recognize the game app's name and become popular for downloads in order to earn more money? I tried to check a certain name of the game and the search result appeared to have the same name and genre but owned by different authors. If that case, I was thinking if it is a better idea if I took the same name of the app I'm gonna put it but not exactly before publishing it on Google Play. If not, then I might think of a catchy name of the app and promote it to my friends so that it can spread and share to others in order to gain number of downloads for earnings and popularity. Any thoughts?

# Answer
It depends on what you mean by good.

Is it ethically good? No, at least not in my book. You're cheating people, confusing them, and purposely misleading them by naming your app something similar to their app just to get people to download it by mistake.

Is it good marketing? No. People will figure out what you are all about, and avoid your stuff.

Is it good at generating bad reviews from people? Yes! Most definitely yes! Glad I was able to get one yes in there.
> 7 votes

---
Tags: legal, marketing
---


# Question
Title: How can I use a camera matrix with different resolutions?
I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution.

How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same?

I use Monogame to run the game on different Windows Phone devices.

My camera class:

```
 public class Camera
{
    public Vector2 Cameraposition;

    public Camera(Vector2 cameraposition)
    {
        Cameraposition = cameraposition;
    }

    public void Update(GameTime gameTime, Vector2 CamPosition)
    {
        Cameraposition = CamPosition;
    }

    public Matrix GetMatrix()
    {
        return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, -Cameraposition.X, -Cameraposition.Y, 0, 1);
    }
}

```

In Game1:

```
//I use the camera in Game1 like this:
//At the beginning(in LoadContent):
Vector2 cameraposition = new Vector2(PlayerStartpos.X - GraphicsDevice.Viewport.Width / 2, PlayerStartpos.Y - GraphicsDevice.Viewport.Height / 2);
camera = new Camera(cameraposition);

//Updating the camera position
 protected override void Update(GameTime gameTime)
    {
        player.Update(gameTime);
        Newcameraposition = new Vector2(player.Playerposition.X - GraphicsDevice.Viewport.Width / 2, player.Playerposition.Y - GraphicsDevice.Viewport.Height / 2);
        camera.Update(gameTime, Newcameraposition);

        base.Update(gameTime);
    }

//Drawing:
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix());
 ...

```

# Answer
> 1 votes
Your question is not an *exact* duplicate, so I won't try to close it. But it's close enough that I feel comfortable in simply sending you over to my old answer on **Supporting Multiple Resolutions**.

That answer is specifically for the XNA Platformer Sample, so you should probably download a copy of that to play around with to get a feel for how the code in my answer works. Then you can apply it to your own game.

---

Note, in particular, how I use matrix multiplication to combine two matrix operations, as mentioned in comments on your question:

```
Matrix camera = Matrix.CreateScale(scale, scale, 1)
        * Matrix.CreateTranslation(translateX, translateY, 0);

```

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


title: Camera roll has no effect

text:
# Question
Title: Camera roll has no effect
Consider my following (abstracted) C# w/ SharpDX code:

```
class Game
{
    Camera _camera = new Camera();

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        // Roll
        if (e.KeyCode == Keys.Home)
        {
            _camera.TurnRoll(-0.05f);
        }
        else if (e.KeyCode == Keys.End)
        {
            _camera.TurnRoll(0.05f);
        }
        // Other rotation / movement works...
    }
}

class Camera
{
    private Vector3 _position;
    private Vector3 _rotation;
    private Vector3 _right;
    private Vector3 _up;
    private Vector3 _forward;
    private Matrix  _view;

    public Camera()
    {
        _right = Vector3.Right;
        _up = Vector3.Up;
        _forward = Vector3.ForwardLH;
        UpdateViewMatrix();
    }

    public void TurnRoll(float roll)
    {
        // Relative rotation
        _rotation.Z += roll;
        UpdateViewMatrix();
    }

    private void UpdateViewMatrix()
    {
        Matrix cameraRotationMatrix = Matrix.RotationYawPitchRoll(_rotation.Y, _rotation.X, _rotation.Z);
        Vector3 cameraTarget = Vector3.TransformCoordinate(Vector3.ForwardLH, cameraRotationMatrix);
        cameraTarget = cameraTarget.Normalize();
        cameraTarget += _position;

        // I bet the problem lies in and/or after this line
        Matrix rotateYTempMatrix = Matrix.RotationY(_rotation.Y);

        _right   = Vector3.TransformCoordinate(Vector3.Right,     rotateYTempMatrix);
        _up      = Vector3.TransformCoordinate(Vector3.Up,        rotateYTempMatrix);
        _forward = Vector3.TransformCoordinate(Vector3.ForwardLH, rotateYTempMatrix);

        _view = Matrix.LookAtLH(_position, cameraTarget, _up);
    }
}

```

My problem: Even when pressing the Home and End keys, the camera roll visibly stays untouched. I have trouble correcting my UpdateViewMatrix function, and I bet that the error is in there. I'm a bit lost with the maths here and my tries to use another rotation matrix to update the \_up vector all failed or created other problems.

Can anybody clear my math mind up and help me correct this method?

**EDIT:** Solved with the help of winged's answer below. I edited the code to be

```
private void UpdateViewMatrix()
{
    Matrix rotation = Matrix.RotationYawPitchRoll(_rotation.Y, _rotation.X, _rotation.Z);

    _forward = Vector3.TransformCoordinate(Vector3.ForwardLH, rotation);
    _forward += _position;

    _up = Vector3.TransformCoordinate(Vector3.Up, rotation);

    _view = Matrix.LookAtLH(_position, _forward, _up);
}

```

However, this is still not completely correct. The camera rolls now, which solves this question. But if it is rolled and I try to yaw it, the yaw happens like as if the camera is non-rolled and moves along the default Y-axis :/. Especially when looking downwards 90 degrees this causes something like gimble-lock to happen (or IS it gimble lock?) because rolling and yawing the camera has the same effect then.

**EDIT2:** I completely replaced my rotation with quaternions. I don't know why people think these are "harder" or at least "different" to understand. This solution works perfectly.

```
public void Turn(Vector3 turning)
{
    // Relative rotation
    Quaternion delta = Quaternion.RotationYawPitchRoll(-turning.Y, -turning.X, -turning.Z);
    _rotation = delta * _rotation;
    _rotation.Normalize();
    UpdateViewMatrix();
}

public void TurnRoll(float roll)
{
    Turn(new Vector3(0, 0, roll));
}

private void UpdateViewMatrix()
{
    Matrix view = Matrix.RotationQuaternion(_rotation);
    Matrix translation = Matrix.Translation(-_position.X, -_position.Y, -_position.Z);
    _view = translation * view;
}

```

# Answer
> 2 votes
I guess that the problem lies in here:

`_up = Vector3.TransformCoordinate(Vector3.Up, rotateYTempMatrix);`

You're calculating the up vector (and also the rest of them) from a matrix unrelated to the `cameraRotationMatrix` matrix, in which you have stored the new rotation. Usually, what I do is multiply an old rotation matrix by the new rotation matrix, and then calculate the up vector from the outcome matrix.

Hope this helps.

---
Tags: mathematics, camera, sharpdx
---


# Question
Title: Is a game like Subway Surfers suited for 2D or 3D?
I imaginated a mobile game and now I'm getting doubts as to whether its possible for my idea to be developed in 2D. Here's a crude illustration of the game scene:

It's pretty much like Subway Surfers. The game objective is simply a kid going along the street and buying particular fruits/vegetables. Can the sprites be changed in perspective?

As a side note, there's a reason for my particular love towards 2D. That's because:

* I don't want to employ someone for 3D designing, I can manage 2D myself.
* I want to finish developing this game quickly.

# Answer
Either one. Consider that even if the game world is in 3D, you can still use 2D for rendering. This is primarily a design decision. If you're more comfortable with 2D, then use 2D.

See these related questions about making a similar style of game:

Best technique to create oldschool (fake 3D) racing game?

How would I implement an endless road the player runs down?

Road parallax background

You'll see that some of them describe 2D methods and others describe 3D methods. You're the only one that knows exactly what your project requirements are. It's up to you to decide which one to use.

It appears to me that Subway Surfers is created in 3D. There will be some differences between 2D and 3D no doubt.

Pseudo 3D:

3D:
> 7 votes

---
Tags: 2d, 3d, game-design, mobile
---


# Question
Title: Direct access to frame buffer pixels data
I'm trying to develop a 3d graphics engine, i use a framebuffer class which is of my own creation but the fps is too low, and i think it's because i use putpixel() function from winbgim library,

my function to show framebuffer on screen is:

```
void framebuffer::showonscreen()   //from buffer to screen(space to space 1d to 2d)
{

    int i;
    for(int y=0; y < length; y++)
    {
        for(int x=0; x < width; x++)
        {
            i = x + screeny[y];
            putpixel(x, y, colbuf[i]);
        }
    }
}

```

Is there any alternative to this putpixel function or a technique to speed it up, or any other manual(without using libraries) way

I heard about giving a direct access to memory blocks, or using the vram

Would any one know how to help me in this problem?

Please, HELP is appreciated.

# Answer
> 1 votes
I do not have experience with the libraries you are using, but I know that with SDL you can easily access the video memory and reserve memory from the gpu for any sort of read/write tasks. Just keep in mind that reading from video memory is very inefficient, and you want to transfer data back and forth as little as possible.

The cpu is really badly designed for rendering graphics, while it's great for calculating tasks. Old games (pre-opengl/directx) used different speed-up techniques. One of the most common was to not update the whole screen once a frame, but update only the changed parts. Using this and sdl you should be able to improve your framerate a bit, but don't keep your hopes up for as fast rendering as rasterizing using the gpu gets you.

# Answer
> 3 votes
You don't get direct access to the framebuffer (or any other hardware resource) from user mode code on *any* modern OS - it just doesn't run at a high enough privilege level. So like it or not you're going to have to use some form of library to get there, because otherwise the option is to start writing your own device driver.

This needn't be too intrusive. For example, you could use OpenGL, create a context, disable all states and texturing, then your framebuffer::showonscreen method just needs to make a single glDrawPixels call.

# Answer
> 0 votes
An option you may choose to use is creating a buffer of the screen size and directly put the whole buffer to the context rather than doing it per pixel(As it is cheaper for it to be one call than 1,000's due to the amount of pixels you have).

I'm not familiar with the winbgim library, but I'm sure it has some optimized function to render a whole image, or something along those lines, to the screen. In this case you will do all the changes of the data to the buffer you created and then pass the buffer to this image function which will handle the displaying to the screen.

You'll have to look into how the buffer information is managed by the library.

If it doesn't have an option to pass in an array, or pointer, to a buffer you created then I suggest you probably look into using OpenGL rather than that library. I've done this same thing in OpenGL where I modify the buffer I make myself before passing it to the GPU to be rendered through the glDrawPixels() function available through GLEW.

But as Lasse has said you aren't going to get that much performance out of the CPU compared to a GPU implementation. Even my CPU based implementation with all of the stuff it needed to do was hitting the low end of 20 FPS.

---
Tags: frame-buffer
---


# Question
Title: What's the difference between Update and FixedUpdate in Unity, and should I bother?
I was told to use `Update()` for graphics and `FixedUpdate()` for physics, but sometimes my inputs won't register when I use `FixedUpdate()`. It works fine if I use `Update()` for everything though.

Should I bother with `FixedUpdate()`, or am I doing something wrong?

# Answer
`FixedUpdate` can run faster or slower than `Update` depending on your settings. That'll depend on load (how fast `Update` is running) and speed you have set for `FixedUpdate` (found in Edit-\>Project Settings-\>Time). Ideally, since `Update` is run once per frame, this is where you want to capture input. If you need to act on input in the `FixedUpdate` method (like controlling physics bodies), set flags in `Update` then handle them in `FixedUpdate`:

```
bool leftMouseDown = false;

void Update()
{
    if(Input.GetMouseButtonDown(0))
        leftMouseDown = true;
}

void FixedUpdate()
{
    if(leftMouseDown )
    {
        //update physics bodies with input
        leftMouseDown = false;
    }
}

```

It's still a good idea to control physics from the `FixedUpdate` method, since it's unlikely the physics needs to be updated as often, and physics on a fixed update is much easier to predict (determinism) than physics on a variable update.
> 11 votes

# Answer
You need to understand what each one does. `Update()` gets called as often as possible (not sure, maybe it can be capped), either way - each frame. `FixedUpdate()` gets called every constant amount of time (hence "fixed").

Input goes into `Update()`, as simple as that (because as you noticed `FixedUpdate()` might not catch the input event). Game logic however might go into either one. Physics needs to be deterministic and that's why it should be in `FixedUpdate()`. Other things don't have to. Depending on the usage you have to decide which function is appropriate.

Althouth it's worth to say that some applications have all game logic update in `FixedUpdate()` (even outside of `Unity`) - it's called "fixed step game loop". Having all update code in a fixed step function gives you determinism and makes your app more likely to behave the same way each time (and on each device). Also allows for some fancy features, like replays.
> 7 votes

---
Tags: unity, c#, game-loop
---


# Question
Title: Why are my Unity procedural animations jerky?
I'm working in Unity and getting some crazy weird motion behavior. I have a plane and I'm moving it. It's *ever so slightly* getting about 1 pixel bigger and smaller. It looks like the it's kind of getting squeezed sideways by a pixel. I'm moving a plane by `cos` and `sin` so it will spin on the `x` and `z` axes. If the planes are moving at `Time.time`, everything is fine. However, if I put in slower speed multiplier, I get an amazingly weird jerk in my animation. I get it with or without the lerp. How do I fix it? I want it to move very slowly. Is there some sort of invisible grid in unity? Some sort of minimum motion per frame?

I put a visual sample of the behavior here.

Here's the relevant code:

```
public void spin()
{

         for (int i = 0; i < numPlanes; i++ )
    {
        GameObject g = planes[i] as GameObject;

        //alt method
        //currentRotation += speed * Time.deltaTime * 100;
        //rotation.eulerAngles = new Vector3(0, currentRotation, 0);
        //g.transform.position = rotation * rotationRadius;

        //sine method
        g.GetComponent<PlaneSetup>().pos.x = g.GetComponent<PlaneSetup>().radiusX * (Mathf.Cos((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle));
        g.GetComponent<PlaneSetup>().pos.z = g.GetComponent<PlaneSetup>().radius * Mathf.Sin((Time.time*speed) + g.GetComponent<PlaneSetup>().startAngle);
        g.GetComponent<PlaneSetup>().pos.y = g.GetComponent<Transform>().position.y;
        ////offset
        g.GetComponent<PlaneSetup>().pos.z += 20;

        g.GetComponent<PlaneSetup>().posLerp.x = Mathf.Lerp(g.transform.position.x,g.GetComponent<PlaneSetup>().pos.x, .5f);

        g.GetComponent<PlaneSetup>().posLerp.z = Mathf.Lerp(g.transform.position.z, g.GetComponent<PlaneSetup>().pos.z, .5f);
        g.GetComponent<PlaneSetup>().posLerp.y = g.GetComponent<Transform>().position.y;
        g.transform.position = g.GetComponent<PlaneSetup>().posLerp;

    }

    Invoke("spin",0.0f);
}

```

The full code is on github.

---

There is literally nothing else going on. I've turned off all other game objects so it's only the 40 planes with a texture2D shader.

I removed it from Invoke and tried it in Update -- still happens. With a set frame rate or not, the same problem occurs. Tested it in Fixed Update. Same issue.

The script on the individual plane doesn't even have an update function in it. The data on it could functionally live in a struct.

I'm getting between 90 and 123 fps. Going to investigate and test further. I put this in an invoke function to see if I could get around it just occurring in update. There are no physics on these shapes. It's a straight procedural animation.

Limited it to 1 plane - still happens. Thoughts?

---

Removed the shader - still happening.

# Answer
> 2 votes
The simple example of:

```
public float speed = 2;

void Start () {
    spin ();
}

public void spin() {
    Vector3 newPos = this.transform.position;
    newPos.x = 20 * Mathf.Cos((Time.time*speed));
    newPos.z = 20 * Mathf.Sin((Time.time*speed));

    this.transform.position = newPos;
    Invoke("spin",0.0f);
}

```

Works just fine for me. Increasing the speed makes the plane orbit faster. I suspect you have an issue somewhere else in your code.

Or you're having performance issues that's causing the animation to not be smooth. If you're making this call on a number of planes, it can be slow. Using `Invoke` requires reflection, which can be slower than just calling the method itself. Do some profiling to find out if it's a performance issue. Or you can simply try hitting the "Stats" button in the top right of the editor window to see your FPS and time per frame.

# Answer
> 0 votes
You should be manipulating a fixed frame rate which calls `Update()` on your `GameObject`s. You should not be using `Invoke()` for timing your game loop, and especially not rendering or physics updates. Using the wrong timing mechanisms will often cause temporal artifacts such as that which you're currently seeing.

`Application.targetFrameRate` should give you the control you desire.

# Answer
> 0 votes
Couple of quick thoughts:

1. Did you mean to reference g.GetComponent().radius instead of g.GetComponent().radiusZ perhaps?
2. The inclusion of the start angle into the Cos and Sin functions may be resulting in an unexpected value. Perhaps try removing it and seeing if the jerkyness removes? Same goes with the offset.

Because removing the speed value from the trig functions fixes your issues, I believe that your problem lies in those two lines.

---
Tags: c#, unity, animation, procedural
---


title: creating an html5 game

text:
# Question
Title: creating an html5 game
I am working on a really simple online version of the parachute shooters game that was preprogrammed on old iPods. I'm pretty new to game development and so at first I tried to build the whole game with jQuery, so each object in the game was a div, etc. I had seen an online snake game written that way and it worked pretty well. That wasn't really working for me, so I scraped it and am now going with doing it all in `canvas`.

What would be the best way to go about making that game? As of right now, I am using `setInterval()` to act as separate threads controlling the user's pellets and the falling parachutes separately. Is that a good idea? Is there a better way to do it?

Thanks for any feedback.

# Answer
I would go for a draw function that is called in interval. And for the game objects you deal with them in an array and updates them in your loop. Then if you want to have good performance try to only redraw the part of the canvas that is needed to be updated.

Here is a good tutorial http://jlongster.com/Making-Sprite-based-Games-with-Canvas
> 1 votes

---
Tags: game-design, html5, html-canvas
---


# Question
Title: Can't edit specific variables from the inspector panel, while variable is static
In order to make the variable accessible from other classes, I have to make it static.

When I make it static, I can't edit it from the Unity's Inspector panel.

No way to be able to do both: accessible and editable from the panel?

---

EDIT:

This is the code so far (by following Savlon's idea)

**BouncingBall.js**

```
#pragma strict

public static BouncingBall instance;
public var velocityX : float = 1;
public var velocityZ : float = -1;

function Awake(){
    instance = this;
}

function Update () {

    transform.Translate(new Vector3(velocityX, 0, velocityZ) * Time.deltaTime);

    if (this.transform.position.x > 4.5){
        velocityX = -velocityX;
        this.transform.position.x = 4.49;
    }
    if (this.transform.position.x < -4.5){
        velocityX = -velocityX;
        this.transform.position.x = -4.49;
    }
    if (this.transform.position.z > 4.5){
        velocityZ = -velocityZ;
        this.transform.position.z = 4.49;
    }
    if (this.transform.position.z < -4.5){
        velocityZ = -velocityZ;
        this.transform.position.z= -4.49;
    }
}

function OnCollisionEnter(col : Collision){
    if(col.gameObject.name == "PlayerPad"){
        velocityZ = -velocityZ;
    }
}

```

**brick.js** (where I call the variable from)

```
#pragma strict

function OnCollisionEnter(col : Collision){

    if(col.gameObject.name == "Ball"){
        BouncingBall.instance.velocityZ = -BouncingBall.instance.velocityZ;
        Destroy(this.gameObject);
    }
}

```

# Answer
Yeh you can't create a static variable and have it accessible from the inspector panel that I know of. However, you could try this

In your class that has the editable variable you could create a static instance variable of your script and have the editable variable as public so you can edit and access it like so.

```
public class StaticVariable : MonoBehaviour
{

public static StaticVariable instance; //Static instance variable of your script
public int editableVariable;           //Variable you want to edit in the inspector

void Awake ()
{
    instance = this;               //Set this script as the instance variable
}

// Other class methods here...
}

```

To edit that variable from another class you would write:

```
StaticVariable.instance.editableVariable = 1;

```

or to access it you would write:

```
int variable = StaticVariable.instance.editableVariable;

```

That way you can still edit it in the inspector and access it from another class.

Not sure if this is what you are looking for or whether you would be able to use it... if not just let me know and I'll delete this answer as it is not helpful :)

**Note - This method is written for C# NOT Javascript.**
> 1 votes

---
Tags: unity, javascript
---


title: OpenGL rendering looks squeezed

text:
# Question
Title: OpenGL rendering looks squeezed
I am rendering bunch of cubes of unit size, but for some reason they look like they are squeezed a bit in the screen-space y axis. Why is this?

My projection matrix:

```
Projection = Matrix4.CreatePerspectiveFieldOfView (fovy, width / height, zNear, zFar);

```

My view matrix:

```
View = Matrix4.LookAt (position, position + Direction, up);

```

My Model matrix:

```
Matrix4 modelMatrix = Matrix4.CreateTranslation(new Vector3(chunkPos.X * 32, chunkPos.Y * 32, chunkPos.Z * 32));

```

Here's how I form the MVP matrix:

```
ViewProjection = View * Projection;
ModelViewProjection = Model * ViewProjection;

```

And finally the vertex shader:

```
gl_Position = mMVP * vertex;

```

Screenshots displaying the problem:

I tried to fix the problem by adding a y-axis scale of 1.5 to my View matrix, and it seems it helped a bit with the problem. The result:

## The question

I want to understand why I have to scale it this way. I thought the aspect ratio I give to the CreatePerspectiveFieldOfView would do this correction for me.

# Answer
> 5 votes
And literally 1min after I post the question I found out the answer. The problem was that on my projection matrix creation the width and height are integers, and thus the aspect ratio would be always 1. I changed the width and height to floats, and it started working.

---
Tags: opengl, camera, opentk
---


# Question
Title: How do I implement friction in a billiards game?
I'm having trouble implementing friction in a billiards game.

Currently, the ball only slows on collision with the edges, but I also want some friction with the background.

How can I implement friction? (I'm using PhysicsJS.)

# Answer
What you're looking for is some dampening function, i.e. friction with the table.

Dampening is actually a rather easy function:

```
v *= factor;

```

Where `factor` is a number between `1` (no dampening) and `0` (immediate halt).

The actual number for factor depends on your surfaces. For example, `0.99` could be ice, `0.9` could be some grass, `0.8` could be sand.

You'll have to experiment a bit till you get the numbers the way you want.

As for PhysicsJS: I only had a quick look at the documentation and I think the best way to solve this would be modifying the balls' acceleration directly. I *think* you can "subclass" bodies so it shouldn't be too hard to create a body that's always going to slow down on its own.
> 4 votes

# Answer
After looking through the documentation for PhysicsJS I couldn't really find anything but I would access your velocity vector and over time reduce that velocity to simulate friction.

```
//Java (yes i know its not Javascript)
public void update(){
     if(vx > 0){
          vx -= 0.01f;
     }
     if(){
          vy -= 0.01f;
     }
}

```

Thats how I would do it in a Java game.
> 0 votes

---
Tags: physics, javascript, billiards
---


# Question
Title: A problem with texture atlasing in Unity
I have the texture below and I need to get rectangular parts from it. I could finally combine meshes of different quads to improve performance, but I with quads of different tilings, this means different materials, then combining meshes will fail.

Can anybody tell me how to have a part of that texture in C#? Such that all quads will be of the same material only then combining meshes passes.

Thanks in advance.

# Answer
I modified this code to get what I need. I modified it and this is my final code:

```
    Vector2[] uvb;
    Vector2[] uva = new Vector2[] { new Vector2(0, 0), new Vector2(1, 1), new Vector2(1, 0), new Vector2(0, 1) };
    float w, h, left, bottom, posX, posY;
    Rect uv = new Rect();
    MeshFilter filter;

    for (int i=0; i<rects.Count; i++)
    {
        AdaptedRect rect = rects[i];

        w = rect.width * blockWidth;
        h = rect.height * blockHeight;

        left = rect.left * blockWidth;
        bottom = rect.bottom * blockHeight;

        posX = groundRect.left + left + w / 2;
        posY = groundRect.bottom + bottom + h / 2;

        squareBlocksPool[i].transform.position = new Vector3(posX, posY, squareBlocksPosZ);
        squareBlocksPool[i].transform.localScale = new Vector3(w, h, blockThickness);
        squareBlocksPool[i].SetActive(true);

        // ATLASING
        uv.x = 0;
        uv.y = 0;
        uv.width = rect.width / columns;
        uv.height = rect.height / rows;

        filter = (MeshFilter)squareBlocksPool[i].GetComponent<MeshFilter>();
        uvb = new Vector2[uva.Length];

        for (int p = 0; p < uva.Length; p++)
        {
            uvb[p] = new Vector2(uva[p].x * uv.width + uv.x, uva[p].y * uv.height + uv.y);
            filter.mesh.uv = uvb;
        }
    }

```
> 1 votes

---
Tags: c#, unity, textures, texture-atlas, mesh
---


title: Frustum culling based on MVP matrix?

text:
# Question
Title: Frustum culling based on MVP matrix?
Tutorials on the internet usually say to extract plane data from MVP (model view projection) matrix (or VP?) and then test the bouding volume against each of the frustum planes. I've thought of a different approach:

1. calculate model's bounding sphere (center + radius)
2. define point `A = center`, `B = center + float3(radius, 0, 0)` \- some point on the sphere
3. multiply `A` and `B` by `MVP matrix` to get point coords in clip(?) space
4. calculate radius in clip space (distance from `A` to `B`)
5. check if sphere is in the frustum, sth like: `A.x - radius < 1 && A.x + radius > -1`

Would this work (it would be only an approximation but should be good enough)? In `(5)` what values should I test against? `-1` and `1`? Because I'm not sure if I'm not mixing up spaces.

# Answer
No, it won't work.

The transformation of a sphere by a projection into NDC is not a sphere. You pick a single point on the sphere, and then assume you get the whole bounding volume back with just a single distance, but it is incorrect (i tried finding pictures of the resulting volume but failed. While you can see the deformation on how a sphere turns into an ellipsoid in xy plane, the transformation along the z-axis is the one that is most dramatic).

Let's walk through an example (using OpenGL projection, but the principle is the same in other NDC spaces), with `near=1, far=infinity, -left=right=-bottom=top=1`. The resulting projection matrix is:

```
[1  0  0  0]
[0  1  0  0]
[0  0 -1 -2]
[0  0 -1  0]

```

Take a sphere centered at `[0, 0, -10]`, of radius 1... And let's transform 3 points on the sphere:

```
[0, 1, -10, 1],
[0, 0,  -9, 1] and
[0, 0, -11, 1]

```

the post-projection coords give resp:

```
[0, 1, 10 - 2, 10]
[0, 0,  9 - 2,  9]
[0, 0, 11 - 2, 11]

```

in NDC, this gives:

```
[0, 0.1, 0.8     ]
[0, 0,   0.777...]
[0, 0,   0.8181..]

```

so, the sphere points are respectively 0.1, 0.0222.., 0.01818... away from the center in NDC. This is a single example, but you can clearly see they're not on a sphere in NDC space, and the Z direction completely changes the proportions along Z.

Not only that, but actually transforming to the NDC is incorrect if you don't clip your volume to the clipping planes first.

Say for example you want to test the point `[0, 0, 2]` (behind the camera). The projection gives: `[0, 0, -3, -4]`. A naïve simple w divide gives `[0, 0, 0.75]`... and that's "inside" the NDC cube.
> 3 votes

# Answer
Clip-space does not have the range \[-1,1\] that you are describing. That is NDC space, which is achieved by dividing the clip-space coordinate by its W component. What is more, depending on the API, NDC may not be \[-1,1\] in all directions. This is the case in OpenGL, but in D3D the Z component ranges from \[0,1\] in NDC while X and Y range from \[-1,1\].

I mention this because unless you have an orthogonal projection (and even then, W is not guaranteed to be **1.0**), W is going to vary by distance in clip-space in order to produce perspective and therefore the actual frustum shape. Now, this frustum shape only applies in other coordinate spaces. Once you get into NDC space, the viewing volume is a cube (or in the case of D3D, half of a cube) and all of the geometry has been warped for perspective. At this point all you need to do is test your object's bounding volume (sphere in your case) against this ***cube***.

In short, ***frustum*** culling does not apply if you transform your coordinates as far as you seem to be proposing. The shape of the viewing volume is no longer a frustum. The general idea behind frustum culling is to avoid transforming the input objects that far and cull them in a more natural space such as world, where the shape of the viewing volume is actually a frustum.
> 1 votes

---
Tags: matrix, frustum-culling
---


title: What makes a game a 3D game?

text:
# Question
Title: What makes a game a 3D game?
This may sound pretty obvious to game devs here but I'm wondering if a game can be called 3D if it has 3D assets but static isometric like camera view and not rotating at all.

I tried searching the different types of video game graphics but I only find the inverse which is called 2.5D because it tries to fake 3D and that it uses 2D isometric assets.

My question is

1) What really makes a game a 3D game?

2) If a game have 3D assets with a static non rotating isometric camera view is not called a 3D game, then what?

# Answer
There are two ways to look at the dimensionality of a game: either the *technical* dimensionality or the *experienced* dimensionality.

*Technical* dimensionality refers to how the game is implemented at the level of its code and tools. A game that is *technically* 3D expresses its rendering, physics, collision, and simulation of the world in terms of code that operates on three dimensional primitives *and* uses all three dimensions of those primitives, at least sometimes.

This is different than a game that is *experienced* in 3D. Experienced dimensionality refers to the style of agency a player has within the game world. If the player has relatively free roam of a 3D world, that game experience is 3D. If the player is confined, however, to a 2D plane within an otherwise 3D world, that would be a 2D game experience.

When we say a game is "3D" we usually mean it is 3D in one of the two senses above. Often the surrounding context of the conversation will provide the clues needed for you to infer which type of 3D is being specified. Sometimes, however, when the context isn't there we clarify and say a game is "3D but with 2D gameplay," or something.
> 6 votes

# Answer
Well everything is 3d. The way you look at the scene is what changes. So to make something look 3d you have to do what your eye does, that is use a perspective projection.

However if you look at the scene with ortho projection it will 2d (lack of depth).

Now for game types, it is subjective, but if you can perceive depth the game is usualy 3d or 2,5d (if strict isometric).
> 0 votes

# Answer
Depends on the context, really. You have several kinds of 3D, and a "3D game" can mean any of them. It could mean the game has:

* a 3D perspective
* polygonal 3D
* hardware-accelerated 3D
* a 3D gameplay
* stereoscopic 3D

And any combination of those.
> 0 votes

---
Tags: graphics, terminology
---