# Question
Title: Figuring out if two objects overlap on screen
I want to figure out if 2 3D models overlap *on screen*. My general idea is:

1. Compute the bounding box of each model
2. Transform the bounding box to the View Volume using the ViewProjection matrix
3. Check if bounding boxes overlap in the view volume, ignoring the Z-axis

For step 1 I've used the answer to this question. But I'm having problems implementing step two.

I wrote the function below but its giving me inconsistent results. The numbers seem good for corners that fall inside the view volume (after multiplying by the ViewProjection matrix). But if an object falls off the screen the numbers seem incorrect. What am I doing wrong?

```
public static BoundingRectangle ProjectBoundingBox(BoundingBox box, Matrix viewProjection)
{
    var minX = float.MaxValue;
    var maxX = float.MinValue;

    var minY = float.MaxValue;
    var maxY = float.MinValue;

    var corners = box.GetCorners();

    foreach (var corner in corners)
    {
        var projectedCorner = Vector4.Transform(corner, viewProjection);
        projectedCorner /= projectedCorner.W;

        minX = Math.Min(minX, projectedCorner.X);
        maxX = Math.Max(maxX, projectedCorner.X);

        minY = Math.Min(minY, projectedCorner.Y);
        maxY = Math.Max(maxY, projectedCorner.Y);
    }

    return new BoundingRectangle(minX, maxX, minY, maxY);
}

```

Edit: the numbers

If you see the attached screenshot you see two semi-transparent stained glass windows.

```
Fully visible window:
    Bounding Box: Min( -43.62131  25.6  -10.32131 ), Max( -37.38873  34.4  -4.08873 )
    Projected Coordinates: Min(-0.7539723,-0.5401732), Max(-0.2793865, 0.27869606)

Partially visible window:
    Bounding Box: Min( -40.5142  25.6  -1.2 )  Max( -40.5  34.4  7.6 )
    Projected Coordinates: Min(-32.07214, -23.4672337), Max(47.5241241, 0.334790081)

```

As you can see the projected coordinates for the only partially visible window are gigantic. I would expect MaxX to be something like -0.9 and MinX maybe -5. But the numbers are way off.

The culprit seems to be some of the corners of the bounding box. For example `(-40.5142 34.4 7.6)` is transformed to `(47.52412 -12.65482 1.539964)`. What is interesting here is that the W coordinate is negative and less than 1 (-0.18), while for the corners that do seem correct w is positive and larger than 1.0.

Edit #2:

Here's a second picture where I've added a visualization of the projected rectangle. On the left you see the exact scenario where it goes wrong. The right side of the rectangle for the partially visible window is incorrect, while if I slightly wiggle the camera either way you get the result on the right with the correct rectangles around the models.

# Answer
> 0 votes
So @DexterZ splitting out everything that happens with the matrix transformation helped me reason about the code.

It turns out w is only negative when the point being transformed is behind the camera instead of in front of it. A simple `abs()` reflects the w component so that its correctly transformed to screen space again. An ugly corner case.

This is what I ended up with in the end, and it seems to work well so far:

```
private static Vector2 ToViewSpace(Vector3 worldPosition, Matrix viewProjection)
    {
        var x = (worldPosition.X * viewProjection.M11) + (worldPosition.Y * viewProjection.M21)
                                                       + (worldPosition.Z * viewProjection.M31)
                                                       + viewProjection.M41;

        var y = (worldPosition.X * viewProjection.M12) + (worldPosition.Y * viewProjection.M22)
                                                       + (worldPosition.Z * viewProjection.M32)
                                                       + viewProjection.M42;

        var w = (worldPosition.X * viewProjection.M14) + (worldPosition.Y * viewProjection.M24)
                                                       + (worldPosition.Z * viewProjection.M34)
                                                       + viewProjection.M44;

        // w is negative when the camera has zoomed beyond the world position in which case
        // it needs to be negated to be able to compute the correct screen position
        w = Math.Abs(w);

        x = x / w;
        y = y / w;

        return new Vector2(x, y);
    }

```

# Answer
> 1 votes
you may try this 3D position to Screen position , I use this and works on my end ^ \_^ y

**USAGE :**

```
 Vector2   mScrPosMax = Position3DToScreenPoint( _MyEntityBBox.Max, _MyCamViewProj, 1024, 700);
 Vector2   mScrPosMin = Position3DToScreenPoint( _MyEntityBBox.Min, _MyCamViewPorj, 1024, 700);
 //
 int       mRectWidth  = (int)( Math.Abs(mScrPosMax.X - mScrPosMin.X) );
 int       mRectHeight = (int)( Math.Abs(mScrPosMax.Y - mScrPosMin.Y) );
 //
 Rectangle mRect = new Rectangle((int)mScrPosMax.X, (int)mScrPosMax.Y, mRectWidth, mRectHeight);

```

**THE FUNCTION :**

```
    /// <summary>
    /// 3D position to screen point
    /// <param name="point3D">Point in 3D space</param>
    /// <param name="camViewProj">Camera view projection</param>
    /// <param name="screenWidth">Screen width</param>
    /// <param name="screenHeight">Screen height</param>
    /// <returns>Returns position on screen.</returns>
    public static Vector2 Position3DToScreenPoint( Vector3 point3D, Matrix camViewProj, float screenWidth, float screenHeight )
    {
        float m_ScreenProjX  = ( point3D.X * camViewProj.M11) + ( point3D.Y * camViewProj.M21) + ( point3D.Z * camViewProj.M31) + camViewProj.M41;
        float m_ScreenProjY  = ( point3D.X * camViewProj.M12) + ( point3D.Y * camViewProj.M22) + ( point3D.Z * camViewProj.M32) + camViewProj.M42;
        float m_ScreenProjW  = ( point3D.X * camViewProj.M14) + ( point3D.Y * camViewProj.M24) + ( point3D.Z * camViewProj.M34) + camViewProj.M44;
        //
        m_ScreenProjX  = m_ScreenProjX / m_ScreenProjW;
        m_ScreenProjY  = m_ScreenProjY / m_ScreenProjW;
        //
        m_ScreenProjX  = ((float)(((m_ScreenProjX + 1.0) * 0.5) * screenWidth  ));
        m_ScreenProjY  = ((float)(((1.0 - m_ScreenProjY) * 0.5) * screenHeight ));
        //
        return new Vector2( m_ScreenProjX, m_ScreenProjY );
    }

```

# Answer
> 1 votes
I forgot to mention that there's a built-in **Viewport.Project** and **Viewport.Unproject** from the framework that intended to do exactly the same thing.

But Heres a good read for for projecting 3d position to screen space : https://www.scratchapixel.com/lessons/3d-basic-rendering/computing-pixel-coordinates-of-3d-point/mathematics-computing-2d-coordinates-of-3d-points

Cheers ^ \_^ Y

---
Tags: monogame, projection, overlay
---


# Question
Title: Unity, NavMeshAgent SetDestination acts funny
I had a scene set as the following picture.

And a NavMesh baked as the following picture.

But my "player" (The left-bottom corner sphere) don't go where I want it want to go!

Test vedio

**Source Codes:**

```
public Camera cam;
public NavMeshAgent agent;
public GameObject particle;
// Update is called once per frame
private void Start()
{
    particle.GetComponent<Renderer>().material.color = Color.red;
}
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray,out hit))
        {
            Vector3 v = hit.point;
            agent.SetDestination(v);
            Instantiate(particle,v,transform.rotation);
        }
    }
}

```

Could somebody please help me out!?

Much appreciated!!!

PS.

I found out through my "particle" that after first few hits, the "hit position" starts to "float"!

That's why my "particle" became bigger!

It doesn't "hit" the plane no more!

It always hit at somewhere above the plane!

That's why my "player" can NOT go to the destination!

Could somebody teach me how to fix it please!

Much appreciated!

# Answer
> 1 votes
I found out that my issue is that the "ray" is NOT always hitting the "plane"!

It always hit some imaginary thing "above" the plane (except the first hit) and I don't know why!

So to fix the problem, I first assigned a `Ground` layer to the plane, then add a `Public LayerMask lm` to the script. Then finally change the `Raycast(ray,out hit)` to `Raycast(ray,out hit, 1000, lm)`.

And voila! Problem solved!!!

**Source Code:**

```
public Camera cam;
public NavMeshAgent agent;
public GameObject particle;
public LayerMask lm;
// Update is called once per frame
private void Start()
{
    particle.GetComponent<Renderer>().material.color = Color.red;
}
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = cam.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if(Physics.Raycast(ray,out hit, 1000, lm))
        {
            Vector3 v = hit.point;
            agent.SetDestination(v);
            Instantiate(particle,v,transform.rotation);
        }
    }
}

```

PS. Please don't forget to assign the `lm` in the inspector to `Ground`.

---
Tags: unity, navmesh
---


# Question
Title: Is it possible to make realistic animations in 2D?
I plan to make a skateboarding game and I am wondering about one thing: is it possible to make 2D realistic animations to simulate skate's and skater's rotations or should I resort to 3D for realistic visual effects?

P.S: As you guess I am new to game development.

# Answer
> 1 votes
If realism is really a concern for you, 3D animations will work the best. We live in a 3D world after all. Note that you can have 3D modelling & animation, but keep the gameplay in 2D. For instance, check Trials: https://youtu.be/mhsusQvTab8?t=2m23s.

On the other hand 2D animation can look great if done properly, even if it's *not* realistic. Check Rayman Origins for instance: https://www.youtube.com/watch?v=syNWMkBSmLU. It's also simpler to implement & author.

But since you're a beginner, I suggest you start small and prototype some basic gameplay without even thinking about animation. You'll see how this goes: animation is tightly coupled with gameplay, so it's probably something to figure out after you have a first playable prototype.

---
Tags: 2d, animation
---


# Question
Title: Mobile game - different actions based on different tap input?
I am creating a mobile game in which you can destroy blocks and interact with blocks like in Minecraft.

However, the problem is, in Minecraft you destroy blocks using left mouse button click and interact using right mouse button click, but on mobile I don't have 2 buttons, only 1 - the screen tap.

Of course, I could create a button to toggle between 2 modes, but I am sure there is a more elegant way that would not be so annoying for players.

What are the options?

# Answer
A common way is to differentiate between two different modes of interaction is tapping vs. holding. A short tap could mean interaction while holding down on the object starts the destruction process.

Another option might be to use gestures like dragging. Drag gestures are usually associated with moving. Mining a block in Minecraft moves it from the world to the player's inventory. So dragging the block from the world into the inventory bar could be a gesture for mining. Simliarly, dragging from the inventory bar into the world could be a gesture for placing blocks.

One thing a mouse can't do but a touchscreen can are multi-touch gestures. A two-finger pinch is associated with zooming while a two-finger turn is associated with rotation. But neither make much sense for this scenario. Another way to use two fingers is to have one finger determine the context of the other. Have a number of icons at the edge of the screen which represent different modes of interaction. The player places one finger on the icon and then performs the action with the other. The drawback of using multi-touch gestures is that it is no longer possible to play the game one-handed. The user either needs to put the phone down or hold it with one hand while playing with the other.

Another thing *some* touchscreens can do is pressure-sensitivity. You can differentiate between pressing lightly and pressing hard. But keep in mind that not all low-end smartphones have pressure-sensitive touchscreens (or at least none which are very good). Also, different manufacturers have different ideas of how much pressure translates to which input value.
> 0 votes

---
Tags: game-design
---


# Question
Title: Do i need to integrate leader-board and achievement in my game and then publish in alpha testing for google play?
I'm confused about whether I need to publish my .apk file on Google Play Console with or without achievements and leaderboard.

1. If I publish the game without achievements and leaderboards, then, how can I integrate the google play service at a later date?
2. The first thing I saw was that I should go for alpha publish. Is that necessary?
3. If I do publish the alpha version for the game without including achievements and leaderboard, how can I add these later? In this video, first the game is published without the achievements/leaderboard, and later he integrates them. So how does it show results since we didn't include these buttons for leaderboard and achievements?

# Answer
> 1 votes
It is not necessary to do an alpha publish. The apk you upload to publish to the store will only have what you include on it. To update the game with leaderboards, you could upload another apk built with the same key and a new version number. This will be treated as an update for users who have already installed the game.

# Answer
> 0 votes
You do not need to upload an apk that has achievements or leaderboards. If you wish to add them later, all you have to do is follow along the steps shown in the video.

Also, you are not forced to create achievements in the Google Play Developer Console, and use them. Notice in the video that it takes time to publish the changes. Once the settings in the Google Play Developer Console are published, you can still choose not to have code for unlocking the achievements. But once they are published, users will be able to see them.

You will just have to add relevant code to unlock achievements when you want to update your apk, and when you are about to create a build, you will have to increment the build version in player settings. This will allow you to update the app on the Developer Console.

Whenever you upload a build to the Developer Console, you have the option of setting the environment to which you wish to publish. Alpha, Beta or Release. I don’t remember for sure, but I don’t think you can go back to Alpha or Beta after uploading a Release build. If you have already tested your game, you can release without alpha or beta without issues. If you are publishing it for your testers, or for open alpha/beta, you can do that, and then later release a finished product having fixed most of the bugs.

ALSO IMPORTANT NOTE: When you create a keystore for uploading the app to the Play Store, do not lose the password. You will not be able to update your app if you do not sign it with the same keystore details.

---
Tags: unity, google-play-services, leaderboards, achievements
---


# Question
Title: How to implement multicolored flashing sprite effect like in Contra and the Messenger?
I want to implement an effect similar to what you see in this clip of Contra.

When the boss takes damage, he flashes wildly with different colors.

A similar effect can be seen in this clip from the Messenger (with the addition of an outline).

I don't care how they did it in Contra or the Messenger. I want to achieve a similar effect, preferably with a shader using GLSL.

**Any ideas on how to go about it?**

The effect seems to alternate the sprites between red and blue palettes, but I'm not sure if palette swapping is an effective way to achieve this, especially since I don't have my art assets in gray scale.

Maybe a hue shift shader is a viable alternative? Or maybe there's another way.

# Answer
I think you could achieve this effect by using a rotating color palette. You can do this in GLSL by passing in a grayscale image and a 1D texture containing the color palette. You'd sample the grayscale image and use the resulting value to lookup into the 1D texture. You get the palette rotation by adding a value to the grayscale value. Something like this (not tested, probably has mistakes):

```
uniform sampler2D image;
uniform sampler1D colorPalette;
uniform float offset; // <- value between 0 and 1 that increases on each frame and wraps around
void main()
{
    float grayscalePixel = texture2D(gl_TexCoord[0], image);
    float paletteLookup = fract(grayscalePixel + offset);
    return texture1D(paletteLookup, colorPalette);
}

```
> 3 votes

---
Tags: 2d, shaders, glsl, fragment-shader, graphic-effects
---


# Question
Title: Libgdx get texture from Texture Atlas with findRegion
I have this code

```
textureAtlas = TextureAtlas("atlas.atlas")

val box = textureAtlas.findRegion("box")

```

I want to create a texture with "box". Is it possible? box.texture return the original texture, not the regioned. Oh and I don't want to use Sprite and SpriteBatch. I need this in 3D, not 2D.

Thanks

# Answer
TextureAtlas actually not separating pieces. When you get region from atlas its just saying that this is the area you gonna use (u,v,u2,v2) and this is original reference to whole texture.

This is why batch.draw(Texture) and batch.draw(TextureRegion) are not same in use.

However taking part of picture as texture is possible.

* You can use pixmap to do it.

First generate pixmap from atlas texture. Then create new empty pixmap in size of "box" area you want. Then assign pixel arrays and generate texture from your new pixmap.

It may be quite expensive due to your Textureatlas size.

* You can use framebuffer. Create FBbuilder and build new frame buffer.Draw texture region to this buffer and get texture from it.

Problem here is the sizes of texture will be same as viewport/screen sizes.I guess you can create new camera to change it to sizes you want.

```
GLFrameBuffer.FrameBufferBuilder frameBufferBuilder = new GLFrameBuffer.FrameBufferBuilder(widthofBox, heightofBox);
    frameBufferBuilder.addColorTextureAttachment(GL30.GL_RGBA8, GL30.GL_RGBA, GL30.GL_UNSIGNED_BYTE);
    frameBuffer = frameBufferBuilder.build();
    OrthographicCamera c = new OrthographicCamera(widthofBox, heightofBox);
    c.up.set(0, 1, 0);
    c.direction.set(0, 0, -1);
    c.position.set(widthofBox / 2, heightofBox / 2, 0f);
    c.update();
    batch.setProjectionMatrix(c.combined);
    frameBuffer.begin();
    batch.begin();
    batch.draw(boxregion...)
    batch.end();
    frameBuffer.end();
    Texture texturefbo = frameBuffer.getColorBufferTexture();

```

Texturefbo will be y flipped. You can fix this with texture draw method by setting scaleY to -1 or You can scale scaleY to -1 while drawing on framebuffer or can change camera like this

```
up.set(0, -1, 0);
direction.set(0, 0, 1);

```

to flip to camera on y axis.

Last thing came to my mind is mipmapping this texture.Its also not so hard.

```
    texturefbo.bind();
    Gdx.gl.glGenerateMipmap(GL20.GL_TEXTURE_2D);
    texturefbo.setFilter(Texture.TextureFilter.MipMapLinearLinear,
    Texture.TextureFilter.MipMapLinearLinear);

```
> 1 votes

# Answer
Inside an TextureAtlas you can have many pointers to textures, so you can add one that just goes to the box.png and retrieve it's region like so:

```
box.png
size: 128,128
format: RGBA8888
filter: Nearest,Nearest
repeat: none
box
  rotate: false
  xy: 0, 0
  size: 128, 128
  orig: 128, 128
  offset: 0, 0
  index: -1

test.png
size: 1024,1024
format: RGBA8888
filter: Nearest,Nearest
repeat: none
testA
  rotate: false
  xy: 974, 974
  size: 48, 48
  orig: 48, 48
  offset: 0, 0
  index: -1
testB
  rotate: false
  xy: 974, 974
  size: 48, 48
  orig: 48, 48
  offset: 0, 0
  index: -1

test2.png
size: 1024,1024
format: RGBA8888
filter: Nearest,Nearest
repeat: none
testA
  rotate: false
  xy: 2, 358
  size: 576, 324
  orig: 576, 324
  offset: 0, 0
  index: -1
testB
  rotate: false
  xy: 928, 438
  size: 48, 48
  orig: 48, 48
  offset: 0, 0
  index: -1

```

Then just do:

```
TextureAtlas at = new TextureAtlas(<somefile_path);
Texture t = at.findRegion("box).getTexture();

```

You mention **original texture**, so the texture must be just the box. If the texture has many images, then it's an atlas and you will need to get that region and make an individual texture from that using Pixmap.
> 1 votes

---
Tags: libgdx
---


title: Billboard quad in same draw call?

text:
# Question
Title: Billboard quad in same draw call?
I am currently drawing a isometric world in 3D, meaning the floors and walls are all quads aligned to the original axis in the world and using a rotated orthogonal camera to "distort" the images into an isometric projection.

The textures of the walls and floors are just rectangular textures on a axis aligned quad, the camera is doing the rest. I am building a single mesh from everything and adding vertices in the order of back to front manually. So no OpenGL sorting is used. The order is important since I am using alpha blending.

The other quad represents an object on a tile but can very well be a dynamic object such as a player or NPC. This is currently drawn along the regular Y(up) axis. It's texture is already painted isometric and since there is an angle it gets distorted. To counteract this I am currently stretching the quad in Y(up) direction. This works fairly well but obviously it creates artifacts, especially when it needs tiling.

I figured my best option is to draw these as camera aligned billboard but I need control of the draw order, just like I am drawing it now so I can fit these objects in between walls and other objects. However I am not sure how to create these billboards properly. I could create a quad with the screen dimensions I need and then perhaps rotate the verts or perhaps change projection matrix when I need to draw a billboard. They obviously have to be aligned properly to the world.

So how would I approach this problem in detail? Perhaps with some code how to transform a quad to face the camera and keeping it aligned with the world? In particular, since I am using a fixed camera projection I would like to leverage this and reduce calculations if that is possible.

I have created the following method to translate vertices to have the quad face the camera. This "should" add a billboard in the center of my world but it does not.

```
public void addBillboardAtCenter(float x, float y, float z, FloorObject floorObject) {
    //Not sure if these are correct.
    Vector3 cameraRightWorldspace = new Vector3(1, 0, 0).mul(cam.invProjectionView);
    Vector3 cameraUpWorldspace = cam.up.cpy().mul(cam.invProjectionView);

    Vector3 bottomLeft = new Vector3(0, 0, 0); // center of billboard
    bottomLeft.add(cameraRightWorldspace.scl(-.5f));
    bottomLeft.add(cameraUpWorldspace.scl(-.5f));

    Vector3 topLeft = new Vector3(0, 0, 0); // center of billboard
    bottomLeft.add(cameraRightWorldspace.scl(-.5f));
    bottomLeft.add(cameraUpWorldspace.scl(.5f));

    Vector3 bottomRight = new Vector3(0, 0, 0); // center of billboard
    bottomLeft.add(cameraRightWorldspace.scl(.5f));
    bottomLeft.add(cameraUpWorldspace.scl(-.5f));

    Vector3 topRight = new Vector3(0, 0, 0); // center of billboard
    bottomLeft.add(cameraRightWorldspace.scl(.5f));
    bottomLeft.add(cameraUpWorldspace.scl(.5f));

    // Bottom left
    verts[vi++] = bottomLeft.x;
    verts[vi++] = bottomLeft.y;
    verts[vi++] = bottomLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Bottom right halfway
    verts[vi++] = bottomRight.x;
    verts[vi++] = bottomRight.y;
    verts[vi++] = bottomRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Top left
    verts[vi++] = topLeft.x;
    verts[vi++] = topLeft.y;
    verts[vi++] = topLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;

    // Top right halway
    verts[vi++] = topRight.x;
    verts[vi++] = topRight.y;
    verts[vi++] = topRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;
}

```

Another attempt, this yields a slightly rotated (27.5 degree?) version of my sprite with it's center positioned at the center of my world.

```
public void addBillboard(FloorObject floorObject) {
    Vector3 direction = new Vector3(-1, 0, 0).nor();
    Vector3 cameraDirection = cam.direction.cpy().nor();

    Vector3 leftRight = direction;

    float dot = cameraDirection.cpy().dot(direction);

    Vector3 updown = new Vector3(0, 1, 0);
    if (Math.abs(dot) < 1f) {
        updown = direction.cpy().crs(cameraDirection);
    }
    updown.nor();

    Vector3 position = new Vector3(0, 0, 0);

    Vector3 bottomLeft = position.cpy().add(updown).sub(leftRight);
    Vector3 topLeft = position.cpy().sub(updown).sub(leftRight);
    Vector3 bottomRight = position.cpy().add(updown).add(leftRight);
    Vector3 topRight = position.cpy().sub(updown).add(leftRight);

    // Bottom left
    verts[vi++] = bottomLeft.x;
    verts[vi++] = bottomLeft.y;
    verts[vi++] = bottomLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Bottom right halfway
    verts[vi++] = bottomRight.x;
    verts[vi++] = bottomRight.y;
    verts[vi++] = bottomRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Top left
    verts[vi++] = topLeft.x;
    verts[vi++] = topLeft.y;
    verts[vi++] = topLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;

    // Top right halway
    verts[vi++] = topRight.x;
    verts[vi++] = topRight.y;
    verts[vi++] = topRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;

}

```

# Answer
I came up with a very short (in code) solution. Involving the view matrix of the camera, I do not have thorough understanding on matrices but they essentially contain the rotation, scale and transformation. So in my last example I created 2 vectors "leftRight" and "upDown" and I renamed these to just "right" and "up" representing the camera right and up direction in the world view, often called model view as well. This is how I got the correct values from the camera's view matrix.

```
    right.x = modelview.val[0];
    right.y = modelview.val[4];
    right.z = modelview.val[8];

    up.x = modelview.val[1];
    up.y = modelview.val[5];
    up.z = modelview.val[9];

```

It just looks up the values in the array. I tried this very earlier but used incorrect lookup indices. Having these, the math to transform a vertex is pretty straightforward.

```
    float size = 1.4142135624f;

    Vector3 bottomLeft = position.cpy().sub(right.cpy().scl(size * .5f));
    Vector3 bottomRight = position.cpy().add(right.cpy().scl(size * .5f));
    Vector3 topRight = position.cpy().add(right.cpy().scl(size * .5f)).add(up.cpy().scl(size * 2));
    Vector3 topLeft = position.cpy().sub(right.cpy().scl(size * .5f)).add(up.cpy().scl(size * 2));

```

Since my floor quads are of size 1x1 I need to do Pythagoras `1.414..` since it needs to fill up a complete tile. Then I calculate the position of each vertex, since I needed to place the bottom center of the quad in a exact world position I multiply the size by `.5` and my billboards need to be double the size in height so I multiply the size with the up vector by 2. To make this faster, create 2 constants (width and height) for this so the multiplications won't be necessary. Then when these are calculated I can just batch my vertices like usual.

```
    // Bottom left
    verts[vi++] = bottomLeft.x;
    verts[vi++] = bottomLeft.y;
    verts[vi++] = bottomLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Bottom right halfway
    verts[vi++] = bottomRight.x;
    verts[vi++] = bottomRight.y;
    verts[vi++] = bottomRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV2();
    verts[vi++] = 1;

    // Top left
    verts[vi++] = topLeft.x;
    verts[vi++] = topLeft.y;
    verts[vi++] = topLeft.z;
    verts[vi++] = floorObject.getU();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;

    // Top right halway
    verts[vi++] = topRight.x;
    verts[vi++] = topRight.y;
    verts[vi++] = topRight.z;
    verts[vi++] = floorObject.getU2();
    verts[vi++] = floorObject.getV();
    verts[vi++] = 1;

```

There are still very minor artifacts on some "zoom" levels where pixels suddenly take an additional step out of 2:1 and start to look slightly "jittered" but I am really happy with the result.

*zoomed in it follows a proper 6:3 pattern (original screenshot size)*

*Zooming out 3 times creates some artifacts (tripled screenshot size), would expect to still follow a 2:1 pattern. Also when moving the camera you can see pixels being added and removed*

I think this is because I am giving my tiles a unit size of 1x1 and the camera is navigating in many decimals. I could probably make my tiles bigger and have the camera snap to rounded numbers to at least reduce this effect.
> 1 votes

---
Tags: opengl, java, libgdx, opengl-es2, isometric
---


title: Catmull Rom Spline - Constant Speed

text:
# Question
Title: Catmull Rom Spline - Constant Speed
Given the equations found in the answer here:

Determine arc-length of a Catmull-Rom spline to move at a constant speed

How would one A) Apply this to a 3D Catmull-Rom Spline, and B) write A out programmatically (for the math illiterate)?

# Answer
There are a few ways to move along at a constant speed along a path whose "segments" are not a constant length - and it's not trivial to make them that way.

I would approach the problem by making a "Mover" of sorts which follows a "Path".

```
public interface Path<T> {
   public T getPoint(float delta);
}
public class Mover<T> {
   public Path<T> path;
   public T position;
   public T lookahead;
   public float lookaheadDelta;
   public float delta;
   public float speed;
   public void init() { ... }
   public void update(float dt) { ... }
}

```

(sorry if you haven't learned about generics/templating, just replace T with Vector3)

Most "path" implementations like Catmull-Rom spline can give you a point given a delta value that ranges from 0 to 1. Based off of this the Mover moves along the path looking "lookaheadDelta" ahead and moving towards that point. The smaller this value the smoother the movement, but if it's too small you might make to many path calculations per update.

The update method is important, it tries to move speed\*dt units along the path. If the distance between lookahead and the current position is less than this value than you need to iteratively calculate the new lookahead based on the lookaheadDelta and continually move towards it.

It would look something like this:

```
public void update(float dt) {
  float move = dt * speed; // units to move
  while (move > 0.0) {
    // between current position and target
    float room = distance( lookahead, position );
    // how much we're actually moving this iteration
    float actual = Math.min( move, room );
    // the normalized vector between lookahead and position
    float direction = (lookahead - position) / room;
    // move my position accordingly
    position += direction * actual;
    // update move to be the remaining amount we need to move
    move -= actual;
    // reset target
    if (actual != room) {
      delta += lookaheadDelta;
      lookahead = path.getPoint(delta);
    }
  }
}

```

And don't forget about initializing it!

```
public void init() {
  position = path.getPoint(0.0);
  delta = lookaheadDelta;
  lookahead = path.getPoint(delta);
}

```

Don't forget to add in logic to check when delta \>= 1.0 which means you're at the end!

You could even calculate lookaheadDelta based on the estimated length of the spline and the units of your game. I would guess 100 data points would be enough making 0.01 a good value for lookaheadDelta.

You could also cache "direction" and "room" after each lookahead calculation.
> 1 votes

# Answer
I encountered similar issues while attempting to solve this for a Catmull-Rom spline without access to the source code in to fetch the coefficient derivatives.

My spline was based on time parameters of 0 - 1000, but this could easily be adapted for 0 - 1.

Since the position and time do not have 1:1 ratio, tracking the difference in position of the next desired step and then adjusting the next time step accordingly gave me the uniform values I was looking for.

My basic approach was as follows:

```
        Vector nextPosition = spline.GetPointAtTime(splineTime + 1);
        Vector positionDelta = (nextPosition - position);

        float distance = positionDelta.Magnitude();

        float ratio = 1 / distance;
        splineTime = splineTime + speed * ratio;

```

Where the speed is some predefined constant. The object position is then set per frame by getting the amended spline time in the last line of the code.
> 1 votes

---
Tags: 3d, mathematics, algorithm, software-engineering, curves
---


# Question
Title: processing request in order on game server
I am creating a simple multiplayer puzzle game in which multiple players can join a lobby and compete with each other. the player that submits the answer first gets the highest point, the player that submits the answers second gets the second highest point and so on..

How do I maintain the order of request on the server side?

I assume i cannot use an event-based server as it would become impossible to process requests in order.

a simple multithreaded server would be an ideal choice in this case as the requests will be short-lived.

initially, I was thinking to create the server in python but since it has not so good support for "real threads" it would mean compromising on performance.

***My two main questions are:***

1. how is this scenario generally handled?
2. how is this scenario generally handle if the language of choice is python?

# Answer
When you have one or more threads which access the game state, then you want to avoid that more than one thread does so at the same time. Otherwise you can run into very hard to reproduce bugs which occur when one thread tries to access a data structure while another thread is in the middle of changing it.

In order to avoid this, you can use a Lock.

When your networking thread wants to check on the state of the game to see if it is the first to answer the question, use `lock.acquire()`. When no other thread has the lock acquired at the moment, the execution will continue immediately. When there is another thread which acquired the lock, then execution will pause until that thread does a `lock.release()`. That means a lock allows you to define a section of code where only one thread is allowed at a time. All other threads need to wait until it's their turn.

Pseudocode:

```
def checkAnswer( answer )

    lock.acquire()

    if questionAlreadyAnswered:
         print "you were too slow."
    else
         if answer == correctAnswer:
              print "correct!"
              questionAlreadyAnswered = true
         else
              print "wrong!"

    lock.release()

```
> 0 votes

---
Tags: networking, multiplayer, python, multithreading
---


# Question
Title: How do I set the gravity of a plane world
As you can see in the image, the character is set to move on a ground plane, however that causes an issue with Box2d's gravitational pull.
The player can go sideways, upwards and downwards on the plane.
Is there any way I can use gravity in this case?

# Answer
Reading the comments I think Box2D is overkill to achieve what you want. Why not just have a velocity vector and decrease it over time?

```
    Vector3 velocity = new Vector3();

    //Update method
    if (Gdx.input.isKeyJustPressed(Input.Keys.RIGHT)) {
        velocity.x = horizontalSpeed * delta;
    } else if (Gdx.input.isKeyJustPressed(Input.Keys.LEFT)){
        velocity.x = -horizontalSpeed * delta;
    } else {
        // Reduce velocity if no key is pressed
        velocity.x *= .9f;
    }
    // Do same for Y axis, with a different speed variable since it's not fully top down.

    // Then add velocity to your position
    position.add(velocity);

```

You can also use the deceleration method for acceleration by increasing the velocity until your max speed is reached. This however does have a bigger impact on controlling your character then deceleration and is more often used in racing games to simulate a car.
> 1 votes

---
Tags: libgdx, box2d
---


# Question
Title: Can DDS be used in OpenGL in Linux without license/patent issue?
Is there a 'standard' for OpenGL game creation intended for both Windows and Linux? I understand DDS is the DirectX standard (or, at least, it appears to be). Is there one that does not have potential patent/license issue or does it really not matter?

I am asking as I would like to avoid focusing on DDS as the format to use, only to have that kick me in the teeth later when some license/patent/??? issue requires me to remove and replace DDS with *\[texture format here\]*. This is not about what is better or an opinion post, but what is (relatively) safe from the constraints mentioned earlier?

# Answer
There is no disk texture format that is standard for OpenGL, but the DDS data format is relatively easy to read in and use in OpenGL since DDS is essentially a wrapper for compressed textures and the compression format used is supported by OpenGL. Thus you may find DDS suitable for cross-platform development.

The only patent related issue with DDS was with the S3 compression technology used, however the patent on that expired earlier this year so there is no possibility of further problems.
> 1 votes

---
Tags: opengl, c++, textures, linux
---


title: Terrain collision detection

text:
# Question
Title: Terrain collision detection
How should I go about making terrain collision system without hightmap ?

What I have tried is building a heightmap from a blender model, but that works only if the vertices are evenly spaced. Mine are not and I am not sure how to proceed from here.

How do i store the mesh info ? Do I store a Plane object for every triangle in the mesh and then plug those in some kind of grid/quad tree etc ? Is that the best thing to do ? My terrain has around 2000 faces, wouldn't that be too much ?

# Answer
> 2 votes
A heightmap is just a mapping from 2D horizontal positions to heights. It's often *implemented* as a regular grid of height samples we could encode in say a texture's grid of pixels, but that's by no means a requirement.

Instead, we could implement it as a 2D quadtree/bounding volume hierarchy (or other spatial partition), storing our vertices or triangles by their horizontal positions/extents. This lets us quickly isolate which triangles of the terrain lie within the footprint of a prospective collider. If each node of the tree also tracks its max height, we can use this as an early-out to skip checks for objects elevated above the terrain.

Once you have the potential triangles involved, then it's just a series of triangle-primitive collision checks, like a regular mesh collision. We just use the nature of the terrain to help us isolate the relevant triangles more easily.

> "My terrain has around 2000 faces, wouldn't that be too much?"

That's a question for your profiler, but there's no particular reason to expect it would be. A good spatial partition should let us get to the relevant triangles in a number of steps logarithmic in the number of faces, so you're looking at a tree depth of a dozen or less. After that, your time spent on collisions will be determined by how many triangles you need to check, so as long as your colliding objects aren't spanning hundreds of triangles worth of terrain, you should be fine. (And if they are, it might be a good idea to let them collide with a simplified terrain with fewer triangles - if I'm trying to simulate a cruise liner, it's not going to care about every little bump and divot.)

---
Tags: opengl, terrain
---


title: OpenGL Deferred Shading Pixelation

text:
# Question
Title: OpenGL Deferred Shading Pixelation
I'm working on a 3-pass deferred lighting system for a voxel game, however I am having problems with pixelated lighting and ambient occlusion.

The first stage renders the color, position and normal of each pixel on the screen into separate textures. This part works correctly:

The second shader calculates an ambient occlusion value for each pixel on the screen and renders that to a texture. This part doesn't work correctly and is pixelated:

Raw occlusion data:

The third shader uses the color, position, normal and occlusion textures to render the game scene onto the screen. The lighting in this stage is also pixelated:

The SSAO (2nd pass) fragment shader comes from the www.LearnOpenGL.com tutorial for Screen Space Ambient Occlusion:

```
out float FragColor;

layout (binding = 0) uniform sampler2D gPosition; // World space position
layout (binding = 1) uniform sampler2D gNormal; // Normalised normal values
layout (binding = 2) uniform sampler2D texNoise;

uniform vec3 samples[64]; // 64 random precalculated vectors (-0.1 to 0.1 magnitude)
uniform mat4 projection;

float kernelSize = 64;
float radius = 1.5;

in vec2 TexCoords;

const vec2 noiseScale = vec2(1600.0/4.0, 900.0/4.0);

void main()
{
    vec4 n = texture(gNormal, TexCoords);

    // The alpha value of the normal is used to determine whether to apply SSAO to this pixel
    if (int(n.a) > 0)
    {
        vec3 normal = normalize(n.rgb);
        vec3 fragPos = texture(gPosition, TexCoords).xyz;
        vec3 randomVec = normalize(texture(texNoise, TexCoords * noiseScale).xyz);

        // Some maths. I don't understand this bit, it's from www.learnopengl.com
        vec3 tangent = normalize(randomVec - normal * dot(randomVec, normal));
        vec3 bitangent = cross(normal, tangent);
        mat3 TBN = mat3(tangent, bitangent, normal);

        float occlusion = 0.0;

        // Test 64 points around the pixel
        for (int i = 0; i < kernelSize; i++)
        {
            vec3 sam = fragPos + TBN * samples[i] * radius;

            vec4 offset = projection * vec4(sam, 1.0);
            offset.xyz = (offset.xyz / offset.w) * 0.5 + 0.5;

            // If the normal's are different, increase the occlusion value
            float l = length(normal - texture(gNormal, offset.xy).rgb);
            occlusion += l * 0.3;
        }

        occlusion = 1 - (occlusion / kernelSize);
        FragColor = occlusion;
    }
}

```

The lighting and final fragment shader:

```
out vec4 FragColor;

in vec2 texCoords;

layout (binding = 0) uniform sampler2D gColor; // Colour of each pixel
layout (binding = 1) uniform sampler2D gPosition; // World-space position of each pixel
layout (binding = 2) uniform sampler2D gNormal; // Normalised normal of each pixel
layout (binding = 3) uniform sampler2D gSSAO; // Red channel contains occlusion value of each pixel

// Each of these textures are 300 wide and 2 tall.
// The first row contains light positions. The second row contains light colours.

uniform sampler2D playerLightData; // Directional lights
uniform sampler2D mapLightData; // Spherical lights

uniform float worldBrightness;

// Amount of player and map lights
uniform float playerLights;
uniform float mapLights;

void main()
{
    vec4 n = texture(gNormal, texCoords);

    // BlockData: a = 4
    // ModelData: a = 2
    // SkyboxData: a = 0;

    // Don't do lighting calculations on the skybox
    if (int(n.a) > 0)
    {
        vec3 Normal = n.rgb;
        vec3 FragPos = texture(gPosition, texCoords).rgb;
        vec3 Albedo = texture(gColor, texCoords).rgb;

        vec3 lighting = Albedo * worldBrightness * texture(gSSAO, texCoords).r;

        for (int i = 0; i < playerLights; i++)
        {
            vec3 pos = texelFetch(playerLightData, ivec2(i, 0), 0).rgb;

            vec3 direction = pos - FragPos;
            float l = length(direction);

            if (l < 40)
            {
                // Direction of the light to the position
                vec3 spotDir = normalize(direction);

                // Angle of the cone of the light
                float angle = dot(spotDir, -normalize(texelFetch(playerLightData, ivec2(i, 1), 0).rgb));

                // Crop the cone
                if (angle >= 0.95)
                {
                    float fade = (angle - 0.95) * 40;
                    lighting += (40.0 - l) / 40.0 * max(dot(Normal, spotDir), 0.0) * Albedo * fade;
                }
            }
        }

        for (int i = 0; i < mapLights; i++)
        {
            // Compare this pixel's position with the light's position
            vec3 difference = texelFetch(mapLightData, ivec2(i, 0), 0).rgb - FragPos;
            float l = length(difference);

            if (l < 7.0)
            {
                lighting += (7.0 - l) / 7.0 * max(dot(Normal, normalize(difference)), 0.0) * Albedo * texelFetch(mapLightData, ivec2(i, 1), 0).rgb;
            }
        }

        FragColor = vec4(lighting, 1.0);
    }
    else
    {
        FragColor = vec4(texture(gColor, texCoords).rgb, 1.0);
    }
}

```

The size of each block face in the game is 1x1 (world space size). I have tried splitting these faces up into smaller triangles, as illustrated below, however there wasn't much visible difference.

My thoughts are:

* The resolution of angles between pixels and light sources are not high enough, causing the banding lighting effect
* I am not tessellating the triangles on the block faces enough.

How can I increase the resolution of the lighting and SSAO data to reduce these pixelated artifacts? Thank you in advance

# Answer
> 2 votes
I used to get pixelated light when precision of gBuffer textures was low. Use GL\_RGB16F or GL\_RGB32F as internal format for position. Position can be reconstructed from depth texture like this, so no need to save position and waste space in gBuffer:

```
vec3 worldSpaceFromDepth(in float depth) {
    float z = depth * 2.0 - 1.0;

    vec4 clipSpacePosition = vec4(uv0 * 2.0 - 1.0, z, 1.0);
    vec4 direct = pc.projectionCameraMatInverse * clipSpacePosition;
    return direct.xyz / direct.w;
}

```

Here is my gBuffer setup:

```
_depthComponentTexture = new Texture(_width, _height, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT, GL_NEAREST);
_worldNormalSpecPower = new Texture(_width, _height, GL_RGBA16F, GL_RGBA, GL_NEAREST);
_albedoSpecularIntensity = new Texture(_width, _height, GL_RGBA8, GL_RGBA, GL_NEAREST);
_3viewNormalSSAOShaderless = new Texture(_width, _height, GL_RGBA16F, GL_RGBA, GL_NEAREST);

```

---
Tags: opengl, shaders, glsl, lighting, deferred-rendering
---


# Question
Title: How to setup engine properly in ktx-ashley?
I'm trying to setup simplest Ashley project with only 2 entities and get this error:

```
Exception in thread "LWJGL Application" java.lang.IllegalStateException: createComponent(T::class.java).apply(configure) must not be null

```

Here is the code:

```
class AshleyScreen(game: Main): KtxScreen {

    private val engine = Engine()

    override fun show() {
        engine.add {
            entity {
                with<DrawableComponent> {
                    sprite = Sprite(Texture("image1.png"))
                }
                with<TransformComponent> {
                    position.set(0f, 400f)
                }
            }
            entity {
                with<DrawableComponent> {
                    sprite = Sprite(Texture("image2.png"))
                }
                with<TransformComponent> {
                    position.set(500f, 50f)
                }
            }
        }
        val renderSystem = RenderSystem()
        engine.addSystem(renderSystem)
    }

    override fun render(delta: Float) {
        engine.update(delta)
    }
}

// Components
class DrawableComponent(var sprite: Sprite): Component
class TransformComponent(val position: Vector2 = Vector2()): Component

//Systems
class RenderSystem: IteratingSystem(allOf(DrawableComponent::class).get()) {
    val batch = SpriteBatch()
    val tm = ComponentMapper.getFor(TransformComponent::class.java)
    val dm = ComponentMapper.getFor(DrawableComponent::class.java)

    override fun processEntity(entity: Entity, deltaTime: Float) {
        val t = tm[entity]
        val d = dm[entity]
        d.sprite.setPosition(t.position.x, t.position.y)

        clearScreen(0.8f, 0.8f, 0.8f)
        batch.begin()
        d.sprite.draw(batch)
        batch.end()
    }
}

```

Compiler complains on `engine.add` line.

# Answer
Well, you should just add default values for both components:

```
class DrawableComponent(var sprite: Sprite = Sprite(Texture("image.png"))): Component
class TransformComponent(val position: Vector2 = Vector2()): Component

```
> 0 votes

---
Tags: libgdx, kotlin, ashley
---


# Question
Title: What is best for 2D movement: velocity or AddForce?
So I have tried both Velocity and addForce but I'm not getting the result I was expecting which makes me wonder if I fully understand what they do.

Move script (test script 1)

```
void Update () {

    if(Input.GetKeyDown(KeyCode.Space)){
        rb.velocity = new Vector2(rb.velocity.x, jumpHeight);
    }

    if(Input.GetKeyDown(KeyCode.A)){
        rb.velocity = new Vector2(-moveSpeed, rb.velocity.y);
    }

    if (Input.GetKeyDown(KeyCode.D)){
        rb.velocity = new Vector2(moveSpeed, rb.velocity.y);
    }
}

```

Move2 script (test script 2)

```
void FixedUpdate() {
       float x = Input.GetAxis("Horizontal");
       float y = Input.GetAxis("Vertical");

       rbody.velocity = new Vector2(x*speed, y*speed);
  }

```

Both scripts are used independently.

Velocity when I press the key down (D or A) it stops after short time but addForce seems to do the same while that is set in FixedUpdate() or Update(), which is confusing as I thought it would keep it moving till the key was released? I have also found that if I press D it moves then stops but if I release D and press again and repeat the player does not move until I press a different move direction. Any ideas?

# Answer
By default, rigidbodies in Unity behave according to Newton's First Law of Motion:

> An object continues to move at a constant velocity, unless acted upon by a force.

So when you add a force to an object, then it gains a velocity and retains that velocity until something slows it down.

But this is not the case if you manipulate the velocity directly. Assigning a new Vector2 to your velocity cancels any velocity the object had before. So with your `Move2` script, the object will never retain a velocity between frames, because when the user does not do any input, then the velocity will get reset to `new Vector2(0, 0);` on every fixed update.

But the script should work as a proper absolute movement controller **if** you do not have any other scripts or physics effects which affect the velocity of the object.

The first script hits at a misunderstanding of what `Input.GetKeyDown` does. When the user is holding down the key, then this method will only be true on single time - during the first frame where the user pressed the key. If you want to do something every frame while the user is holding the key, use `Input.GetKey`.

Regarding the question in the title *"What is best for 2D movement: velocity or AddForce?"*: It depends on what you want to do.

* AddForce takes the mass of the object into account. So if you want the player's mass to change and accordingly make the player "feel" lighter or heavier to control, then you should use AddForce. If you do not care about the player's mass, then it might be more convenient to deal with velocity.
* When you set the velocity to a new value, you cancel all forces which act on the object. Sometimes this is exactly what you want. But often it is not, because you also cancel any forces which got applied from the physics system or from other scripts. So you usually want to add a new vector to the existing velocity vector, not replace it with a new one.
> 2 votes

---
Tags: unity, c#, 2d, physics
---


# Question
Title: Replacing harcoded strings used internally to locate stuff
**The fields:** (example)

```
public static final FileHandle ASSETS_DIR = Gdx.files.internal("");
public static final String TEXTURES_DIR = "textures/";
public static final String TEXTURES_ATLAS_DIR = TEXTURES_DIR + "packed/";
public static final String TEXTURES_WHEELS_DIR = TEXTURES_DIR + "wheels/";
public static final String TEXTURES_TIRES_DIR = TEXTURES_DIR + "tires/";
public static final String TEXTURES_VEHICLES_DIR = TEXTURES_DIR + "vehicles/";
public static final String TEXTURES_COMPUTER_DIR = TEXTURES_DIR + "computer/";
public static final String TEXTURES_GARAGE_DIR = TEXTURES_DIR + "garage/";
public static final String TEXTURES_UI_DIR = TEXTURES_DIR + "ui/";
public static final String TEXTURES_CURSOR_DIR = TEXTURES_DIR + "cursors/";

public static final String DATA_DIR = "data/";
public static final String VEHICLE_DATA_DIR = DATA_DIR + "vehicles/";
public static final String COMPUTER_DATA_DIR = DATA_DIR + "computer/";
public static final String BROWSER_PATH = COMPUTER_DATA_DIR + "browser/";

public static final String ATLAS_WHEELS = "atlas_wheels.atlas";
public static final String ATLAS_GARAGE = "atlas_garage.atlas";
public static final String ATLAS_COMPUTER = "atlas_computer.atlas";
public static final String ATLAS_UI = "atlas_ui.atlas";

public static final String FONTS_DIR = "fonts/";
public static final String FONT_STYLE_A = "fstl_stcrd";

```

\*Example:\**

You can see here I use some literals from time to time. I can create a constant for that, but I don't think that's the best solution. I'm still having strings all around the code and maybe wasting memory (not the concern here, just saying though).

```
public static LinkedHashMap<String, Texture> loadTextures(Car car) {
    final FileHandle root = car.getData().getAssetsDirectory();
    final JsonValue specs = new Json().fromJson(null, root.child(CHASSIS_DATA_FILENAME));

    final LinkedHashMap<String, Texture> textures = new LinkedHashMap();

    // Order is important for proper packing. Big parts first or it will create more pages than needed.
    textures.put("body", new Texture(root.child(Model.Layer.BODY.getName() + ".png")));
    textures.put("mask", new Texture(root.child(Model.Layer.MASK.getName() + ".png")));
    textures.put("tire", new Texture(GameAssetManager.TEXTURES_TIRES_DIR + specs.get("wheels").get("tire").asString() + ".png"));
    textures.put("wheel", new Texture(GameAssetManager.TEXTURES_WHEELS_DIR + specs.get("wheels").get("wheel").asString() + ".png"));

    for(BodyPart.SubLayer lp : BodyPart.SubLayer.values()) {
        BodyPart p = car.getBody().getBodyPart(lp);

        if(p == null)
            continue;

        FileHandle bf = root.child(lp.getName() + "/" + String.valueOf(p.getPartID()) + ".png");

        if(!bf.exists())
            continue;

        Texture t = new Texture(bf);
        textures.put(lp.getName(), t);
    }

    return textures;
}

```

**The problem:**

I have string literals (only for internal usage) separeted in relevant classes for each one (GameAssetManager has fields that indicate where to locate resources and CarAssets has fields to find specific resources, etc...).

Sometimes non of those fields meet my requeriments and I have to revert to hardcoding a string for a particular piece of code and I don't want to have strings scattered throughout my code because as it grows, i know it will become a pain int the butt.

I'm thinking of implementing some kind of 'config.json' file and use inside the program just pointers to strings inside that file like:

```
0x0000AB0F: "textures/vehicles/wheel.png"
0x0000AB1F: "textures/vehicles/tire.png"
0x0000FC03: "enemy/body.png"

```

And in code just do:

```
String s = Utils.getString(0x0000AB0F);

```

The only (annoying) problem i see is that i still have to go back and forth between the 'config.json' file and the code im writing to locate the proper code for the string that I'm looking for.

By the way, I didn't came up with this hex to string thing. I saw it in the source code of another game I used to script years ago and I thought it was neat.

I'm want to get some information before beggining to make this big code changes. I searched around and didn't find the right answer.

What do you think will be the best approach?

Thanks for your time.

# Answer
> 3 votes
Your architecture seems to be an example of Stringly Typed: You are using strings where more specialized data types would make more sense.

In this case, most strings seem to refer to directories, which in Java are usually represented best by objects of class `File`. So `TEXTURES_TIRES_DIR` should be a `File`, not a `String`.

Similarily, your `JsonValue specs` should be converted to a more strongly typed class as soon as you load it (By the way: this would also be a good place to validate the file and throw a useful error message if something is missing). So instead of calling `specs.get("wheels").get("tire").asString() + ".png"` you should be able to call something like `specs.getTireTexture()` or `specs.getTexture(CarParts.TIRE)` (with CarParts being an `enum`).

> I'm thinking of implementing some kind of 'config.json' file and use inside the program just pointers to strings inside that file like:

```
0x0000AB0F: "textures/vehicles/wheel.png"
0x0000AB1F: "textures/vehicles/tire.png"
0x0000FC03: "enemy/body.png"

```

> And in code just do:

```
String s = Utils.getString(0x0000AB0F);

```

You might notice that this code is completely unreadable. When you later look at the above line, you have no way to tell which texture is actually loaded here without looking at your config file. You can not even tell whether that hex-code is correct or not. This is not just a small annoyance, it is a huge annoyance which will drive you crazy in the long-run.

If you want some lightweight lookup mechanism for string locations, at least use properly named int-constants so the code stays human-readable. But using constants is still a bad idea, because adding a single character to any of the strings in the file will invalidate any indexes which come after it. So if you want to have such a lookup table, then you should build it at runtime after parsing the file.

# Answer
> 1 votes
Use a little bit of both:

In your JSON file, instead of using these hex codes as keys, use named strings, the ones equivalent to your string constant names.

The idea here is that you can change the data without the need to recompile, it will also be easier to localise your game (change language? change the JSON file).

Also, I advise strognly against using these hex code without you knowing why you'd use them: this will make your code *very hard* to read.

Sorry for the brevity, I'm on my phone.

---
Tags: java, libgdx, architecture, design-patterns
---


# Question
Title: Determine view-matrix with camera placed in a scene graph
My scene is organized with a simple scene graph where the child multiplies its transformation with the one of the parent.

For normal objects, likes meshes, this works as expected, but I also want to insert the camera into the scene graph. To get the view-matrix I need to take the inverse of the global transformation matrix, which works except that this messes up the near/far plane dimensions. Because if a node above the camera has a scaling of 0.1 (across every dimension) the inverse will scale the whole world by a factor of 10.

Is there a simple way to get rid of the scaling or do I need to update my near and far plane based on the final view scaling?

# Answer
> 0 votes
You can remove a uniform scale from an affine transformation matrix (including a View matrix) by taking the three columns (or three roes) of the top-left 3x3 block of the matrix and normalizing each one, as though they were ordinary 3-vectors.

Do this before multiplying by your projection matrix, since after this your matrix represents a perspective transformation, not an affine transformation anymore.

Note that if you have a *non*-uniform scale somewhere in your hierarchy, you can get into a more complicated situation where the axes are no longer perpendicular to one another. You can orthonormalize the upper-left 3x3 block to correct this, but the results will depend on how you choose to compromise between the three axes' directions, so it's tough to define an unambiguous "correct" output for this case. I recommend using non-unform scales only at the leaf nodes of your scene graph, and avoiding it in parent nodes wherever possible.

---
Tags: mathematics, matrix, geometry, scene-graph
---


# Question
Title: Detecting collision between browser window middle point and other sprites visible in the window
In HTML5 canvas, I have an object which is always in the middle point. On the big map there are other moving objects. I want to detect if the middle point of the window hit any shape we see on the window. I wonder if there is a way to only detect collision between the middle point and the shapes that are visible in the window so I don't have to iterate through all shapes on the map (could be many thousands of shapes).

Is there a good solution to this kind of collision detection? Assume that I have already known how to write the collision detection code for the middle point and shapes.

# Answer
This is solved by the same kind of spatial partitioning we use for other collision checks.

Rather than treating your objects as one long undifferentiated list, sort them into a data structure that you can query based on a position or region.

For example, you could divide your game world into a coarse grid, and in each grid cell store a list of collision objects that overlap or have their origin in that cell. When you want to look for collisions at a given point, you look up the grid cell that contains that point, and check only the objects in that cell (and adjacent cells, if you're not duplicating entries when they overlap multiple cells)

A more adaptive strategy is to use something like a quadtree, k-d tree, BSP tree, or R-tree to partition your world more finely where objects are dense, and sparsely where there are few objects. These can reduce your search time to a logarithm of your number of objects.
> 1 votes

# Answer
If you dont want to do the iteration what pops to mind is drawing it (those particles) on invisible canvas (maybe smaller one for performance) and then reading the middle pixel is it colored or black.
> 0 votes

---
Tags: collision-detection, javascript, html5, browser-based-games
---


# Question
Title: calculating and saving latencies for multiplayer game
i am making a simple multiplayer puzzle game which basically presents a group of connected users some simple questions and whoever answers first wins the game. but i am having some issue in designing this game. assuming there are two players **A** and **B** connected & player **A** submits answers before player **B** but player **A** has some network lag, the server thinks that player B submitted the result first so player B wins.W chich is not correct.

i thought of calculating latencies for each player and store it on the server in something like in-memory database **redis**.

so when any player submits their answer i can just minus the latency with the time when the game started. that way i can know which player actually won.

i was thinking to use `fping` program to get latencies every 2 seconds and store it. but the problem is when there are 1000 players playing simultaneously calculating ping times would take more time than 2 seconds( loop for every connected player then find their ping times & store them in db) so the next run to calculate ping time will be delayed.

How is this usually handled?am i going in wron direction?

# Answer
> 2 votes
I don't know of a way to correctly trace a user's reply back to the time it was sent without being vulnerable to cheating.

(eg. a cheater deliberately sends all their replies 100 ms later than normal so the server thinks their latency is `realLatency + 100ms`. Then when they send their answer without this extra delay, the server back-dates it to `realAnswerTime - 100ms`, letting them effectively send answers "back in time" to beat other users).

Instead, I'd recommend solving this problem with game design:

Take the maximum variance in communication latency you're willing to accept between players in one match. (ie. the maximum latency you consider playable, minus the minimum latency you expect to see) We'll use this number as a tuning parameter you can choose to make a wider or narrower window of opportunity for rival answers.

When an answer comes in, wait for that maximum allowed duration to see if other answers also arrive in that window.

If multiple correct answers come in within that window, call it a tie. You can decide whether a tie means multiple players win, or nobody wins, or the players split the victory in some way.

This window can still be quite short in terms of human perception of time (even fairly bad one-trip network latencies are on par with an eye blink) so most rounds should still have a decisive winner. And crediting multiple players with a tie is generally going to be preferable, in terms of perceived fairness, to crediting the *wrong* player with a win due to variability or manipulation of network timings.

Here's a few examples, assuming our window is a generous 200 ms.

First, anekix's scenario: (values in ms)

```
Player     Latency   Answer Time   Arrival Time    Vs Window
-----------------------------------------------------------------------
Player A      50        5000          5050       First (5050 + 200 = 5250)
Player B     100        7000          7100       Too Late (7100 > 5250)
Player C      50        8000          8050       Too Late (8050 > 5250)

```

Here, player A's correct answer came in way before the others, at 5050 ms. We hold the window of opportunity open for an extra 200 ms after this correct answer, but both the other player's answers arrive later than that window. So Player A takes a solo victory. Which makes sense - they were first by a margin we couldn't confuse with mere network latency.

Here's a tighter scenario:

```
Player     Latency   Answer Time   Arrival Time    Vs Window
-----------------------------------------------------------------------
Player A      50        5000          5050       First (5050 + 200 = 5250)
Player B     100        4960          5060       In Window (5160 < 5250)
Player C      50        5300          5350       Too Late (5350 > 5250)

```

Here, Player B actually answered first, but because they're on a higher-latency connection, we received Player A's answer sooner. Because the window of opportunity we chose is larger than the difference between the most and least-lagged player's latencies (200 \> 100 - 50), we don't hand a solo win to Player A incorrectly. Instead, we deem the 10 ms difference in arrival times as "too close to call" and we say that player A and player B tied. Player C's answer arrived outside the window though, so they still lose the round.

For conditions where you expect players to be on very different network conditions, you'll want to allow a larger window. For conditions where you expect players to be more similar (eg. in the same room as with a Jackbox Party Pack game, or a group assembled by matchmaking that only pairs players with similar pings), you can use a smaller window to have fewer ties and more timinig precision for identifying solo winners.

You can playtest with a range of tuning values and play conditions to find the level that gives you the right perceived fairness.

# Answer
> 0 votes
Use timestamps. Calculate how long it is between a user seeing an answer and when they answer it. Compare these times on the server. Could be prone to cheating though.

---
Tags: multiplayer
---


title: How do I architect around Object Pools?

text:
# Question
Title: How do I architect around Object Pools?
**Example** I have an "Enemy" `class`, and 5 types of enemy `subclasses`.

These enemies will be spawn often, so I want to use an object pool.

However, this means I can no longer use an object pool for Enemies, now I have to use an object pool for each enemy subclass, so now, I have to make 5 object pools, and that's an arbitrary number that could just as easily be 25.

eg.

```
// Each with their own implementations of Enemy's "attack" or similar method
class Dragon extends Enemy { ... }
class Ogre extends Enemy { ... }

ObjectPool<Ogre> ogrePool;
ObjectPool<Dragon> dragonPool;
// etc ...

```

It seems a bit weird.

So what can I do? If I take out the subclasses, I can either put all the functionallity of every subclass into the base class, and keep an id of the type of class this base class represents, calling the appropriate functions accordingly... But this leaves a bloated hard to maintain class that requires a lot of modification everytime I add or remove a subclass behaviour.

eg:

```
class Enemy {
    enum EnemyType {OGRE, DRAGON, ETC;}
    EnemyType enemyType;

    public Enemy(EnemyType type) { this.enemyType = type; }

    public void attack() {
        switch(enemyType) {
            case Ogre:
                //Do ogre attack
                break;
            // etc...
    }

    // ...

}

// Now I can instantiate things from 1 object pool

```

Alternately I could try and use composition. I could have enemy contain components of other classes that govern behaviour. For example, I could have something like an "WeaponBehaviour" and "ArmourBehaviour". Then, the type of weapon behaviour, armour behavour, etc, would differentiate the different subclasses. However, every time i obtain an inatnace of my enemy class, I would have to instantiate each behaviour, and would end up likely needing an object pool for each behaviour.

eg:

```
class Enemy {
    WeaponComponent weaponComponent;
    ArmourComponent armourComponent;

    public Enemy() {}

    public void init(WeaponComponent weapon, ArmourComponent armour) {
        weaponComponent = weapon;
        armourComponent = armour;
    }

   public void attack() {
       weaponComponent.attack();
   }

   // ...

}

// And then instantiate things like so:

ObjectPool<Enemy> enemyObjectPool;
Enemy enemy = enemyObjectPool.obtain();
enemy.initialize(new OgreWeapon(), new OgreArmour());
// or alternately have an object pool for OgreWeapons and OgreArmour

```

None of the solutions I can think of seem like they are ideal, and I was wondering what a good way to organize this was.

# Answer
I personally prefer your second idea of using composition, but if you wanted to stay with the style of using generics as you do currently, but not having to initialize multiple pools maybe you could allow one object pool to spawn different enemies/objects,a small snippet just to give you an idea of what I mean:

```
 ObjectPool myObjectPool = new ObjectPool();
 myObjectPool.Init<Ogre>(10); //Cache 10 Ogre Objects
 myObjectPool.Obtain<Ogre>(); //Get an ogre
 myObjectPool.Release<Ogre>(); //Return it to the pool

```

This type of ObjectPool could instead be an "ObjectPoolManager", that internally maps types to instances your current ObjectPool system
> 1 votes

# Answer
You mentioned an object pool for each enemy subclass...

> > "It seems a bit weird."

But it would work, right? Seems fine to me. Subclassing helps you organize your code, while object pools are inherently a space-for-time tradeoff.

Another approach (which you allude to) would be to reduce your number of classes with parameterization. One extreme of this is to replace subclasses with a giant switch(enemyType){} case statement. There may be ways to structure the actual source to make the "bloat" more palatable.

Another approach somewhere in between would be a *stateless* behavior object, one which operates on an Enemy instance but can be shared across all enemies of that type. Something like

```
Enemy e;
e.setBehavior(enemyBehaviorXxx);  // only one instance of each enemy behavior

```

and in one of Enemy's methods,

```
enemyBehavior.updateMe(this);

```

This requires that Enemy expose enough methods/fields for any EnemyBehavior to do its work. (Sort of semi-bloat, I guess.) You may end up with a few

```
public int generalVar1;
public int generalVar2;

```

Which you may find "weird". I'd even agree, but probably do it anyway. It's all tradeoffs.
> 1 votes

# Answer
You could use polymorphism.

let all your diferent enemies inherit from the same class or implement the same interface, I'll call it Enemy

Then all of your enemies would belong to the class Enemy, and that allows you to do the following

```
Enemy enemyA = new EnemyA();

Enemy enemyB = new EnemyB();

```

and finally you could do something like

```
Queue<Enemy> Pool; :)

```

Something to have in count is that you can call methods and use properties in common if they are defined in the father or "base" class, but properties that are not inside the Enemy class can't be accesed
> 0 votes

---
Tags: gameobject, object-pools
---


title: Godot 3.0 Constant 2D Angular Velocity

text:
# Question
Title: Godot 3.0 Constant 2D Angular Velocity
I am making a Top-Down shooter in Godot 3.0 on Linux.

I would like to have my character rotate to face the mouse-pointer at a constant speed, and have rotation speed power-ups that allow the player turn faster.

So far, this is done by having a Position2D object called "Center" share the same position (but not be a child of) the player (below just called "Sprite"). The center always looks to the mouse, and the Sprite rotates with linear interpolation to eventually reach the same rotation as the "Center".

The weight of linear interpolation is calculated by dividing the difference in rotation (in radians) by an arbitrary constant speed.

Problem: The speed of rotation increases as rotation occurs, or more specifically, the time it takes to reach the same rotation (a rotational difference of zero) becomes shorter over time.

I have the following code:

```
extends Sprite

onready var center = get_parent().get_node("Center")

var current_time = 0
var total_time = 0
var start_rot = 0
var end_rot = 0

func _process(delta):
    center.look_at(get_global_mouse_position())
    var amt = 0
    var theta = abs(self.rotation - center.rotation)
    var speed = 0.05

    total_time = theta/speed

    start_rot = get_rotation()
    end_rot = center.rotation

    if not total_time == 0:
        amt = current_time/total_time

    current_time += delta
    amt = clamp(amt,0,1)
    var rot = lerp(start_rot,end_rot,amt)
    center.rotation = fmod(rot,(PI*2))
    set_rotation(fmod(rot,(PI*2)))

    get_parent().get_node("Control/rotation").text = str(int(self.rotation_degrees))
    get_parent().get_node("Control/theta").text = str(theta)
    get_parent().get_node("Control/time").text = str(total_time)

```

What am I doing wrong?

# Answer
> 1 votes
A simple solution would be to get the angle to the target and then just rotate counter-clockwise if the angle is negative and clockwise if it's positive:

```
func _physics_process(delta):
    var angle = get_local_mouse_position().angle()
    if angle < 0:
        rotate(-angular_speed*delta)
    elif angle > 0:
        rotate(angular_speed*delta)

```

You also have to decrease the angular speed when the angle gets close to 0, otherwise it would jitter:

```
    if abs(angle) < .3:
        angular_speed = abs(angle / .3)
    else:
        angular_speed = 1

```

# Answer
> 1 votes
@skrx "+1" Thanks!

I wasn't able to make get\_local\_mouse\_position().angle\_to\_point(position) work as intended, but using your method of angular speed, I was able to rework it to suit my purposes:

```
func _physics_process(delta):
    center.look_at(get_global_mouse_position())

    var angular_speed = 2
    var angle = rotation - center.rotation
    angle = fmod(angle,PI*2)
    center.rotation = fmod(center.rotation,PI*2)

    rotation = fmod(rotation,PI*2)
    if abs(angle) > PI :
        angle = -angle
    if abs(angle) > .05:
        if angle > 0:
            rotate(-angular_speed*delta)
        elif angle < 0:
            rotate(angular_speed*delta)

```

# Answer
> 0 votes
@skrx Not only does this work, this actually shortens the code!

This allows removing the fmod adjustments, and the if statement used to change the rotational direction past its half-way point, only rotating the shortest distance, and removes the use of Center entirely!

I did have to change the &gt and &lt symbols back to your original orientation (I had to switch them for my rotation difference method to work)

The new code is as follows, and works exactly as intended, thanks again!

```
func _process(delta):
    var angular_speed = 2
    var angle = get_local_mouse_position().angle()
    if abs(angle) > .05:
        if angle < 0:
            rotate(-angular_speed*delta)
        elif angle > 0:
            rotate(angular_speed*delta)

```

---
Tags: rotation, interpolation, godot
---


title: Separating axis theorem OBB vs Sphere

text:
# Question
Title: Separating axis theorem OBB vs Sphere
I am trying to implement collision detection in 3D between OBB/AABB and sphere. For this i'm using sat/separating axis theorem. For sat to work in 3D i need face normals of obb (sphere to face), each vertex of obb - sphereCenter (sphere to vertex) and edge normals to sphereCenter (sphere to edge). The last i dont know how to calculate. First picture is working fine(sphere to vertex) and other two cases are giving false positives. Any other way to find minimum translation vector and distance of sphere and aabb would also be appreciated.

Box vs Sphere:

```
void Physics::colliderBoxVsSphere(BoxCollider* c1, SphereCollider* c2, glm::vec3& mtvAxis, float& mtvDist){
    auto spPos = c2->getPosition();

    std::vector<glm::vec3> obb;
    c1->getOBB(obb);
    auto mid = midPos2(obb);

    // (1) identity axes
    std::vector<glm::vec3> axes;
    c1->getEntity()->transform()->appendIdentiyAxes(axes);

    // (2) vertices
    std::vector<glm::vec3> verts;
    for (auto& vert : obb) {
        auto axisVec = glm::normalize(spPos - vert);
        verts.push_back(axisVec);
    }

    // (3) edges
    //TODO

    axes.insert(axes.end(), verts.begin(), verts.end());

    CollisionMath::instance()->OBBCollideSphere(obb, spPos, c2->getRadius(), axes, mtvAxis, mtvDist);
}

```

SAT:

```
bool CollisionMath::OBBCollideSphere(const std::vector<glm::vec3>& obb, const glm::vec3& spherePos, float sphereRad, const std::vector<glm::vec3>& axes, glm::vec3& mtvAxisRet, float& mtvDistanceRet){
glm::vec3 pos1 = midPos(obb);
glm::vec3 pos2 = spherePos;

float mtvDist = std::numeric_limits<float>::max();
glm::vec3 mtvAxis = glm::vec3(0, 0, 0);
for (auto& axis : axes) {
    if (axis == glm::vec3(0, 0, 0)) continue;

    glm::vec2 p1 = Math::instance()->projectOnAxis(obb, axis);
    glm::vec2 p2 = Math::instance()->projectSphereOnAxis(spherePos, sphereRad, axis);

    float d1 = glm::dot(pos1, axis);
    float d2 = glm::dot(pos2, axis);

    if (d1 > d2) {
        if (p1.x > p2.y)
            return false;
        else {      //intersect get depth
            float depth = p2.y - p1.x;
            if (depth < mtvDist) {
                mtvDist = depth;
                mtvAxis = axis;
            }
    }
}
        else {
            if (p2.x > p1.y)
                return false;
            else {      //intersect get depth
                float depth = p1.y - p2.x;
                if (depth < mtvDist) {
                    mtvDist = depth;
                    mtvAxis = -axis;
                }
            }
        }
    }

    mtvAxisRet = mtvAxis;
    mtvDistanceRet = mtvDist;

    return true;
}

```

Project on axis:

```
float min = glm::dot(verts[0], axis);
float max = min;

for (unsigned i = 1; i < verts.size(); ++i) {
    float d = glm::dot(verts[i], axis);
    if (d > max) max = d;
    if (d < min) min = d;
}

return glm::vec2(min, max);

```

project sphere on axis:

```
glm::vec3 A = center + axis * rad;
glm::vec3 B = center - axis * rad;

float min = glm::dot(B,axis);
float max = glm::dot(A,axis);

return glm::vec2(min, max);

```

# Answer
Don't use separating axis theorem for this. It's overkill for spheres.

Instead:

1. Use the OBB's orientation & translation information to inverse-transform the sphere's center into the box's local space.

`localSphereCenter = box.InverseTransformPoint(sphere.worldCenter)`
2. Find the closest point on the box to this point. Now that you're working on the box's local axes, this is as simple as a component-wise clamp on each axis:

`closest.x = max(box.localMin.x, min(localSphereCenter.x, box.localMax.x));`
`... likewise for y, z`
3. Transform that point back to worldspace (to account for scale in your OBB, if applicable), then take the offset vector from this closest point to the sphere center. If it's shorter than your radius, the sphere intersects the box.

The minimum translation vector (if the center is not in the box) is then this offset vector scaled to the remaining length:

```
 translation = (sphere.radius - offset.length) * offset.normalized

```

If the sphere center is inside the box, then this displacement vector will be zero. You can clamp the point to the nearest face of the box, then form a penetration vector equal to the sphere center minus this closest face point. Your minimum translation vector is then:

```
translation = -1 * (sphere.radius + penetration.length) * penetration.normalized

```

Since we've computed these separations/penetrations in the box's local space, remember to transform them back to world space at the end to use them for moving objects.
> 5 votes

---
Tags: collision-detection, physics
---


# Question
Title: How to apply bindpose for vertex skinning?
I'm creating a model/animation viewer in C# using OpenTK for a game's models. Before stating my problem I want to describe a bit what I've accomplished so far in case I'm fundamentally missing something.

First of all I parsed the model skeleton. Like described pretty much everywhere on the web, what I do is to traverse all the hierarchy starting from the root bone and start building up the joint matrices. The game file provides separately translation,rotation and scale vectors. In order to create all the joint matrices I'm using only the rotation values, which I am converting into a rotation matrix and I'm saving it as the localMatrix. I'm saving the translations as joint position (localPosition) and I'm using them later on to calculate the worldPosition of my joints by transforming that using the parent's worldMatrix.

The following methods are responsible for getting the joint world Matrix and its world Position

```
public Vector3 worldPosition {
        get
        {
            if (parent != null)
                return parent.worldPosition + Vector3.Transform(this.localPosition, parent.worldMat);
                this.worldMat);
            else
                return this.localPosition;
        }
}
public Matrix4 worldMat
    {
        get
        {
            if (parent != null)
                return Matrix4.Mult(this.localMat, parent.worldMat);
            else
                return this.localMat;
        }
}

```

Using that piece of code I can preview the skeleton perfectly. I also managed to parse the animations. I used the rotation information on each frame in order to update each joints local matrix and therefore I was able to successfully preview the animation on the joint skeleton.

Now the only thing I am missing is to bind the mesh on the skeleton (I'm trying to do that using a vertex shader). Wherever I search on the web, i find that i need to apply the following equation:

I got the blendIndices and the blendWeights so that's not a problem as well. I'm completely confused with the bone matrices though. If I understand correctly matrix\[i\] is the joint's world transformation matrix. The other inverse matrix is supposed to transform my vertex back to the bindpose? Since my model is already in the bindpose what do I need this matrix for?

I tried applying just the joint worldmatrices that I have precalculated, but the mesh was completely corrupted. So I'm definitely missing something.

I've also found some matrices in the model file which seem like they are probably prebaked joint world matrices. In fact I compared their values and they are EXACTLY the same with the ones I'm calculating through traversing the bone hierarchy. Their only difference though is that they also contain translation information. So my question is: Do bone matrices contain translation information as well? If so, then this means that my way of parsing the skeleton is wrong? I just can't thing of another way to use the full matrices (rotation + translation) in order to correctly position the joints.

# Answer
> 1 votes
I think the bindpose matrix you are referring to is also the bone offset matrix, which is related to its parent. It transform the bone from the mesh space to its local space. A final transformation of a bone is normally calculated like this:

```
FinalTransform = ParentTransform * (Translation * Rotation *Scaling) * OffsetMatrix

```

Are you missing the parent's transform here? Would be better if you can provide a code snippet.

---
Tags: c#, matrix, skeletal-animation, opentk, skinning
---


# Question
Title: Is it good to use 24 fps animation in 60 fps game?
Is it normal to use 24 fps animation in 60 fps game or it will hurt perfomance or create bugs?

# Answer
> 2 votes
Most 3d animation systems work with keyframes and interpolation curves between them.

Your 3d animation program might use a 24 FPS timeline as an UI convention. But that doesn't mean that the engine will perform the animation in 24 FPS. The plain English definition of a 3d animation could be roughly stated as "Between timecodes 0.2s and 0.6s, this bone moves from position A to position B in a linear motion". When the rendering engine is then prompted to render the model at timecode 0.225s, it will use linear interpolation to calculate a position 1/16th between A and B.

That means that it is usually not that important that the framerate in the animation program and the target framerate of your game are identical. There are just two minor details you might have to be aware of:

* If the preview in your 3d animation program renders in 24FPS, then the animations might not look as smooth as they look in the actual game, giving you a slightly false impression
* Your rendering engine will rarely render *exactly* the keyframes. So if you spend a lot of effort into getting the keyframe poses exactly right, then you might get disappointed that your game never renders them without at least a tiny bit interpolation towards a different keyframe.

You might wonder why 24 FPS is the default in some animation programs even though most gamers expect at least 60 FPS from their 3d games. The reason is that 24 FPS is the standard framerate for TV and cinema. You might be using a program (or are using it in a configuration) which primarily targets animators for film, not animators for games. But that doesn't necessarily mean the tool you are using is inappropriate. Many animation tools work great for either use-case.

# Answer
> 1 votes
From your question I assume you've made an animation in a 3D software and you test it with 24 fps.

When you are using an animation like that in an actual game, the only difference is that if a game runs on 24 fps, the animation will finish in one second, if the game runs on 60 fps, the animation will run in 0.4 seconds.

Does it make a difference? Obviously, unless a game is made to specifically handle animations based on real time and not fps.

Does it hurt performance? I guess you could say if an animation runs for twice as long, it will be using resources for longer, but the footprint is so minimal, that it makes no sense to pay attention to it.

Does it create bugs? It depends on the game, if the game uses a logic like "run this animation, then 1 second later run this code" assuming that the animation will be finished, then yes some funny bug-behaviour will occur. But hopefully most games check when the animation is actually finished before executing code that depends on it.

---
Tags: 3d, animation, frame-rate
---


# Question
Title: Why can't I load images in processing.js and let them be dynamic?
I can't easily load images. I can only render an image once unless I put this: `<img src="images/papermario.png" hidden></img>` in my html. I also still need to be able to use..... `get(x, y, w, h)` to get the pixels of an image But I run into this error: `processing.js:13709 Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.` when ever I operate it on the canvas. Also when I try to load the image sometimes it doesn't load.

So how should I fix it? (It still needs to be a processing js image object)

JS: `var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
var processing = new Processing(canvas, function(processing)
{
 processing.size(800, 800);
 processing.background(0xFFF);`

````
var mouseIsPressed = false;
processing.mousePressed = function()
{
    mouseIsPressed = true;
};
processing.mouseReleased = function()
{
    mouseIsPressed = false;
};

var keyIsPressed = false;
processing.keyPressed = function()
{
    keyIsPressed = true;
};
processing.keyReleased = function()
{
    keyIsPressed = false;
};

processing.getImage = function(url)
{
    //Loading of the home test image - img1
    var img1 = new Image();

    //drawing of the test image - img1
    img1.onload = function()
    {
        //draw image
        ctx.drawImage(img1, 0, 0);

        //ctx.fillStysle = "rgba(200, 0, 0, 0.5)";
        //ctx.fillRect(0, 0, img1.width, img1.height);
    };
    img1.src = url;//Set image url

    processing.externals.sketch.imageCache.add(img1.src);

    var img2 = processing.loadImage(img1.src);

    //img2.url = url;
    //img2.onload = img1.onload;

    return img2;
};

// use degrees rather than radians in rotate function
var rotateFn = processing.rotate;
processing.rotate = function(angle)
{
    rotateFn(processing.radians(angle));
};

with (processing)
{
    var img1 = getImage("images/papermario.png");

    //var img2 = createGraphics(180, 180, P2D);
    background(0, 0, 0);
    image(img1, 0, 0);
    //var img2 = get(0, 0, 400, 400);

    draw = function()
    {
        background(255, 255, 200);

        image(img1, 0, 0);

        //ctx.drawImage(img1, 0, 0);s

        //image(get(0, 0, 180, 180), 80, 80);
        //var img1 = getImage("images/papermario.png");
        //img1.onload();

        //image(img2, 40, 0, 40, 40);
        //image(img2, 0 + millis() / 1000, 0, 30, 30);
    };
}

if (typeof draw !== 'undefined')
{
    processing.draw = draw;
}

````

`});`

# Answer
> 1 votes
You cannot load and use images from other domains with HTML5 canvas. Make sure to serve your images from the same domain/server as your processing code. Alternatively, enable cross origin access on the server which is serving your image.

Read more here: https://stackoverflow.com/questions/22097747/how-to-fix-getimagedata-error-the-canvas-has-been-tainted-by-cross-origin-data

---
Tags: javascript, html5, loading, processing
---


title: MonoGame tick cannot go lower than 16ms

text:
# Question
Title: MonoGame tick cannot go lower than 16ms
I'm trying to build play with MonoGame and I'm trying basing this regarding the GameTime steps. In my main Game class that is being run in the main entrypoint of my project, I'm doing something like that:

```
gameScreen.IsFixedTimeStep = true;
gameScreen.TargetElapsedTime = TimeSpan.FromMilliseconds(1000d / 120);

```

With a TargetElapsedTime at about 8ms, the "Draw" method of my current screen should display an ElapsedGameTime of 8ms but it's always displaying me 16ms.

Is it normal? Can't we go lower than 60fps in FixedTimeStep? I've tried to make a custom loop on another running at 120 fps (without going through the MonoGame pre/post-draw) and it's running correctly.

Can you guys give me some hint?

\[EDIT - Add more info\] I've fetched few answers before asking my question and some people were talking about the Vsync issue. So i've set up this:

```
_graphics.SynchronizeWithVerticalRetrace = false;

```

But the result is the same

# Answer
I was suggest on another platform this link:

http://community.monogame.net/t/cap-frame-rate-to-30-fps/10122

At the end of the post, someone suggest this:

```
graphics.PreparingDeviceSettings += (sender, e) =>
{
    e.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.Two;
};

```

This solution helped me to fix my solution, but I had to tweak it a little beat. In order to make it work, I had to do this:

```
graphics.PreparingDeviceSettings += (sender, e) =>
{
    e.GraphicsDeviceInformation.PresentationParameters.PresentationInterval = PresentInterval.Immediate;
};

```

Some doc on the internet say that regarding this parameter:

> "PresentInterval.Immediate can be used to perform the flip as soon as possible and not wait for the vertical rectrace. Although your game can suffer from tearing artifcats, this mode is helpful when performing performance analysis because **it does not limit the speed at which your game can draw.**"

If anyone have more information, or up and down about this solution, feel free to say it to me.
> 1 votes

---
Tags: monogame, game-loop, timestep
---


# Question
Title: Are there any formulas/algorithms that could allow level to decide how many dice can be used for a roll?
See, I'm trying to work on an cRPG system and I want a formula or algorithm I guess, where the level affects how many dice can be rolled for any action (in addition to a default number of dice and other calculations). Such as the following:

Lv.1-10: 1 dice

Lv.11-20: 2 dice

Lv.21-30: 3 dice

Lv.31-40: 4 dice

Lv.41-50: 5 dice

Lv.51-60: 6 dice

Lv.61-70: 7 dice

Lv.71-80: 8 dice

Lv.81-90: 9 dice

Lv.91-100: 10 dice

# Answer
> 6 votes
Yes, there is.

```
numberOfDice = floor( ( Level - 1 ) / 10 ) + 1

```

The `floor` method will essentially take the integral part of the result of the division `(Level-1)/10` (it will round it down). If you're going to use any popular language or framework, I suggest you lookup the `floor` method.

I would also have suggested to rely on the integer division, but since it's not clear what will be your target language/framework, I don't know how it will behave. You could probably test it first. In this case, you would just have to drop the `floor` function:

```
numberOfDice = ( ( Level - 1 ) / 10 ) + 1

```

---

As a footnote, you could probably look up the JavaScript `Math.floor()` function to get familiar with it.

---
Tags: rpg, random, combat
---