# Question
Title: May I put a ClickListener to the Stage or better if every Actor/Group has its own?
On the web it's almost always better to have a single click event listener at the top of a hierarchy. For example in a tabular data representation the `<table>` element would listen for all its child elements instead of each `<tr>` or `<td>` having their own listeners, since the event knows its originating element anyway.

Instinctively I'd do the same in LibGDX Scene2D and put my ClickListener to the `Stage` instead of the Actors or Groups.

So far I haven't seen anything which suggests I'm doing it wrong, but as I'm new to LibGDX I thought I'd ask.

# Clarification

I'm a bit worried about possible memory management issues, similarly to when certain Disposables aren't properly disposed, or when I forget to use pooling on objects which are constantly reused.

# Answer
> 1 votes
In short answer, `Stage` extends `InputAdapter` so you could subclass `Stage` and override all of the `InputAdapter` methods. If you did this, you would have to implement your own algorithm to determine which Actor was touched.

Personally, I think that using the event propagation and hit detection that `Stage` already has is worth putting the listeners on the Groups/Actors. However, this doesn't mean that you have to handle all events in the `Actors` themselves.

If you want all input handling to be done in a central location, I suggest using the command pattern. This way, you can inject commands into your `Actors` that they will call when they receive input and the commands will forward any relevant data to your central input handler.

**Answer After Clarification**

As far as memory overhead, your memory footprint won't be drastically different by attaching listeners to your `Actors`. Regardless of whether you use attach any listeners, each `Actor` creates a `DelayedRemovalArray` to hold all of the listeners. Each of your listeners will take differing amounts of memory, depending on how much your data listener implementation stores, but this amount will probably never be large.

Listeners attached to `Actors` are not pooled and, unless you use a resource needing disposal in your handler, do not need to be disposed. The garbage collector will take care of all listener handles when there are no more references to them.

The only processing bottleneck I can see with listeners would be if you are constantly creating them and destroying them. You could potentially pool listeners, but then you would have to free them once the `Actor` using them is no longer in use. In this scenario, I suggest pooling the `Actor` instead as similar `Actors` are going to need similar listeners.

Trying to optimize listener memory is probably an over-design to begin with and I would wait until they have become a proven problem before doing anything about them. Having `Actors` hold their own listeners will make your game more modular and will prevent a monolithic event handler which will be hard to maintain.

**TL;DR;**

The benefits of keeping the code modular and using the `Stage's` event propagation system outweigh any potential memory optimization by having a single monolithic listener. I suggest putting them on the `Actors`.

---
Tags: java, libgdx, optimization, events
---


# Question
Title: Unity2D: Increase spawn object movement when player collects every 10 points
I want to make my spawned objects (enemy prefabs) movement speed up every 10 points my player collects. This is my movement script, attached to my enemy prefab (so that it can be spawned in my game and move):

```
public static int movespeed = 20;
public Vector3 userDirection = Vector3.right;

public void Update()
{
    transform.Translate(userDirection * movespeed * Time.deltaTime);
 }
}

```

And this is my score script attached to my player:

```
public Text ScoreText;
public AudioClip Coinsound;
public Text Highscoretext;
public GameObject enemy;
Movement movement;

private int Score;
public int highScore = 0;

void Start ()
{
    Score = 0;
    SetScoreText ();
    if (PlayerPrefs.HasKey ("Highscore"))
    {
        highScore = PlayerPrefs.GetInt("Highscore");
    }
}
void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Pick Up")) {
        other.gameObject.SetActive (false);
        Score = Score + 1;
        SetScoreText ();
        AudioSource.PlayClipAtPoint (Coinsound, transform.position);

    }
}

```

As mentioned before I want to make my spawned enemy prefabs to move faster when my player collects every ten points. Thank you :)

# Answer
Since you speed is a static variable, you can adjust it from anywhere, and it will affect every entity using that speed. So, update your player script to adjust the speed when it updates the score.

```
void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag ("Pick Up")) {
        other.gameObject.SetActive (false);
        Score = Score + 1;
        SetScoreSpeedFactor(Score);
        SetScoreText ();
        AudioSource.PlayClipAtPoint (Coinsound, transform.position);

    }
}

SetScoreSpeedFactor(int score){
    int scoreFactor = (score/10);
    MovementScript.AdjustSpeed(scoreFactor);
}

public static int basemovespeed = 20;
private static int movespeed = 20;
public Vector3 userDirection = Vector3.right;

public static void AdjustSpeed(int adjustmentValue) {
    movespeed = basemovespeed + adjustmentValue;
}

public void Update()
{
    transform.Translate(userDirection * movespeed * Time.deltaTime);
}

```

This will simply calculate the speed adjustment value as how many times 10 fits into the score. So, if your score is 20, the `scoreFactor` will equal 2. Therefore the result of calling `AdjustSpeed` will set your `movespeed` to `22`.
> 3 votes

# Answer
If you were to have an empty object, then you enable/disable, thru script,it to increase the spawn rate as in when ever it becomes enabled, it is disabled and increases spawn rate, then when ever the score gets high enough, have it enable it. This is a very simple way to trade info between scripts instead having to get the varible from each script.
> -2 votes

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


# Question
Title: Can my game be 8-bit even though it has hi-res text?
My game has 8-bit sounds, 8-bit graphics, 8-bit everything. Except one thing: the level selection screen. It has small text and therefore must be hi-res to be readable. What should I do? **Edit:** The arrows on either side of 'select level' are for going to multiple level screens when there is more levels to be shown. A great answer has been given, but more are welcome.

# Answer
When we think of 8-bit games, we often think of the 8-bit era, where the graphic style was the result of the obvious hardware constraint. In today's age, 8-bit is often associated with a graphical design that *replicates* these games. They do not necessarily restrict themselves to the same native resolutions. In fact, most standard hardware natively runs much larger resolutions. So in fact, a higher resolution that still *bases* its graphical design in 8-bit is still common - and still considered "8-bit".

Given that you are displaying information relevant to the level, itself, you have to consider the trade-off in redesigning the interface to use "8-bit" text. You could try conveying the information in a non-textual format; icons are a popular choice. But it is far easier to miss the mark in expecting your users to understand the information, where as the text itself is straight forward, and you can assume greater understanding across a wider range of users.

Is your game any less of an 8-bit game for using high-resolution text? Maybe. I would argue it is a semantic difference - too insignificant to really impact the 8-bit feel. Is your game still 8-bit for using it? Definitely. From what you explain, the rest of the game is entirely 8-bit. To say the text excludes it is simply nit-picking. If the game is good, and still has an 8-bit feel, most users won't care.

In your current case, you have made the trade-off of a small degree of graphical consistency for far more significant general usability. Your game will profit far more from users being able to understand your text and what it conveys about the level, and if your game is fun and enjoyable, the miniscule amount of "high-res" resource should not detract from the general 8-bit feel.

**I say leave it, it works well**.

If you're still concerned, *ask your users*. Get some playtests, and ask the users some non-probing questions concerning their opinions, their impression of "what genre is this" (given that 8-bit is now considered a genre of its own - some users may not even consider 8-bit a genre, so try to have some more experienced gamers in your testing), and their impressions of the overall style. At the end, you can ask more direct questions. Start with questions that do not infer any specific answer (dont start with "do you think this is 8-bit"), so you can achieve a more natural impression.
> 4 votes

# Answer
You could add arrows to cycle thru multiple slides with only a couple levels on each one. Maybe 3 per a slide? Thiis way you could divide the game into multiple "acts".
> 3 votes

---
Tags: graphics, graphics-programming
---


# Question
Title: Pixel-perfect rendering to a rendertarget with a fullscreen quad
I have some trouble rendering a bunch of values to a rendertarget. The values never end up in the exact range I want them to. Basically I use a fullscreen quad and a pixel shader to render to my rendertarget texture and then intend to use the texture coordinates as basis for some calculations in the shader. The texture coordinates of the quad range from (0,0) in the top left to (1,1) in the bottom right corner... the problem is, after interpolation, these values don't arrive at the pixel shader as such.

**An example:** I render to a 4x4 texture and the shader in this case simply outputs the texture coordinates (u,v) in the red and green channels:

```
return float4(texCoord.rg, 0, 1);

```

What I want to get out of it is a texture where the pixel in the top left is RGB (0,0,0) and thus black, the pixel in the top right is RGB (255,0,0) and thus a bright red and the pixel in the bottom left is RGB (0,255,0) - a bright green.

However, instead I get this here on the right:

**(straight quad rendering, no correction)**

The top left pixel is black, but I only get a relatively dark red and dark green in the other corners. Their RGB values are (191,0,0) and (0,191,0). I strongly suspect it has to do with the sampling locations of the quad: the top left pixel correctly samples the top left corner of the quad and gets (0,0) as UV coordinates, but the the other corner pixels don't sample from the other corners of the quad. I have illustrated this in the left image with the blue box representing the quad and the white dots the upper sampling coordinates.

Now I know about the half pixel offset you should apply to your coordinates when rendering screen-aligned quads in Direct3D9. Let's see what kind of result I get from this:

**(quad rendered with DX9's half pixel offset)**

Red and green have gotten brighter but still aren't correct: 223 is the maximum I get on the red or green color channel. But now, I don't even have pure black anymore, but instead a dark, yellowish gray with RGB(32,32,0)!

What I actually need would be this kind of rendering:

**(target render, reduced quad size)**

It looks like I have to move the right and the bottom border of my quad exactly one pixel up and to the left, compared to the first figure. Then the right column and the bottom row of pixels all should correctly get the UV coordinates right from the border of the quad:

```
VertexPositionTexture[] quad = new VertexPositionTexture[]
{
    new VertexPositionTexture(new Vector3(-1.0f,  1.0f, 1f), new Vector2(0,0)),
    new VertexPositionTexture(new Vector3(1.0f - pixelSize.X,  1.0f, 1f), new Vector2(1,0)),
    new VertexPositionTexture(new Vector3(-1.0f, -1.0f + pixelSize.Y, 1f), new Vector2(0,1)),
    new VertexPositionTexture(new Vector3(1.0f - pixelSize.X, -1.0f + pixelSize.Y, 1f), new Vector2(1,1)),
};

```

However this didn't quite work out and caused the bottom and right pixels to not render at all. I suppose these pixels' centers aren't covered by the quad anymore and thus won't get processed by the shader. If I change the pixelSize calculation by some tiny amount to make the quad a tiny amount bigger it kinda works... at least on a 4x4 texture. It doesn't work on smaller textures and I fear it subtly distorts the even distribution of uv values on bigger textures as well:

```
Vector2 pixelSize = new Vector2((2f / textureWidth) - 0.001f, (2f / textureHeight) - 0.001f);

```

*(I modified the pixelSize calculation by 0.001f - for smaller textures, e.g. 1D lookup tables, this doesn't work and I have to increase it to 0.01f or something bigger)*

Of course this is a trivial example and I could do this calculation much more easily on the CPU without having to worry about mapping UVs to pixel centers... still, there has to be a way to actually render a full, complete \[0,1\] range to pixels on a rendertarget!?

# Answer
Your problem is that UVs are designed to be texture coordinates. A coordinate of 0,0 is the top left corner of the top left pixel in the texture, which is not where you normally want to read the texture. For 2D you want to read the texture in the middle of that pixel.

If my maths is right what you need to do to work round that is:

`return float4((texCoord.rg - (0.5f/textureSize)) * (textureSize/(textureSize-1)), 0, 1);`

That is you subtract the appropriate offset to get the top left pixel at 0,0 and then apply a scale to get the bottom right correct.

The same thing could also be achieved by expanding the UV coordinates for the geometry outside of the 0-1 range.
> 4 votes

# Answer
> It looks like I have to move the right and the bottom border of my quad exactly one pixel up and to the left, compared to the first figure.

Almost, but only half of the pixel. Just subtract 0.5 from your quad vertices. E.g. you want 256x256 quad with same texture, here are your points:

```
p1 = (-0.5, -0.5)
p2 = (-0.5, 255-0.5)
p3 = (255-0.5, 255-0.5)
p4 = (255-0.5, -0.5)

```

Or, you may instead add half of the texel in the pixel shader ( texCoord.rg + 0.5\*(1.0/texSize) )

Half pixel offset is a known fact in DX9. This and this articles may help you as well.
> 0 votes

# Answer
This is certainly being caused by linear sampling. If you look at the texels to the right and below the full-black top-left pixel, you'll see that they have 63 in the R and/or G channels, and 2 of them have 2 in B. Now look at the muddy-dark-yellow you get; it's 31 in R and G and 1 in B. That's definitely a result of averaging texels over a 2x2 group, so the solution is to set your texture filter to point.
> 0 votes

# Answer
That is simply beacuse you are using the texCoords from vertex output which is interpolated by hard drive after processing vertex shader.
> -2 votes

---
Tags: xna, directx, shaders, directx9, rendertargets
---


title: GLFW VBO in World Space

text:
# Question
Title: GLFW VBO in World Space
Last year I wrote a basic 3D game for one of my modules using freeglut. Everything was fine and dandy because I used the deprecated immediate-mode of drawing things (glBegin, glVertex, glEnd) for drawing all my geometry, and it was fine; everything was positioned where I expected it to be.

This time around, I'd like to use GLFW and Vertex Buffers to create my geometry, since this is what is being used now, as well as increase the performance of my application.

I've read and looked at many tutorials, but I don't understand how I can define the vertex position in world coordinates, as opposed to screen coordinates (-1 to 1).

If someone could provide a basic sample code of how this small feat is achieved, I would be very grateful.

Thanks.

# Answer
What you are looking for seems to be how to setup a synthetic camera. Objects can be placed in the world in arbitrary positions, however in order to actually see them you need to have a camera appropriately positioned.

**How to setup the camera?**

By asking this question I assume you don't know how synthetic cameras work. You should be familiarized with the Model, View and Projection matrices and how they relate. For a good tutorial, I recommend http://learnopengl.com/#!Getting-started/Camera.

**How to setup the camera in modern pipeline?**

Assuming you know what Model, View and Projection matrices are, you probably know by now that these were embedded within the fixed pipeline. However, nowadays we must calculate them ourselves, and one of the most used libraries to do that is the GLM (OpenGL Mathematics library).

To calculate them, we use glm::lookAt for the view and glm::projection for the projection matrix. Calculating these matrices, and assuming you have a model matrix (you can set it to identity for now), you should multiply them in this order: projection * view * model. The ModelViewProjection matrix must be sent to your shader and each object vertex should be multiplied by it.

**Example**

I have a very basic Plane demo scenario that you can use. First, set the matrices.

```
modelMatrix = glm::mat4(1.0f);
viewMatrix = glm::lookAt(
    vec3(0.0f, 0.0f, -1.0f), //eye
    vec3(0.0f, 0.0f, 0.0f), //center
    vec3(0.0f, 1.0f, 0.0f)); //up
projectionMatrix = glm::perspective(glm::radians(60.0f), 1.0f, 0.1f, 100.0f);
modelViewMatrix = viewMatrix * modelMatrix;
modelViewProjectionMatrix = projectionMatrix * modelViewMatrix;

```

Now you must send the MVP matrix to the respective shader using the appropriate opengl functions (glUniform\*) and multiply the MVP matrix for each vertex within the vertex shader.

```
gl_Position = MVP * vec4(VertexPosition, 1.0);

```

Now, let's position an object. We know the camera is looking towards +z and positioned at (0,0,-1). So if we place a 1x1 plane at (0,0,2) you should be able to see it perfectly.

I have a couple of very simple demos showing that.You can check out here: https://github.com/tiiago11/cga-demos/blob/master/demos/glsl40\_plane/src/Plane.cpp

Hope it helps.
> 0 votes

---
Tags: coordinates, vbo, glfw
---


# Question
Title: How to code a non-newtonian spaceship control script?
I'm working on a simple 3D space combat game, and I've decided to go with simplified physics over proper newtonian motion, similar to the space sim Oolite, and more 'arcade' style games. I basically want my ships to move how spacecraft do in Star Wars.

This is what I'm trying to achieve specifically; ability to rotate along each axis, and with solely forward motion relative to the spacecraft. In the case of impacts and collisions I want to spacecraft to move under normal physics, but for any rotation/velocity incurred by the collision to quickly bleed off.

I can find a lot of tutorials that show how to achieve this kind of flight by setting angular drag and such in a standard aircraft controller. This seems like it is a waste of resources however, since you are using the drag equations to cancel out the newtonian thrust equations. Since I'm aiming for hundreds of ships in a single battle I need to keep things as efficient as possible.

So is there a simpler, more efficient way to have this kind of controller?

# Answer
I found out how to do this, so I'll put it up in case anyone else is trying to do the same.

Unity has a function called Transform.Rotate which can be used to rotate a game object around its own axis. I used this for roll, pitch, and yaw. The I used the similar Transform.Translate for forward motion.
> -1 votes

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


# Question
Title: Import Material from blender into unity Export FBX
There have been several questions like this but nothing that is quite the same. I've noticed when Mixamo can create models with materials attached in their FBX. I'm trying to do the same in blender, several people say that this cannot be done.

When I export an FBX from unity how can I get the material in with it, whether, that be importing the material through a separate process, or some how baking them in with the FBX?

# Answer
> 3 votes
You will get materials attached when you import FBX from Blender into Unity but it will assign unity's standard material/shader. What you won't have is the texture assigned into the diffuse/albedo slot of the Unity standard material. Unfortunately, you will have to save the texture in Blender separately, then import it into unity before assigning it into the albedo slot of your material. In 3DS Max or Maya, the FBX exporter has an option called 'embed media'. Ticking this before exporting into Unity solves this problem. This means, when you export the FBX model into Unity, it will automatically be assigned with a standard material and the corresponding texture will be correctly assigned to the albedo slot. Unfortunately, I do not see this option when exporting FBX models in Blender.

Secondly, a material is actually just a shader code written which gets sent to the GPU. Normally, the material from 3D modelling tools do not get exported into a game engine. Game engines have their own materials which come with texture slots. You simply assign the textures you made in your 3D modelling tool into these slots. So when you said "When I export an FBX from unity how can I get the material in with it", what you really mean is for the texture to be automatically assigned to the albedo slot in the standard material.

---
Tags: unity, blender, fbx, import
---


# Question
Title: How does Mikktspace work for calculating the tangent space during normal mapping?
Increasingly the 3D industry is adopting the standard of Mikktspace for calculating tangent space for normal mapping and other effects which rely on accurate and consistent calculation of tangent space from one application to another. Blender, xNormal, Unity, Substance Painter and Unreal Engine are just a few I can think of which now use Mikttspace. I'm personally attempting to re-code my own projects to adopt this standard as well.

But there are very few resources on how Mikktspace works as it is a relatively new thing. What little resources there are, are usually scarce on details and very technical, not very user friendly to understand, or assume the coder has a certain level of knowledge which is a bit above the average newbie just starting out who needs things explained more carefully.

I am looking for a clear explanation of how Mikktspace works and how to implement it, with a simple explanation of how the maths and code works in a way which is not limited to just one language.

For the sake of example, lets suppose a programmer has a mesh object, with a index of vertices, each with a position, normal and UV coordinate, and list of triangles which reference that index.

For example:

* `Vertex`: { X Y Z NX NY NZ S T }
* `VertexIndex`: A list of `Vertex`
* `Triangle`: { V1 V2 V3 } *(in correct winding order for normal direction)*
* `TriangleList`: A list of `Triangle`

In simple terms, how would one go about calculating per vertex a tangent vector (TX TY TZ) and bitangent vector (BX BY BZ) for each vertex in a way which conforms to Mikktspace?

# Answer
> 3 votes
There is more code to that project:
https://github.com/teared/mikktspace-for-houdini/tree/master/source

Also you can find information about tangent space normal maps here:
https://archive.blender.org/wiki/index.php/Dev:Shading/Tangent\_Space\_Normal\_Maps/ http://image.diku.dk/projects/media/morten.mikkelsen.08.pdf

Other information about the tanget space normal maps (Mikktspace) are not very clear.

A brief explanation on the methods is very long and therefore I have included the two links above to refer to the good explanation about tangent space normal maps.

Note: Blender also gives advice on why not to use this method.

I hope this was helpful :)

---
Tags: transformation, normal-mapping
---


title: Simulating Physics - dt vs formula

text:
# Question
Title: Simulating Physics - dt vs formula
I was just wondering, when simulating physics is it usually a good idea to get the time delta from the last frame and apply the relevant motion equations?

Something like:

```
void simulate(float dt)
{
    vel += (force / m) * dt;
}

```

In this case wouldn't there be an accumulated error over time due to precision? For example when trying to simulate a circular motion?

Or would it be better to get the entire elapsed time from the beginning, and then apply the motion:

```
void simulate(float elapsedTime)
{
    vel = vel0 + (force/m)*elapsedTime;
}

```

And since this doesn't depend on the previous simulate() steps, it's less likely to cause precision errors?

Thanks!

# Answer
Using delta time will indeed introduce rounding/precision errors over time, but will allow you to change the force or mass instantly and go from there.

Using the second approach will not introduce accumulated precision errors, but won't allow you to change force or mass unless you calculate a new `vel0` first and subtract a time offset from `elapsedTime`, in which case it quickly turns into your first approach.
> 2 votes

---
Tags: physics, simulations
---


# Question
Title: Are AAA games still made with programming languages?
I've been interested in how AAA games are made recently.I looked up how Fallout 4, one of my favourite games, was made. It turns out bethesda games uses a drag-and-drop style engine with maybe a little bit of scripting here and there, like Unity or Unreal. I also looked up how GTA 5 was made. It turns out that rockstar games has its own engine, Rockstar advanced game engine (R.A.G.E). Slightly disappointed , I'm just wondering whether any AAA game out there is still actually programmed with code. I know that the engine is probably made with code, and if a game company has its own libraries with useful functions/classes that makes sense, since some things will be very tedious to directly repeat. But do AAA industries still use proper code for the actual game?

# Answer
Yes, absolutely.

Fallout 4 was *not* made *entirely* with Bethesda's drop-and-drop tools. Nor was GTA. Even if they were, that means those games could not be made without those tools, and how do you think those tools came about?

Somebody wrote them. In a programming language.

The engines your thinking of here do a lot of things. Among those things is provide high level tools (such as drop-and-drop scripting tools) that can be used to prototype gameplay and related systems, iterate on them quickly, or allow non-technical developers (like designers or artists) to affect change in game systems without needing a programmer to intervene.

But programmers wrote those systems in programming languages in the first place. Further, as with most any abstraction, these systems introduce extra complexity which can negatively impact performance, and so they are often not used (outside of prototyping) for extreme time-critical aspects of the game (even the gameplay code). You will not find the core rendering loop driven by Blueprint in Unreal, for example. Nor will you find the kernel of the physics simulation in Fallout 4's drag-and-drop system.

Programming languages are still very much a thing.
> 6 votes

# Answer
They tend to use the most cost effective tool for the job. AAA games are expensive to make & have no guarantees of return on investment. Visual engines provide several ways to mitigate risk by saving time &/or money:

* They are already built, so you don't need to code up & test the engine.
* They are often more well documented than in house solutions, especially if they are themselves a commercial product.
* They allow people who may have less coding expertise (modelers, designers, artists; basically anyone who isn't a coder) to participate more directly in prototyping & iteration.
* By providing an framework, there is the perception fewer development choices to make, E.G. what language to use, how to handle events, etc.
* They may target more than one platform, reducing the cost of porting.

That being said, there are still reasons not go with a visual engine:

* The reasons listed in favor of a visual engine don't provide sufficient value.
* You want some look, system or level of performance that cannot be achieved with a visual engine.
* You hope to license your own engine as a product.
* You need a combination of sub systems (graphics, audio, etc) that isn't provided by an engine.
* Writing your own engine is a design goal in of itself; probably a rare AAA concern.
* You want to target a combination of platforms that aren't covered by available engines.
> 1 votes

# Answer
Yes, visual editors in engines only get you so far.

For example in unreal engine you can and most likely will be adding pure code files to the project for the very specifics of your game, while using the faster visual editor for all the usual stuff that is almost entirely covered in the engine itself already.

So basically, you are right about source code being more usefull in that it gives the author more control over what's going on, but in a game, there are so many common things that it's just a waste of money to develop it 100% from scratch.

Also, there are engines that are still purely code based, also known as libraries. All those super advanced "engines" are just a bunch of libraries with a visual editor.
> 1 votes

---
Tags: software-engineering, game-industry
---


# Question
Title: Make a flying object rotate so the camera sees the rotation
When I attach a camera to my flying object (plane), when I rotate the object, the camera is perfectly following it so you can't really "feel" the plane rotating. I want to create the effect that you see in flying games where you see the plane rotating along the x axis (so you see the nose go up and tail down) while also semi-following the plane, creating a better effect.

How do I achieve this?

# Answer
I think a good idea would be to link the camera to a GameObject inside your plane, like its gravity center, so you can control the camera rotation easily and it'll be independant from your acual plane.

This way, you can make your camera follow the plane on rotation if you want to, and you can also move your camera without moving the object.

### Example:

I found those examples which are pretty much everything you need : http://forum.unity3d.com/threads/simplle-free-fly-camera-script.167604/ https://unity3d.com/learn/tutorials/projects/roll-ball-tutorial/moving-camera
> 1 votes

# Answer
Seems to me the effect can be achieved by simply not parenting the camera and using a script to do the same with addition of smoothness, that way the camera will be abit behind the rotation and then catch up, not instantly, and the rotation will seem more apparent.
> 0 votes

# Answer
this should work. 1. Make a cube object. 2. Add a rgidBody to it. 3. Drrag the camera under it(child it). 4. On the cube, click the freeze restrain's arrow. This reveals 6 toggles. 5. Click the z of the bottom row, OR, the way your plane is rotating(by the x,y, or z axis). 6. Drag the cube that contains the camera under the plane object. 7. Now hit play and the cube won't rotate, and neither will the camera, and you can see the plane rotate.
> -1 votes

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


# Question
Title: Custom Unity mouse input with WM_INPUT - receiving weird values
# About

I am trying to get the raw mouse input of the system into a C# application. I am using `WM_INPUT` (MSDN link) to get access to the data. To do so I am using the user32.dll. This (stackoverflow link) helped me alot with writing the API Wrapper. I do this because I want to try if there is any difference (when using my own custom mouse input) to the Unity API that gives me raw mouse input. I hope that's reason enough to post here at "Game Development".

# Current approach

The following snippet shows the `WndProc` method. `rimTypeMouseCount` already shows that the windows messages seem to get fetched correctly. When I turn the polling rate of my mouse up or down I can see this also by checking the count - Lower polling rate means a lower count, higher polling rate means a higher count while logging for equal time intervals. That's good so far.

### WndProc callback method:

```
protected override void WndProc(ref Message m)
{
    if (m.Msg == 0x00ff) {
        uint dwSize = 40;

        byte[] raw = new byte[40];
        IntPtr rawPtr = Marshal.AllocHGlobal(raw.Length);

        APIWrapper.GetRawInputData((IntPtr)m.LParam, 0x10000003, rawPtr, ref dwSize, Marshal.SizeOf(new APIWrapper.RAWINPUTHEADER()));

        Marshal.Copy(rawPtr, raw, 0, 40);

        GCHandle handle = GCHandle.Alloc(raw, GCHandleType.Pinned);
        APIWrapper.RAWINPUT rawData = (APIWrapper.RAWINPUT)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(APIWrapper.RAWINPUT));
        handle.Free();

        if (rawData.header.dwType == 0)
        {
            rimTypeMouseCount++;
            logMouseX = logMouseX + rawData.mouse.lLastX.ToString() + Environment.NewLine;
            logMouseY = logMouseY + rawData.mouse.lLastY.ToString() + Environment.NewLine;
        }
    }

    base.WndProc(ref m);
}

```

### RAWINPUT struct:

```
[StructLayout(LayoutKind.Explicit)]
    internal struct RAWINPUT
    {
        [FieldOffset(0)]
        public RAWINPUTHEADER header;

        [FieldOffset(16 + 8)]
        public RAWMOUSE mouse;

        [FieldOffset(16 + 8)]
        public RAWKEYBOARD keyboard;

        [FieldOffset(16 + 8)]
        public RAWHID hid;
    }

```

# Problem

But there is a problem with `logMouseX` and `logMouseY`. Those to strings simply append the mouse deltas of the x and y axis with every call. Unfortunately `logMouseX` only logs the values 0 or 65535 while `logMouseY` logs 0 only. I also tried to log messages like left mouse button up/down and so on. Nothing seems to work actually. For me it seems a little that the numbers might be random or something like that.

# Question

This is what I (think I) do:

1. `APIWrapper.GetRawInputData(...)` needs a pointer to a byte array. So I simply allocated space in unmanaged memory with marshalling and got a pointer as a result.
2. I am calling the function that fills the array the pointer is pointing at.
3. I am taking the pointer that points to the filled array and copy its content into an actual byte array.
4. To access the fields of the struct `RAWINPUT` I need to cast the byte array to a `RAWINPUT` struct.
5. I do this with the three lines that use a GCHandle. I actually found that snippet somewhere but never worked with that class before.

Might it be that I am messing up something there? Maybe something like a Big-Endian and Little-Endian mix up?

# Notes

* I found out that the values I get when using `rawData.mouse.lLastX` & `rawData.mouse.lLastY` behave like this:

+ X is zero when moving the mouse downwards and 65535 when moving upwards
    + Y is zero always no matter if I move the mouse left or right
* I found out that using `rawDataL.hid.pbRawData` includes more information about the movement. There I get values in dependency of how fast I am moving the mouse. Unfortunately there is no X or Y component so this only works for one axis (downwards/upwards).
* I found a simpler way of casts. Unfortunately I still get the stranges values as described above. It looks like this now:

### Casting part of WndProc:

```
uint dwSize = 40;

byte[] raw = new byte[40];
GCHandle handle = GCHandle.Alloc(raw, GCHandleType.Pinned);

APIWrapper.GetRawInputData((IntPtr)m.LParam, 0x10000003, handle.AddrOfPinnedObject(), ref dwSize, Marshal.SizeOf(new APIWrapper.RAWINPUTHEADER()));

APIWrapper.RAWINPUT rawData = (APIWrapper.RAWINPUT)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(APIWrapper.RAWINPUT));

if (rawData.header.dwType == 0)
{
    // accessing data
}

handle.Free();

```

# Answer
> 0 votes
I posted my question here (MSDN link) and I was told that the offsets of the RAWMOUSE struct are not correct.

So I simply logged all bytes of the raw data array and finally could see all the data I need and therefore the correct offsets. I guess the offsets differ when using 32 bit or 64 bit machines. Here are the relevant code changes:

WndProc changes:

```
RawMouseData rawData = (RawMouseData) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(RawMouseData));

```

RawMouseData struct:

```
[StructLayout(LayoutKind.Explicit)]
internal struct RawMouseData
{
    [FieldOffset(20)]
    public ButtonFlags buttonFlags;
    [FieldOffset(22)]
    public ushort buttonData;
    [FieldOffset(28)]
    public int lastX;
    [FieldOffset(32)]
    public int lastY;
}

```

This is how the data log of the raw byte array looks like for each mouse movement direction:

```
Downwards:      Upwards:
Byte 29: 0      Byte 29: 0
Byte 30: 0      Byte 30: 0
Byte 31: 0      Byte 31: 0
Byte 32: 0      Byte 32: 0
Byte 33: 1      Byte 33: 255
Byte 34: 0      Byte 34: 255
Byte 35: 0      Byte 35: 255
Byte 36: 0      Byte 36: 255

Left:           Right:
Byte 29: 255    Byte 29: 1
Byte 30: 255    Byte 30: 0
Byte 31: 255    Byte 31: 0
Byte 32: 255    Byte 32: 0
Byte 33: 0      Byte 33: 0
Byte 34: 0      Byte 34: 0
Byte 35: 0      Byte 35: 0
Byte 36: 0      Byte 36: 0

```

The faster I move the mouse the bigger (when moving downwards or right) or smaller (when moving upwards or left) the values get.

---
Tags: c#, windows, mouse
---


# Question
Title: How to avoid character controller collider for slide over floor.?
I have a character controller to move my player on a surface. All the things work fine, but I can't make a perfect slide with the character controller on the surface.

When I try to slide, my player animation plays in the center of capsule collider, which is attached to the player. That's why my player can not touch floor, which means my animation play in mid air. After some time I found that my problem occurs due to using the character controller. I am using `Character.Move()` to move my player.

**Can anyone help me? How can I avoid the collider on the character controller, or change something to make my player slide animation perfectly align with the floor.?**

I am using `controller.transform.Rotate(0,0,60)` to rotate my player on floor.

**This is my script:**

```
using UnityEngine;
using Assets.Scripts;
using System.Collections;
using UnityEngine.SceneManagement;

public class ControllerMovement : MonoBehaviour {

private Vector3 moveDirection = Vector3.zero;
public float gravity = 20f;
private CharacterController controller;
public float JumpSpeed = 8.0f;
public float Speed = 0.1f;
public int swipeStep = 3;
int swipeD,pos;
bool rx ;
int i=0;
public Transform CharacterGO;
bool isInSwipeArea;
private Animator anim;
IInputDetector inputDetector = null;

// Use this for initialization

void Start()
{
    moveDirection = transform.forward;
    moveDirection = transform.TransformDirection(moveDirection);
    moveDirection *= Speed;
    UIManager.Instance.ResetScore();
    UIManager.Instance.SetStatus(Constants.StatusTapToStart);
    GameManager.Instance.GameState = GameState.Start;

    anim = CharacterGO.GetComponentInChildren<Animator> ();
    inputDetector = GetComponent<IInputDetector>();
    controller = GetComponent<CharacterController>();
}

// Update is called once per frame
void Update()
{
    switch (GameManager.Instance.GameState)
    {
    case GameState.Start:
        if (Input.GetMouseButtonUp(0))
        {
            //anim.SetBool(Constants.animaationStarted, true);
            var instance = GameManager.Instance;
            instance.GameState = GameState.Playing;
            UIManager.Instance.SetStatus(string.Empty);
        }
        break;
    case GameState.Playing:
        UIManager.Instance.IncreaseScore (0.001f);
        CheckHeight ();
        DetectJumpOrSwipeLeftRight ();

        //apply gravity
        moveDirection.y -= gravity * Time.deltaTime;
        //move the player
        controller.Move (moveDirection * Time.deltaTime);
        break;

    case GameState.Dead:
        ////anima.SetBool(Constants.//animaationStarted, false);
        if (Input.GetMouseButtonUp(0))
        {         SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
        }
        break;
    default:
        break;
    }
}
private void CheckHeight()
{
    if (transform.position.y < -10)
    {
        GameManager.Instance.Die();
    }
}

private void DetectJumpOrSwipeLeftRight()
{
    var inputDirection = inputDetector.DetectInputDirection();

    if (Input.GetKeyDown (KeyCode.Space)) {
        moveDirection.y = JumpSpeed;
        anim.SetBool ("RunToJump", true);
    } else {
        anim.SetBool ("RunToJump", false);
    }
    if(Input.GetKey(KeyCode.A) && controller.isGrounded){
        controller.transform.Translate (-0.1f,0,0);
    }
    if(Input.GetKey(KeyCode.D) && controller.isGrounded){
        controller.transform.Translate (0.1f,0,0);
    }
    if (Input.GetKey (KeyCode.S) && controller.isGrounded) {
        anim.SetBool ("RunToSlip", true);
        controller.transform.Rotate (-40, 0, 0);
        Invoke ("StopSlidding", 0.2f);
    }
        }
 void StopSlidding(){
    anim.SetBool ("RunToSlip", false);
    controller.transform.Rotate (40,0,0);

  }

 }

```

# Answer
Change your sliding animation with translated down position and use root motion of this animation in Unity.

Or use a parent child setup for controlling a character or figure.

In parent keep the Scripts, CharacterController component.

In child keep the character body with animator component.

In the script use `GetComponentInChildren<Animator>()` instead of `GetComponent<Animator>()`.

When sliding, translate down the child as you need towards ground. Go back to normal position when not sliding. You can resize height of the `CharacterController` if you need.

You can do it in same object but above way keeps them separate and interfering with each other with better control.
> 1 votes

# Answer
@hardwork, I think, and if I read your question right, you could change the location of the animating part, not the controller, whiile it's sliding to have not so mid air. Then, change it back to it's normal location later on. In javaScript, you'd use "transform.position", but I'm not sure if that is it in C#. You can type in that under the Js search, then swap it over to C#.
> -1 votes

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


title: LWJGL 3.0.0 glMapBuffer

text:
# Question
Title: LWJGL 3.0.0 glMapBuffer
I am currently working on a project and usually in C++ I use the function.
`ByteBuffer glMapBuffer(int target, int access)`

usage:

```
FloatBuffer buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY).order(
    ByteOrder.nativeOrder()).asFloatBuffer();

```

But in java (lwjgl 3.0.0) this function returns null, because of this reason it throws a NullPointerException.

Anyone any idea how to use this function in java?

There are several functions:

```
glMapBuffer(int target, int access)
glMapBuffer(int target, int access, ByteBuffer old_buffer)
glMapBuffer(int target, int access, long length, ByteBuffer old_buffer)

```

I hope this is specific enough, thank you for your help :D

# Answer
> 2 votes
**Edited Answer**

Before writing to a Buffer Object, you must have some space allocated in GPU's memory, you can grow or shrink the Buffer Objects via:

```
glBufferData(int target, long size, int usage);

```

When the Buffer Object already have `size` bytes, you can call `glMapBuffer` passing the full size, or some smaller number (you dont have to actually shrink the Buffer Object if it will most likely grow again soon)

```
glMapBuffer(int target, int access)

```

Returns a brand new ByteBuffer, with the current size of Buffer Object;

```
glMapBuffer(int target, int access, ByteBuffer old_buffer)

```

Returns a new ByteBuffer, or reuses the old object (if not null), with the current size of Buffer Object (not the old\_buffer object);

```
glMapBuffer(int target, int access, long length, ByteBuffer old_buffer)

```

This is like the previous one, but it is faster because it don't have to query for the Buffer Object's size.

When passing an old\_buffer, it unmaps it first (and may use some optimization) before mapping it again.

Don't forget to call `glUnmapBuffer(int target)` at the end of it all. (After that your mapped ByteBuffer will be in an invalid state and you must not read/write to it)

**Example**

```
private int id;
private long currentSize;

public void updateBuffer(...) {

    long calculatedSize = ...;
    if (currentSize < calculatedSize) {
        currentSize = calculatedSize;
        glBufferData(GL_ARRAY_BUFFER, currentSize, GL_DYNAMIC_DRAW);
    }
    ByteBuffer bb = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
    try {
        FloatBuffer floatBuffer = ...
        ...
    } finally {
        glUnmapBuffer(GL_ARRAY_BUFFER);
    }
}

```

---
Tags: opengl, java, lwjgl, lwjgl3
---


title: Display a variable in the UI

text:
# Question
Title: Display a variable in the UI
I have been searching and searching for an answer to this question but nobody seems to be helping me. I have wasted the past two hours trying to figure out how to do this, so **please** help me out here.

I am making a FPS game in Unreal Engine 4, and I want to display ammo. I can do that fine, but changing the text of the UI displaying the ammo is turning into a nightmare. I need to access the text label variable

Inside of the blueprint that handles the actual gun firing

From there I should be able to adjust the text to match what my ammo is.

Unfortunately, no matter what I try, I cannot change the variable in my blueprint. I can't even make the variable public to begin with! What do I need to do to accomplish this?

# Answer
> 2 votes
Widget Blueprints can bind the Visuals to Functions.

If you click on "Create Binding" on your Text Block, it will create a function that returns a FText Variable.

Within this function simply get your ammo from your controller/pawn/state and return it.

---
Tags: gui, unreal-4, blueprints
---


# Question
Title: Unity - UI button not triggering custom script function
I have created simple movement buttons in my game. They should trigger functions of the player's scripts, but I can't link the button to the player object/script canonically from the inspector 'cause the player is created at runtime. So I created a custom script attached to the buttons:

```
using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ActionButton : MonoBehaviour {

    private Button btn;

    void Start()
    {
        btn = GetComponent<Button>();
        btn.onClick.AddListener(TriggerFoo);
    }

    public void TriggerFoo()
    {
        Debug.Log("Btn triggered!!!!");
    }
}

```

Haven't implemented yet the behavior I want to achieve with it, but even at this point the button doesn't print the string on console.

Here is how the button is set up in the inspector:

I am missing something very obvious here....?

# Answer
> 1 votes
### What your missing is an `EventSystem` object.

Your button is passing an `OnClick` event when you click on it; but without an `EventSystem` to manage your events, this can have *seemingly* unpredictable results. The `EventSystem` is its own component, and it does not appear to matter where you place it in your hierarchy, just as long as you only have one of them.

I personally had a very similar issue while testing an android prototype game I had made. It took me several months to figure it out, and even than, it wasn't me that figured it out - I also had to ask about it, here on GameDev. While someone was able to point out my initial issue through comments, I am still quite unclear on the overarching issue that had me confused; it appears (or at least, in my case) that input *may* work *without* an `EventSystem` in an actual build. *Assume it won't, and ensure you always include one*. I keep one on my main camera, and have been able to successfully test your code with it.

### If your using the `CrossPlatformInput` package, you also need to ensure you have matching axis in your `InputManager`.

Since you have not mentioned it, I assume you are *not* using the Unity package `CrossPlatformInput`. Just in case you are, buttons still won't work if you do not have corresponding axis set in your `InputManager`.

For `CrossPlatformInput` to work, it needs to interact with four separate axis in your `InputManager`: Vertical, Horizontal, Submit and Cancel. If you do not have these axis, fatal errors will block your `UI` from handling input. *Simply having these axis does not suitably set them up for `CrossPlatformInput`*, but having them there allows your other input to work as intended.

# Answer
> -1 votes
Click the + thing right under onclick. Now, choose the object "still" (the button). Now, simply find the script then function. In your setup, the button is only storing the script, and the button component isn't actually using it.

---
Tags: unity, gui
---


title: Check which object triggered another

text:
# Question
Title: Check which object triggered another
**Two animated car object both contain a rigid body, a box collider and a script with an `OnTriggerEnter` event.**

I want to check which car *started* the collision event, by hitting the other car.

Consider two cars; regardless of whether carA hits carB or carB hits carA, both cars contain the same script with the same event. So both cars become the trigger.

How do I identify which car started the collision? I wish to do so without the use of raycasting, as it is too expensive for what I am wanting to do.

# Answer
> 1 votes
You can find out the tag or name of the objects that collided, this information is stored in the `Collider other` you pass to the `OnTriggerEnter(Collider other)` function.

Deciding who hit who is something you need to set the criteria for.

# Answer
> 1 votes
You could create a boolean, for example `bool canCrash`, and make sure it is `true` when ever the car changes from the previous position. Then, on collision, you check if `canCrash == true` and, if it isn't but the speed of the car was higher than the car it collided into.

I think that's the right direction to go.

# Answer
> 0 votes
## You can check the speed of both cars

During collision, there will be two cases:

1. One car is moving, one car is stationary.
2. Both cars are moving.

You need to decide which car intentionally hit the other, and obviously, `OnTriggerEnter()` will not help. To check for speed, use `GetComponent<Rigidbody2D>().velocity` or `GetComponent<Rigidbody>().velocity`.

### case one - one car is stationary

In the first case, it's pretty simple. The car that has speed is the car that is hitting the other car.

### case two - both cars are moving

It's tricky for the second case. You can say the car with more speed intentionally hit other car; though it's not always true, it will work most of the time.

# Answer
> 0 votes
Playing around collision and the `Debug.Log()`, I have confirmed that `OnTriggerEnter` triggers in a specific order; that is, when carA moves into carB, it will set off the `OnTriggerEnter` method attached to carB. This always seems to happen first, with the `OnTriggerEvent` method attached to carA triggering, second.

Working off of the answer submitted by ***Vadim Tatarnikov***, I set up `bool collisonInstigator` that typically defaults as `false`. I was than able to check for `collisionInstigator == true` during `OnTriggerEnter`. If `collisionInstigator == false`, we assume that the `other` collider is the instigator, and set `other.<script>.collisionInstigator = true`. When the instigators `OnTrigger` method calls, which we can assume will be directly *after* the first, we find that `collisionInstigator == true`.

This tells us that we are currently in the `OnTrigger` method for the car that *started* the collision, allowing us to run our logic as required. The only other thing we have to do is ensure that we set `collisionInstigator = false` at the end of our logic, to set it back up for the next potential collision scenario, assuming your not calling for the instigator to be destroyed or any other logic that would make further collisions with that game object impossible.

```
public class CarAI : MonoBehaviour
{
    public bool collisionInstigator = false;

    void OnTriggerEnter(Collider other)
    {
        if(collisionInstigator == true)
        {
            // I am crashing into the other car; run logic

            DebugCollision(other.gameObject);   // confirm order through debug
            collisionInstigator = false;        // don't forget to reset the flag!
        }
        else
        {
            // I am being crashed into by the other car
            other.GetComponent<CarAI>().collisionInstigator = true;
        }
    }

    ///<summary>Using tags, we can double check our logic regarding which GameObject
    /// is the "instigator"</summary>
    void DebugCollision(GameObject other)
    {
        string myName = gameObject.name;
        string otherName = other.gameObject.name;

        Debug.Log(myName + " is colliding with " + otherName);
    }
}

```

Using `DebugCollision(GameObject other)` to debug a clearer formatted string of the collision, I confirmed that the above script will correctly pick the "instigator" across a variety of speeds, using both `Transform.Translate()` and `RigidBody.AddForce()` methods.

# Answer
> -1 votes
I think you'd be more lucky to use `OnCollisionEnter` to avoid a double event.

You could also combine your condition with a second criteria, deciding which is the "collider" and which is "collided" (depending on your game context). For instance, you could check for the fastest car, the car that is changing direction, the car with the most on the outside.. there would be a behavior for the "collider", and a behavior for the "collidee".

You could also tweak the collision event with tag name identification; if the tags of both cars are "AI cars", treat them as a bounce, only. If one tag is "player car", treat it as a real shock.

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


# Question
Title: Fire Emblem/Advance Wars/Turn Based Strategy like Artificial Intelligence
I have made a Fire Emblem/Advance Wars like game, and I was wondering if there are any particular techniques in the AI's in those games.

I was wondering how to let the AI make the best decisions. I have the tiles a unit can move to, I have the enemy unit positions and I have formulas to calculate battle outcomes, now I want to add those together so that, for example, the AI attacks the weakest unit, blocks a chokepoint or just moves closer to the enemy if nobody is in range.

What is the best approach to this?

# Answer
Here's the easy approach, which is typically the one used for board games:

Write a heuristic which is able to determine how good a position one side is in. Think of it as estimating "from this position, how likely am I to win?" Factors to consider are relative force strength, how well your units are supporting each other, how large an area you threaten, vs. how many of your units are threatened, and the inverse of all these factors for the enemy faction. Figure out a whole bunch of factors like these, weight them according to their importance, and turn them into a 0% -\> 100% estimate for how likely you think it is that you'll win.

Now do this:

1. Each turn, look at all possible moves you can make. For each possible move, evaluate your heuristic on the resulting game state that you'd reach after making that move.
2. After testing each move, actually make the move which had the best resulting heuristic value.

As a result, your AI will pick the moves which maximise those things that your heuristic measures, which you believe correspond to being more likely to win. If having fewer or weaker units makes you less likely to win, the AI will prefer moves which don't result in losing units. If the opponent having fewer or weaker units makes you more likely to win, the AI will prefer moves which do result in the opponent losing units. And so on.

If you want to be clever, you can "look ahead" more moves; assume that the opponent will be doing things similar to you, and so for each move, also take the best move from the opponent's point of view, and find the best heuristic for your side, after the opponent's best move. And take that move; that would be 2-ply thinking. You can keep flipping back and forth, taking best moves, and thinking deeper and deeper about the future state of the game board, as long as you have processor time to think about it.

Of course, if there are lots of different possible moves each turn, or if those moves have different possible outcomes (say, if random numbers are involved), then this becomes a little more complicated. But in systems like Advance Wars or Fire Emblem where random numbers have only a small impact, this approach should be perfectly serviceable.
> 2 votes

# Answer
Games like Fire Emblem and Advance Wars use finite state machines on the individual unit level. That is, all of the units act independently without any concern for achieving the armies overall condition for victory (this is most easily seen when the AI messes up by having one unit do a bad move which prevents another unit from doing a better move). The units that have different behaviors (go towards enemy, hold position, etc) simply have different FSMs.

FSMs are good for game AI because they're easy to implement and give good behavior (assuming you write good FSMs). The AI doesn't need to actually be smart or think, it just needs to make good moves.

At some point more sophisticated (let's call it "real") AI will be better, but it's much more costly to implement. It's kind of like an FSM has linear growth while "real" AI has parabolic growth, in terms of cost v quality.

I remember an anecdote about a game AI programmer for an FPS (I forget the game) that got fed up having to update FSMs so he re-wrote the whole AI system with some "real" AI. This gave some really unexpected (but ultimately desirable) behavior where the enemies were doing cool things like breaking through windows instead of going through doors. In the sequels to this game they went back to using FSMs.
> 0 votes

---
Tags: game-design, ai, turn-based-strategy
---


# Question
Title: How to automate baking pizza in Corona SDK?
I'm writing a game about making pizza in Corona SDK. When you buy chefs, the new chef is supposed to make some pizzas on its own like automation.

I tried everything I knew about, I couldn't think of anything that would do what I'd like so I ask you guys to help me.

Here is the code I think is relevant:

```
local widget = require("widget")

local pizzeria = display.newImage("background.png")
pizzeria.x=160
pizzeria.y=230
pizzeria:scale(1,1)

local pizzas=0
local chefs = 0
local pizzatext = display.newText( "Pizzas:", 100, 200, display.contentWidth*0.6, display.contentHeight * 0.7, native.systemFont, 16)
pizzatext:setFillColor( 10, 0, 0)

local pizzacount = display.newText(pizzas,165,200,display.contentWidth*0.7,display.contentHeight*0.7,native.systemFont,16)
pizzacount:setFillColor(10,0,0)

local chefstext = display.newText("chefs:",320,200,display.contentWidth*0.7,display.contentHeight*0.7,native.systemFont,16)
chefstext:setFillColor(10,0,0)

local chefscount = display.newText(chefs,363,200,display.contentWidth*0.7,display.contentHeight*0.7,native.systemFont,16)
chefscount:setFillColor(10,0,0)

local function pizzamaker( event )
  if ( "ended" == event.phase ) then
    pizzas=pizzas+1
    pizzacount.text=pizzas
  end
end

local function addchef( event )
  if("ended" == event.phase) then
    if(pizzas>=5) then
      chefs=chefs+1
      chefscount.text=chefs
      pizzas=pizzas-5
      pizzacount.text=pizzas
    end
  end
end

local pizzamaker = widget.newButton
{
  left = 100,
  top = 400,
  defaultFile="button.jpeg",
  overFile = "button.jpeg",
  label = "Make Pizza",
  height = 50,
  width= 100,
  onEvent = pizzamaker
}

local addchef = widget.newButton
{
  left = 100,
  top = 100,
  defaultFile="pizzachef.png",
  overFile="pizzachef.png",
  height = 50,
  width = 50,
  onEvent = addchef
}

```

# Answer
> 0 votes
You can use `timer.performWithDelay(delay, listener, iterations)` so that every `x` milliseconds the listener gets called for `n` iterations. Here is the corresponding documentation.

In this case, we would need to delclare a new function which makes pizzas, above the `addChef` function.

```
local function makeChefPizza()
    pizzas=pizzas+1
end

```

Then, we add `timer.performWithDelay` to your `addChef` function:

```
local function addchef( event )
  if("ended" == event.phase) then
    if(pizzas>=5) then
      chefs=chefs+1
      chefscount.text=chefs
      pizzas=pizzas-5
      pizzacount.text=pizzas

      timer.performWithDelay(5000, makeChefPizza, -1) -- This line here
    end
  end
end

```

This will call the `makeChefPizza` every 5000 milliseconds (5 seconds) and iterate forever (-1 means forever), see docs.

---
Tags: lua, corona-sdk
---


# Question
Title: Libgdx body passing through block then fall on it
I'm using libgdx and its physic engine Box2d. My question is : how could I make my box2d body go through a block , ignore the first collison than make the block active so the ball can fall onto it. A good example is doodle jump.

# Answer
> 1 votes
I finally made it :)

Here's my code :

```
public void preSolve(Contact contact, Manifold oldManifold) {
        fixtureA = contact.getFixtureA();
        fixtureB = contact.getFixtureB();
          if(fixtureA.getBody().getUserData() == "platform" && fixtureB.getBody().getUserData() == "ball"|| fixtureA.getBody().getUserData() == "ball" && fixtureB.getBody().getUserData() == "platform"){
              if (fixtureA.getBody().getUserData() == "platform") {
                  platform_y = fixtureA.getBody().getPosition().y;
                  ball_y = fixtureB.getBody().getPosition().y;
              } else if(fixtureA.getBody().getUserData() == "ball") {
                  ball_y = fixtureA.getBody().getPosition().y;
                  platform_y = fixtureB.getBody().getPosition().y;
              }
                 if(ball_y < platform_y + 1.5F) {             //the ball is below
                     contact.setEnabled(false);
                 }
          }

    }

```

# Answer
> 2 votes
Set a flag whenever collisions are detected.

Something like this:

```
method Ball.onCollisionWith(block) {
    if (block == self.dontCollide) {
        self.dontCollide = block
        -- Do nothing else, passing through collision
    } else {
        -- Reset flag so next collision will pass again
        self.dontCollide = nil
        resolveCollision(self, block)
    }
}

```

The `Ball` will then ignore every second collision due to its `dontCollide` flag being set.

# Answer
> 1 votes
I've had a similar problem in the past, have a look at this Tutorial. I found it answered my question. Its not for java but the code was very easy to copy over

# Answer
> 0 votes
I used your solution but instead of using getUserData I set up category bits on my platforms and player. The ground has different category bits to platforms so that only the platforms can be passed through. You can define category bits in your main game class as follows:

```
public static final short GROUND_BIT = 1;
public static final short PLATFORM_BIT = 2;
public static final short PLAYER_BIT = 4;

```

Next, in your Presolve we only want to pass through platforms, so we add this code to check if Fixture A and B are either the Player or Platforms:

```
@Override
public void preSolve(Contact contact, Manifold oldManifold) {

    //THIS SHOULD ALLOW PLAYER TO PASS THROUGH PLATFORMS AND COLLIDE ON THE WAY DOWN
    Fixture fixtureA = contact.getFixtureA();
    Fixture fixtureB = contact.getFixtureB();

    float platform_y;
    float player_y;

    platform_y = fixtureA.getBody().getPosition().y;
    player_y = fixtureB.getBody().getPosition().y;

    if(fixtureA.getFilterData().categoryBits == Engine.PLAYER_BIT
            && fixtureB.getFilterData().categoryBits == Engine.PLATFORM_BIT ||
            fixtureA.getFilterData().categoryBits == Engine.PLATFORM_BIT
                    && fixtureB.getFilterData().categoryBits == Engine.PLAYER_BIT ) {

        //Gdx.app.log("Player Y ", "" + player_y);

        if (fixtureA.getBody().getUserData() == "platform") {
            platform_y = fixtureA.getBody().getPosition().y;
            player_y = fixtureB.getBody().getPosition().y;
        } else if(fixtureA.getBody().getUserData() == "player") {
            player_y = fixtureA.getBody().getPosition().y;
            platform_y = fixtureB.getBody().getPosition().y;
        }

        if(player_y < platform_y + 0.22f) {  //the player is below platform
            contact.setEnabled(false);
        } else {
            contact.setEnabled(true);
        }
    }
}

```

When I build my level the Platforms use this loop to build them from a Tiled map, and set the Category bits to the fixtures:

```
//////////////////////////////////////////////////////////////////////////
    //Platform Layers - with category bit PLATFORM_BIT
    for(MapObject object : map.getLayers().get(2).getObjects().getByType(RectangleMapObject.class)) {
        Rectangle rect = ((RectangleMapObject) object).getRectangle();
        bdef.type = BodyDef.BodyType.StaticBody;
        bdef.position.set((rect.getX() + rect.getWidth() / 2)  / Engine.PPM, (rect.getY() + rect.getHeight() / 2) / Engine.PPM);

        body = world.createBody(bdef);
        shape.setAsBox(rect.getWidth()/2 / Engine.PPM, rect.getHeight()/2 / Engine.PPM);
        fdef.shape = shape;

        //Set the category Bits to Platform
        fdef.filter.categoryBits = Engine.PLATFORM_BIT;
        body.createFixture(fdef);
    }

```

My Player also has category bits set and the maskBits define what he can collide with:

```
fdef.filter.categoryBits = Engine.PLAYER_BIT;
    fdef.filter.maskBits = Engine.GROUND_BIT | Engine.PLATFORM_BIT;

```

This should be all you need to get it working.

The only issue is trying to work out what the value here should be:

```
if(player_y < platform_y + 0.22f) {             //the player below

```

The 0.22f in my case makes sure tht the player gets a certain height above the platform before checking. If you set this too high or too low, the player may not land on the platform at all. I have not worked out what the .22f is in relation to my world coordinates or sprite size yet, but will update if I can replace this with a value derived from the Player's height for example.

Hope this helps a little.

GIT

https://github.com/stoddsie/8-Bit-Platform-Engine

---
Tags: box2d, libgdx
---


# Question
Title: Using an SDL_Renderer within a texture wrapper class in SDL2
I have a `CTexture` class which needs a renderer to create and show textures. I don't know the scope I should put the renderer in. I´ve got it to work as a global variable, but I don't know if it´s a good way.

`CTexture` instances will be created within other classes, so it seems to be a mess to pass the renderer as an argument.

What do you think I should do?

# Answer
I have found the best practice to be to pass the renderer instance to a `CContentLoader` class or a `CTextureFactory` class. Those classes could either be singletons, like I do, or simply instances that get passed to the parts of your code that need to create textures.

There's nothing your actual `CTexture` wrapper should need the renderer for after it has been created. Rendering should be handled by a separate class, that is not a job for `CTexture`, but instead a job for a class that's job is to render things, perhaps a `CRenderer`.

Limit the access to the `SDL_Renderer`, as if you have global access to it, you might be tempted to start changing rendering flags from various places, and that gets hairy really quick, when you suddenly need to change how the rendering works and looks in your game.
> 0 votes

---
Tags: textures, sdl2, c++
---


title: Unity Create Room Error

text:
# Question
Title: Unity Create Room Error
I get the following error

> “NullReferenceException: Object reference not set to an instance of an object”

I have updated it by adding extra arguments but I still get that issue. Below is my code, the issue is on the final line.

```
using UnityEngine;
using UnityEngine.Networking;

public class Host : MonoBehaviour {

[SerializeField]
private uint roomSize = 8;
private string roomName;
private NetworkManager networkManager;

void start () {
    networkManager = NetworkManager.singleton;
    if (networkManager.matchMaker == null) {
        networkManager.StartMatchMaker();
    }
}

public void SetRoomName (string _name) {
    roomName = _name;
}

public void CreateRoom() {
    if (roomName != “” && roomName != null) {
        Debug.Log (“Creating Room: ” + roomName + ” with room for ” + roomSize + ” players.”);
        networkManager.matchMaker.CreateMatch(roomName, roomSize, true, “”, “”, “”, 0, 0, networkManager.OnMatchCreate);
    }
}
}

```

# Answer
> 1 votes
Your start-method isn't executed because you spelled it wrong. It's `void Start ()`, not `void start()`.

---
Tags: unity, multiplayer
---


# Question
Title: Detecting when object is fully in collider
How to make that when object is fully in collider, just that moment "something happens", now I only know triggering.Hmm I mean when that cube is fully in the collider.

# Answer
> 2 votes
You can use the `OnTriggerStay` callback, and make sure that you don't trigger the action before the collider is fully container by the container. So basically you just need an extra check inside `OnTriggerStay`.

```
void OnTriggerStay(Collider other)
{
    if (other.bounds.Contains(this.bounds.min) && other.bounds.Contains(this.bounds.max))
    {
        PerformAction();
    }
}

```

Unity doesn't provide a standard functionality for this, but this very basic approach should do the job.

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


# Question
Title: How do I spawn more than one spawnpoint in my scene in Unity?
I have different enemy AIs and two spawn-points in a scene, so far. The problem I am having is that only one enemy AI spawns, and the other enemy AI won't spawn, in that scene. How can I fix this problem?

Here is my code:

```
using UnityEngine;
using System.Collections;

public class EnemiesSpawner : MonoBehaviour
{
    public GameObject [] enemy;
    public Transform [] spawnPoints;
    public float spawnTime = 5f;
    public Vector3 spawnValues;

    void Start ()
    {
        //Call the "Spawn" function every 10 seconds.
        InvokeRepeating("Spawn", spawnTime, spawnTime);
    }

    void Spawn ()
    {
        int spawnPointIndex = Random.Range (0, spawnPoints.Length);

        Instantiate(enemy[Random.Range(0, enemy.Length)],
            spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);

        Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x),
            1, Random.Range (-spawnValues.z, -spawnValues.z) );
    }
}

```

# Answer
It's because your have single enemy assigned to instantiate.

You need an array of enemies to be spawned.

```
public GameObject[] enemy;

```

Then when you instantiate, either do it at random or as you need.

```
Instantiate(enemy[Random.Range(0, enemy.Length)], //will choose from enemy array
            spawnPoints[spawnPointIndex].position,
            spawnPoints[spawnPointIndex].rotation);

```

In usual case there are two random things to be taken care of. Random enemy and random point to spawn.
> 1 votes

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


# Question
Title: LWJGL int vertex attribute not working in shader
I'm trying to send an integer attribute to my GLSL shader. The shader receives the attribute as follows:

```
layout (location = 3) in int integer_value;

```

I'm creating the attribute as follows:

```
glBindBuffer(GL_ARRAY_BUFFER, this.integerValueVboId);
glBufferData(GL_ARRAY_BUFFER, integer_values_buffer, GL_STATIC_DRAW);
glVertexAttribPointer(3, 1, GL_INT, false, 0, 0);

```

`this.integerValueVboId` is a valid ID generated with all the other VBOs. `integer_values_buffer` is an `IntBuffer` confirmed to contain the correct integer values.

When I set one of the integer values to `1`, the shader receives the integer value `1065353216`, which I have found to be the value obtained when one interprets a float `1.0f` as an integer value.

# Answer
> 0 votes
When specifying an integer attribute you need to use glVertexAttribIPointer:

> For glVertexAttribPointer, if normalized is set to GL\_TRUE, it indicates that values stored in an integer format are to be mapped to the range \[-1,1\] (for signed values) or \[0,1\] (for unsigned values) when they are accessed and converted to floating point. Otherwise, values will be converted to floats directly without normalization.
>
> For glVertexAttribIPointer, only the integer types GL\_BYTE, GL\_UNSIGNED\_BYTE, GL\_SHORT, GL\_UNSIGNED\_SHORT, GL\_INT, GL\_UNSIGNED\_INT are accepted. **Values are always left as integer values**.

(My emphasis)

---
Tags: opengl, java, glsl, lwjgl
---


# Question
Title: LibGdx, I moved ShapeRenderer projection matrix, but shadered waves did not move
I am use Libgdx with ShapeRenderer to draw rect and shaders passed to ShapeRenderer, to draw a waves. In game I made pseudo-parallax effect by changing projection matrix in SpriteBatches. But in ShapeRenderer+shader translating matrix leads to moving rect, but drawed waves didnot move Please help

```
package com.mygdx.game;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Vector2;

public class MyGdxGame extends ApplicationAdapter implements
InputProcessor
{

    private float mX;
    private float mY;
    private ShaderProgram mGradientShader;

    private Matrix4 mProjection = new Matrix4();

    private ShapeRenderer mShapeRender;

    public MyGdxGame()
    {

    }

    private float iGlobalTime = 0.0f;
    private Vector2 mScreenResolution;
    @Override
    public void create ()
    {
        final float screenWidth = Gdx.graphics.getWidth();
        final float screenHeight = Gdx.graphics.getHeight();
        mScreenResolution = new Vector2( screenWidth, screenHeight );
        mX = screenWidth / 2.0f;
        mY = screenHeight / 2.0f;

        String vertexShader = Gdx.files.local( "vertex.glsl" ).readString();
        String fragmentShader = Gdx.files.local( "fragment.glsl" ).readString();
        ShaderProgram.pedantic = false;
        mGradientShader = new ShaderProgram( vertexShader, fragmentShader );
        String s = "";
        if( false == mGradientShader.isCompiled() )
        {
            s = mGradientShader.getLog();
            Gdx.app.log( "Asteroid", s );
        }

        mProjection.setToOrtho2D( 0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight() );

        mShapeRender = new ShapeRenderer( 19, mGradientShader );

        Gdx.input.setInputProcessor( this );
    }

    @Override
    public void render ()
    {
        Gdx.gl.glClearColor( 1, 0, 0, 1 );
        Gdx.gl.glClear( GL20.GL_COLOR_BUFFER_BIT );
        Gdx.gl.glBlendFunc( GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA );
        Gdx.gl.glEnable( GL20.GL_BLEND );

        mProjection.translate( 1.0f, 0.0f, 0.0f );

        final int width = 400;
        final int height = 400;

        mGradientShader.begin();
        mGradientShader.setUniformf( "u_parentAlpha", 1.0f );
        mGradientShader.setUniformf( "iGlobalTime", iGlobalTime );
        mGradientShader.setUniformf( "iResolution", mScreenResolution );
        mGradientShader.setUniformf( "u_size", width, height );
        mGradientShader.setUniformMatrix("u_projTrans", mProjection );
        mGradientShader.setUniformf("u_center", mX, mY );
        mGradientShader.end();

        mShapeRender.begin( ShapeType.Filled );
            mShapeRender.rect( mX - width / 2.0f, mY - height / 2.0f, width - 100, height );
        mShapeRender.end();

        iGlobalTime += Gdx.graphics.getDeltaTime();
    }

    @Override
    public boolean keyDown(int keycode) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean keyTyped(char character) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {

        mX = screenX;
        mY = Gdx.graphics.getHeight() - screenY;
        return false;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        mX = screenX;
        mY = Gdx.graphics.getHeight() - screenY;

        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        // TODO Auto-generated method stub
        return false;
    }
}

//###########################Vertex shader
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec4 v_color;
varying vec2 v_texCoords;

void main()
{
    v_color = a_color;
    v_color.a = v_color.a * (255.0/254.0);
    v_texCoords = a_texCoord0;
    gl_Position =  u_projTrans * a_position ;
}

//###########################Fragment shader
#ifdef GL_ES
#define LOWP lowp
    precision mediump float;
#else
    #define LOWP
#endif

varying LOWP vec4 v_color;
varying vec2 v_texCoords;

uniform sampler2D u_texture;

uniform float u_outterRadius;

uniform vec2 u_center;
uniform float u_parentAlpha;
uniform float iGlobalTime;
uniform vec2 iResolution;
uniform vec2 u_size;

float speed = 0.03;
float invAr = iResolution.y / iResolution.x;

void main()
{
    //determine origin
    vec2 position = ( gl_FragCoord.xy - u_center )  / u_size.xy;

    //determine the vector length of the center position
    float len = length( abs( position ) );

    float softness = 0.01;

    float waves_count = 2.0;
    float wave_spliter = 0.05;

    vec2 center = u_center / iResolution;

    vec2 uv = gl_FragCoord.xy / iResolution.xy;

//  vec3 col = vec4( uv, 0.5 + 0.5 * sin( iGlobalTime ), 0.0 ).xyz;
//  vec3 col = vec4( uv, 0.5, 0.0 ).xyz;
    vec3 col = vec3( 0.5, 0.5, 0.5 );

    vec3 texcol;

    float x = ( center.x - uv.x );
    float y = ( center.y - uv.y ) * invAr;

    float r = ( - 1.0 ) * sqrt( x * x + y * y ); //uncoment this line to symmetric ripples
    //float r = ( - 1.0 ) * ( x * x + y * y);
    float z = 1.0 + 0.5 * sin( ( r - iGlobalTime * speed ) / 0.003 );

    texcol.x = z;
    texcol.y = z;
    texcol.z = z;

    gl_FragColor = vec4( col * texcol, z * ( 1.0 - 2.0 * len ) );
}

```

# Answer
> 0 votes
Спасибо за помощь
Я нашел решение:

```
private Vector3 mMatrixGetTranslation = new Vector3();

```

в render ()

```
mProjection.getTranslation( mMatrixGetTranslation );
float tranX = ( Gdx.graphics.getWidth() + mMatrixGetTranslation.x * Gdx.graphics.getWidth() ) / 2.0f;
float tranY = ( Gdx.graphics.getHeight() + mMatrixGetTranslation.y * Gdx.graphics.getHeight() ) / 2.0f;

```

и наконец

```
mGradientShader.setUniformf("u_center", mX + tranX, mY + tranY );

```

---
Tags: opengl, libgdx, shaders, glsl, projection
---


# Question
Title: why are texture atlases called texture atlases and not image atlases
More specifically, is there anything about texture atlases specific to textures? From what I've read of them, they might just as well be called image atlases. Images are not the same as textures, but textures can be created out of images.

# Answer
Because whoever coined the term in the first place was using the technique in a way related textures, in all likelihood. The term is quite old and well established that it isn't even cited in research papers any longer, and hasn't been going back some years.

There's nothing specific about the technique that really applies to textures. You could just as easily use it for image data that isn't going to be used as a texture in 3D graphics. In fact, taken to logical extremes, the basis of the idea is to pack smaller instances of a thing into larger instances of a thing to optimize for some constraint. We do this often in other areas of software engineering. For example it's the basic technique behind creating "pack file" archives of all a game's resources.
> 2 votes

---
Tags: textures, image, terminology, texture-atlas
---


# Question
Title: Tile Map Collision in 2D Platformer (C# Monogame)
I am trying my hand at making a small 2D platformer. Currently I am trying to implement collision on a tile map. I have been trying to experiment with different ideas but can not find a way for the life of me. Currently, bounding boxes have been set up around the player and the blocks.

My current algorithm is as follows:

```
        for (int i = 0; i < blockBound.GetLength(0); i++)
        {
            if (playerBound.Intersects(blockBound[i]))
            {

                if (playerBound.Bottom > blockBound[i].Top)
                {
                    jumping = false;
                    player.pos.Y = player.prevPos.Y;
                }
            }
        }

```

I have tried using an intersect amount by subtracting the blockBound\[i\].Top value from the playerBound.Bottom value and moving the player by that much back to their previous position but it only caused the player to move in and out of the block rapidly.

When doing the same thing with all sides, you could probably guess, always makes the collision code run.

Also with this code, when the player jumps, it appears to have somewhat of a jolt for lack of a better word when it begins jumping, compared to the normal smooth jump it has without any collision.

Is there a better way of doing this and if so, how?

# Answer
> 1 votes
You could use the Separating Axis Theorem, for which there are many excellent tutorials out there. The one that I still remember being very helpful was the one made by the team of the game "N":

Part 1: Collision between two objects

Part 2: Tile grids

It features interactive elements to play around with, making it really easy to understand the process intuitively.

Also, if you are having only rectangles as colliding objects, you can skip the part with round shapes. Although you probably want the lower end of your game character to be something like a circle, to avoid getting stuck at places, where one floor tile ends and the next one starts.

# Answer
> 0 votes
I suggest you to check out this sample game on a simple platformer game. It has an example of one side collision as well.

MonoGame.Samples Platformer2D on Github

Hope it helps!

---
Tags: c#, xna, collision-detection, monogame, platformer
---


# Question
Title: How to get rid of an image upon collision detection in SDL?
I am fairly new to SDL in C, but I have written a simple game whereby a character has to reach the end of a level and avoid bad stars on the way. If he hits a star, he dies. There are also good stars he can collect and get points.

I have set up my point system so now when he hits a good star, he should get a point. However, when he hits a star, he actually gets lots of points, as long as he is touching the star, which I don't want. I think that what's happening is because the stars are moving and he rubs up against the stars; each pixel he moves counts as a new collision so he gets a point per collision. Ideally, he should only get one point per star.

So I have two problems: 1) I need to figure out how to make it so that he can only get one point when he hits a star. 2) Since he is supposed to be 'collecting' the stars, I want to make the star disappear when he collects it.

So it's similar to most of these types of games, whereby, the player collects something, it disappears and they get a point.

EDIT:

This is struct I've made:

```
typedef struct {
    int x, y, w, h, baseX, baseY, mode;
    float phase;
} Goodstar;

```

I've then referenced it in another struct like so:

```
Goodstar goodStars[GOOD_STARS];
SDL_Texture *goodStar;

```

`[GOOD_STARS]` is equal to 100.

And then here's my collision detection code:

```
// Check for collision with good stars
for (int i = 0; i < GOOD_STARS; i++) {
    if (collide2d(game->man.x, game->man.y, game->goodStars[i].x, game->goodStars[i].y, 48, 48, 32, 32)) {
        if (!game->man.isDead) {
            game->man.points++;
        }
        break;
    }
}

```

So right now it only checks for a collision and then adds a point.

EDIT 2:

This is the code you suggested and it works:

```
for (int i = 0; i < GOOD_STARS; i++) {
    if (!game->goodStars[i].awarded) {
        if (collide2d(game->man.x, game->man.y, game->goodStars[i].x, game->goodStars[i].y, 48, 48, 32, 32)) {
            if (!game->man.isDead) {
                game->man.points++;
                game->goodStars[i].awarded = 1;
            }
            break;
        }
    }
}

```

And this is my initialisation code:

```
  // Initialise stars
  for (int i = 0; i < GOOD_STARS; i++) {
    game->goodStars[i].baseX = 320 + random() % 38400;
    game->goodStars[i].baseY = random() % 480;
    game->goodStars[i].mode = random() % 2;
    game->goodStars[i].phase = 2 * 3.14 * (random() % 360) / 360.0f;
        game->goodStars[i].awarded = 0;
  }

```

# Answer
> 0 votes
So the general approach is the following: you check if the player collides with a star, and if it does, you award the player a point, and then destroy the star.

All right, so seeing your code, I would simply add a boolean called `awarded` or something similar to the `Goodstar`. Initialize that to `false` when you create your stars.

Now, when the player collides with a star, mark `awarded` as `true`, and in the future, don't award points to players if `awarded` is true. So something like

```
for (int i = 0; i < GOOD_STARS; i++) {
    if (!game->goodStars[i]->awarded)
    {
        if (collide2d(game->man.x, game->man.y, game->goodStars[i].x, game->goodStars[i].y, 48, 48, 32, 32)) {
            if (!game->man.isDead) {
                game->man.points++;
                game->goodStars[i]->awarded = true;
            }
            break;
        }
    }
}

```

You would also then not render stars that have `awarded` set to true.

---
Tags: collision-detection, sdl, c, sdl2
---


# Question
Title: Why doesn't JavaScript's Math.cos function match this vector tutorial?
I'm following this MATHguide lesson on combining vectors and have reached this part:

> Next, we need to convert their forces to horizontal and vertical components. Let's use k for Kim's vector and n for Noah's vector.
>
> k = \<30, 130°\> = \<30 cos 130°, 30 sin 130°\> = \<-19.3, 23.0\>. n = \<40, 65°\> = \<40 cos 65°, 40 sin 65°\> = \<16.9, 36.3\>.

To get the X part of Kim's vector, I run `30 * Math.cos(130)`, I get `-11.018739913640896`, which is not -19.3. To get the Y part of Kim's vector, I run `30 * Math.sin(130)` which is `-27.903178505602853`, which is not the `23.0` listed by the example.

Where did I go wrong?

# Answer
In Javascript, as usual, `Math.sin` and `Math.cos` want the angle parameter in radians. You are feeding it degrees, and that's why your results are off.

You probably want to introduce an utility function `toRadians`, which takes in the angle in degrees and returns the angle in radians.

```
function toRadians(angle) {
    return (angle * Math.PI) / 180.0;
}

```

You can find references all over the internet about angle conversions, but that's how it's done.

Now, if you execute `Math.cos(toRadians(130)) * 30`, you get about -19.3, which seems to be what you were looking for.
> 3 votes

---
Tags: mathematics, javascript, trigonometry
---


# Question
Title: Anti Aliasing: How to implement supersampling in OpenGL?
I'm learning OpenGL by working on a small Oculus Rift project, which implies, anti aliasing is everything :). Since the application of the barrel distortion shader requires rendering to a framebuffer in higher resolution anyways, my goal would be to perform super sampling anti aliasing (unfortunately, the very good answers to this question do not explain super sampling anti aliasing). In order to tackle the problem step by step, I first try to ignore the distortion aspect, and try to render my framebuffer directly.

The strange thing I realized is that, although I use a really huge resolution for the off-screen framebuffer (3840x2400; performance is not the issue), the outcome is not anti aliased at all.

I render my framebuffer by setting up a simple VBO quad in combination with the following vertex/fragment shaders:

**Vertex Shader:**

```
attribute vec2 Position;
attribute vec2 TexCoord;
varying vec2 oTexCoord;
void main()
{
  oTexCoord = TexCoord;
  gl_Position = vec4(Position, 0, 1);
}

```

**Fragment Shader:**

```
uniform sampler2D sampler;
varying vec2 oTexCoord;

void main()
{
  gl_FragColor = texture2D(sampler, oTexCoord);
}

```

I currently see four possible causes why my result is not anti aliased:

1. It's related to general texture rendering settings, which would go into the direction of this question, i.e., I have to change texture filtering or mipmapping (haven't learned these things yet). For sake of completeness: I'm using `glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);` for the texture attached to my FBO.
2. I have to manually implement a super sampling in the fragment shader, which would go into the direction of the comments in yet another question. The idea here would be that instead of using `texture2D(sampler, oTexCoord)` directly as fragment color, one would vary `oTexCoord` slightly left/right/up/down and blend the colors to a final result (similar to a Gaussian blur?). Is there some kind of standard fragment shader which accomplishes that in a sophisticated manner? I would actually be a bit surprised if this is really required, because this would imply that without extra work textures are never anti aliased by using a basic fragment shader?
3. I have to bind a multisampling texture to my FBO, which according to this tutorial has some issues that I do not fully understand. However, if I understand it correctly, what I'm looking for is not an anti aliasing in the off-screen FBO itself, but anti aliasing when rendering an (potentially arbitrary) texture to the primary framebuffer. Besides, the resolution of the FBO is already huge.
4. The last cause could be related to general OpenGL settings. In order to analyze this I factored out the whole rendering part allowing to switch between rendering via off-screen framebuffer and directly rendering to the primary framebuffer. I ensured that my display device (using LWJGL) is using 8 MSAA samples and I set:

```
glEnable(GL_MULTISAMPLE_ARB)
glHint(GL_MULTISAMPLE_FILTER_HINT_NV, GL_NICEST)

```

Interestingly, I indeed get an anti-aliased result when I render directly! So the problem really seems to come from rendering my framebuffer texture.

Any hint is highly appreciated! I also would be glad to have a good reference/example on supersampling in OpenGL in general -- but, the fact that I have trouble finding anything tells me that I have have understood something completely wrong?

**Update**

Thanks to Fault's answer, hinting me towards linear texture interpolation, I'm now one step closer to solving the problem. The reason why I did not see a difference between `GL_NEAREST` and `GL_LINEAR` filtering was that I was simply using a framebuffer which was much too large! By switching from 8x supersampling to 2x supersampling I finally could see a difference.

I'll try to explain my findings for other OpenGL learners. Studying this great tutorial made clear why a too large framebuffer is a problem: Linear interpolation simply means that OpenGL will use the 4 closest texels from the texture to determine the fragment color. When the texture has a much higher texel density in comparison to the fragment area (see this illustration from the tutorial), this averaging simply has no big effect. The general solution for texturing is to use mipmaps, i.e., smaller size versions of the texture. For a framebuffer texture this is probably not a good idea (right?). Creating several mipmap levels for each rendered frame seems to be pretty inefficient.

My next question was why texture filtering does not simply determine the fragment area and iterate over the correct texels. The problem is that, in contrast to the FBO-to-screen-rendering, general texture filtering is not isotropic, i.e., the fragment area not necessarily lines up with the texel space (example).

So, if I see it correctly, there are two ways to implement supersampling in OpenGL:

1. By sticking to an oversampling factor of 2 and using the above shader with bilinear filtering. But imho the result looks worse in comparison to 4x MSAA (rendering without framebuffer). And one has to be aware of the counter-intuitive behavior that increasing the oversampling actually leads to worse quality.
2. Since for FBO-to-screen-rendering it is "rather simple" to compute the fragment area, a sophisticated aliasing fragment shader could be used. In comparison to the first approach this is probably much slower but should allow much better quality. Furthermore, increasing the size of the framebuffer now also (should) improve quality. However, I currently have no idea how to implement such an anti aliasing shader (how to calculate the fragment area? Should I use grid/stochastic/poisson disc sampling?). I still wasn't able to find any reference or example implementation.

# Answer
> 3 votes
`glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);`

GL\_NEAREST tells the GPU to sample *the nearest pixel, and the nearest pixel only.* When downsampling, you want *an average* of the nearest pixels, so you should change it to `GL_LINEAR`. This tells it to linearly interpolate between the nearest pixels, thus if you sample at a point directly between 4 pixels, it will give you their average colour. Along an edge, it would sample the edge colour, and the background colour, and give you something in between (anti-aliasing).

# Answer
> 3 votes
As you have stated your approach works if the intermediate framebuffer is 2x the size of the final screen resolution. That is beause the bilinear sampling takes 4 texels into account. Now if your intermediate framebuffer is 4x the original screen size you will have to call texture2d four times with a certain offset, add the samples together and calculate the average by dividing by 4.

For best results you should also consider:

* make sure your sample points are exactly in the middle of 4 texels
* Implement bicubic sampling instead of using bilinear (you can switch back to Nearest for that)
* linearize your samples after fetch, gamma correct after averaging

For best performance:

* implement downsampling as a separable convolution along X and Y if multisampling required more than 5x5 samples

---
Tags: opengl, antialiasing, frame-buffer
---


# Question
Title: What should I use instead of pixels in a LibGDX game?
Recently I have read here: https://xoppa.github.io/blog/pixels/ that I should not use pixels in my game. But Im not sure that I have understood this so I have some questions.

1. Xoppa writes that pixels may look different on different devices but I thought all the time that viewport solves the problem of different screen size and aspect ratio. Was I wrong?
2. How can I draw all assets without using pixels?
3. I have an idea to support all screen ratios and sizes by using ExtendViewport with the biggest screen that I will support. It looks like this:

> viewport = new ExtendViewport(1080, 1920, 1440, 1920, camera);

And everything works well on the smartphone during test. Game is prepared for 16:9 screen and if somebody have for example 4:3 screen he will se more background texture.

But I dont know how game will work on weaker devices. Is one viewport (1920x1440) enough? Or I should make more viewports for several sceen sizes for example 1920x1440, 1280x960 and 800x600?

Just I dont understand why I should not use pixels in game if everything works well. Can somebody explain it to me in simple way?

# Answer
Reason's why I use meters instead of pixels

* using pixel is mostly not recommended because base on my experience, when you are using libgdx box2d body the unit is known as *meters*, for example you created a `Vector2 position = Vector2(1,1);` the x and y value is *1 meter*, so in that case if you use pixels for example 32 pixel the body value would be 32 meters.
* to minimize the value

To convert from pixels to meters is easy.

```
float UNIT = 32.0f; // unit of 1 meter is 32 pixels in the given unit
float PIXELS_TO_METERS = 1 / UNIT;

float meterValue = PIXELS_TO_METERS * PIXEL_VALUE

```

For example, you have a camera and set its width to 800 pixels and height to 480 pixels. Then you just need to multiply it by `PIXELS_TO_METERS` to get the meter value.

```
public final static float WIDTH = 800;
public final static float HEIGHT = 480;

// This is the typical pixels value of WIDTH and HEIGHT
OrthographicCamera camera = new OrthographicCamera(WIDTH, HEIGHT);

// Now we applied the pixel to meter conversion.
float FRUSTUM_WIDTH = WIDTH * PIXELS_TO_METERS;
float FRUSTUM_HEIGHT = HEIGHT * PIXELS_TO_METERS;

OrthographicCamera camera = new OrthographicCamera(FRUSTUM_WIDTH, FRUSTUM_HEIGHT);

// or set it directly
OrthographicCamera camera = new OrthographicCamera(25, 15);

```
> 1 votes

# Answer
It is more convenient. Say you are developing a 2D 4X game, a simplified version of the original civilization games. Your ingame world is divided into a 20x20 map of tiles. Tell me, to place your tiles, would you rather draw a tile at `tiles[2][2].draw(20,20);` or at `tiles[2,2].draw(2,2);` to draw a tile at `(x,y) -> (2,2)` from the origin of your world. This is a negligible difference in this case, but as the coordinates increase in value, you could eventually have to write `tiles[2][2].draw(2000,2000);`depending on your world size.

This might be a bit arbitrary, so let me give you another example. When designing a UI, would you rather have to guess where each UI element should be drawn pixel-wise, or would you rather divide your viewport into 100 units (a 10x10 map of coordinates) and draw it at 10,10 or 1000,1000. And, no, the viewport will not handle pixel -\> device screen adjustments, it will handle world coordinates -\> device screen positioning, so using pixels will still mess up your rendering.
> 0 votes

---
Tags: java, android, libgdx
---