title: Implementing strafe jumping

text:
# Question
Title: Implementing strafe jumping
As a Defrag player, I would like to add advanced movements to my (simple) game, in particular strafe jumping. I currently have basic fps movements (WASD and free look to be clear), but how can I add quake-like movement techniques? This article explains very well the theory behind it, but I really don't know where to start to actually implement it.

# Answer
The article you linked to first explains how the game works and then discusses at length how to exploit the way it works to strafe-jump. I believe only a few paragraphs are useful to you: the one about how the engine decides whether to add an acceleration vector times a small amount of time (which amounts to a small variation of the speed vector):

> So when we try to apply an acceleration at some angle to the velocity, we will be allowed to accelerate provided that the component of our current velocity in the proposed direction is less than 320ups.

and how it truncates that small variation of speed so the component of the resulting speed vector along the acceleration direction doesn't exceed a predefined maximum:

> If your *v.cos(delta)* is less than 320 but still very close to 320, applying the usual constant acceleration for a single frame would be enough to take you over 320ups in that direction. This is something the engine checks for, and if the situation exists, the applied acceleration will be only enough to take you up to the 320ups limit (so it would be 320 - v.cos(theta) ), and not beyond.

Just to spare you some confusion when actually implementing the thing, note that the author refers to the vector "a" as the "acceleration vector" but throughout the article it is used sometimes as a unit vector having the same direction as the acceleration vector as in

> v.a = v.cos(delta)

or as an amount of speed as in

> arccos( (320-a)/v )

or even as a distance (length) as in

> a = s.T

where "s" is the global maximum speed (the `g_speed` variable in the engine) and T is the duration of a frame. So be careful when handling such quirky maths. Here's a rundown to make everything clear:

To sum up in physics/applied maths notation: the player has a speed vector *v(t)* at time *t* and we want to compute his speed vector *v(t+dt)* at time *t + dt* where *dt* is a small amount of time. Here, *dt* will be the duration of a frame, or *1/(framerate)*. There exists a speed constant *V* used to cap other speeds or something along those lines, and we will use that constant.

We know *v(t)* and we can deduce the direction *u* towards which the player wants to move using the currently pressed movement keys. *u* is a unit vector. **The amount of speed we initially want to add to *v(t)* is *A.dt.u* where *A*, a real number, is the unique, global movement acceleration constant**, so that *v(t+dt) = v(t) + A.dt.u*.

Note that *A* is not a speed, but an acceleration! **The engine uses the same variable `g_speed` for the global acceleration induced by pressing movement keys AND for the maximum speed**, because it simplifies the handling of movement when on the ground, hence the confusion we saw earlier.

We want to add that amount of speed *A.dt.u*, but we need to truncate it if it makes the component of the resulting vector *v(t+dt)* bigger than *V* **along *u***. Therefore, we get the following pseudocode:

```
// what we want to compute
Vector3D nextSpeed;
// the acceleration direction u, which is a unit vector
Vector3D accelDir = computeAccelDir(pressedkeys);
// our dot product, "v.cos(delta)"
float vcosdelta = currentSpeed.dotProduct(accelDir);
// the total speed along the acceleration direction u (unless we truncate it)
float totalSpeedComponent = vcosdelta + A*dt;
// is it small enough?
if (totalSpeedComponent < V)
{
    nextSpeed = currentSpeed.add(accelDir.times(A*dt));
} else { // no! it's too big! We must truncate -_-'
    nextSpeed = currentSpeed.add(accelDir.times(V - vcosdelta));
}

```

Sorry for the poor variable names. Please have better variable naming habits than mine. Here, I compute and store `float totalSpeedComponent` even though I could directly use `V - vcosdelta - A*dt` in the first `if` statement, but that was for understandability.

I hope I didn't miss anything. Remember you can customize both A (the global movement-induced acceleration) and V (the maximum speed along acceleration direction).

That being said, just translate that and adapt it to your codebase, I think I got most of it right.

**major edit:** I forgot to add that this only works in the air! Don't forget to make it so that, if the player lands with the jump key pressed, he only touches the ground for 1 frame at most before he jumps again! Special handling of physics might be required during that particular frame. It's 6AM. Bed.
> 5 votes

# Answer
Actually, I think driven by the question in this post, Adrian "Flafla2" Biagioli has created a very well written and explained post/answer on this same topic.

Here: http://flafla2.github.io/2015/02/14/bunnyhop.html

The product of the post is a C# implementation of the system:

```
// accelDir: normalized direction that the player has requested to move (taking into account the movement keys and look direction)
// prevVelocity: The current velocity of the player, before any additional calculations
// accelerate: The server-defined player acceleration value
// max_velocity: The server-defined maximum player velocity (this is not strictly adhered to due to strafejumping)
private Vector3 Accelerate(Vector3 accelDir, Vector3 prevVelocity, float accelerate, float max_velocity)
{
    float projVel = Vector3.Dot(prevVelocity, accelDir); // Vector projection of Current velocity onto accelDir.
    float accelVel = accelerate * Time.fixedDeltaTime; // Accelerated velocity in direction of movment

    // If necessary, truncate the accelerated velocity so the vector projection does not exceed max_velocity
    if(projVel + accelVel > max_velocity)
        accelVel = max_velocity - projVel;

    return prevVelocity + accelDir * accelVel;
}

private Vector3 MoveGround(Vector3 accelDir, Vector3 prevVelocity)
{
    // Apply Friction
    float speed = prevVelocity.magnitude;
    if (speed != 0) // To avoid divide by zero errors
    {
        float drop = speed * friction * Time.fixedDeltaTime;
        prevVelocity *= Mathf.Max(speed - drop, 0) / speed; // Scale the velocity based on friction.
    }

    // ground_accelerate and max_velocity_ground are server-defined movement variables
    return Accelerate(accelDir, prevVelocity, ground_accelerate, max_velocity_ground);
}

private Vector3 MoveAir(Vector3 accelDir, Vector3 prevVelocity)
{
    // air_accelerate and max_velocity_air are server-defined movement variables
    return Accelerate(accelDir, prevVelocity, air_accelerate, max_velocity_air);
}

```

All credits to Adrian.
> 2 votes

---
Tags: c++, game-mechanics
---


# Question
Title: How to find the "up" direction of the view matrix, with GLM
Using OpenGL and the GLM matrix library, I want to translate my camera relative to the world coordinate system. This requires me to compute the necessary view matrix. To initialise the view matrix, I used:

```
view_matrix = glm::lookAt(eye, centre, up);

```

Where `eye = (0, 0, 10)`, `centre (0, 0, 0)`, and `up = (0, 1, 0)`. Suppose I want to now translate the view matrix by 5 unites in the camera's y-direction, i.e. to move upwards relative to the model. I tried:

```
view_matrix = glm::translate(view_matrix, glm::vec3(0, 5, 0));

```

This works fine at first, because the view and world coordinate systems are aligned. However, if I then rotate my camera a bit, and then perform this translation, it no longer works. Instead, it moves the camera along the world coordinate system, rather than the camera coordinate system.

So what I need to do, is to find the vector which represents the "up" direction of the camera, and then translate along this vector. This is similar to the inverse of the `glm::lookAt(eye, centre, up)` function.

In summary: Is it possible to find the "up" vector of the view matrix using the GLM library?

# Answer
> 1 votes
When you rotate your camera you should apply the same rotation matrix to your up vector. That should result in an up vector in the same direction as your view matrix's up direction.

# Answer
> 1 votes
The View Matrix is usually built with the "Look At" data, the Eye, Center and Up vectors. And it looks like this **(in column major)**:

```
| ux vx -nx -eyex |
| uy vy -ny -eyey |
| uz vz -nz -eyez |
| 0  0    0     1 |

```

Where **u**, **v** and **n** are the normalized vectors for the camera referential. **u** is the up vector, **n** is the direction the camera is looking at and **v** is perpendicular to both **n** and **u**.

If you want to get the up vector from the matrix you could get the indices `view[0]`, `view[4]` and `view[8]`. If the up vector you provided is not orthogonal then it may change a bit after the cross products, so you may get a slightly different up vector than the one you provided.

---

You actually want to do the rotation after the translation.

```
glm::translate( ... )
glm::rotate( ... )

```

So that the translation happens in the camera coords. If you translate in front, the camera moves in the direction its facing. (Should be z+)

However, if you need to keep track of the current position/rotation of the camera, you should calculate the new Eye and Center vectors yourself instead of applying stand-alone rotations and translations to the camera.

---
Tags: opengl, linear-algebra, glm
---


title: Decelerate moving platform at targets

text:
# Question
Title: Decelerate moving platform at targets
I'm trying to make a moving platform move at a constant speed and then when it is near the target start to slow down, I have trying to do this with Lerp, but I'm not satisfied with the results because of two reasons: it goes way too fast between targets, and way too slow near targets.

Also, when it reaches a target it immediately boosts off in the opposite direction. What I want to achieve is for the platform to move steadily between targets, decelerate near targets, and when reaching a target start to accelerate back to the steady speed.

What is the best way for achieving this? Lerp, Smoothstep, other? Thanks! (I'm using Unity)

My current solution:

```
 _dVeloctiy = _velocity * Time.fixedDeltaTime;
 Vector3 newPosition = Vector3.Lerp(_rigidBody.position, currentTargetPosition, _dVeloctiy.magnitude);
  _rigidBody.MovePosition(newPosition);

  Vector3 dPosition = _rigidBody.position - currentTargetPosition;

  if (dPosition.magnitude > 0.05f)
  {
      _isTurning = false;
  }

  if (dPosition.magnitude < 0.05f && !_isTurning)
  {
      currentTargetPosition = (currentTargetPosition == targetPosition1 ? targetPosition2 : targetPosition1);
      _isTurning = true;
  }

```

# Answer
> 0 votes
Your best friend is probably to use `Mathf.Sin`, the platform will move at constant speed and decelerate when reaching either side.

```
using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
    private void Update()
    {
        var f = Mathf.Sin(Time.time);
        var position = transform.position;
        position.x = f;
        transform.position = position;
    }
}

```

**Configuration:**

I assume that it is initially placed at the center location between zones it has to reach (platform is the white cube) :

It will start by moving from the center, if you'd like it to start moving from an edge instead then use `Mathf.Cos`.

Last thing, specifying a longer distance should be pretty easy and I'll let you figure that out :D

Here's a web-app to let you play with sines and so on: https://www.desmos.com/calculator

(remember, use `x * pi` to normalize the sine)

---
Tags: unity, lerp, moving-platforms
---


title: opengl matrix multiplication

text:
# Question
Title: opengl matrix multiplication
Can someone provide some type of example of multiplying a 4x4 matrix without using loops?

```
typedef struct matrix4
{
    data[16];
} m4;

```

can someone provide a sample of how you you'd multiply two of these in the opengl column major way?

# Answer
> 2 votes
In matrix multiplication, each index in the resulting matrix is the dot product of the ith row in matrix A and the jth column in matrix B:

```
Cij = A.row( i ) . B.col( j );

```

Say we have this matrix, which represents indices in row-major representation,

```
Indices in row-major representation

 0  1  2  3
 4  5  6  7
 8  9 10 11
12 13 14 15

```

In row-major it will be stored in an array and elements belonging in the same row will be stored sequentially.

```
0, 1, 2, 3, 4, 5, 6, 7 ... 15

```

In column-major it's the opposite, elements in the same column will be stored sequentially.

```
0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15

```

This corresponds to transposing the row-major matrix. Multiplying two transposed matrices is the same as transposing after multiplying them. So in the end you can multiply column-major matrices in the exact same way as you multiply row-major matrices.

Still I'll show you how to multiply in the "column-major way". If we transpose the matrix above, you can easily see which linear indices correspond to which matrix index in the column-major representation,

```
Indices in column-major representation

0  4  8 12  // Indices 0,4,8,12 are the first row
1  5  9 13  // Indices 0,1,2,3 the first column, etc
2  6 10 14
3  7 11 15

```

For example, the value in (0,0) and (2,2) can be calculated like this

```
C00 = C[0] = A[0] * B[0] + A[4] * B[1] + A[8] * B[2] + A[12] * B[3]
C22 = C[10]= A[2] * B[8] + A[6] * B[9] + A[10] * B[10] + A[14] * B[11]

```

And I'll leave the remaining indices for you.

---
Tags: opengl, matrix, c
---


# Question
Title: Determining a sensible gear-like hierarchy for a series of connected objects
I would like a series of objects to behave in similar manner to a series of connected gears.

This means that each black object in the diagram below will rotate at a speed based on the ratio of their radius compared to their parent's radius.

The problem is how can I determine a sensible parent child hierarchy algorithmically?

Is there a tried and tested mathematical procedure for such a task?

# Answer
> 4 votes
Let's consider three gears: \\$G\_1\\$, \\$G\_2\\$ and \\$G\_3\\$.

Now each gear has a given radius \\$r\_1\\$, \\$r\_2\\$ and \\$r\_3\\$. The problem is to find the angular velocity for each gear (denoted \\$\omega\_1\\$, \\$\omega\_2\\$ and \\$\omega\_3\\$). From a physics course we know that the tangent velocity v is proportional to the radius: \\$v\_1 = \omega\_1 r\_1\\$.

Now, if a given gear, say \\$G\_1\\$, is connected to a second gear \\$G\_2\\$, then the tangent velocities match: \\$v\_1=v\_2=v\\$, where \\$v\\$ is the overall velocity of the system, a *global parameter* for a system of connected gears.

Now it follows that \\$\omega\_1r\_1 = v\\$ so \\$\omega\_1 = \frac{v}{r\_1}\\$ for each gear. That way you can find out the angular velocity of all gears in a system.

The next step is finding the rotation direction. For this, simply choose a gear (say G\_1), fix the rotation direction (say to \\$+\omega\_1\\$), look which gears are connected to it. If \\$G\_2\\$ is connected to it, its angular velocity is \\$-\omega\_2\\$.

There is still the problem of the clinch situation:

For small-scale problems I would advise to simply do this gear-wise for all gears: Then, if for any gear you want to set a different direction than already set - set all angular velocity values (or the system velocity) to 0 - the system is "jammed"!

You simply do this for each set of connected gears.

Its not a very sophisticated method to do this but I think it should work. :-)

One more comment: you can easily save the gear structure in the so-called "adjacency matrix". It is a matrix that is 1, if gear i is connected to gear j and 0 otherwise. As an example, take the 3x3 matrix consisting of only ones - where each of three gears is connected to the other - it represents a jammed system! In your scripts, use the adjacency matrix to write the script that determines the rotation directions!

# Answer
> 0 votes
You might be using a net-like structure, where each gear knows about all gears it is in contact with.

When you need to apply a rotation, you pick a master gear that you start with and recursively rotate all its neighbors.

If you want an algorithm to find a master gear - there's really none. You just pick gears that has only one neighbor and choose one of them (e.g. by it's size or net distance from other gears).

Note, that you need to deal with clinch situations, when you have three gears interlocking each other.

# Answer
> -1 votes
This seems like a standard engineering problem. It is definitely possible to determine the rotations of all gears, even with multiple drivers. Read up on Gear Trains. If this is a big part of your work, it might be worth picking up a book on engineering dynamics. Good luck!

---
Tags: mathematics, algorithm, physics
---


# Question
Title: Sounds overlapping when playing too many at the same time
I am pretty novice when it comes to game sound management, so excuse my ignorance.

I am having an issue when playing too many sounds at the same time where some sounds stop playing, or doesn't play at all, almost like some sounds overlap others. I've read some about the sounds using individual buffers and that there should be no problem playing these at the same time at runtime. When I only had a small ammount of sounds in the game, it all worked flawlessly. My SoundManager had no problem playing multiple sounds at the same time ( I loaded the sound to memory when I was going to play it and disposed it when it was done playing, approx. 5 seconds).

My SoundManager Class

I've recorded a video to better illustrate what this sound problem is. As you can hear in the video below, the attacking sounds can only be heard at some points, as for some enemy sounds. The idling sounds of the enemies (breathing and bat sounds) seem to work without issues, though.

Video

Thank you for helping, because I have no clue how to fix this issue. Is there something that I've left out in my SoundManager?

# Answer
After some research and testing, I've now managed to resolve my own issue.

The problem lied within memory management. I followed this tutorial Stiegert and got inspiration from his SoundManager class to create a new SoundManager of my own that uses LRU Caching.

Thanks Alexandre Vaillancourt for the assistance
> 2 votes

---
Tags: libgdx, sound
---


title: Skydome and Ambient Intensity (Unity)

text:
# Question
Title: Skydome and Ambient Intensity (Unity)
I've made a custom skydome in my game. For all my lights I have set them to not affect the skydome. The only thing affecting the skydome is the ambient light.

For my game I have ambient intensity at 0.8, but this makes my skydome much darker than the original texture. What I want to do is to set the ambient intensity for the skydome to 1.0 and for all other objects to 0.8.

Is there any way I can say before drawing the skydome set ambient intensity to 1.0, and right after set it back to 0.8? Or is there perhaps a simpler solution? :)

# Answer
> 3 votes
The skydome material's shader should be set to Unlit/Texture to ignore the lighting.

---
Tags: unity, lighting, sky
---


# Question
Title: How do I clear the previous frames of a canvas animation?
I am trying to rotate an object, but all the previous frames still show up on the canvas. Here is my code.

This didn't work:

```
this.ctx.clearRect(0, 0, this.canvas.canvasWidth, this.canvascanvas.Height);

```

How I can make only the current frame visible?

# Answer
> 1 votes
You currently have a typo in the line you posted:

```
this.canvascanvas.Height

```

should be:

```
this.canvas.canvasHeight

```

Alternatively, you can use `canvas.width` and `canvas.height` as shown in this StackOverflow answer.

**Debugging tip**

When this type of code snippets don't work, try just outputting their values to the console with `console.log(...)`. In your case, outputting the value of `this.canvascanvas.Height` would have wield `undefined`, which would have been a clear indication that something is wrong with the variable (in this case, that it doesn't exist).

---
Tags: javascript, animation, html-canvas
---


title: How should asset bundles be divided?

text:
# Question
Title: How should asset bundles be divided?
The only way to load an asset from an asset bundle into memory is to load the entire thing, decompress and pull out the asset you want, then unload the entire thing, except the assets you want. This seems impractical for sharing assets between bundles. For example, if asset bundle A wants a single asset from asset bundle B, it must load all of B, pull out the asset, then destroy B. The alternative to this is to extract the shared assets and create a new bundle call asset bundle C. The problem with this is that B must have been designed this way before being built, which it won't be if it was built before A (it has to be since A depends on B).

Using the resources folder results in a huge blob of bytes that, from what I understand, cannot be changed after build, and is certainly not differ able for patches.

Putting the pros of asset bundles and the resource folder together, I figure that having an asset bundle for every asset is the best of both worlds. Is there problems with this? Is my understanding of asset bundles or the resource folder flawed?

# Answer
You are correct in your assumptions. For our project we have an editor script which runs through all our assets, packs some of them into small bundles and saves information about each bundle into config. When we need to load something at runtime our system determines whether it should fetch data from Resources or asset bundles. This way we can adjust our build size and memory footprint. The hard part with this approach is to correctly unload bundles after you are done with them, otherwise you can end up with memory leaks or black textures. Also keep in mind that loading a bunch of small bundles is way slower than loading one big bundle, it can significantly hurt user experience.
> 1 votes

---
Tags: unity, resource-management
---


# Question
Title: How to manipulate the two variables that rotate the camera with Input.GetAxis(“Mouse X/Y”)?
A helpful fellow showed me the script for a free look camera mode that rotates with the mouse. The script is included at the bottom of the page.

I want to have a system that right clicks once to enter this camera mode and right clicks again to exit it and slerps back to the original position. I tried to do it, but it seems like when I right click once and then right click again, it works ok because it's the first time I do it. But when I right click again, it snaps back to the rotation that it last left off from in free look (the starting rotation of the slerp).

Does this have to do with the way the yaw and pitch variables are stored? I assume that after exiting free look, yaw and pitch still hold the values from the last rotation. Consequently, I tried resetting yaw and pitch, but it still has the same old problem.

On the other hand, after playing around a bit, sometimes it resets to a particular rotation no matter what. So does that mean I need to do a bit of testing and say,

```
if (rotation = x)
{
    pitch = y;
} // figure out what y should be through trial and error testing)

```

or something like that?

---

```
using UnityEngine;
using System.Collections;

public class FirstPersonCam : MonoBehaviour {

    public float speedH = 2.0f;
    public float speedV = 2.0f;

    private float yaw = 0.0f;
    private float pitch = 0.0f;

    void Update () {
        yaw += speedH * Input.GetAxis("Mouse X");
        pitch -= speedV * Input.GetAxis("Mouse Y");

        transform.eulerAngles = new Vector3(pitch, yaw, 0.0f);
    }
}

```

# Answer
Looks to me like you should set the yaw and pitch to the current rotation's yaw and pitch whenever you enter the freemode.

Should be something simple like

```
if( enterFreemode )
{
     pitch = transform.eulerAngles.x;
     yaw = transform.eulerAngles.y;
}

```

That should ensure that whenever you enter the free camera, you have the same rotation as the original camera.
> 1 votes

# Answer
I'm assuming you are using two different cameras (as you probably should).

If so, then the script below should work for what you want.

Attach this script to the player (or any gameobject that is always active in your scene). Then be sure to assign the cameras to the script from the inspector.

When you are switching cameras, particularly from the other cam to the first-person cam, the FirstPersonCam script is already active so it is going to react to mouse movements immediately. It has to be deactivated, then slerp, then activated when the interpolation is completed. Also, when the script is deactivated, the angles need to be reset so it transitions to a clean state looking straight ahead.

SwitchCamera.cs

```
using UnityEngine;
using System.Collections.Generic;

public class SwitchCamera : MonoBehaviour {
    public float slerpDuration = 1.0f;
    private float slerpTime = 0.0f;

    public List<Camera> cameras;

    private bool interpolating = false;

    private Vector3 oldPosition;
    private Quaternion oldRotation;
    private Vector3 newPosition;
    private Quaternion newRotation;

    void OnEnable() {
        if ((cameras == null) || (cameras.Count < 2)) {
            Debug.LogError("At least two cameras must be added to the 'cameras' list.");
        }
    }

    void Update() {
        if (!interpolating && Input.GetMouseButtonUp(1)) {
            Camera oldCamera = Camera.main;
            Camera newCamera;

            int next = cameras.IndexOf(oldCamera);
            if (++next >= cameras.Count) { next = 0; }
            newCamera = cameras[next];

            oldCamera.enabled = false;
            newCamera.enabled = true;

            EnableFirstPersonCam(false);

            oldPosition = oldCamera.transform.position;
            oldRotation = oldCamera.transform.rotation;

            newPosition = newCamera.transform.position;
            newRotation = newCamera.transform.rotation;

            newCamera.transform.position = oldCamera.transform.position;
            newCamera.transform.rotation = oldCamera.transform.rotation;

            interpolating = true;
            slerpTime = 0.0f;

        } else if (interpolating) {
            if (slerpTime < slerpDuration) {
                slerpTime += Time.deltaTime;

                Camera.main.transform.position = Vector3.Slerp(oldPosition, newPosition, slerpTime);
                Camera.main.transform.rotation = Quaternion.Slerp(oldRotation, newRotation, slerpTime);

            } else {
                interpolating = false;
                EnableFirstPersonCam(true);
            }
        }
    }

    private void EnableFirstPersonCam(bool enabled) {
        FirstPersonCam fpc = Camera.main.GetComponent<FirstPersonCam>();
        if (fpc != null) { fpc.enabled = enabled; }
    }
}

```

I also had to add an OnDisable event to the FirstPersonCam script. (I changed the code a bit, but other than the OnDisable() and the addition of support for Roll), it is the same. Roll is not actually used, since the roll speed is 0.0f;

FirstPersonCam.cs

```
using UnityEngine;
using System.Collections;

public class FirstPersonCam : MonoBehaviour {

    public Vector3 defaultAngles = new Vector3(0.0f, 0.0f, 0.0f); // pitch, yaw, roll in degrees (euler)
    public Vector3 rotationSpeed = new Vector3(-2.0f, +2.0f, +0.0f); // pitch, yaw, roll (degrees per update)

    private Vector3 currentAngles;

    void OnDisable() {
        currentAngles = defaultAngles;
        transform.eulerAngles = currentAngles;
    }

    // Update is called once per frame
    void Update () {
        currentAngles.x += rotationSpeed.x * Input.GetAxis("Mouse Y"); // pitch
        currentAngles.y += rotationSpeed.y * Input.GetAxis("Mouse X"); // yaw
        currentAngles.z += rotationSpeed.z * Input.GetAxis("Mouse ScrollWheel"); // roll

        transform.eulerAngles = currentAngles;
    }

}

```

PS. The SwitchCamera script actually cycles between all cameras in the list, so if you have more than 2, it will transition to the next camera in the list.
> 1 votes

---
Tags: unity, camera
---


title: RPG Game Graphics Help/Review

text:
# Question
Title: RPG Game Graphics Help/Review
I've been working on an simple RPG game and I'm having troubles figuring out how my graphics should look.

I'm wondering if any of you could give some advice on how they are/could be more pleasing to the eye.

Here is a couple of screen shots of the game itself:

Any suggetions/comments!

Thanks!

Sorry, I'm unable to post more pictures, because of my repution :(

Edit: After some working on the look of the game here is where I got to...

# Answer
> 2 votes
I'm not sure if this question is appropriate for this site, but I'll give you my take.

First, kudos on making your game! I am all for doing stuff yourself if you can't find anybody else to do it.

You are certainly going for the pixel art retro look, and that is pretty cool. Make your game in the way you like it the most, and take people's advice just as advice. Stuff people tell you (even me) are not orders, and feel free to disregard everything you hear, or even do things completely differently.

That said, I have some suggestions to make your game look a bit better. I'll be based mostly on your last screenshot.

1. Decide what your resolution is, and stay with it. It seems like you are mixing lots of pixel sizes, and it makes things look pretty inconsistent. For example:

* The rightmost block in the "P" in "HP" is on a 1-pixel grid.
    * The other GUI fonts are on a 2-pixel grid. The mouse cursor is also on a 2-pixel grid.
    * The background floor, and the world in general is on a 4-pixel grid.
    * The items and other GUI elements seem to be on a 6-pixel grid, but the exclamation mark seems to be on a 4-pixel grid. Some pixels on the top right elements are on a 5-pixel grid?
    * The close up character is on a 16-pixel grid.

So, in general, the pixel feeling is completely lost. Choose a resolution, and make it so every graphical element uses that resolution. If you're going for an 8-bit taste, you may want to consider using a relevant resolution, like 320x200 (CGA), and then upscale so it can be seen on a modern monitor.

Once you choose a resolution, make all of your graphics target that resolution. I know you are using the small character sprite and upscaling it, but if you were back in the 80s, a close up would be an awesome way to show more detail in your character!
2. Same goes for your color palette. The entire point behind retro is that you are extremely limited on resources. That goes for colors as well. If seems like you're using arbitrary 24-bit RGB colors, but an 8-bit platform does not have all these colors! Restrict yourself to a very small palette, like CGA's 16 base colors, and make your game with only those colors!

You'll notice those colors are hideous! but that's the beauty of 8-bit. Using very tight restrictions to make awesome stuff.

For resolution and colors, it could be a good idea to choose a target platform, and try to emulate its restrictions, at least in terms of resolution and palette.
3. Choose a font, and a font size, and stay with it. This is true for most games though. So far you're using four fonts (excluding the game title's font): the Start/Exit font, the top HP/MP font, the "Knight" font, and the other font. Choose (or even make!) a font, and stay with it for the entire game.
4. Ditch any kind of effects. You seem to be using a semitransparent curtain to black out the world and show the character details, but such effects would be completely unavailable on an 8-bit platform.

If you're going to show a character details screen, make a character details screen as a separate screen, or at least make a general border for all your elements.
5. I would say ditch the mouse. Mouse in games is much more modern that what you're trying to emulate.
6. Maintain consistency in your terminology and the way you show things to make things more understandable. If "HP" and "Health" are the same thing, why do you call them in a different way? Why do you show one with a bar and the other one with numbers?
7. In general, when showing lists of data, you may want to align the labels and data so the flow is more understandable. For example:

```
       PlatyPi the Knight

           Level     2
              HP   125 / 125
              MP    10 / 125

            Gold    10

        Strength     4
         Defense     4

```
8. If the player is on a menu, let them know of the fact they're on a menu, such as with a title "Character details", and let them know how to get out of it, such as "Press ESC to return to game". Make sure all keystrokes and icons are consistent (ESC always goes back one menu, titles always go on the top, text hints on the bottom, etc.)
9. "Adventure Quest"? ;)

This is just a bunch of very basic ideas that I think could help you make a better looking game. If possible, partner with somebody who has a bit more of an artistic background, and discuss your ideas with them.

Also, look at other games of the same era that you're trying to emulate, and learn about the platform they're on. Try to emulate what they're doing, and you'll have an awesome game!

Once again, congratulations on making your game, and good luck!

---
Tags: c++, game-design, graphics, rpg
---


# Question
Title: Real-time movement client to server to client(s)
So the way that I tried to create a MMO like server communication was by sending strings to every-player containing information and making the client split the string.

*Example*

"John" , 42, 64 : "Bob", 0, 0 : "Lilly", 1943, 120

This worked make it so for every ':' it would create a new character with the following information. And just send it to every-player connected. But once I added bullets and the game world, this started getting long and hard to manage.

*Example*

"John", 42, 64 (42,43 / 45,12 / 45,12, / 46,5 / 12,5), "Help Me", "Running", "Red", "Red", "Blue", 12

I have made a Async multi-client fast server, which works very well, but how can I send information through the server so every client can respond to it correctly.

So for example:

* You start the game it connects to master server (Done)
* You get added the servers player list (Done)
* Make so you spawn as a character on everyone's else's screen and move in real-time every update. (Problem)

Is there any way to get this working with-out using this really long string? I hope I explained this question clearly.

# Answer
> 1 votes
The server should send a new information to the clients only if there was a change in behaviour in one of those clients (input from a player) - and then only send the information about the change.

So to extend your example (this might include lot of stuff that is obvious to you, but just for the clarity...):
**Player connects to the server**:
\- Server looks up all the information about the player that is needed for the clients to display him properly: at minimum this would be the position. Depending on the game we're making this would also include things like rotation, state, character appearance etc. (though for example the appearance can generally be loaded later and a placeholder can be displayed instead). This information is then send to every client (including the player). **And we are not going to send this big bulk of information together again.**
\- Clients create this new player based on the information they received and the player now also knows what his position is so now we can render the world around him. The player would also need information about other players that are nearby - this also could have been sent to him in the previous step.

At this point every client should see everyone that is nearby.

**Player wants to move forward:**
This is very game dependant (is the movement "click to move", WASD, something else?) but let's consider the option where while the *W* keys is pressed, the player is moving forward. Two things should happen when the player presses the key. First, this information and nothing more is sent to the server. So the server receives a message that "John", whatever he's doing right now, wants to move forward.
*Meanwhile on the player's client the second thing happens as we can start performing the forward movement no matter what's going on on the server (look up movement prediction for more information).*
After receiving the information, the server checks if the movement is possible and if it is, sends the movement data to the clients. The clients should already have this player's position and rotation, so we don't need to send it again (although you might want to do that for synchronization purposes, but that can be performed at a different time).

The player shouldn't send anything concerning the movement after that. The server and the clients should all now perform the forward movement calculation inside their own update methods, until the player stops pressing the *W* key. Then we send a new message like before containing only player ID and that we doesn't want to move anymore.

We can apply a similar approach to rotation, shooting, state or changing appearance. When the player presses the "shoot" button, the server gets notified, and can just resend the information to the others, or can attach direction vector as well to ensure more synchronized behaviour.

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


# Question
Title: DDS files with DirectX Tk, Some work, some don't
I am learning DirectX with the DirectX Tool Kit library and everything seems to be going smoothly but I have run in to a tiny little hiccup.

I am currently trying to load DDS textures from file because this method is easier than loading common JPG or PNG files. The problem is that DDS images I create from Paint.NET work fine. Images in PNG or JPG file formats converted to DDS do not work and my program throws an exception.

1. So does anyone have experience with this type of problem and if so, how did you solve the problem?
2. Also is there any workflow oriented software I can use for creating DDS files?

I plan to make my application with DirectX and DirectXTK. (It is too late to turn back now...)

# Answer
**The question is what pixel format are you converting your `JPG` and `PNG` images to for the `DDS`, and with what tool?**

Many of the older tools, including the legacy DirectX SDK texture tool, will default to using a 24bpp format `D3DFMT_R8G8B8`. The problem with this format is that *there is no DXGI format that is 24bpp*. The DDSTextureLoader in DirectX Tool Kit is designed for efficient runtime use, and therefore performs no conversions. Either the `DDS` file in question directly maps to a DXGI format, or it fails to load.

The texconv command-line tool in DirectXTex is a modern converter. It can load and convert older legacy `DDS` file formats that don't have DXGI equivalents as well. See Direct3D 11 Textures and Block Compression.

Depending on what format you are choosing to convert your `DDS` files into, there are potentially other points of failure based on your video card's Direct3D Feature Level. For example, you can't use a `BC4` or `BC5` texture on a Feature Level 9.x device.

The DDSTextureLoader functions don't throw C++ exceptions. They return `HRESULT` values. While a common pattern is to use `DX::ThrowIfFailed` to handle the return value, you can also inspect the HRESULT in the debugger which could well provide a clue as to why it failed.

See the DDSTextureLoader documentation for more for details.

PS: If you are new to DirectX, consider taking a look at the DirectX Tool Kit tutorials.
> 1 votes

# Answer
If Paint.net created dds files work for you and converted jpgs do not and you converted in a different software, convert jpgs to dds in Paint.net. You can also use DirectX texture tool provided with the DirectX SDK which I can say for sure works.

Also keep in mind if you use DXT compression, your textures must be power of two size.

Also try out different DDS texture formats and try switching mipmaps to on/off if you can still not load them.
> 0 votes

---
Tags: c++, 2d, directx11, visual-studio
---


title: Drawing fonts with LWJGL3 with OpenGL

text:
# Question
Title: Drawing fonts with LWJGL3 with OpenGL
I'm very sorry if this question has already been answered, but since I've been struggling with this for many days I thought I'd give it a shot here.

My goal is to somehow render some text on the screen, so I could make a score counter for my game and also maybe add some informative text. If someone could at least point me in the right direction, then I would be very grateful.

Tried to draw text using Bitmaps, but haven't had any luck doing it.

I'm using LWJGL3 and lwjgl-utils.jar for GLU.

So I got this code

```
package com.thecherno.flappy.font;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.DataBufferInt;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import java.awt.GraphicsEnvironment;

import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.glu.GLU;

import static org.lwjgl.glfw.GLFW.glfwGetCurrentContext;

/**
 * A TrueType font implementation originally for Slick, edited for Bobjob's Engine
 *
 * @original author James Chambers (Jimmy)
 * @original author Jeremy Adams (elias4444)
 * @original author Kevin Glass (kevglass)
 * @original author Peter Korzuszek (genail)
 *
 * @new version edited by David Aaron Muhar (bobjob)
 */
public class TrueTypeFont {
public final static int
        ALIGN_LEFT = 0,
        ALIGN_RIGHT = 1,
        ALIGN_CENTER = 2;
/** Array that holds necessary information about the font characters */
private IntObject[] charArray = new IntObject[256];

/** Map of user defined font characters (Character <-> IntObject) */
private Map customChars = new HashMap();

/** Boolean flag on whether AntiAliasing is enabled or not */
private boolean antiAlias;

/** Font's size */
private int fontSize = 0;

/** Font's height */
private int fontHeight = 0;

/** Texture used to cache the font 0-255 characters */
private int fontTextureID;

/** Default font texture width */
private int textureWidth = 512;

/** Default font texture height */
private int textureHeight = 512;

/** A reference to Java's AWT Font that we create our font texture from */
private Font font;

/** The font metrics for our Java AWT font */
private FontMetrics fontMetrics;

private int correctL = 9, correctR = 8;

private class IntObject {
    /** Character's width */
    public int width;

    /** Character's height */
    public int height;

    /** Character's stored x position */
    public int storedX;

    /** Character's stored y position */
    public int storedY;
}

public TrueTypeFont(Font font, boolean antiAlias, char[] additionalChars) {
    this.font = font;
    this.fontSize = font.getSize()+3;
    this.antiAlias = antiAlias;

    createSet( additionalChars );

    fontHeight -= 1;
    if (fontHeight <= 0) fontHeight = 1;
}

public TrueTypeFont(Font font, boolean antiAlias) {
    this( font, antiAlias, null );
}
public void setCorrection(boolean on) {
    if (on) {
        correctL = 2;
        correctR = 1;
    } else {
        correctL = 0;
        correctR = 0;
    }
}
private BufferedImage getFontImage(char ch) {
    // Create a temporary image to extract the character's size
    BufferedImage tempfontImage = new BufferedImage(1, 1,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
    if (antiAlias == true) {
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
    }
    g.setFont(font);
    fontMetrics = g.getFontMetrics();
    int charwidth = fontMetrics.charWidth(ch)+8;

    if (charwidth <= 0) {
        charwidth = 7;
    }
    int charheight = fontMetrics.getHeight()+3;
    if (charheight <= 0) {
        charheight = fontSize;
    }

    // Create another image holding the character we are creating
    BufferedImage fontImage;
    fontImage = new BufferedImage(charwidth, charheight,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D gt = (Graphics2D) fontImage.getGraphics();
    if (antiAlias == true) {
        gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
    }
    gt.setFont(font);

    gt.setColor(Color.WHITE);
    int charx = 3;
    int chary = 1;
    gt.drawString(String.valueOf(ch), (charx), (chary)
            + fontMetrics.getAscent());

    return fontImage;

}

private void createSet( char[] customCharsArray ) {
    // If there are custom chars then I expand the font texture twice
    if  (customCharsArray != null && customCharsArray.length > 0) {
        textureWidth *= 2;
    }

    // In any case this should be done in other way. Texture with size 512x512
    // can maintain only 256 characters with resolution of 32x32. The texture
    // size should be calculated dynamicaly by looking at character sizes.

    try {

        BufferedImage imgTemp = new BufferedImage(textureWidth, textureHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = (Graphics2D) imgTemp.getGraphics();

        g.setColor(new Color(0,0,0,1));
        g.fillRect(0,0,textureWidth,textureHeight);

        int rowHeight = 0;
        int positionX = 0;
        int positionY = 0;

        int customCharsLength = ( customCharsArray != null ) ? customCharsArray.length : 0;

        for (int i = 0; i < 256 + customCharsLength; i++) {

            // get 0-255 characters and then custom characters
            char ch = ( i < 256 ) ? (char) i : customCharsArray[i-256];

            BufferedImage fontImage = getFontImage(ch);

            IntObject newIntObject = new IntObject();

            newIntObject.width = fontImage.getWidth();
            newIntObject.height = fontImage.getHeight();

            if (positionX + newIntObject.width >= textureWidth) {
                positionX = 0;
                positionY += rowHeight;
                rowHeight = 0;
            }

            newIntObject.storedX = positionX;
            newIntObject.storedY = positionY;

            if (newIntObject.height > fontHeight) {
                fontHeight = newIntObject.height;
            }

            if (newIntObject.height > rowHeight) {
                rowHeight = newIntObject.height;
            }

            // Draw it here
            g.drawImage(fontImage, positionX, positionY, null);

            positionX += newIntObject.width;

            if( i < 256 ) { // standard characters
                charArray[i] = newIntObject;
            } else { // custom characters
                customChars.put( new Character( ch ), newIntObject );
            }

            fontImage = null;
        }

        fontTextureID = loadImage(imgTemp);

        //.getTexture(font.toString(), imgTemp);

    } catch (Exception e) {
        System.err.println("Failed to create font.");
        e.printStackTrace();
    }
}

private void drawQuad(float drawX, float drawY, float drawX2, float drawY2,
                      float srcX, float srcY, float srcX2, float srcY2) {
    float DrawWidth = drawX2 - drawX;
    float DrawHeight = drawY2 - drawY;
    float TextureSrcX = srcX / textureWidth;
    float TextureSrcY = srcY / textureHeight;
    float SrcWidth = srcX2 - srcX;
    float SrcHeight = srcY2 - srcY;
    float RenderWidth = (SrcWidth / textureWidth);
    float RenderHeight = (SrcHeight / textureHeight);

    GL11.glTexCoord2f(TextureSrcX, TextureSrcY);
    GL11.glVertex2f(drawX, drawY);
    GL11.glTexCoord2f(TextureSrcX, TextureSrcY + RenderHeight);
    GL11.glVertex2f(drawX, drawY + DrawHeight);
    GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY + RenderHeight);
    GL11.glVertex2f(drawX + DrawWidth, drawY + DrawHeight);
    GL11.glTexCoord2f(TextureSrcX + RenderWidth, TextureSrcY);
    GL11.glVertex2f(drawX + DrawWidth, drawY);
}

public int getWidth(String whatchars) {
    int totalwidth = 0;
    IntObject intObject = null;
    int currentChar = 0;
    for (int i = 0; i < whatchars.length(); i++) {
        currentChar = whatchars.charAt(i);
        if (currentChar < 256) {
            intObject = charArray[currentChar];
        } else {
            intObject = (IntObject)customChars.get( new Character( (char) currentChar ) );
        }

        if( intObject != null )
            totalwidth += intObject.width;
    }
    return totalwidth;
}

public int getHeight() {
    return fontHeight;
}

public int getHeight(String HeightString) {
    return fontHeight;
}

public int getLineHeight() {
    return fontHeight;
}

public void drawString(float x, float y,
                       String whatchars, float scaleX, float scaleY) {
    drawString(x,y,whatchars, 0, whatchars.length()-1, scaleX, scaleY, ALIGN_LEFT);
}
public void drawString(float x, float y,
                       String whatchars, float scaleX, float scaleY, int format) {
    drawString(x,y,whatchars, 0, whatchars.length()-1, scaleX, scaleY, format);
}

public void drawString(float x, float y,
                       String whatchars, int startIndex, int endIndex,
                       float scaleX, float scaleY,
                       int format
) {

    IntObject intObject = null;
    int charCurrent;

    int totalwidth = 0;
    int i = startIndex, d, c;
    float startY = 0;

    switch (format) {
        case ALIGN_RIGHT: {
            d = -1;
            c = correctR;

            while (i < endIndex) {
                if (whatchars.charAt(i) == '\n') startY -= fontHeight;
                i++;
            }
            break;
        }
        case ALIGN_CENTER: {
            for (int l = startIndex; l <= endIndex; l++) {
                charCurrent = whatchars.charAt(l);
                if (charCurrent == '\n') break;
                if (charCurrent < 256) {
                    intObject = charArray[charCurrent];
                } else {
                    intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) );
                }
                totalwidth += intObject.width-correctL;
            }
            totalwidth /= -2;
        }
        case ALIGN_LEFT:
        default: {
            d = 1;
            c = correctL;
            break;
        }

    }

    GL11.glBindTexture(GL11.GL_TEXTURE_2D, fontTextureID);
    GL11.glBegin(GL11.GL_QUADS);

    while (i >= startIndex && i <= endIndex) {

        charCurrent = whatchars.charAt(i);
        if (charCurrent < 256) {
            intObject = charArray[charCurrent];
        } else {
            intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) );
        }

        if( intObject != null ) {
            if (d < 0) totalwidth += (intObject.width-c) * d;
            if (charCurrent == '\n') {
                startY -= fontHeight * d;
                totalwidth = 0;
                if (format == ALIGN_CENTER) {
                    for (int l = i+1; l <= endIndex; l++) {
                        charCurrent = whatchars.charAt(l);
                        if (charCurrent == '\n') break;
                        if (charCurrent < 256) {
                            intObject = charArray[charCurrent];
                        } else {
                            intObject = (IntObject)customChars.get( new Character( (char) charCurrent ) );
                        }
                        totalwidth += intObject.width-correctL;
                    }
                    totalwidth /= -2;
                }
                //if center get next lines total width/2;
            }
            else {
                drawQuad((totalwidth + intObject.width) * scaleX + x, startY * scaleY + y,
                        totalwidth * scaleX + x,
                        (startY + intObject.height) * scaleY + y, intObject.storedX + intObject.width,
                        intObject.storedY + intObject.height,intObject.storedX,
                        intObject.storedY);
                if (d > 0) totalwidth += (intObject.width-c) * d ;
            }
            i += d;

        }
    }
    GL11.glEnd();
}
public static int loadImage(BufferedImage bufferedImage) {
    try {
        short width       = (short)bufferedImage.getWidth();
        short height      = (short)bufferedImage.getHeight();
        //textureLoader.bpp = bufferedImage.getColorModel().hasAlpha() ? (byte)32 : (byte)24;
        int bpp = (byte)bufferedImage.getColorModel().getPixelSize();
        ByteBuffer byteBuffer;
        DataBuffer db = bufferedImage.getData().getDataBuffer();
        if (db instanceof DataBufferInt) {
            int intI[] = ((DataBufferInt)(bufferedImage.getData().getDataBuffer())).getData();
            byte newI[] = new byte[intI.length * 4];
            for (int i = 0; i < intI.length; i++) {
                byte b[] = intToByteArray(intI[i]);
                int newIndex = i*4;

                newI[newIndex]   = b[1];
                newI[newIndex+1] = b[2];
                newI[newIndex+2] = b[3];
                newI[newIndex+3] = b[0];
            }

            byteBuffer  = ByteBuffer.allocateDirect(
                    width*height*(bpp/8))
                    .order(ByteOrder.nativeOrder())
                    .put(newI);
        } else {
            byteBuffer  = ByteBuffer.allocateDirect(
                    width*height*(bpp/8))
                    .order(ByteOrder.nativeOrder())
                    .put(((DataBufferByte)(bufferedImage.getData().getDataBuffer())).getData());
        }
        byteBuffer.flip();

        int internalFormat = GL11.GL_RGBA8,
                format = GL11.GL_RGBA;
        IntBuffer   textureId =  BufferUtils.createIntBuffer(1);;
        GL11.glGenTextures(textureId);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId.get(0));

        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);

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

        GL11.glTexEnvf(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_MODULATE);

        GLU.gluBuild2DMipmaps(GL11.GL_TEXTURE_2D,
                internalFormat,
                width,
                height,
                format,
                GL11.GL_UNSIGNED_BYTE,
                byteBuffer);
        return textureId.get(0);

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }

    return -1;
}
public static boolean isSupported(String fontname) {
    Font font[] = getFonts();
    for (int i = font.length-1; i >= 0; i--) {
        if (font[i].getName().equalsIgnoreCase(fontname))
            return true;
    }
    return false;
}
public static Font[] getFonts() {
    return GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts();
}
public static byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

public void destroy() {
    IntBuffer scratch = BufferUtils.createIntBuffer(1);
    scratch.put(0, fontTextureID);
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0);
    GL11.glDeleteTextures(scratch);
}
}

```

And my Main class looks like this

```
package com.thecherno.flappy;

import com.thecherno.flappy.font.BitmapFonts;
import com.thecherno.flappy.font.Ley2dFontLWJGL3;
import com.thecherno.flappy.font.TrueTypeFont;
import com.thecherno.flappy.graphics.Shader;
import com.thecherno.flappy.input.Input;
import com.thecherno.flappy.level.Level;
import com.thecherno.flappy.maths.Matrix4f;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWvidmode;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.util.glu.GLU;

import java.awt.*;
import java.io.IOException;
import java.nio.ByteBuffer;

import static  org.lwjgl.opengl.GL11.*;
import static  org.lwjgl.opengl.GL13.*;
import static  org.lwjgl.system.MemoryUtil.*;

import static org.lwjgl.glfw.GLFW.*;

public class Main implements Runnable {

private int width = 1280;
private int height = 720;

private Thread thread;
private boolean running = false;

// Setting key callback
private GLFWKeyCallback keyCallback;

private long window; // A "pointer" to memory address of window(id)

private Level level;

public void start() {
    running = true;
    thread = new Thread(this, "Game");
    thread.start(); // This will run the run() method.
}

private void init() {

    if (glfwInit() != GL_TRUE) {
        System.err.println("Could not initialize GLFW!");
        return;
    }

    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    window = glfwCreateWindow(width, height, "Flappy", NULL, NULL);
    if (window == NULL) {
        System.err.println("Could not  create GLFW window!");
        return;
    }

    glfwSetKeyCallback(window, keyCallback = new Input());

    ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
    glfwSetWindowPos(window, (GLFWvidmode.width(vidmode) - width) / 2, (GLFWvidmode.height(vidmode) - height) / 2);

    glfwMakeContextCurrent(window);
    glfwShowWindow(window);
    GLContext.createFromCurrent();

    // GLInit
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_TEXTURE_2D); // Enable Texture Mapping
    glClearColor(0.5f,0.5f,0.5f,0f); // Black Background
    glDisable(GL_DITHER);
    glDepthFunc(GL_LESS); // Depth function less or equal
    glEnable(GL_NORMALIZE); // calculated normals when scaling
//        glEnable(GL_CULL_FACE); // prevent render of back surface
    glEnable(GL_ALPHA_TEST); // allows alpha channels or transperancy
    glAlphaFunc(GL_GREATER, 0.1f); // sets aplha function
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // High quality visuals
    glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST); //  Really Nice Perspective Calculations
    glShadeModel(GL_SMOOTH); // Enable Smooth Shading
//        glViewport(0, 0, 800, 600);
    glMatrixMode(GL_PROJECTION); // Select The Projection Matrix
    glLoadIdentity(); // Reset The Projection Matrix
    GLU.gluPerspective(30, width / (float) height, 1f, 300f);  //Aspect Ratio Of The Window
    glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix
    glDepthMask(true);                             // Enable Depth Mask
    //

    glEnable(GL_DEPTH_TEST);
    glActiveTexture(GL_TEXTURE1);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    System.out.println("OpenGL: " + glGetString(GL_VERSION));

    Shader.loadAll();
    Shader.BG.enable();

    Matrix4f pr_matrix = Matrix4f.orthographic(-10.0f, 10.0f, -10.0f * 9.0f / 16.0f, 10.0f * 9.0f / 16.0f, -1.0f, 1.0f);
    Shader.BG.setUniformMat4f("pr_matrix", pr_matrix);
    Shader.BG.setUniform1i("tex", 1);

    Shader.BIRD.setUniformMat4f("pr_matrix", pr_matrix);
    Shader.BIRD.setUniform1i("tex", 1);

    Shader.PIPE.setUniformMat4f("pr_matrix", pr_matrix);
    Shader.PIPE.setUniform1i("tex", 1);

    Shader.IGTITLE.setUniformMat4f("pr_matrix", pr_matrix);
    Shader.IGTITLE.setUniform1i("tex", 1);

    Shader.BG.disable();

    level = new Level();
}

public void run() {
    init();

    long lastTime = System.nanoTime();
    double delta = 0.0;
    double ns = 1000000000.0 / 60.0;
    long timer = System.currentTimeMillis();
    int updates = 0;
    int frames = 0;

    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        if (delta >= 1.0) {
            update();
            updates++;
            delta--;
        }
        render();
        frames++;
        if (System.currentTimeMillis() - timer > 1000) {
            timer += 1000;
            System.out.println(updates + " ups, " + frames + " fps");
            updates = 0;
            frames = 0;
        }

        if (glfwWindowShouldClose(window) == GL_TRUE) {
            running = false;
        }

    }
    // Key callback thingy.
    keyCallback.release();
    glfwDestroyWindow(window);
    glfwTerminate();
}

private void update() {
    glfwPollEvents();
    /*if (Input.keys[GLFW_KEY_SPACE]) {
        System.out.println("FLAP!");
    }*/
    level.update();

    // Press Escape to exit the game.
    if (Input.isKeyDown(GLFW_KEY_ESCAPE)) {
        glfwDestroyWindow(window);
        glfwTerminate();
        System.exit(0);
    }

    if (level.isGameOver()) {
        level = new Level();
    }
}

private void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    level.render();

    glMatrixMode(GL_PROJECTION);                        // Select The Projection Matrix
    glPushMatrix();                                     // Store The Projection Matrix
    glLoadIdentity();                                   // Reset The Projection Matrix
    glOrtho(0, width, 0, height, -1, 1);                          // Set Up An Ortho Screen
    glMatrixMode(GL_MODELVIEW);                         // Select The Modelview Matrix
    glPushMatrix();                                     // Store The Modelview Matrix
    glLoadIdentity();

    TrueTypeFont trueTypeFont;
    String fontName = "Agent Orange";
    if (!TrueTypeFont.isSupported(fontName)) fontName = "serif";
    Font font = new Font(fontName, Font.ITALIC | Font.BOLD, 40);
    trueTypeFont = new TrueTypeFont(font, true);
    //DRAW STRING FROM THE - CENTER
    //HALF SCALE OF 0.5f
    trueTypeFont.drawString(width / 2, trueTypeFont.getHeight() * 3,
            "at the possible sound of your name.\n" +
                    "No I wouldnt go that far.\n" +
                    "No.", 0.5f, 0.5f, TrueTypeFont.ALIGN_CENTER);

    int error = glGetError();

    if (error != GL_NO_ERROR) {
        System.out.println(error);
    }
    glfwSwapBuffers(window);
}

public static void main(String[] args) {
    new Main().start();
}
}

```

For rendering text I added this code in the Main class

```
    TrueTypeFont trueTypeFont;
    String fontName = "Agent Orange";
    if (!TrueTypeFont.isSupported(fontName)) fontName = "serif";
    Font font = new Font(fontName, Font.ITALIC | Font.BOLD, 40);
    trueTypeFont = new TrueTypeFont(font, true);
    //DRAW STRING FROM THE - CENTER
    //HALF SCALE OF 0.5f
    trueTypeFont.drawString(width / 2, trueTypeFont.getHeight() * 3,
            "at the possible sound of your name.\n" +
                    "No I wouldnt go that far.\n" +
                    "No.", 0.5f, 0.5f, TrueTypeFont.ALIGN_CENTER);

```

At the moment all I get are some white rectangles, so I assume that something is rendering. I've read that rendering white boxes is somehow a typical problem, but I can't find a solution. I'm not using any resources like .ttf or .png fonts/bitmaps for this code, should I? How?

Also, sorry for my english. I would be forever grateful if someone could help me out here.

Best wishes to all of You!

# Answer
Don't know if still relevant, just wanted to update you that I had the very same issue and this fixed it:

*(this is **not** my answer, all credits go to* **adventurerOK** *@ https://stackoverflow.com/questions/10064804/java-lwjgl-slick-unicodefont-acting-up*)

> It seems I have this error now, it will only draw the outlined rectangle before using the font. This seems to be a Slick error, and is a major problem so they should fix it before adding new features. The only work-around is to render fonts last on your frame.
>
> EDIT: Problem Solved!
>
> add this line after you render your font:
>
> **`GL11.glDisable(GL11.GL_TEXTURE_2D);`**
>
> The Slick people should really add that line in as it causes so many bugs!
> 0 votes

---
Tags: opengl, java, rendering, lwjgl, fonts
---


# Question
Title: Isometric 3D grid - what order do I render elements in the grid?
I'm trying to create a screensaver, so strictly speaking this isn't for developing a game, but the subjects discussed on this SE site are a better match than any of the other sites, and I think the answer to my problem will be of value to game developers facing the same issue.

I'm trying to render an isometric grid of bricks, using 2D graphics to represent a 3D grid of bricks.

The algorithm I'm using is rendering them in the wrong order so that bricks are appearing as if they're on top of bricks which they're actually behind. For example:

The white, black, and blue bricks should be rendering behind the long red brick. In terms of render order, they should be drawn before the red brick, but because the red brick is 1 step lower along the Z axis, it gets rendered first.

All of the bricks are aligned to integer coordinates. The "flat" bricks are 1 unit tall, and the "regular" bricks are 3 units tall.

The code I've got so far is:

```
    for (int i = 0; i < world.getDimension().z; i++) {
        for (int j = world.getDimension().y - 1; j >= 0; j--) {
            for (int k = 0; k < world.getDimension().x; k++) {
                BrickInstance brick = world.getBrickGrid().get(k, j, i);
                if (brick != null && !brick.hasBeenProcessed()) {
                    try {
                        BrickRenderer renderer = getBrickRenderer(brick);
                        renderer.setBrick(brick);
                        renderer.setGraphicsOffset(xOffset, yOffset);
                        renderer.drawBrick(gfx);
                    } catch (InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

```

So it loops along z, y, and x axes to determine render order, and the first time it encounters a brick in the grid, it renders the brick and marks it as done.

I also tried swapping the x and z axes:

```
    for (int i = 0; i < world.getDimension().x; i++) {
        for (int j = world.getDimension().y - 1; j >= 0; j--) {
            for (int k = 0; k < world.getDimension().z; k++) {
                BrickInstance brick = world.getBrickGrid().get(i, j, k);
                ...

```

This seems to help at first, but the same problem occurs, a little less obviously:

Here the 1x4x1 green brick is sitting on the 1x1x1 blue brick, but it renders behind it instead of on top of it.

What order should I be rendering these elements so that they overlap correctly? What should my algorithm look like, either in code or pseudo-code or plain English?

---

Github link (I linked to the specific commit, so 6 months from now it should still link to the right version)

# Answer
## What is the problem?

Generally speaking, you want to do a topological sorting, where the nodes are your bricks and the edges mean "is this node behind that other node" relationship.

So all you need to do in order to sort anything anywhere is to decide on "is behind" relationship.

It seems that your code treats bricks as uniform objects in a grid, meaning a single brick should always fit dimensions of a single tile. But your picture shows that some of your bricks are non-uniform, they can have different volume spanning several tiles. Can you imagine an "is behind" relationship to sort the following configuration of such bricks in your world?

If you can, congratulations :-) (seriously though, thing is that any "is behind" relationship will not be transitive in your world).

## Suggested solution

So, like ScrambledRK said, it would be best to represent your bigger-than-a-tile bricks as a combination of smaller bricks taking a tile each. Tile size should be equal to the smallest possible brick size. Then you can use a simple "farthest from origin" sorting function: the further up the screen the object is, the earlier it should be drawn. In your case sorting is not really needed (yet?), so it would be sufficient to use any of these render strategies.

### Bonus round

If you dislike suggested approach for some reason, I guess it also possible to emulate 3D in 2D by giving your cubes volume. In other words, turn them into axis-aligned bounding boxes and sort using boxes bounds. So in topological sort you would compare the pseudo-3d bounds of bricks with each other for "is behind" relationship, like

`bool is_B_behind_A = (B.Bounds.Min.X < A.Bounds.Max.X && B.Bounds.Min.Y < A.Bounds.Max.Y && B.Bounds.Min.Z < A.Bounds.Max.Z)` .

Naive implementation is easy to code, but would be very slow, so some kind of spatial partitioning is a must. But seriously, at this point it would be much easier to ditch 2D for 3D with 'free' depth buffer sorting, since your bricks are fully opaque.
> 3 votes

---
Tags: java, rendering, isometric
---


title: Job based on development

text:
# Question
Title: Job based on development
Are there any companies that offer jobs based on games or app development by an individual in his profile, with out any certificate from any institution ?

# Answer
Pretty much all jobs in game development are as you describe. I say "pretty much" because, while most if not all job ads will list a degree in the requirements, they really care more about your skills and the games that you've made. Of course, those games have to be *really* awesome to make up for deficits in your educational background. But I mean, Carmack never finished college, and he programmed Doom.
> 0 votes

---
Tags: jobs
---


title: Need help with physics 2D Unity

text:
# Question
Title: Need help with physics 2D Unity
I'm making a 2D game in Unity. Basically there's just a rocket that goes where ever the user touches. With the code that i have right now, the rocket instantly rotates towards the point and moves there straight.

```
Vector3 dir = targetPos - transform.position;
float rotZ = Mathf.Atan2(dir.x, dir.y) * Mathf.Rad2Deg;
rb.MoveRotation(-rotZ);
thrust = 10.0f;
rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.up);

```

This code is placed in the Update function.

I want the rocket to start moving in which ever direction It's currently facing and slowly rotate towards the point as it goes there.

# Answer
> 0 votes
This worked for me

```
float rotationSpeed = 1;
transform.rotation = Quaternion.RotateTowards(transform.rotation,Quaternion.euler(0,0,-rotZ), rotationSpeed);

rigidbody2d.AddForceAtPosition(transform.up * Thrust, transform.position - transform.up);

```

Thanks everyone who helped!

# Answer
> 0 votes
You could make a coroutine and make it delay for some time and then activate the rotation function. The spawning position may be randomized using random.range

# Answer
> 0 votes
What you need to do is control the rocket using steering behavior.

At every frame. You want to move the rocket towards its transform.forward, it might be transform.up in the case of 2d.

Then you want to lerp the rockets rotation towards the target location

```
transform.rotation = Quaternion.Lerp(transform.rotation, Quaternion.LookRotation(target), rotationSpeed);

```

RotationSpeed should be a number between 0 and 1. Like 0.3 for a fairly slow rotation

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


title: 1D Terrain Generation in Java

text:
# Question
Title: 1D Terrain Generation in Java
Not able to implement Perlin Noise for 1D Random Terrain Generation. I've tried everywhere and I cannot find anything useful, sure I sort of understand Perlin Noise but everytime I try it nothing works. I'm using LibGDX in Java if that helps, thanks.

Here is the code for P.N.

```
static float Noise(int x) {
    x = (x << 13) ^ x;
    return (float) (1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & Integer.MAX_VALUE) / 1073741824f);

}

public static float PerlinNoise1D(float x, float persistence, int octaves) {
    float total = 0;
    float p = persistence;
    int n = octaves - 1;

    for (int i = 0; i <= n; i++) {

        float frequency = (float) Math.pow(2, i);
        double amplitude = Math.pow(p, i);
        total += InterpolatedNoise(x * frequency) * amplitude;
    }

    return (int) total;

}

private static float InterpolatedNoise(float x) {
    int integer_X = (int) x;
    float fractional_X = x - integer_X;

    float v1 = SmoothNoise1D(integer_X);
    float v2 = SmoothNoise1D(integer_X + 1);

    return CosineInterpolate(v1, v2, fractional_X);

}

public static float CosineInterpolate(float a, float b, float x) {
    float ft = (float) (x * Math.PI);
    float f = (float) ((1 - Math.cos(ft)) * 0.5);

    return a * (1 - f) + b * f;
}

public static float SmoothNoise1D(int x) {
    return Noise(x) / 2 + Noise(x - 1) / 4 + Noise(x + 1) / 4;
}

```

and here is the code for the for loop used to render the tiles (assuming my tiles are 32px x 32px)

```
for (int i = 0; i < Gdx.graphics.getWidth(); i++) {
    float y = PerlinNoise1D(i, 5f, 3);
    for (int j = (int) (y); j < Gdx.graphics.getHeight(); j++) {
        hudBatch.begin();
        hudBatch.draw(hp, i, j);
        hudBatch.end();
        j+=31;
    }
    i+=31;
}

```

P.S I'm sort of trying to create a terraria-like game.

# Answer
I can't comment yet, but it's probably the i++ in the first line of:

```
for (int i = 0; i < Gdx.graphics.getWidth(); i++) {
    float y = PerlinNoise1D(i, 5f, 3);
    //other stuff
}

```

Since gradient noise is smooth at small intervals and abrupt at big intervals try and scale the value. Something like:

```
float y = PerlinNoise1D(i * 0.1, 5f, 3);

```
> 1 votes

---
Tags: maps, tiles, noise
---


title: libgdx - Check if body is touch

text:
# Question
Title: libgdx - Check if body is touch
I have some bodies around the screen(`Ball[] balls`), and I would like to delete them when user touches them.

Also, I have an `Image` as userData of the bodies.

I dont want to make a function to all `Image`, because the balls have to be deleted in an order.

What is the best way to detect if a body is touch?

# Answer
Your best bet is to extend the `Image` class and add a touch listener.

Add this code into your `Image` subclass:

```
private void addTouchListener() {
    this.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y) {
            YourClassName.this.wasTouched();
        }
    });
}

```
> 0 votes

---
Tags: java, android, libgdx, box2d, touch
---


# Question
Title: Right-side weapon rotate to face the mouse target
I have a 3D game looking from top to bottom where I move the mouse to aim at targets.

I have a simple box (the player) with a sphere on its middle-front (that is the pistol) and a cylinder on its right (that is the machine gun).

When I use the pistol I can make the player look at the target in a way it can send the bullets in the correct direction and it will hit the target position... that's okay.

The problem is when I send the bullets from the cylinder. It will not hit the target because it is attached to the right side of the cube. The bullets will come out of the cylinder straight forward and will pass near the target position. How can I rotate the player in a way that the cylinder will be pointing exactly to the target?

# Answer
> 0 votes
You could create an empty game object and make it a child of the cylinder, attach the your shooting script, then change the position of the empty game object to what ever suits you this will solve the rotation problem and will probably not be very noticeable.

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


title: Problem with coroutines unity 3d

text:
# Question
Title: Problem with coroutines unity 3d
I cannot understand why the coroutines are not waiting the designated number of seconds before executing the code below it. At the moment, the animation bleeds into the next state. I could get around this by using .time and if statements but I thought the whole point of coroutines is that you can avoid that sort of mess.

```
         public IEnumerator LoadBow()
     {
         this.gameObject.GetComponent<Animation>().CrossFade("Load_Bow");
         yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Load_Bow"].length);
         aimStates = AimStates.Draw;
     }

     public IEnumerator DrawBow()
     {
         this.gameObject.GetComponent<Animation>().CrossFade("Draw_Bow");
         yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Draw_Bow"].length);
         aimStates = AimStates.Aim;
     }

     public void Aiming()
     {
         moveTarget.SetActive(false);
         switch(aimStates)
         {
             case AimStates.Load:
                 StartCoroutine(LoadBow());
             break;

             case AimStates.Draw:
                 StartCoroutine(DrawBow());
             break;

```

# Answer
> 4 votes
If you call coroutines this way they will be executed in order, one after another. You should fire them up with StartCoroutine(Aiming());

```
    public IEnumerator Aiming()
             {
                 yield return StartCoroutine(LoadBow());
                 yield return StartCoroutine(DrawBow());
                 aimStates = AimStates.Aim;
             }

        public IEnumerator LoadBow()
             {
                 aimStates = AimStates.Load;
                 this.gameObject.GetComponent<Animation>().CrossFade("Load_Bow");
                 yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Load_Bow"].length);
             }

             public IEnumerator DrawBow()
             {
                 aimStates = AimStates.Draw;
                 this.gameObject.GetComponent<Animation>().CrossFade("Draw_Bow");
                 yield return new WaitForSeconds(this.gameObject.GetComponent<Animation>()["Draw_Bow"].length);
             }

```

# Answer
> 1 votes
You could set a boolean for example to false before yield and then after the time had passed set it back to true and then just use if statement to check if the boolean is true/false. What about efficiency, I think there's not much of a difference. From what I understand the delay from coroutine affects only something you change before and after the delay so that's why I use booleans, I find it less complicated I guess and more functional.

---
Tags: unity, animation, fsm
---


title: Multiple input not working properly

text:
# Question
Title: Multiple input not working properly
I have 3 different buttons, one for each action. I want to be able to jump and walk at the same time, but there's a little problem. jumpButton doesn't work while I'm pressing leftButton or rightButton but the opposite works.

I have no idea what I'm doing wrong.

```
public void handleInput() {
    float x0 = (Gdx.input.getX(0) / (float)Gdx.graphics.getWidth()) * 960;
    float x1 = (Gdx.input.getX(1) / (float)Gdx.graphics.getWidth()) * 960;
    float y0 = (Gdx.input.getY(0) / (float)Gdx.graphics.getHeight()) * 640;
    float y1 = (Gdx.input.getY(1) / (float)Gdx.graphics.getHeight()) * 640;

    boolean jumpButton = (Gdx.input.isTouched(0) && x0 > 850 && x0 < 850+80 && y0 > 640-80);
    boolean leftButton = ( ((Gdx.input.isTouched(0) && x0 < 25+80) || (Gdx.input.isTouched(1) && x1 < 25+80)) && ((Gdx.input.isTouched(0) && x0 > 25) || (Gdx.input.isTouched(1) && x1 > 25)) && ((Gdx.input.isTouched(0) && y0 > 640-80) || (Gdx.input.isTouched(1) && y1 > 640-80)));
    boolean rightButton = ( ((Gdx.input.isTouched(0) && x0 < 125+80) || (Gdx.input.isTouched(1) && x1 < 125+80)) && ((Gdx.input.isTouched(0) && x0 > 125) || (Gdx.input.isTouched(1) && x1 > 125)) && ((Gdx.input.isTouched(0) && y0 > 640-80) || (Gdx.input.isTouched(1) && y1 > 640-80)));

    if (jumpButton) {
        // player jumps
    }
    if (leftButton) {
        // player walks to the left
    } else if (rightButton) {
        // player walks to the right
    } else {
        // player stops walking
    }
}

```

# Answer
> 2 votes
Based on my memories and for example this:

While it's difficult to understand the complicated ANDs and ORs, it seems clear that you forgot to check for the jumpButton being pressed *after* the other buttons.

With leftButton and rightButton, you have `Gdx.input.isTouched(0)` as well as `Gdx.input.isTouched(1)` (with OR inbetween them, so I take that as you're checking whether it was the first thing touched or the second). You don't do that with jumpButton, so you only check for the first finger there.

PS: I'd suggest making the code little more clear, for example iterating throught the pointer index (although it's just two options, so...), it would help you aswell. :)

---
Tags: libgdx, movement, input
---


title: ClickListener getTapCount() returns 0

text:
# Question
Title: ClickListener getTapCount() returns 0
I want to detect the double tap on a Container. If it is detected, then i have to remove the Actor associated with it.

This is my first attempt:

```
addListener(new ClickListener() {
    if(getTapCount() == 2) {
        System.out.println("double click detected");
    }
    return true;
});

```

It does not work. The method getTapCount() returns always 0.

# Answer
> 2 votes
Look here, you're using the listener wrong: https://stackoverflow.com/questions/11373390/button-clicklistener-is-not-working-in-libgdx-game (you're not overriding its methods, I suggest looking up some more information about listeners and especially this one). And use this question to make sure you're adding the stage and the actor right and that you're setting the stage as the inputProcessor.

That's the first thing, also, here they have the same problem, but it appears unresolved, although it offers some more information: http://badlogicgames.com/forum/viewtopic.php?t=12501&p=55966

According to the listener's source, the `clicked` event is triggered after you lift your finger and it also counts the taps in that very moment - if the actual interval fits the set `tapCountInterval`.

So the code should be something like this, given your other code concerning the actor and stage is not wrong:

```
// to what are you adding the listener? and shouldn't you use this method instead?
????.setClickListener(new ClickListener() {
    // might need to set the tapCountInterval
    @Override
    public void clicked(InputEvent event, float x, float y) {
        if( getTapCount() == 2) { // put breakpoint here
            System.out.println("double click detected");
        }
    };
});

```

PS: Sharing some more code might clarify the issue aswell. :)

---
Tags: libgdx
---


# Question
Title: Unity - Jump counter for double jump script not working? C#
It was working fine last night but it doesn't work today, the `zJumpCount` stays at zero after I jump now. If the `zJumpcount` stays at zero my double jump code doesn't work. I even ctrl+z'd back to the beginning of the session with no luck.

```
public class zPlayerMovement : MonoBehaviour {

  public float zMoveSpeed;
  public float zJumpThrust;
  public bool IsGrounded;
  public float zJumpCount;
  private Rigidbody zRB;

  void Start () {
    zRB = GetComponent<Rigidbody>();
  }

  void Update () {

    if (IsGrounded == true)
      zJumpCount = 0f;

    if (Input.GetKey(KeyCode.A))
      zRB.transform.Translate(Vector3.left * zMoveSpeed);

    if (Input.GetKey(KeyCode.D))
      zRB.transform.Translate(Vector3.right * zMoveSpeed);

    if(Input.GetButtonDown("Jump") && IsGrounded == true)
    {
      zRB.AddForce(Vector3.up * zJumpThrust, ForceMode.VelocityChange);
      zJumpCount++;
    }

    if (IsGrounded == false && zJumpCount > 0 && zJumpCount < 2)
    {
      if (Input.GetButtonDown("Jump"))
      {
        zRB.AddForce(Vector3.up * zJumpThrust, ForceMode.VelocityChange);
        zJumpCount++;
      }
      if (IsGrounded == false && zJumpCount >= 2)
      {
        if (Input.GetButtonDown("Jump"))
          return;
      }
    }
  }

  void OnCollisionStay (Collision collisionInfo)
  {
    IsGrounded = true;
  }

  void OnCollisionExit (Collision collisionInfo)
  {
    IsGrounded = false;
  }
}

```

# Answer
I never figured out why it stopped working but I found another way to make it work properly. I deleted the first statement in...

```
void Update ()
if(IsGrouned == true){zJumpCount = 0;}

```

...then I added this to the double jump

```
if (IsGrounded == false && zJumpCount >= 2)
{
    **zJumpCount = 0;**
    if (Input.GetButtonDown("Jump"))
        return;
 }

```

Thanks for the help! :)
> 0 votes

---
Tags: c#, unityscript
---


# Question
Title: LWJGL True Type Fonts - Calculate width and height of box
I want to center some text on the screen. At the moment I divide the display height and width by two, and then render. But I also need the height and width of the textbox, so I can subtract it from the box position, making it complete center.

As you can see the text is not in center.

How can I calculate the width and height of some text?

**Edit:** It's not a solution to multiply the font size by number of chars, as a 'W' is much wider than a '.'.

# Answer
> 1 votes
You should read the Javadocs for Slicks TrueTypeFont. It has a Method `public int getWidth(java.lang.String whatchars)` to get the width of a particular String.

To draw perfectly centered it is then simply

```
int positionX = (windowWidth - textWidth) / 2;

```

# Answer
> 0 votes
You can use`Display.getWidth() / 2 - (Your truetypefont).getWidth(your text) / 2` to center it horizontally

---
Tags: lwjgl, slick, text
---


# Question
Title: How to make smooth 2-d zooming in Processing
I am making a 2d game with camera zooming using Processing. Currently, my program reduces the size of each block by one. This works very well when there are only a few blocks on-screen, but not when there are hundreds. The camera zooms out on an exponential scale, and looks very jittery.

I know that some game engines have systems to overcome this, by distorting some of the blocks, but I am making this game from scratch. I want to know if there is a different trick or system that will achieve a smoother zooming.

# Answer
Many 2D games are actually 3D with most objects fixed in certain planes (Unity 2D for example). If this were the case, you could quite literally just move the camera backwards as a quick fix. However, you mentioned processing!

Processing utilizes affine transformations, and has a built in transformation stack. It's hard for me to remember exactly what the function calls were to add or remove matrices from this stack.. I believe it was `pushMatrix()`.

You're probably already using this transformation stack for things like camera movement (And if you aren't you absolutely should, read about affine transformations and translation matrices!!).

However, this `pushMatrix()` function will add a given matrix to the transformation stack, and apply it to every object you draw as it is being drawn (Similar to the idea of OpenGL Shaders).

If you push a matrix to the stack that has scaling information on the diagonal with the rest of the entries as 0 for example:

```
0.1 0.0
0.0 0.1

```

Then it will effectively scale each block down to a tenth of the size. The generic matrix:

```
scaleX    0
0         scaleY

```

Now, if you are using the matrix stack already- you are going to want to make sure this matrix is pushed **after** to your translation matrices. Order of multiplication matters with matrices, and if you apply the scale **then** the translation, depending on how exactly the processing pipeline works under the hood you could potentially scale your translation too!

If you're curious- if memory serves I believe the transformations are done on the coordinate system of the objects being draw. So by scaling, I am scaling the axes which the object is being drawn on. And by translating, I am translating the origin of the axes. Same with rotation.

So in a nutshell using the processing API:

```
float scaleValue = 0.1f;
pushMatrix();
translate(-cameraX, -cameraY);
//Rotate(radians(90)); If you wanted rotation apply it after translation
scale(scaleValue);
rect(objectX, objectY, 100.0f, 100.0f); //ObjectX and objectY are
                                        //object's position in worldspace
//Draw everything else you want effected by these transformations
popMatrix(); //Stop applying these transformations

```

For more information: https://processing.org/tutorials/transform2d/

As a quick aside, I would like to point out that processing does have you do it backwards than what the mathematics would suggest. You will usually want to apply Scale and rotation first followed by translation, mathematically speaking.
> 3 votes

---
Tags: 2d, camera, processing
---


# Question
Title: Advice on how to store level design info?
I'm building a 2D tile-based puzzle game in C#, using Monogame. The game board is an 8x6 grid of tiles, each of which can contain a number of objects. Conveniently, the number of possibilities for what each tile can contain fits nicely into 1 byte. I was wondering what the most sensible way to store level design data would be. I'd like it to be at least vaguely human-editable, as I need to construct a level or two while I build the game. Once I'm sure the game logic is all working and it's playable, I intend to build a level editor to construct the rest of the levels, but I need to build the first few manually.

Currently I'm tempted by the idea of encoding the levels in the colour data of an 8x6 pixel bitmap, but that's possibly overkill. Thoughts?

# Answer
> 5 votes
> I'd like it to be at least vaguely human-editable

I would take this to be your first requirement. Storing it in the colour data of a bitmap is probably *not* going to help here so I'd go with something else.

For a 2D tile based game it might be worth investing some time to learn how to use an existing tile based map editor like Tiled. I'm currently adding Tiled support to the MonoGame.Extended project.

Although, if you want to keep it *really* simple even that might be overkill.

It's interesting to look at how games of the 80's and 90's stored levels. For example, I used to play an awesome little puzzle game called Heartlight PC and I've studied how it works.

You can actually download the original game in the DOS games archive and see for yourself. The levels are stored in a text file called `LEVELS.HL` and look like this:

```
%%%%%%%%%%%%%%%%%%%%
%....@.....@.$.....%
%.*..@$...@@@@...@.%
%....@...$.......@.%
%%%%%%%%%%%%%%%%.$.%
%....@@...@....@...%
%.@...$..@...$.@...%
%.@.%%%%%%%%%%%%%%%%
%$.@...@.@...$@....%
%....@@..@$...@$..@!
%.$....@.@..@..$..@%
%%%%%%%%%%%%%%%%%%%%

```

You can watch that level being played on youtube

The awesome thing about doing something like this is that any text editor becomes your level editor. Obviously it has some limitations, but it's really simple and works pretty well for some games.

# Answer
> 3 votes
XNA has an automatic xnb serializer which means you can write levels in xml (very human editable) on your dev machine and the XNA build process will serialize it into binary for compact storage and distribution. Then the XNA content pipeline will load them for the end user just like it does for a model or texture or anything else the content pipeline can handle. If you want to modify a level, you simply modify the xml and rebuild the project, that simple. Your game ships with the binary, not the xml.

Here is a good place to start: http://blogs.msdn.com/b/shawnhar/archive/2009/03/25/automatic-xnb-serialization-in-xna-game-studio-3-1.aspx

# Answer
> 0 votes
Just store it in JSON. Storing it in the colors of a bitmap seems like you're being tricky for no real reason.

# Answer
> 0 votes
For starters, you should only use an image if you need multiple layers of data. If you just need a single layer, a text file is the best option. Since an ascii char is basically a byte, you could just read every char, and then you should be able to convert char to a byte using typecasting. Next you equal for example tiles\[1,1\] to the char you just read on line 1 of the file, first char

\*you could even use the a value for something else. Problem is this makes editing a bit harder

# Answer
> 0 votes
if you need multiple layers, using an image is perfect. I've implemented an image level system for a similar project myself, and it worked perfectly. I used system.drawing, it has a bitmap class (system.drawing.image.bitmap) with getpixel and setpixel functions. Using getpixel you can load the color of a pixel at a certain coordinate. If you loop through all the pixels, using getpixel, you can get the values of your tiles (for example the r value), add enemies to your enemy list/array(using the g value, switch is useful over here), and perhaps get the lighting values or whatever using the b value. Hope it works for you. If you get stuck, I will send you my implementation in like a couple of days. Good luck :)

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


# Question
Title: How can I can create a world that a player can easily get lost in?
I am a 3D environmental artist and I'm currently planning an independent passion game project of mine. I have the concept of crazy hallways that lead to the rooms that the player has already visited, infinite staircases (similar to super mario 64), basically i want the player to be able to get lost in my world very easily. Does anybody have any tips on how i can make this possible? I am developing my game in Unity3D. Thanks, Mitch

# Answer
You could do this by teleporting the player around - in the case of a staircase, after reaching a certain point just reposition the player several steps back. Of course, the environment would have to be crafted in a way so that the player doesn't notice it (that is, when he looks around in both locations (place where the teleport is and the place he gets teleported to) they need to look the same). You can help this effect by reducing visibility / adding fog and whatnot.
For the rooms, you can try making each room a separate building block and make it so that when the player opens a door (or gets near them), you move the appropriate room on the other side. In this case it would be easier if you don't allow the player to have multiple doors open at the same time.
Basically you want to create some kind of a trigger platform, and when the player collides with it you move either him or the rooms around.
> 1 votes

---
Tags: unity, game-design, path-finding, unityscript
---


# Question
Title: How do I cycle through a BufferedImage array of images and display them?
So, I'm coming from Python and Pygame here, porting most of my code because I didn't like the performance. A lot of the syntax is similar, but I've been having some trouble with a few things, namely this animation function.

I'm attempting to cycle through an array of images and have them display an animation. Here's my code so far:

```
//Animation images.
private BufferedImage[] idling = {Sprite.loadSprite("1"), Sprite.loadSprite("2"), Sprite.loadSprite("3"), Sprite.loadSprite("4"),
         Sprite.loadSprite("5"), Sprite.loadSprite("6")};
private BufferedImage[] walkingLeft = {Sprite.loadSprite("L1"), Sprite.loadSprite("L2"), Sprite.loadSprite("L3"), Sprite.loadSprite("L4"),
         Sprite.loadSprite("L5"), Sprite.loadSprite("L6"), Sprite.loadSprite("L7"), Sprite.loadSprite("L8")};
private BufferedImage[] walkingRight = {Sprite.loadSprite("R1"), Sprite.loadSprite("R2"), Sprite.loadSprite("R3"), Sprite.loadSprite("R4"),
         Sprite.loadSprite("R5"), Sprite.loadSprite("R6"), Sprite.loadSprite("R7"), Sprite.loadSprite("R8")};

```

Then my actual animate function (which I suspect is where the issue is).

```
public Image animate() {
    Image animation = idling[0];
    int current_image = 0;
    int current_image_add = 1;
    if (xa == 0 && ya == 0) {
        if (current_image >= 5)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        if (current_image >= 6)
            current_image = 0;
        current_image += current_image_add;
        animation = idling[current_image];
    }
    if (xa == game.speed) {
        if (current_image >= 7)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        current_image += current_image_add;
        animation = walkingRight[current_image];
    }
    if (xa == -game.speed) {
        if (current_image >= 7)
            current_image_add = -1;
        if (current_image <= 0)
            current_image_add = 1;
        current_image += current_image_add;
        animation = walkingLeft[current_image];
    }

    return animation;
}

```

While I was looking over this class, I actually noticed that I had no curly brackets surrounding my if statements, and that might be causing problems. Python doesn't require them, so I forgot that Java did. So, I answered my first question before I even asked it.

The draw function, simple as it is.

```
public void paint(Graphics2D g) {
    animate();
    g.drawImage(animate(), x, y, null);
}

```

Now that it will actually swap BufferedImage arrays when I change directions, how do I get it to cycle through the images? Apparently my if statement functions will only swap to the first image and not change to the next ones.

Edit: Alright, I figured that adding some clarification on what this does might help. The arrays contain all of the images for the animations. The animate() function sets the current\_image variable to the first index of the array, which is the start of the animation. xa and ya are modified by a move() function elsewhere in the class, which the animate() function checks the value of to determine if the character is moving or not. If xa and ya are zero, the character isn't moving and the idling\[\] array is chosen. Likewise, if xa is positive or negative game.speed, right or left is chosen, respectively.

The point of this function is to cycle through the indexes by returning Image animation as whatever array and index of that array should be running at the time based on movement. At the end of each if block, it sets animation equal to whatever animation set and the current\_image variable to choose the image and index.

# Answer
> 1 votes
It's unfortunate that I have to answer my own question, but I'll post the fix that I worked out in case it helps someone else.

```
int current_image = 0;
int current_image_add = 1;

```

These two variables inside of the animate() function were being reset every time animation() was called, meaning that it never really cycled through anything because it continued to reset to the first frame. Declaring them as global variables instead fixed the problem, like so:

```
public class Player {
    private int current_image = 0;
    private int current_image_add = 1;
    //snip
}

```

This revealed a problem with the cycling going through too fast, but I fixed that as well by adding a timer function. Will not go into that since it doesn't help with the original question.

---
Tags: java, animation
---