# Question
Title: Causing Update loop with Coroutine Unity
Total Noob Alert! \< 7 days with C# and Unity

My Win Game screen becomes SetActive and my Player is SetActive false when you are standing in a trigger and crouch. That all works fine except you cant see the crouch animation because he is IMMEDIATELY SetActive false.

I tried to delay this by creating a coroutine. The problem with that is this is all happening in the Update function (or whatever it's called) because of the getkeydown for crouch. That gets called once per frame so my coroutine is trying to go off once per frame.

I tried creating a bool called isCoroutineStarted and set it to false and then set it to true in the Coroutine to break the loop but that didn't work either.

Don't know what to do so I reverted it back to before where it doesn't show my crouch animation.

Here's my script (It's attached to a Game Object with the trigger):

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

public class xxxxxx : MonoBehaviour {

    public bool xxx = false;

    [SerializeField]
    private GameObject youWinUI;

    [SerializeField]
    private GameObject player;

    // Determines whether or not the player is standing on the xxxxx
    void OnTriggerEnter2D (Collider2D other)
    {
        xxx = true;
    }

    void OnTriggerExit2D (Collider2D other)
    {
        xxx = false;
    }

    //Turns on Win screen and makes player disappear when crouch on xxx
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.S) && xxx == true) {
            youWinUI.SetActive (true);
            player.SetActive (false);
        }
    }
}

```

P.S. ignore the x's no stealsies lol. Also this piece of script works as intended I just want a delay so you can see the crouch animation.

# Answer
> 0 votes
You can use a trick:

While player is performed the crouch, you will increase a (float) counter value.

And when the desired amount has passed, you will disable the player.

Pseudo code will be like :

```
float counter = 0;
bool isCrouchStarted =false;

void Update ()
{
 if (Input.GetKeyDown (KeyCode.S) && xxx == true)
 {
        youWinUI.SetActive (true);
        isCrouchStarted = true;
 }

 if (isCrouchStarted == true)
 {
        counter +=0.1f;  //change the value for increase speed
 }

 if(counter>=1.0f) //change the value for desired time
 {
      player.setActive(false);
      isCrouchStarted =false; // for not getting null ref. and increase value for no reason.
 }

}

```

Hope this helps! Cheers!

---
Tags: unity, c#, 2d, gui, platformer
---


# Question
Title: How to convert or import files from Illustrator in Tiled for game development?
I have created all my images for a game in Illustrator, now I want to convert them in Tiled Sheets for developing my game in libGDX. So could I import or convert these `.ai` files from Illustrator in Tiled?

# Answer
> 4 votes
Tiled doesn't currently seem to support .AI files. You need to convert it to a file format Tiled can use as a tileset source, such as .PNG. That can be done by exporting your image as a PNG.

---
Tags: libgdx, tilemap, tiled
---


# Question
Title: How many polycount for smartphone hardware starting from 2015?
I already know that the answer is "depends". Depend if the hardware is low-mid or high hend. So, I try to re-formulate: is 100K concurrent polycount in a 3d game for smartphone too much ? How many is it a good compromise ?

Thanks

# Answer
> 2 votes
CPU, GPU capabilities, and screen resolution varies too much, even 2015 onward.

And then it still depends on triangle shape, occlusion, OS version, texture types, size, quantities, vertex and fragment shaders and so on...

You need to buy (or borrow) phones and test your game on specific models and then hope for the best.

---
Tags: graphics, mobile
---


title: Converting array to shape drawn: Pygame

text:
# Question
Title: Converting array to shape drawn: Pygame
```
screen=pygame.display.set_mode((500, 700))
Shape=['.....',
       '..O..',
       '.OOO.',
       '.....',
       '.....']
ShapeProperites={'x': 250,
                 'y': 50,
                 'Color':Red}

```

How can I convert this array in Pygame to a shape drawn on a screen with the properties from the dictionary? The list is meant to represent a tetromino. The 0's should be drawn as squares on the screen.

# Answer
I'm not exactly sure what you want your characters to represent, or where you want X and Y to be located, but something like the following should get you started.

First of all, you want to declare the color: `Red = (255, 0, 0)`

Then, in your draw loop you want to render the shape with the following code:

```
x = ShapeProperties["x"]
y = ShapeProperties["y"]
for line in Shape:
    for character in line:
        if character == "O":
            pygame.draw.rect(screen, ShapeProperties["Color"], pygame.Rect(x, y, Size, Size))
        x += Size
    y += Size
    x = ShapeProperties["x"]

```

It starts at the position you've specified in the properties. It then iterates over the lines in the shape, and then over the characters that denote the actual shape. Each character increments X by the `Size`, which you can set to be whatever size you want your shape blocks to be. Once then end of a line is reached, it resets X and increments Y by the size, moving onto the next row.

As an optimization you might want to consider rendering this into a surface of a `Shape` class, and just blitting that surface each frame, instead of re-rendering the whole shape, but this should be enough to get you going.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Consistent normals at any angle in bezier curve
Could not work out or find any solution for this.

I have a spline which consists of bezier curves (in 3d space) — in fact, any straight line will also have such problem.

I take a point on the curve and need to get a normal to this point at any given angle 0 - 360 (say, to build a mesh around it or to calculate an offset for the movement).

I understand that in 3d space we have to define a plane to build normal, normally — by using Vector3.Cross(A, B); In general, one uses curve's tangent as A and, e.x., Vector3.up or right as B.

But, if curve becomes vertical (it can go in any direction, imagine any track that is ground-independent, like in space), it gets aligned with Vector3.up, and the direction of normals goes crazy, swaps direction and so on, which is quite logical. More, it does so not only in straight vertical position, but start to change gradually around it.

So, the question is: how can I get consistent (all in equally correct direction) normals, using any given curve point position and angle for normal rotation?

**Update:**

The initial approach looked like this:

```
public Vector3 GetTangent(...) {

    Vector3 q2 = CalculateTangent (...);

    Quaternion lookAt = Quaternion.LookRotation (q2);
    Vector3 normal = lookAt * Vector3.up;
    normal = Quaternion.AngleAxis (angle, q2) * normal;
    return point + normal * size;
}

```

Which generated the following normals (blue is up):

Now, if I try to use the previous normal for the direction:

```
Quaternion lookAt = Quaternion.LookRotation (q2, previousNormal);

```

first of all, I don't understand what to place here:

```
Vector3 normal = lookAt * ?

```

And any combination of tangent, normal and rotation gives me something like this:

Where it can be clearly seen that normals on the vertical are improved (though not correct), but on the horizontal all went wrong, as if I just changed Vector.up to Vector3.right.

In addition, the code for generating the tube in its main part looks like this:

```
float vStep = (angleTo - angleFrom) / pipeSegmentCount;
if (b == 0 && _tP == 0f) _tP = 0.01f;
if (b == 0 && _t == 0f) _t = 0.01f;
if (b == spline.Nodes.Count - 2 && _tP == 1f) _tP = 0.9f;
if (b == spline.Nodes.Count - 2 && _t == 1f) _t = 0.9f;
Vector3 vertexA = spline.GetTangent (_pP, _tP, _bP, Vector3.up, pipeAngle, pipeRadius);
Vector3 vertexB = spline.GetTangent (_pointsTotal[b] [s], _t, b, Vector3.up, pipeAngle, pipeRadius);
for (int v = 1; v <= pipeSegmentCount; v++, i += 4) {
    vertices [i] = vertexA;
    vertices [i + 1] = vertexA = spline.GetTangent (_pP, _tP, _bP, Vector3.up, v * vStep + pipeAngle, pipeRadius);
    vertices [i + 2] = vertexB;
    vertices [i + 3] = vertexB = spline.GetTangent (_pointsTotal[b] [s], _t, b, Vector3.up, v * vStep + pipeAngle, pipeRadius);
}

```

Where 0.01f and 0.99f are because ends of spline do not have control points and LookRotation produces an error about zero rotation. b and \_bP are node indexes, and \_P suffix is for "previous".

This particular code is used to generate a round rail and move an object beneath it. Thus, it is important that the bottom normal is consistent and always at the bottom (when it is vertical, this bottom is not the world bottom of course, but it protrudes at the side of the tube, object will turn itself accordingly, looking forward the curve).

# Answer
> 4 votes
I'm not sure why you say the suggestion in the comments "gets worse" - I implemented it and it performs as expected:

In each of these examples we have the same cubic spline being wrapped in a tube mesh, using a calculated normal to the spline at each point to decide the orientation of each tube cross-section.

I've marked the 0, 90, 180, and 270-degree points on the tube with coloured stripes to help show the differences in the twist.

On the left we have our original problem: when we try to select a normal in a consistent/memoryless way (eg. by choosing the vector in the normal plane closest to the "up" direction of our parent, substituting a default when the plane is horizontal) then we get sharp discontinuities: the tube can pinch at vertical segments, or show unnatural-looking twisting in near-vertical segments.

In the middle we apply a simple trick: instead of trying to align with some universal up, we align with whatever normal the previous step on our spline used. This keeps twisting distortion to a minimum, and our uv-mapped texture flows smoothly around each bend. But, the normal is free to wander all around the tube, which might be undesirable if your scenario has some structure to it that shouldn't linger at diagonal angles (eg. that green stripe, lazily hanging close-but-not-exactly-on the top of the tube).

On the right we apply a fixup: we slightly exaggerate the y component of the last step's normal, before using it to construct the normal for this step. This has the effect that, away from vertical sections, the tube will try to gradually untwist itself to point its normal as close as it can to vertical. This version picks the closest vertical direction, so it will seek down if that lets it introduce less twist.

So you can see, where the ends of the spline meet, the grid lines up, but the coloured markers are 180 degrees out (we now have blue on top and yellow on the bottom). I used distinct colours in this example to show it explicitly, but if you simply tile your texture twice around the circumference then this kind of mismatch becomes invisible.

---
Tags: unity, c#, vector, normals, beziers
---


title: Unity - Create terrain in Blender?

text:
# Question
Title: Unity - Create terrain in Blender?
I am going to make a terrain ( not too big ) for my RTS and I was wondering whether to use Unity's terrain tool or create a terrain in Blender and import it to Unity?..I have been told that Unity's terrain is intense work for the mobile GPU..So would it be any good to make the terrain in Blender ( in terms of performance )?

# Answer
I don't know about performance but I guess that if you import terrain from blender it'll be just a mesh without terrain's LOD system, you'll need to write it yourself, same thing with grass and detail meshes, you'll need to make your own LOD system for them. It'll require extra work but I'm almost sure that it will be at least a little faster. If you can export terrain with big texture for it, it'll save processing power that is needed for splatmapping in shader.
> 1 votes

---
Tags: unity, performance
---


title: Double touch joysticks

text:
# Question
Title: Double touch joysticks
I am developing a mobile game where I need to control main character in any direction using touch analog joystick (https://pineight.com/mw/images/6/6f/Ipoc\_dpad.png). It's ok but I also want my character to fire in any direction. Thus I am looking for best solution of control.

There are some variants, but no one is ok:

1. Target and fire by pointing finger to exact point of the screen (not comfortable, because player will need to hold device by one hand and use second hand to move over the whole device).
2. Fire to direction where the character moves. This case will limit characters' freedom on move and target. Not good.
3. Use second touch joystick (under opposite hand) to select fire direction - this variant looks better than previous two, however I still not sure how comfortable it will be. I've tried by myself and it looks a bit complex for me to follow both controls at the same time.

Did you saw any games achieving the same goal? What you can recommend?

# Answer
I played such mobile game once, unfortunately I can't remember the name right now. However, there was a joystick in the bottom left corner for walking in any direction and another joystick in the bottom right for firing whereever you want to. This was easy to use, assuming you want to use landscape mode. The player has a clear view over the whole screen and can still have full freedom over movement and firing directions.

Technically, I would just put the screen in two halves, left and right. When detecting a touch, just do a quick check if left/right half is being touched and proceed with your joystick evaluation afterwards. As most devices allow multi-touch nowadays, take care of cheating-attempts (firing should be only possible in one direction at a time, even if two touches are detected on the firing-half of your screen).

**Edit:** Well I didn't expect that - randomly googling for "ios shooter monster" gave me just the right result: the games' name was "Monster shooter". Lucky day.
> 1 votes

---
Tags: android, ios, mobile, control, joystick
---


# Question
Title: Drawing thousands of isometric tiles per frame with a high FPS
This question seems similar to other questions but no other topics I saw helped. I'm making a game in GML (GameMaker Language).

Regardless of the language/software, this should be a universal topic.

Okay, so I currently barely exceed 60FPS on a game with no code in the tick (step? frame? iteration?) so it should most definitely not be a CPU issue. My computer is fantastic and I can run nearly all (if not, all) games at ultra and high settings. Anyway, my game is isometric and tiles are 32x16.

The terrain data ds\_grid (like a 2D array, but can't be jagged) is never changed except when loading other maps. I need the game to be played in a max of 1080p, and higher resolutions won't be implicitly supported.

So, I have a nested for-loop, to loop through a calculated minx/maxx and miny/maxy, basically defining the rectangular area in the terrain data ds\_grid that I need to render. However, at the moment, in 1080p, after applying a variable called count to increment every iteration of the nested loop, I have nearly 8000 draw calls every frame, rendering every tile near the view.

Remember, the tiles are both isometric and small, so there are a lot of things needed to be rendered. There are multiple grass tiles to reduce texture repeating. There is also a water tile, and I may add other terrain tiles. So basically, I need a method of rendering tons of tiles (that don't change) with a much higher (preferably at least 300) FPS.

MORE INFO: in GM, a ds\_grid is a data structure that is very similar to a 2D array, where the main differences are that it cannot be jagged (it's similar to a table) and any cell can hold any data type, so I could have strings and real numbers etc. all in the same ds\_grid.

My ds\_grid contains enumeration values, such as tile.grass or tile.water.

The terrain does not fit within the screen borders, and resolution directly affects view size.

# Answer
> 1 votes
You can achieve lighting-fast batching (as Tetrad suggested) by making use Vertex Buffers. I recently answered a similar question on the GameMaker forums: Tips for rendering optimization.

Looking at this more objectively, if all of this data remains static throughout the game, you can pre-build a vertex buffer. Gamemaker will try to do this dynamically whenever you call draw\_sprite, however changes in render state will break a rendering batch, slowing down the renderer.

If you are not running in YYC, the actual process of iterating through the loop can also be expensive.

To add a little clarification, to build a vertex buffer, you can simply replace all of your calls to draw\_sprite with something that writes data to your vertex buffer. Once a vertex buffer has been built, you can draw it with incredible speed with 1 simple draw call. This will enable you to render millions of tiles.

You can find information on how to create vertex buffers here: GameMaker ShaderOverview - Part 1 (There are 4 parts to this tutorial, starting with shaders, finishing on Vertex Buffers).

**Additional Information:**

* The reason rendering in the way you are is slow is because a communication bottleneck exists between the CPU and GPU. Both are sitting idle whilst messages from the CPU are being sent to tell the GPU to do something. As each of these draw calls is simple, the GPU gets it done incredibly fast, then goes back to waiting. A vertex buffer resolves this by essentially merging all of those individual calls into a single message, allowing both devices to get on with what they should be doing.
* To clarify terminology, batching is the process of merging these draw calls. There exist two types of batching, and GameMaker employs both of these in one way or another, however as it is handled automatically, there is not always enough control:

+ **Dynamic Batching:** This is the process of dynamically building vertex buffers. It is used when there is a constant change in the number of things being rendered. As work has to be done to construct this buffer, and after construction, the buffer needs to be sent from the CPU to the GPU before it can be drawn, this is slow. GameMaker uses dynamic batching whenever you call any common drawing function, however render state changes such as changing texture, changing rendering colour, blend mode etc; will cause the batch to break, reducing the efficiency of this process.
    + **Static Batching:** This is the process of pre-creating a vertex buffer containing a collection of static geometry for your scene. You can often create multiple different static buffers, as these are incredibly fast. They get created once, sent and stored in GPU memory, so you only need a simple draw call to trigger the render.

---
Tags: rendering, isometric, game-maker
---


title: Multiple textures/texture atlas

text:
# Question
Title: Multiple textures/texture atlas
Is there any performance difference between using multiple textures and using texture atlas in splatmapping? I would want to use multiple ones beacouse tiling and changing them would be easier but performance is more important.

# Answer
> 1 votes
I would say that a few years ago, creating a texture atlas would have been better, however now, I believe that GPUs would be more optimal at sampling from multiple different textures. There are a few reasons for this:

* Normally, when doing texture splatting, you are sampling the same texture coordinate across multiple different textures. Having multiple samplers is more suited to the GPU as it makes use of contiguous memory access. The GPU will cache regions of textures around the sampled locations whenever you do your first texel fetch. If neighbouring pixels are using neighbouring colour data, the textures will already be available in the shader units local texture cache. If you had used an atlas, you may end up jumping around the same large texture, having to re-fetch each time, causing a texture cache crash.
* When you use a texture atlas, you can also run into pretty severe problems when it comes to texture filtering, with bleeding edges between the texture boundaries and such. Independent samplers generally function better in this regard.
* as DMGregory said, atlasing would also increase the complexity of your shader, ultimately reducing the overall performance.

Though all this being said, it is still important to evaluate both options. As splatting is quite a fast operation, it may be difficult to notice a difference. If there is no measurable difference, stick with independent textures.

The one downside to this however is that you do have a hard limit of the number of samplers that can be used, though you can make use of texture arrays or multi-pass rendering if you need to use lots of textures. It is worth noting that older GPUs will have less texture samplers available. The modern standard is 32 textures however. Some older cards will only support 16.

---
Tags: unity, textures, optimization, texture-atlas
---


# Question
Title: Metaballs created through raycasting in fragment shader - billboards are still recognizable
Good day everyone,

I'm currently programming a fluid simulation through use of metaballs and I have a very specific problem/question.

The steps I use for metaball simulation: 1. Simulate particles' positions 2. Create billboards that always face the camera with the particles' positions at its center 3. Cast a ray from camera to every fragment/pixel and determine the value of every particles' contribution along the ray.

Currently, I have nice looking metaballs with lighting, however, when you look closely you can see the edges of a billboard that is infront of another metaball because the colors are slightly off. The fragments that fail the raycasting test get discarded, but they are obviously still somehow interfering and I just don't know how or why.

Want I want to know, because I have thought about it and didn't come to a conclusion: since the actual fragments of the billboards where there is no implicit surface are discarded, that means that not the color value of the "obstructing" discarded billboard gets changed, but instead that of the actual goal billboard. where are possible points of conflicts that may create this behaviour?

Thanks in advance!

EDIT: I think I am wrong about my earlier assumption: the raycast used to determine the implicit surface most likely hits a metaball BEHIND the billboard, so it actually doesn't get discarded... it then takes the normal of the actual intersection, but uses the light direction vector that is made by using the fragment's position, not the actual intersection. So, my guess is that I need a better condition to let the raycast know it didn't hit anything instead of continuing and hitting a ball that is a little further away.

# Answer
I solved it and it was a rather stupid mistake on my part.

I post this though because it might help others using raycasts to create surfaces, even though the answer "should" be obvious: When calculating the vectors used for lighting, I used the billboard fragment's position instead of the intersection point. The mistake is easy to make because you are actually setting the color for the billboard fragment, but you actually do it by "acting" as if you were coloring another fragment. So: unless it's about the raycast itself, always use the intersection point, not the billboard point!
> 2 votes

---
Tags: shaders, graphics, raycasting, fragment-shader
---


title: Animator Bool or Trigger?

text:
# Question
Title: Animator Bool or Trigger?
I'm wondering about these two things. for what is better to use Bool rather than Trigger ? If i'm going to use Trigger, I should use it for what ?

# Answer
> 14 votes
The Bool type is appropriate for representing a state that holds true over a period of time e.g. carrying an item or entering sneak mode .

The Trigger type is appropriate for representing an action that will occur for a short period e.g. recoil from a gun firing or stumbling after a collision. Usually after this action is complete the animation returns back to a normal or default state.

From a mechanical perspective a value passed to Animator.SetBool() will persist within the animation system until changed by a subsequent call to this method. Conversely if a true value is passed to Animator.SetTrigger() the value within the animation system will be automatically reset to false after it has been used in a state transition.

---
Tags: unity, animation
---


# Question
Title: How do I create an animation without noticeable loops?
I'd like to create vivid idle and passive animations for a creature, but I want to avoid the appearance of obvious loops in the animation and avoid the use of obviously-identifiable pre-baked animation clips.

How can I accomplish this?

# Answer
Make your animation duration the Least Common Multiple of varying loop times. For example, to make a looping atom animation, with a nucleus and 3 'electrons', I might have 3 spheres rotating around a center. Each orbit would have a different period.

Electron 1: 1 sec orbit

Electron 2: 2 sec orbit

Electron 3: 3 sec orbit

Using the LCM method, we'd arrive at a loop length of 6 seconds. This loop will be much more subtle than if they all looped over 3 seconds.

One other thing to note is to make sure that your start and end frames are not identical - meaning.. If you animate from 0 degree rotation to 360 degree rotation over 60 frames, your loop is really 0-59. Your final frame of the loop should be the frame before you're back to start. Otherwise, you'd have a duplicated frame in your loop.
> 1 votes

# Answer
The easiest way to do this is to make sure there are common start and end points of the animations to link them together smoothly. You could choose to have all animations start and end at exactly the same point, however this might be fairly obvious. You could have a few start and end points, with multiple animations for all the start and end points, this should minimize the looping effect.
> 0 votes

# Answer
MotionBuilder is a good tool for cleaning up animations to make nice cycles.

Failing that: if it's just an idle animation, you could just ping-pong the animation to avoid glitches. That is, when you get to the end of the animation start playing backwards until you get to the beginning and then start playing it forwards again. It's a clumsy hack but might work for some anims.
> 0 votes

# Answer
Procedurally vary the timing of your animation frames. Instead of having each animation always take the same time, randomize the duration a bit. For example, if the character's idle animation is simply turning their head left and right, randomized timing will give the appearance that the character's view sometimes lingers on things, sometimes sways casually through the landscape and sometimes twitches nervously because they thought they saw something.

While I would certainly not suggest doing that for running (where any irregularity in rhythm would look unnatural) or more active actions like attacking (where timing is too important to be left to chance), it can help to make a simple idle animation look more natural.

Another thing you can do to make idling look more natural is to have multiple idle animations and cycle them in a random order.
> 0 votes

---
Tags: ai, skeletal-animation
---


# Question
Title: How to be two while creating game assets
A friend and I are developing our first game, he as a graphic artist and I as a developer.
I'm confident with his drawing art and he his confident with my development skills, but the discussion comes when we are designing other art assets togethert, such as sound, music, screenplay, gameplay...

We often argue on subjective matters, such as "It would be better if there are more narratives" or "In my mind the music is too peaceful".

How would you recommend to collaborate on these art work?

# Answer
I know from personal experience that even slight differences in creative vision can easily tear a team of volunteers apart. In more professional development teams there is usually a lead designer who has the final say on all creative decisions, but when neither of you is paying the other for their work, it is hard to agree on who of you that is supposed to be. If you want to work in a relation where you both see eye to eye, it is important that you make sure you both are on the same page.

First of all, it is helpful to agree on the style of gameplay, narration and atmosphere as closely as possible *before* even the first bit of work is done. Otherwise you risk that both of you feel the need to defend the work you have already done and are less able to make compromises. During this meeting you might realize that you two actually have vastly different creative visions and in fact want to make two completely different games. That means that unless one of you volunteers to take the creative backseat and make the game the other person wants to make, it might not be a good idea to work together.

But remember that game design is an incremental process. After a while you might realize that neither of you really likes the directions you initially agreed to anymore. In that case you can agree on changing the direction, but it is important that you make that decision together.

Another important technique to avoid unconstructive power struggles is a clear separation of responsibilities and creative control. Go through all the aspects mentioned in the question and decide who of you is in control of each. The other person is of course encouraged to give feedback. But that feedback should usually be more substantial than just personal preference and backed up by objective arguments. The only subjective argument you might want to allow is "this doesn't work well together with \[thing I am responsible for\]", because with such a separation of powers it is easy to create an inconsistent work.

But most of all, remember that this is your first game. You both are still learning. It is OK when it is not perfect. You should concentrate on making a playable product. Do not let misguided perfectionism get in the way of that. Yes, your first game will probably suck. But that's OK. Too many projects died because the developers just couldn't settle for a "good enough" solution but lacked the skills and resources to deliver the "perfect" solution they envisioned. Creating stuff that sucks and then reflecting on why it sucks is the first step on the road to creating greatness.
> 1 votes

---
Tags: art, project-management
---


# Question
Title: spriteBatch.draw is not getting overloaded
I am following this tutorial from gamefromscratch.com tutorial 11. I am using **libGdx** framework in **Android studio** .

```
public class OrthogonalTiledMapRendererWithSprites extends OrthogonalTiledMapRenderer {

public OrthogonalTiledMapRendererWithSprites(TiledMap map) {
    super(map);
}

@Override
public void renderObject(MapObject object) {
    if(object instanceof TextureMapObject) {
        TextureMapObject textureObj = (TextureMapObject) object;
            spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY()); // getting error in this line
    }
}
}

```

I am getting an unresolved error in the following line

```
spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY());

```

The code in render() method is

```
public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    }

```

I am new in game development please help me solve this error. Thanks in advance

# Answer
The issue seems to be that `spriteBatch` isn't available in the scope. The tutorial you've referenced uses `this.getSpriteBatch()` to get a `SpriteBatch` to use while rendering, but as the comments on the tutorial page point out, this method isn't available anymore.

Instead of `spriteBatch` or `getSpriteBatch()`, you have to use the more abstract version `getBatch()` which is inherited from `OrthogonalTiledMapRenderer` which inherits the method actually from `BatchTiledMapRenderer`.
> 0 votes

---
Tags: libgdx, android-studio
---


# Question
Title: How to render this stereopanorama for VR in unreal engine4
How to render this stereopanorama for VR in unreal engine4

# Answer
It's 2 equirectangular images stacked one on top of the other. The top is the left eye, and the bottom is the right eye.

What you need to do is place the camera inside a sphere and project the top half of the image onto that sphere and render it for the left eye, then project the bottom half onto the sphere and render it for the right eye.

To do that, the texture coordinates you use should map the x-coordinate of the texture map to longitude and the y-coordinate to latitude. Here are the equations used to do that:

> x = (λ - λ0) * cos(φ1);
>
> y = (φ - φ1);

where:

> λ is the longitude of the location to project;
>
> φ is the latitude of the location to project;
>
> φ1 are the standard parallels (north and south of the equator) where the scale of the projection is true;
>
> λ0 is the central meridian of the map;
>
> x is the horizontal coordinate of the projected location on the map;
>
> y is the vertical coordinate of the projected location on the map.

So to get your texture coordinates for each vertex, you can do the following:

```
GLfloat getThetaForXandY(const GLFloat x, const GLfloat y)
{
    GLfloat result  = atan2f(x, y);
    if (result < 0.0f) {
        result += M_PI * 2.0;
    }

    return result / (M_PI * 2.0);
}

GLfloat getPhiForA(const GLfloat a)
{
     return acos(a) / M_PI;
}

```

Here `a` is a value between 0 and 1 and can just be the `y` coordinate of your vertex. (Note that the code's `theta` is the equation's `lambda`.)
> 2 votes

---
Tags: unreal-4, virtual-reality, htc-vive
---


# Question
Title: optimizing collision detection with stationary objects (walls, floors, obstacles, etc.)
For detecting collisions between sprites, I know a 2D spatial hash is a way to optimize the number of collision checks that need to happen. But is there a way to optimize even further for objects that we know won't be moving in the scene? My sensibilities tell me that there should be because:

* We know exactly where the object is at all times.
* (At least in my game) there are bound to be a **lot** of floor/wall/ceiling tiles, far more than would be efficient to include in the spatial hash.

So, is there a way to optimize collision detection for this use case?

# Answer
You use separate quadtrees (or flat 2D arrays) one for static objects, one for moving objects.

This way the static objects won't need to be checked against other static objects.

Your tilemap itself can be that static object array.
> 1 votes

---
Tags: 2d, collision-detection, sprites, optimization
---


title: Depth test -opengl

text:
# Question
Title: Depth test -opengl
Does depth test runs before fragment shader,hence not even processing the fragment with frag shader if fragment is discarded Or It first runs the fragment shader and then depth test I.e. fragment shader runs for even the discarded frags.

If prior is false,then can it be achieved some how?

# Answer
> 0 votes
The answer is: **Both**.

If your fragment shader writes to `gl_FragDepth` it will do the depth test **after** your shader.

If you leave `gl_FragDepth` alone it will do the depth test **before** your shader.

source: https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/gl\_FragDepth.xhtml

---
Tags: opengl, shaders, graphics, depth-buffer
---


title: Enable/ Disable Line Renderer points

text:
# Question
Title: Enable/ Disable Line Renderer points
I have a Line Renderer component with 4 points, I would like to disable and enable the last 2 points at a certain time. My question is, how would I in code (C#) enable and disable individual Line Renderer points?

Thanks in advance!

# Answer
> 2 votes
As mentioned in a comment above, you can't enable or disable individual points in the LineRenderer. But, you can change/add/remove points dynamically, which can get a similar effect.

Here's a sample script that builds a random zig-zag path by adding segments to the end of the line, then progressively chops the line back until it disappears completely.

```
[RequireComponent(typeof(LineRenderer))]
public class RandomZig : MonoBehaviour {

    LineRenderer _line;

    public int maxSize = 30;

    public float delay = 0.25f;

    // Use this for initialization
    void Start () {
        _line = GetComponent<LineRenderer>();
        StartCoroutine(AddSegments());
    }

    IEnumerator AddSegments()
    {
        float previous = 0f;
        for(int i = 0; i < maxSize; i++)
        {
            _line.SetVertexCount(i + 1);

            float wander = previous + (Random.value - 0.5f) * 2f;

            _line.SetPosition(i, Vector3.forward * i + Vector3.right * wander);
            // Note you can use SetPositions if you need to assign a whole array at once.

            previous = wander;

            yield return new WaitForSeconds(delay);
        }

        StartCoroutine(RemoveSegments());
    }

    IEnumerator RemoveSegments()
    {
        for(int i = maxSize - 1; i > 0; i--)
        {
            _line.SetVertexCount(i);

            yield return new WaitForSeconds(delay);
        }
    }
}

```

---
Tags: unity, c#, rendering, game-component, lines
---


title: Libgdx: how to pick a random texture?

text:
# Question
Title: Libgdx: how to pick a random texture?
I'm trying to pick a random texture from a fodler placed in assets and use it but it's giving me errors. I'm doing so in the main game screen class

```
    final  File dir = new File("img");
    Random rand = new Random();
    File[] files = dir.listFiles();
    File file = files[rand.nextInt(files.length)];
    Image = new Texture(Gdx.files.internal(file.getPath()));

```

The error is

```
java.lang.NullPointerException: Attempt to get length of null array

```

to my knowledge this error should only be there if `File[] files = dir.listFiles();` is null, and it isn't, currently two pictures are there. So what's happening?

I tried supplying the full path in the first line to `img` folder but to no avail. Plus I don't want to supply the full path anyway, it will change from device to another.

# Answer
Use the FileHandle from libgdx. With *Gdx.files.internal()* you access to your assets folder.

Try this :

```
// Get directory
FileHandle dir = Gdx.files.internal("img");

// Get a random texture of dir
Texture randomTexture = new Texture(dir.list()[random.nextInt(dir.list().length)]);

```

Should work perfectly if your textures are in *assets/img/*

Hope it helps
> 1 votes

# Answer
Try to refresh (right click \> refresh) the folder, which contains the files you want to load, within eclipse (or whatever else you are using). This solved many problems I had loading files so far.
> 0 votes

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


# Question
Title: Do games process all received user input?
A mouse might have a frequency of 125Hz, meaning that the system will read off the mouses position every 8ms. Keyboards work in a similar manner.

If a key is pressed and held down, events are continuously raised.

**Does every one of these events make it to the game loop?**

I imagine that if the game loop does not complete fast enough, the user interactions will buffer, causing a noticeable interaction latency.

I can think of ways to deal with this:

* Add a maximum size to the input buffer so that as new events arrive, older ones are pushed from the front of the queue as the new events are pushed to the back of the queue (enqueued).
* When the key is pressed, send a "key-down" message and let the game loop repeat the received message until a "key-up" message is received.

**Can anyone think of other ways to deal with user input, and do any of my suggestions have obvious flaws?**

**UPDATE** I am not developing a game, I am doing research and so my above questions are purely academic. I am not using any API.

# Answer
> 2 votes
It depends on what kind of API you are using to read user input.

There are polling-based APIs where you read the current state of input devices in your game when it is convenient (like Unity). When that happens too infrequently, it is possible to miss input events. To avoid that from happening, the loop which handles input should run faster than the graphics loop.

There are event-based APIs where your program has an event queue it needs to process (like WinAPI). In such APIs, the event queue can *theoretically* overflow, but *practical* this is rarely a problem, unless you need a very long time to handle some events.

There are also event-based APIs where you assign event handler functions to certain input events (like in browser-based Javascript). These functions are called the moment the event happens. These usually do not miss events. But the drawback is that you often have little control over when these event handlers are called, so you don't know what state your application is currently in when it happens. It can often be smart to turn these into a queue-based API by having those event handlers push the events to a global event queue which you then process at a controlled moment of your game loop. That way you have better control over when events are processed.

You did not mention what platform and API you are using to develop your game, so you need to check for yourself what options you have available.

---
Tags: input
---


# Question
Title: How to swap out the visual mesh component of an actor at run-time
I am attempting to replace the visible component of a pawn with a different component at runtime (in my case a `UCustomMeshComponent` with randomly generated vertices) and running into problems.

I set up my pawn like this in its constructor (where `OurMesh` is a `UCustomMeshComponent *` member variable):

```
ATestGeomPawn::ATestGeomPawn() : OurMesh(NULL)
{

    PrimaryActorTick.bCanEverTick = false;
    AutoPossessPlayer = EAutoReceiveInput::Player0;

    // root is a scene component so this is placeable in the editor
    RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent"));

    // camera attached to root
    UCameraComponent* Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("OurCamera"));
    Camera->SetupAttachment(RootComponent);
    Camera->SetRelativeLocation(FVector(-250.0f, 0.0f, 250.0f));
    Camera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f));

    // create an initial visible component
    RegenGeometry();

}

```

And `RegenGeometry()`'s intent is to set up the new component, destroying the old one if it exists (first time through it won't). `RegenGeometry()` may be called at any time (in my tests I have it bound to an action event):

```
void ATestGeomPawn::RegenGeometry() {

    // destroy old mesh
    if (OurMesh) {
        OurMesh->DestroyComponent();
        OurMesh = NULL;
    }

    TArray<FCustomMeshTriangle> tris;
    // code for setting up tris omitted for brevity

    // create and attach new mesh
    OurMesh = NewObject<UCustomMeshComponent>(this);
    OurMesh->SetCustomMeshTriangles(tris);
    OurMesh->SetupAttachment(RootComponent);

}

```

However, this leads to all sorts of bad results. I've tried various hand-wavey iterations of this:

* The code as shown above just crashes the editor immediately, *even if I don't actually have an `ATestGeomPawn` placed in the map*.
* If I use the now-deprecated `NewNamedObject` instead, with the same name every time, it works initially but subsequent calls to `RegenGeometry()` cause the mesh to disappear, with weird results shown in this video I made.
* If I use `NewNamedObject` but generate a new name every time, it works initially but does not remove the initial component from the hierarchy, and has a similar visible outcome to the above, shown in this other video I made.
* If I call `RegenGeometry()` in `BeginPlay()` instead of the constructor, it is never visible.

How do I do this properly?

I'm *super* new to the Unreal SDK, as in yesterday morning I was doing a crash course through tutorials and docs to try and get this done. I eventually arrived at the above. I have a feeling that my mistake here is some misunderstanding of life-cycles, replication, or maybe e.g. ~~reference counting due to say player input on the pawn or something~~:

Update: The player input theory is eliminated. I tried the exact same thing as above but with a regular actor instead of a pawn (camera eliminated, no player input, just `RegenGeometry()` in constructor and nothing else), and the editor crashed in the same way. So it isn't related to this being a pawn.

I'm not sure which direction to head in next.

(Full source, if relevant: TestGeomPawn.h and TestGeomPawn.cpp; the "grow" stuff I just threw in from the tutorial to make sure player input was working)

# Answer
> 0 votes
So after a lot of hunting I stumbled on somebody else's code, and it turns out the problem is in the component creation. `SetupAttachment` isn't the right thing to do for runtime-created components. Instead of:

```
OurMesh = NewObject<UCustomMeshComponent>(this);
OurMesh->SetCustomMeshTriangles(tris);
OurMesh->SetupAttachment(RootComponent);

```

I changed it to:

```
OurMesh = NewObject<UCustomMeshComponent>(this);
OurMesh->RegisterComponent();
OurMesh->SetCustomMeshTriangles(tris);
OurMesh->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform, NAME_None);

```

And it seems to be working, aside from the component initially created in the constructor sticking around in the object tree the whole time (which seems to be related to "default" values, but it doesn't seem to be having any bad effects, so...).

---
Tags: c++, unreal-4, unreal
---


title: What is time based endless game called?

text:
# Question
Title: What is time based endless game called?
Im making a project proposal for a game whose gameplay involves endless road where player just has to dodge obstacles but it also has time limit. Its as if temple run but can only be played for certain time limit and you have to make as high score as possible within that time. Temple run can be called as "endless runner" game but if it had time what would it be called. I want to know how would you describe this game type in one or two words? As in "first-person-shooter" or "Racing" etc??

# Answer
According to some definitions, an "endless runner" is a game that requires forward motion at all time.

http://www.giantbomb.com/endless-runner/3015-7179/

Thus it requires only that the player can't stop moving; i.e., that the motion does not end. It does not require that the game itself does not end.

So your game would be an endless runner if the player is forced to keep moving, irrespective of the duration or whether the end of the game/level is based on a timer or a certain distance travelled (and, in fact, these would be the same thing in most "endless runners", as the player usually move along at the same speed).
> 1 votes

---
Tags: game-design, graphics, education
---


# Question
Title: Wait for AudioClip finish before destroy Object
If I Play the gun sound on my "bullet" object, how can I prevent the end of Audio sound if the bullet hit something so it destroy. To clarify:

Bullet prefab -\> Audio Source -\> Audio Clip = MachineGun.mp3 PlayOnAwake = true

When I instantiate bullet, MachineGun AudioClip is played. But the bullet is fast and hit something before the clip is end. This Kill the machine audio effect making it irrealistic.

How can I tell Unity "Play the sound to the end, despite the object is destroyed".

I've tried

Destroy(gameObject, AudioClip.length)

But it seems not works

# Answer
> 1 votes
One option is to use AudioSource.PlayClipAtPoint(), this will create a new audiosource for the clip at the given position and then automatically clean up after the playback is complete.

---
Tags: unity, audio
---


title: Mapping polar coordinates to cube

text:
# Question
Title: Mapping polar coordinates to cube
I am trying map polar coordinates to points on a cube. I was able to map the front, back, left and right faces of the cube, but I am struggling with the top and bottom. Here is what I have:

```
/// <summary>
/// Converts polar coordinates to uv coordinates on a cube.
/// </summary>
/// <param name="p">The polar coordinate; p.x = longitude, p.y = latitude.</param>
/// <param name="face">The face of the cube that p maps to.</param>
/// <returns>The xy coordinate on the cube face.</returns>
private Vector2 PolarToCubeFace(Vector2 p, out CubemapFace face)
{
    face = CubemapFace.Unknown;
    Vector2 result = Vector2.zero;

    float lng = p.x; // East-to-West.
    float lat = p.y; // North-to-South.

    if (lat >= 45 && lat <= 135){ // Front, back, left, or right face.
        face = (lng > 0 && lng <= 90) ? CubemapFace.PositiveZ :
            (lng > 90 && lng <= 180) ? CubemapFace.PositiveX :
            (lng <= -90 && lng > -180) ? CubemapFace.NegativeZ :
            CubemapFace.NegativeX;

        result.y = (lat - 45) / 90f;
        result.x = mod(lng, 90) / 90f;
    }
    else{ // Top or bottom face.
        // Need help here.
    }
    return result;
}

```

# Answer
> 1 votes
Usually you'd do this by first mapping from spherical coordinates to a cartesian vector on a sphere:

```
float cos = Mathf.Cos(latitude);
Vector3 v = new Vector3(
              cos * -Mathf.Sin(longitude),
              Mathf.Sin(latitude),
              cos * Mathf.cos(longitude));

```

This particular version puts Longitude zero in middle of the PositiveZ face, but you can change this as needed.

Next, to figure out which cubemap face we're in, we need to check which component of this vector is greatest in absolute value:

```
Vector3 abs = new Vector3(Mathf.Abs(v.x), Mathf.Abs(v.y), Mathf.Abs(v.z));

int greatestIndex = 0;
for(int i = 1; i < 3; i++)
    if(abs[i] > abs[greatestIndex])
        greatestIndex = i;

```

By dividing by this greatest value, we scale the vector v so that it sits on a unit cube:

```
v /= abs[greatestIndex];

```

Now we just need to read the appropriate components for which face we're on:

```
CubemapFace face;
Vector2 facePos;

switch(greatestIndex)
{
    case 0:
        if(v.x > 0)
        {
            face = CubemapFace.PositiveX;
            facePos.x = v.z;
            facePos.y = v.y;
        }
        else
        {
            face = CubemapFace.NegativeX;
            facePos.x = -v.z;
            facePos.y = v.y;
        }
        break;
    case 1:
        if(v.y > 0)
        {
            face = CubemapFace.PositiveY;
            facePos.x = -v.x;
            facePos.y = v.z;
        }
        else
        {
            face = CubemapFace.NegativeY;
            facePos.x = -v.x;
            facePos.y = -v.z;
        }
        break;
    case 2:
        if(v.z > 0)
        {
            face = CubemapFace.PositiveZ;
            facePos.x = -v.x;
            facePos.y = v.y;
        }
        else
        {
            face = CubemapFace.NegativeZ;
            facePos.x = v.x;
            facePos.y = v.y;
        }
        break;
}

```

Here the facePos coordinates are in the range -1...1, with the x coordinate increasing as we move eastward across the four equatorial faces. The top and bottom faces are oriented to align with the PositiveZ face. All this is easy to change if you need a different orientation convention.

---
Tags: unity, c#, mathematics, coordinates, trigonometry
---


title: Why isn't OnCollisionEnter2D working?

text:
# Question
Title: Why isn't OnCollisionEnter2D working?
I've made a hole. I have animals tagged as animals. When an animal walks into the hole, they disappear. I tried `OnTriggerEnter2D()` as well, and set the collider to `isTrigger`, but it still didn't work. I can get it to work without the tag part, but anything that bumps into each other sets each other to inactive.

```
public class BlackHole : MonoBehaviour
{
    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "animal")
        {
            other.gameObject.SetActive(false);
        }
    }
}

```

# Answer
The fact that this *works*, but *only* if you omit the tag statement, implies that the only possible cause derives from your tagging. You must ensure that the required game objects have the *exact* same tag; in this case, `animal`. Tags are case sensitive, so a game object tagged as "Animal" will not return `true` if you check for a tag of "animal".

As a final note, when we create custom tags, they do not automatically apply to a game object - even if we have been directed to the custom tags screen through the tag selection for that game object. It is fairly easy to forget this, but we *must* actually set the tag to the game object, after creating it.
> 1 votes

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


# Question
Title: Maximum audio delay before the player notices?
Given some event in a game, what is the maximum delay to producing audio that the player will properly associate the audio with that event (and not perceive lag)?

# Answer
> 52 votes
The following result are calculated for lip synchronization which is concidered to be *"the most noticeable a/v sync error"*.

---

Wikipedia says

> For television applications, audio should lead video by no more than 15 milliseconds and audio should lag video by no more than 45 milliseconds. For film, acceptable lip sync is considered to be no more than 22 milliseconds in either direction.

---

The Media and Acoustics Perception Lab says

> The results of the experiment determined that the average audio leading threshold for a/v sync detection was 185.19 ms, with a standard deviation of 42.32 ms

---

The ATSC says

> At first glance it seems loose: +90 ms to -185 ms as a “Window of Acceptability”

and

> * Undetectable from -100 ms to +25 ms
> * Detectable at -125 ms & +45 ms
> * Becomes unacceptable at -185 ms & +90 ms
>
> (– Sound delayed,+ Sound advanced)

---

**To conclude**

The results aren't so far from one another. It seems that the maximum acceptable delay is around 150ms, which is 9 frames at 60 frame per second.

# Answer
> 9 votes
## It depends of the event

Feeling that, say, an explosion you see and hear is a single event will have the tolerances described in other answers - no more than ~50ms; some people may be more sensitive (e.g. musicians), so I'd suggest to aim at 30ms or no more than 2 frames at 60fps.

I believe that the perceived distance should affect those tolerances. People expect far sounds to be slightly delayed, since in real life sound lags sight by approximately 1ms per each foot of distance. So an explosion on an zoomed out RTS game 'map' might have a larger tolerance for sound lag than the player firing their own gun in an FPS.

Specialized cases, such as having a proper feel for a music/rythm game may require much tighter tolerances, 15-20ms or even lower - for example, if the player hears both the "input action" such as singing into a mic or banging a plastic instrument, and also a sound generated by your system for the same event, then a 50ms lag will cause the "original" and "played" sounds to mix weirdly.

In addition, keep in mind the lag between start of the audio file and the "event" inside that audio file - in many audio clips, the "event" won't be right on the edge, you may have a sound of a lightning strike where the 'strike' happens 200ms after the beginning, which would be obvious to everyone, and pretty much all sound files, even a drum-hit, will have *some* delay there.

## Don't measure averages - look at worst case

Sight&hearing are deeply connected in human perception, and if one of them stutters relatively to other, then it will be perceivable. It's not okay if most of the time it's very fast but occasionally there's a 0.2 second delay while something is loading - people will notice such situations. This is why audio is often kept running on a separate thread, isolated from the other activities and just getting rapid notifications on what preloaded clips should be played.

# Answer
> 5 votes
Any situation where a player causes the sound (music games, guns in FPS) will need very low delay as the player has sent an impulse to make it happen at that moment, so as with a musician hearing their instrument delayed, will be particularly aware of very small delays. Sound engineers fret about recording delays below 5 mSec ruining the "groove"

The Journal of the American Academy of Audiology states that people (not just musicians), when listening to their own voice delayed, are aware of delays as short as 3mSec, and a delay of longer than 10 mSec was objectionable 90% of the time .

Humans use the time delay between their ears for directional information, and thus must be able to process and extract information from delays below 1mSec

The 185.19 ms quoted above is irrelevant as it is referring to a leading sound error, and anyhow, to what people found acceptable when passively watching a film, not actively engaged in a game.

# Answer
> 5 votes
The accepted answer here mainly discusses perception of audio synchronization in passively watching video. In these cases, the audience can't easily pin down exactly when the audio should play except by attending to telltale signs in the video. This means they have limited anticipation of the sound.

There are two important cases in games where this low-anticipation assumption doesn't hold:

1. When the **player themselves caused the sound** (as SamB points out), so from the moment they form the intent to press the button they know exactly when they expect to hear the sound.
2. When the **sound is supposed to land on on a periodic beat**, as in music games or anything with a ticking timer/counter, this rhythm allows the player to anticipate the next sound and notice if plays out of time.

In this talk from GDC 2013, Mathieu Pavageau argues that players can perceive differences in synch precision **above about 5ms**, much less forgiving than the examples from lip synching would suggest. Check out the sections "Time Perception Examples" and "Example of Ubisoft Games" to hear it for yourself. You can hear the Rayman Origins menu doesn't sound "laggy" per se when synched within 16 ms (video frame), but when synched within 5 ms it sounds noticeably better & tighter.

Pavageau advocates using a low-level audio callback to get this kind of sub-frame precision if you want tight-feeling rhythmic gameplay of this variety.

# Answer
> 2 votes
For games which require a person to react to audio cues, every millisecond by which the sound is delayed will cause the person's response to likewise be delayed. Someone who is simply watching a movie or cut-scene may not notice too much if the audio and video aren't exactly in sync, but it's often important and sometimes critical that audio be in sync with *what the player is expected to be doing*.

# Answer
> -1 votes
In theory, everything above 50ms can be noticeable when it comes with it's association to pictures, at 25ms you can start hearing a sound and its delay as two separated sounds, so I would say I'll highly recommend you stay under 50ms and if you can even stay at something from 5ms to 15ms it would be really nice.

I hope this will help you!

https://en.wikipedia.org/wiki/Delayed\_Auditory\_Feedback

---
Tags: audio
---


title: Why is sin = Y and cosine = X?

text:
# Question
Title: Why is sin = Y and cosine = X?
I'm new to game development in some phases and I want to understand everything I do (at least most of it) so I've started developing in MonoGames framework (XNA) and I saw a function like this.

```
rocket.angle = System.Math.Atan2(rocket.rocketdirection.X , -rocket.rocketdirection.Y);

```

I didn't understand this function (I was following a tutorial) and dove deeper into understanding `sin`, `cos` and `tan`. Now I have some understanding over it but one thing is unclear to me.

This was shown to me in a way to show how you calculate `sin`, `cos` and `tan` and I didn't understand it.

* Why is the circle represented as 1,1 and -1,-1?
* And why is `Y = sin` and `X = cos`?
* And through this `tan = cos/sin`?

Can somebody explain this picture in a better way, in a way that is relatively easy to understand?

# Answer
I will try to answer briefly.

1. **Why is the circle represented as 1,1 and -1,1?**

This thing is usually called *Unit Circle*, because its radius equals to *1*. How it is relative to trigonometry you're trying to solve? Let's see.

2. **Why is Y = sin and X = cos?**

Well, let's look at the picture I've made five minutes ago (sorry, it's not the best my work).

You can mention at the picture the point B with coordinates \\$X, Y\\$ and the constructed triangle \\$ABC\\$. First of all, this is the **right triangle**. So we can continue our mind work.

The definition of sine states: \\$sin(φ)\\$ is the ratio of the length of the **opposite to angle \\$φ\\$** side and the length of the **hypotenuse**. For our example \\$sin(\angle BAC) = \frac{BC}{AB}\\$ because \\$BC\\$ is **opposite** to \\$\angle BAC\\$ and \\$AB\\$ is simply hypotenuse.

As you can see,

a) \\$BC\\$ equates to \\$y\\$.

b) \\$AB\\$ equals to 1 (because it is a **Unit Circle** and \\$AB\\$ is a radius).

c) \\$\frac{BC}{AB} = \frac{y}{1} = y\\$, so \\$sin(\angle BAC) = y\\$.

The same logic easily can be applied for *cos* but this time we will talk not about **opposite side** to the angle, but **adjacent side**. In other words, \\$cos(φ)\\$ is a ratio of the length of the **adjacent to angle \\$φ\\$** side to the length of the **hypotenuse**.

In the same way we see that \\$cos(\angle BAC) = \frac{AC}{AB} = \frac{x}{1} = x\\$.

3. **How we can see that \\$tan = \frac{sin}{cos}\\$?**

Well, it is the easiest part. The \\$tan(φ)\\$ of the angle \\$φ\\$ is the ratio of the length of the **opposite to the angle \\$φ\\$** side and the length of the **adjacent to the angle \\$φ\\$** side.

For our example \\$tan(\angle BAC) = \frac{BC}{AC} = \frac{y}{x}\\$. I hope this is a clear starting explanation.

Further reading about the unit circle
> 20 votes

# Answer
When you ask **Why is sin = Y and cosine = X?** I read your question as **Why is the function that gives me the Y axis called "sin" and why is the function that gives me the X axis called "cosine"?**, so I'll start by answering that...

At its heart, it is a naming convention. If you have a unit circle with the common trigonometric functions...

... you'll see that all the function that go to the Y axis are "co" something (cosine, cosecant, cotangent).

Looking at the same unit circle you will find that `cos(θ)` and `sin(θ)` will give the X and Y coordinates respectively for the point on the unit circle that is at `θ` angle from the X axis.

These functions where historically defined in terms of circles, in fact they come from the Sanskrit `Jyā` (sine) and `koti-jyā` (cosine), which where the names of those functions used by Indian mathematicians circa 500 AD. They were later translated to Latin, and from there to English. *But, you don't care about that, you care about making games (or solving math problems, or whatever)!*

---

**Why is the circle represented as 1,1 and -1,-1?**

It is a *unit circle*, that means that it is a circle with radius = 1, and thus it reaches down to -1 and up to 1. The reason why they use radius = 1 is because this makes it easy to scale the functions to a different radius.

**And why is Y = sin and X = cos?**

You may wonder why they aren't the other way around. Well, they had to be one way or the other, and whichever it was you would be asking the same... so the answer is: for historic reasons.

**And through this tan = cos/sin?**

No, this is **WRONG**. Actually `tan(x) = sin(x) / cos(x)`.

I hope to demostrate this in an intuitive manner. To start let's take the 0BC triangle from the image above:

I have added `cos` in the triangle for ease of reference (`sec` was removed because we don't need it).

We can see this triangle is a Right Triangle, and also that it contains another smaller Right Triangle. Furthermore, both triangles have one angle with the value `θ`, therfore they are Similar Triangles. Which means that we can map one triangle over the other by only scaling, rotating and translating (moving). This can be seen in the following animation.

In the animation we used rotation and scaling, neither of these transformations changes the angles of the triangles.

Pay attention to what segment was mapped over what segment during the transformation. In particular:

* The magenta segment (`tan(θ)`) was mapped over the black segment (`1`).
* The olive segment (`sin(θ)`) was mapped over the green segment (`cos(θ)`)

Now, let's see what does that mean.

First `tan(θ)` went to `1`. Meaning that

```
scaling_factor * tan(θ) = 1
=>
scaling_factor = 1 / tan(θ)

```

So the scaling factor is `1 / tan(θ)`.

Second, `sin(θ)` went to `cos(θ)`. Meaning that:

```
scaling_factor * sin(θ) = cos(θ)

```

By replacing the scaling factor we have:

```
1 / tan(θ) * sin(θ) = cos(θ)
=>
sin(θ) / tan(θ) = cos(θ)
=>
sin(θ) = cos(θ) * tan(θ)
=>
sin(θ) / cos(θ) = tan(θ)

```

And that's what we were set to demostrate.
> 11 votes

---
Tags: mathematics, monogame
---


# Question
Title: Restricting object going out of screen while resizing-LibGdx
I have an object that I am resizing from bottom to top.

```
private void setStickSize() {
    if (MyInputProcessor.isTap) {
        stickSprite.setSize(stickSprite.getWidth(),stickSprite.getHeight()+500.0f);
       stickSprite.setY(MathUtils.clamp(stickSprite.getY(),0,700));
       // MyInputProcessor.isTap = false;
       }

```

Here the sprite is growing out of the screen after calling this in update().I used clamp() to stop this sticksprite within the screen.But no effects on the code. Why clamp() is not working here? How can I restrict the sprite resizing effectively within the screen?

I am drawing the sprite like this.

```
    private void drawStick() {
     stickSprite.setPosition(stick.getX(),stick.getY());

     batch.draw(
            stickSprite.getTexture(),stick.getX(),stick.getY(),
             stickSprite.getWidth()/2 ,stickSprite.getHeight()/2,
             stickSprite.getWidth(),
             stickSprite.getHeight()*0.01f,
             stickSprite.getScaleX(),stickSprite.getScaleY(), 0,
            stickSprite.getRegionX(),stickSprite.getRegionY(),
            stickSprite.getRegionWidth(), stickSprite.getRegionHeight(),
             false,false);
        }

```

Entire gameScreen:

```
public class GameScreen implements Screen{

// ---objects
private SwatterGame game;
private AssetManager assetManager;
private final ScoreController scoreController;
private ObjectFactory objectFactory;
private Stick stick;
Sprite stickSprite;
// ----constructs
private ShapeRenderer shapeRenderer;
private SpriteBatch batch;
// ----Textures--
Texture bgTexture,platformTexture,stickTexture;

public GameScreen(SwatterGame game) {
    this.game = game;
    assetManager = game.getAssetManager();
    scoreController = game.getScoreController();
}

@Override
public void show() {
    loadAssets();
    game.viewPort.apply();
    game.camera.position.set(GameConstants.WORLD_WIDTH / 2, GameConstants.WORLD_HEIGHT / 2, 0);
    game.camera.update();
    batch = new SpriteBatch();
    shapeRenderer = new ShapeRenderer();

    MyInputProcessor myInputProcessor = new MyInputProcessor();
    InputMultiplexer im = myInputProcessor.returnInput();
    Gdx.input.setInputProcessor(im);
    initObjects();
   game.camera.zoom =3f; game.camera.update();
}

@Override
public void render(float delta) {
    clearScreen();
    batchDraw();
    update(delta);
    drawDebug();
}

private void loadAssets() {

    bgTexture = assetManager.get(Assets.background);
    stickTexture = new Texture(Gdx.files.internal("rect3.png"));
    stickSprite = new Sprite(stickTexture);
}

private void initObjects() {
    objectFactory=new ObjectFactory();
    player=objectFactory.createPlayer();
    stick=objectFactory.createStick();

}
@Override
public void resize(int width, int height) {
    game.viewPort.update(width, height);
    game.camera.position.set(game.camera.viewportWidth / 2, game.camera.viewportHeight / 2, 0);

}

private void drawDebug() {
    shapeRenderer.setProjectionMatrix(game.camera.projection);
    shapeRenderer.setTransformMatrix(game.camera.view);

    // player
    shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
    shapeRenderer.setColor(1, 0, 1, 1);
//  shapeRenderer.rotate(0.f, 0.f,1.0f, 45.f);
    rect(shapeRenderer, player.getCollisionRectangle());
    // stick
    rect(shapeRenderer, stick.getCollisionRectangle());
    shapeRenderer.end();
}

//shape rendering
private void rect(ShapeRenderer renderer, Rectangle rectangle) {
    shapeRenderer.rect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
}

private void circle(ShapeRenderer renderer, Circle circle) {
    shapeRenderer.circle(circle.x, circle.y, circle.radius, 100);
}

private void update(float delta) {
    player.update(delta);
    stick.update(delta);
    setStickSize();
}
private void batchDraw() {
    batch.setProjectionMatrix(game.camera.combined);
    batch.begin();
    //drawing background
    batch.draw(bgTexture,GameConstants.BG_X,GameConstants.BG_Y);
    batch.draw(platformTexture, GameConstants.PLATFORM_X,GameConstants.PLATFORM_Y);
    //drawBottom();

    drawStick();
    batch.end();

}

private void setStickSize() {
    float newHeight=stickSprite.getHeight() + 500.0f;
        if (MyInputProcessor.isTap) {
        stickSprite.setSize(stickSprite.getWidth(), newHeight);
      //    MyInputProcessor.isTap= true;

        }
        }

private void drawStick() {
     stickSprite.setPosition(stick.getX(),stick.getY());
   //  stickSprite.setSize(stickSprite.getWidth(),stickSprite.getHeight());
     stickSprite.draw(batch);
        }

private void clearScreen() {
    Gdx.gl.glClearColor(Color.GRAY.r, Color.GRAY.g, Color.GRAY.b, Color.GRAY.a);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}
}

```

# Answer
> 0 votes
**EDIT:**

```
// Set a fix y for you sprite
sprite.setY(fixY);

// Set a max height for your sprite
float maxHeight = Gdx.graphics.getHeight() - sprite.getY(); // Here you say that you want the max height of the sprite to be the difference between screen height and sprite.getY() so it will be in the screen

// Compute your new height
float newHeight = /* Compute new height here */;

// Set your height
sprite.setHeight(MathUtils.clamp(newHeight, 0, maxHeight));

```

This way :

You fix a Y for your sprite. Then compute the max height of your sprite, depending of his Y position and the screen height. For example :

```
 sprite.getY() = 80
 Gdx.graphics.getHeight() = 480
 maxHeight = 480 - 80 = 400

```

Then compute the new height of your sprite. Finally set this with the clamp you compute before.

I already said that before, but you should draw your sprite with `sprite.draw(batch)` so it really takes it's attributes to be displayed. Here you do some weird things in the batch.draw

---

Clamp works like this :

You put your value, then min and max, so if your value is superior to max it will return max and if your value is inferior to min it will return min. Here you're setting y by a clamp with min = 0 and max = 700. What you want to do is a clamp between 0 and max = 700 - sprite.getHeight().

In fact, your set Y here will not say anything if you are at Y = 700. But if you're screen height is \<= to 700 you won't see it. Because origin is at bot left corner.

If you want your sprite to stay IN screen, you should not clamp on Y, but on setHeight().

What you want is that sprite.getY() + sprite.getHeight() \< Gdx.graphics.getHeight()

---
Tags: libgdx
---


# Question
Title: Rich text in Debug message in Unity console
I'm currently writing a debug script and would like to add colors to certain parts of the debug messages. Reading the unity docs lead me to believe that I can use the Rich text formatting. Like it is explained here. I'm using the `Debug.LogForamt()`.

> Logs a formatted message to the Unity Console.
>
> For formatting details, see the MSDN documentation on Composite Formatting. Rich text markup can be used to add emphasis.

This is from the unity docs. My code looks like this :

```
Debug.LogFormat("Status of some gameObject is : <color = red>{0}</color>" +
"Status of another gameObjcet is: <color = red>{1}</color>",
gameObject1.activeInHierarchy,gameObject2.activeInHierarchy);

```

This just outpust the strings as plain text. What am I doing wrong ?

# Answer
> 1 votes
Have you tried to remove the extra spaces and / or set the color in hex format?

```
Debug.LogFormat("Status of some gameObject is : <color=#ff0000ff>{0}</color>" + "Status of another gameObjcet is: <color=#ff0000ff>{1}</color>", gameObject1.activeInHierarchy,gameObject2.activeInHierarchy);

```

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


title: Animated lighting in amusement parks

text:
# Question
Title: Animated lighting in amusement parks
What is the best way to handle animated lights on rides in a night time amusement park scene?

Is there a better way that doing lots of emission lights?

At the moment I have been using emission lights, but there could be a lot of them in a park (some are just static lights) and I would also like to animate some of them on some rides.

Best example I could find was from GTA 5:

Video: https://youtu.be/zVj8D0lqgl4?t=146

# Answer
> 3 votes
It's just an animated emissive texture that ignores incoming light. If you don't need them to actually provide light to the surrounding geometry the set the global illumination parameter for them to none and they will be cheap.

---
Tags: unity, lighting
---


# Question
Title: Make an object rotates by an arbitrary angle and rotates toward a target in Unity
I have an object facing up in Unity. I need it to move from point A to point B, without prior knowledge of where A and B are. So when I place it at point A, I need to rotate it toward point B. I used this:

```
this.gameObject.transform.rotation = Quaternion.FromToRotation(A.position, B.position);

```

However, before doing the movement, I also need to rotate the object by 90° around the X axis. I used this:

```
this.gameObject.transform.rotation = Quaternion.Euler(90.0f, 0.0f, 0.0f);

```

These two functions worked, but separately. When I try to use these two functions together, the last function called overrides the other.

# Answer
This should about do it I think. You can use the * operator to multiply quaternions together :

```
  float rotationAngle = 90 ;
        Quaternion qA = Quaternion.FromToRotation(A.position, B.position);
        Quaternion qB = Quaternion.AngleAxis(rotationAngle, Vector3.right);
        Quaternion qC = qA * qB;
        transform.rotation = qC;

```
> 0 votes

---
Tags: unity, quaternion
---


title: 2D collision detection for a block game

text:
# Question
Title: 2D collision detection for a block game
# Background Knowledge:

The player can be freely transformed around the screen but each block is locked to a grid. This grid is 16x16 pixels and the players bounding box is 20x44 pixels. The blocks are stored in a `List<MapObject> MapData` where `MapObject` consists of three variables (X, Y, type).

# Short Question

What is the best way to detect 2D collisions for a game that is made with thousands of blocks or is there a problem with what I am currently doing?

# Problem

I started off with simple AABB collision detection and it worked fine until I started adding a large map with over 54,000 blocks. Currently the code goes like this:

1. Loop through every object in the MapData list
2. Check Collision (Player, Object) return direction
3. Move player next to the object in the opposite direction of the collision

However, the problem with this is that it has to loop through thousands of objects some of them being very far away.

So I came up with another solution where I would create a matrix of blocks around the player. This method

```
public List<Vector2> GetNearByGrids(Rectangle playerRect, int gridDistance)

```

This method works like this:

1. Get the top, bottom, left and right boundaries of playerRect + gridDistance in pixels
2. Convert these boundaries into grid form
3. Fill in each grid cell within these boundaries and add them to the grid matrix

or the code

```
public List<Vector2> GetNearByGrids(Rectangle playerRect, int gridDistance)
    {
        /*
         * Create a bounding box "gridDistance" around the player
         * Check if any of the points are negative and set a bool
         * Convert Pixels->Grid
         * Add them to the grid matrix
         * return grid matrix
        */

        List<Vector2> gridMatrix = new List<Vector2>();

        int pxTop = playerRect.Y - (gridDistance * gridY),
            pxBottom = (playerRect.Y + playerRect.Height) + (gridDistance * 16),
            pxLeft = playerRect.X - (gridDistance * gridX),
            pxRight = (playerRect.X + playerRect.Width) + (gridDistance * 16);

        bool isTopNeg = pxTop < 0,
            isBotNeg = pxBottom < 0,
            isLeftNeg = pxLeft < 0,
            isRightNeg = pxRight < 0;

        float top = 0, bottom = 0, left = 0, right = 0;

        #region Pixel->Grid Conversion If/Else
        if (isTopNeg)
        {
            if (-pxTop <= gridY)
                top = -1;
            else
            {
                float temp = (((float)pxTop) / gridY) - 1;
                top = (int)temp;
            }
        }
        else
        {
            if (pxTop <= gridY)
                top = 1;
            else
            {
                float temp = (((float)pxTop) / gridY) + 1;
                top = (int)temp;
            }
        }

        if (isBotNeg)
        {
            if (-pxBottom <= gridY)
                bottom = -1;
            else
            {
                float temp = (((float)pxBottom) / gridY) - 1;
                top = (int)temp;
            }
        }
        else
        {
            if (pxBottom <= gridY)
                bottom = 1;
            else
            {
                float temp = (((float)pxBottom) / gridY) + 1;
                bottom = (int)temp;
            }
        }

        if (isLeftNeg)
        {
            if (-pxLeft <= gridX)
                left = -1;
            else
            {
                float temp = (((float)pxLeft) / gridX) - 1;
                left = (int)temp;
            }
        }
        else
        {
            if (pxLeft <= gridX)
                left = 1;
            else
            {
                float temp = (((float)left) / gridX) + 1;
                left = (int)temp;
            }
        }

        if (isRightNeg)
        {
            if (-pxRight <= gridX)
                right = -1;
            else
            {
                float temp = (((float)pxRight) / gridX) - 1;
                right = (int)temp;
            }
        }
        else
        {
            if (pxRight <= gridX)
                right = 1;
            else
            {
                float temp = (((float)pxRight) / gridX) + 1;
                right = (int)temp;
            }
        }
        #endregion

        // Add each grid cell to the matrix
        for (float i = top; i < bottom; i += 1.0f)
        {
            for (float j = left; j < right; j += 1.0f)
            {
                gridMatrix.Add(new Vector2(j, i));
            }
        }

        return gridMatrix;
    }

```

With this grid matrix in a list I would then for loop through the list and check player collision with each object. For each item in the matrix I would use LINQ on the MapData list to check if there was an item in that grid space.

```
if (MapData.FindIndex(x => x.X == collisionMatrix[i].X) >= 0) { ...

```

Then inside of that if statement I would do steps 2 & 3 from the original collision detection.

2. Check Collision (Player, Object) return direction
3. Move player next to the object in the opposite direction of the collision

But this isn't working like I hoped it would. I was wondering if anyone picked up on something wrong with this that I didn't. Or if anyone had a solution to this problem that was completely different.

If you need more information I'll try my best to get it for you,

### Solution

The map is loaded into chunks which contain a 4x4 grid of blocks. If the user collides with a chunk the collision detection function will go into more detail and check collision for each block in that chunk. The result of the collision detection function is this

```
class CollisionResult
{
    public CollisionResult(CollisionResultType result, MapObject obj)
    {
        this.result = result;
        this.obj = obj;
    }

    public CollisionResultType result { get; set; }
    public MapObject obj { get; set; }
}

// Collision Class
public List<CollisionResult> ChunkCollisionDetection(WCPlayer player, List<MapChunk> chunkData)
{

List<CollisionResult> collisionResults = new List<CollisionResult>();

foreach (MapChunk chunk in chunkData)
{
    int chunk_x = (chunk.X * 16) - 16, chunk_y = (chunk.Y * 16) - 16;

    if (
        player.Rect.X + player.Rect.Width >= chunk_x &&     // X-Axis: Player->Left, Object->Right
        chunk_x + 64 >= player.Rect.X &&                    // X-Axis: Player->Right, Object->Left
        player.Rect.Y + player.Rect.Height >= chunk_y &&    // Y-Axis: Player->Above, Object->Below
        chunk_y + 64 >= player.Rect.Y                       // Y-Axis: Player->Below, Object->Above)
    )
    {
        // Collision with chunk -> Check for collision with blocks inside of chunk
        foreach (MapObject obj in chunk.MapObjects)
        {
            int obj_x = (obj.X * gridX) - gridX, obj_y = (obj.Y * gridY) - gridY;

            if (
                player.Rect.X + player.Rect.Width >= obj_x &&       // X-Axis: Player->Left, Object->Right
                obj_x + gridX >= player.Rect.X &&                   // X-Axis: Player->Right, Object->Left
                player.Rect.Y + player.Rect.Height >= obj_y &&      // Y-Axis: Player->Above, Object->Below
                obj_y + gridY >= player.Rect.Y                      // Y-Axis: Player->Below, Object->Above)
            )
            {
                if (player.Rect.Y + player.Rect.Height >= obj_y && player.Rect.Y + player.Rect.Height <= obj_y + gridY)
                {
                    Vector2 newPos = new Vector2(player.Position.X, (obj.Y * GridY) - player.Height - GridY);
                    player.SetPosition(newPos, new Rectangle((int)newPos.X, (int)newPos.Y, player.Rect.Width, player.Rect.Height));

                    // Let the player jump again
                    player.Jumping = true;

                    collisionResults.Add(new CollisionResult(CollisionResultType.CollisionBelow, obj));
                }
                else if (player.Rect.X + player.Rect.Width >= obj_x && player.Rect.X + player.Rect.Width <= obj_x + (gridX / 2))
                {
                    Vector2 newPos = new Vector2((obj.X * GridX) - player.Width - GridX, player.Position.Y);
                    player.SetPosition(newPos, new Rectangle((int)newPos.X, (int)newPos.Y, player.Rect.Width, player.Rect.Height));

                    collisionResults.Add(new CollisionResult(CollisionResultType.CollisionRight, obj));
                }
                else if (obj_x + gridX >= player.Rect.X && obj_x + gridX <= player.Rect.X + (player.Rect.Width / 2))
                {
                    Vector2 newPos = new Vector2((obj.X * GridX), player.Position.Y);
                    player.SetPosition(newPos, new Rectangle((int)newPos.X, (int)newPos.Y, player.Rect.Width, player.Rect.Height));

                    collisionResults.Add(new CollisionResult(CollisionResultType.CollisionLeft, obj));
                }
                else if (obj_y + gridY >= player.Rect.Y) // Y-Axis: Player->Below, Object->Above
                {
                    Vector2 newPos = new Vector2(player.Position.X, obj.Y * GridY);
                    player.SetPosition(newPos, new Rectangle((int)newPos.X, (int)newPos.Y, player.Rect.Width, player.Rect.Height));

                    collisionResults.Add(new CollisionResult(CollisionResultType.CollisionAbove, obj));
                }
            }
        }
    }
}

return collisionResults;
}

```

Thanks, Isaac

# Answer
The first thing you should do is breaking up the terrain into chunks. This helps in both rendering and collision detection.

Using these chunks to do collision detection greatly reduces the complexity. If one of your chunks contains 20\*20 "blocks" in it, then you need to check collision against 1/400th as many areas.

Here you should use the swept AABB algorithm to avoid fast moving projectiles going through solid objects.

After you assured you collide with one of the chunks, you need to check if the player collides with any of the blocks in that chunk. You should also use swept AABB for this.

You need to find the closest collision point and only do the collision after that

Swept AABB:

https://www.gamedev.net/resources/\_/technical/game-programming/swept-aabb-collision-detection-and-response-r3084
> 0 votes

---
Tags: c#, collision-detection, xna-4.0, grid
---


# Question
Title: How to load and display an image in OpenGL ES 3.0 using C++
I'm trying to make a simple app on Android Studio using the NDK, JNI to call C++ code that load and display an image. I have managed to create the surface and draw a simple Triangle already.

Now, I'm looking for a way to load and display an image in OpenGL ES 3.0 using C++. I have done the search around but all of them is either missing some important function or written in Java. It would be great if someone could guide me with a simple example, thanks in advanced :) .

# Answer
> 1 votes
In your shaders you need to define a new uniform variable with the type "sampler2D"

```
uniform sampler2D sampler;

```

Now, you need to somehow load an image into a byte array. After you created this, you create a new opengl texture object using `glGenTextures`. You bind it with `glBindTexture(GL_TEXTURE_2D, &textureId)`.

You need to load in the data to the texture object with glTexImage2D.

After this you pretty much have the texture in the GPU. Now you need to bind it again, but now you need to specify in which texture slot you want to put it in. These are marked with the `GL_TEXTUREX` constants, where X is the slot id. Depending on the OpenGL version, there's either 8, 16 or 32 possible slots.

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, &textureId);

```

After everything is bound, you load the uniform sampler. You need to load in the slot id you put the texture in as an integer:

```
// samplerLoc is the location returned by glGetUniformLocation
// You should save this somewhere
glUniform1i(&samplerLoc, 0);

```

And in the shader you can sample the texture with

```
vec4 color = texture2D(sampler, textureCoords);

```

(If the model doesn't have texture coordinates, then you need to add that the same way you added vertex coordinates)

---
Tags: textures, opengl-es, image
---


# Question
Title: What to replicate in a PvP online action game?
We're developing a 2D PvP online action game. You can think of it like Super Smash Bros. We have a function call tree for characters like below:

```
CharacterInput.Update()
|-- CharacterController.StartJump()
    |-- CharacterMovement.TranslateState( "Jump" )
        |-- CharacterJumpState.OnEnter()
            |-- CustomRigidbody2D.Move( delta )

```

I think the pseudo-code above is kinda straight forward. It's a typical `Controller`-`Movement` structure where the `Movement` part is made using several character states. Also, the `Movement` part is responsible for animations, physics, visual effects and sound effects.

So, to make this networked, we need to replicate some values over the network.

To make it clear, we're using Photon Bolt for Unity, which provide a `ExecuteCommand` way to deal with server authority and client prediction. You can check it out **here**.

So in terms of replication, we realized that according to the structure, we should decide which part to replicate. According to the call tree above, we can split our character logic into these layers:

* Input Layer: LeftStick, RightStick, A, B, X, Y, ...
* Controller Layer: MovementDirection, ShootDirection, IsJump, IsShoot, IsMelee, ...
* Movement Layer: CurrentState and all of its member variables
* Rigidbody, Animation Layer: Velocity, GravityScale, CurrentAnimationState

Theoretically, replicate any of these layers can make it work because the process of higher layer to lower layer is deterministic. Once the higher layer is replicated, lower layers should be the same across the network.

Sadly, this is just theory. In reality, you must deal with lag, and unreliable packet delivery.

For example, if you only replicate the inputs, an unstable network may make it out of sync because state A may transit itself to state B if animation ends, but actually it should be transitted to state C if player presses some button.

However, if you only replicate rigidbody and animation, all the visual effect or audio effect triggered by CharacterState can't work, because `CharacterMovement` doesn't even know which state it is in...

So, my question is, how do other games replicate their character? Especially in a PvP game?

# Answer
> 1 votes
Thanks for your answers. I've found a perfect answer for my question. I looked up the UE4 source code and found this:

```
// CharacterMovementComponent.h
virtual void ReplicateMoveToServer(float DeltaTime, const FVector& NewAcceleration);

// In ReplicateMoveToServer(), FSavedMove_Character::SetMoveFor() is invoked.
void FSavedMove_Character::SetMoveFor(ACharacter* Character, float InDeltaTime, FVector const& NewAccel, class FNetworkPredictionData_Client_Character & ClientData)
{
    DeltaTime = InDeltaTime;

    SetInitialPosition(Character);

    AccelMag = NewAccel.Size();
    AccelNormal = (AccelMag > SMALL_NUMBER ? NewAccel / AccelMag : FVector::ZeroVector);

    // Round value, so that client and server match exactly (and so we can send with less bandwidth). This rounded value is copied back to the client in ReplicateMoveToServer.
    // This is done after the AccelMag and AccelNormal are computed above, because those are only used client-side for combining move logic and need to remain accurate.
    Acceleration = Character->GetCharacterMovement()->RoundAcceleration(NewAccel);

    bPressedJump = Character->bPressedJump;
    JumpKeyHoldTime = Character->JumpKeyHoldTime;
    JumpMaxCount = Character->JumpMaxCount;

    // CheckJumpInput will increment JumpCurrentCount.
    // Therefore, for replicated moves we want it to set it at 1 less to properly
    // handle the change.
    JumpCurrentCount = Character->JumpCurrentCount > 0 ? Character->JumpCurrentCount - 1 : 0;
    bWantsToCrouch = Character->GetCharacterMovement()->bWantsToCrouch;
    bForceMaxAccel = Character->GetCharacterMovement()->bForceMaxAccel;
    MovementMode = Character->GetCharacterMovement()->PackNetworkMovementMode();

    // Root motion source-containing moves should never be combined
    // Main discovered issue being a move without root motion combining with
    // a move with it will cause the DeltaTime for that next move to be larger than
    // intended (effectively root motion applies to movement that happened prior to its activation)
    if (Character->GetCharacterMovement()->CurrentRootMotion.HasActiveRootMotionSources())
    {
        bForceNoCombine = true;
    }

    TimeStamp = ClientData.CurrentTimeStamp;
}

```

Turns out that UE4 replicates CharacterMovement with all its state variables to make it work.

# Answer
> 0 votes
Like **Ashkariel Eter** suggested in his comment, in a pure client/server model client sends only his inputs such as key presses, mouse movement, clicks to the server. In response the server updates the state of your character in the world and replies with a packet containing the state of your character and other players near you.

Such approach resolves the problem of unreliable network. If some packets get lost, some of your inputs won't go through and your local state and server state will desynchronize - whoops! But wait, it is not such a big deal, the server will send you near world state in next snapshot and your client will be able to correct any resulting differences. Such unreliable network tends to generate strange artifacts on client-side like running into walls and sudden teleportation when server snapshot is received - sounds familiar?

Also you should definitely take a look on lag compensation techniques and communication system based on unreliable network and unreliable protocol. Photon Bolt for Unity takes care for most of these issues for you, leaving you only to decide whether to use those features for your game or not, in PVP online action game you would want to use those perks.

1. Networking for game programmers, what every programmer needs to know about game networking.
2. Lag compensation techniques

---
Tags: networking, multiplayer, synchronization, pvp
---


# Question
Title: What are the advantages and disadvantages of different grids in a turn-based strategy-game?
The two most common types are using **hexagons** and **squares**. My question is rather concerned with game design. Why are specifically those two found so often? What are disadvantages that speak against using other polygons such as triangles, pentagons or octagons?

# Answer
There are very few regular polygons, which can get stacked next to each other seamlessly. These are triangles, squares and hexagons (your question mentions using pentagons or octagons, neither of which can be actually put next to each other seamlessly).

Using hexagons and squares over triangles has a very big advantage: tiles can have the same rotation. When you have triangles, some of those will be upside-down, so you need to draw everything twice if you want to maintain visibility.

You should decide it yourself whether you want to use hexagons or squares. Most computer games use the isometric projection, because it' easier on the math side, and provides a great pseudo-3d look, but board games like catan use hexagons because there's a smoother angle between the connections, so roads don't seem like they have only right angles.
> 4 votes

# Answer
Square grids and pentagon grids offer a way to repeat the same shape in the same pattern in both x and y.

You can make a grid of triangles, but some triangle will point 'up' while its immediate neighbours will point 'down'.

And I have never seen a grid of pentagons or octagons. These shapes are not repeatable easily.

Humans tend to think in Cartesian space, so square grids offer that simplicity, not only for the player, but for the developer too. That's the main advantage with these.

Hexagon grids have the advantage of "reducing" the "unfairness" of movement costs when travelling on diagonal tiles in games where movement cost is important, when comparing to square grids.
> 3 votes

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


# Question
Title: Syncing first person arms and enemy character for struggle in games
Some FPS have it where your arms are struggling or doing something melee to a character model. Both the arms and the character you're interacting with are sync'd up in the animation. What's the general idea behind how that syncing is done?

# Answer
In short, make sure the animations are in-sync when animated, so that you can easily play both animations at the same time. Some systems, like Mecanim in Unity, allow for transitions and so you would have to watch out that the transition does not blend too far in to the new animation. In the same way you'd want to play the animation instantly and not wait for another animation to finish first.

```
initial animation --> struggle animation --> potentially branch to different animations

```

It's not too dificult to pull off, but of course requires that the enemy is correctly placed in front of the player. This offset should be the same as when the animation was done in Blender, for example. Generally you have a "root" or "world" object, which is used to position characters at their initial position.

Systems like Mecanim also have some more advanced IK controls, so you can place the arms relative to another point, so that the enemy wouldn't have to be spot-on.

Perhaps if you had a more concrete goal or animation that wasn't working I could guide you a little better. Images of what your character rigs look like as well would be valuable information.
> 1 votes

---
Tags: animation
---