# Question
Title: XNA/MonoGame screen scale and keeping aspect
My aim is to make a simple 2D platformer, the idea is that it will be a base resolution of 480x270 (16:9) which can scale x2, x4(1920x1080) or go full screen.

I basically do:

graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 270;

and call methods do double or x4 them and then call graphics.ApplyChanges() which work well, I assume any 1x1 pixels from 1x resolution now appear as 2x2 or 4x4.

However in full screen the image is just stretched to whatever fits, how can I make it "letterboxed"?

# Answer
Turns out a MonoGame bug was causing most of my issues, which I (inadvertently) helped fix.
> 0 votes

---
Tags: xna, monogame, resolution
---


# Question
Title: What is the difference between graphics filters in Adventure Game Studio?
Adventure Game Studio supports following graphics filters:

* max nearest-neighbour filter and 2x-8x nearest-neighbour filter
* 2x-8x anti-aliasing filter

What graphics filter offers the best image quality? What is the difference between "nearest-neighbour filter" and "anti-aliasing filter"?

# Answer
> 3 votes
The filter that gives the "best" results will depend on the particular aesthetic you are going for.

The graphics filters have two components. The "x" portion of the filter refers to how many times the filter scales the source pixels. A "2x" filter doubles them, a "3x" filter triples them, et cetera. Think of them like magnification or zoom levels.

The next component to the filter is how the resulting scaled pixels are interpolated. A "nearest-neighbor" interpolation filter is essentially a no-op for integer zoom levels like those provided by AGS. This will result in a *blocky* image.

An anti-aliasing filter, by contrast, tries to smooth jagged edges (aliasing) in the scaled pixels. There are several different ways of implementing anti-aliasing and it's not clear which methods AGS uses. However, the result will generally be smoother than a nearest-neighbor interpolation filter, which is generally a more desirable, "modern" look... although there will be a tendency for actual, desirable hard edges in images to get fuzzy.

The scaling factor affects how big the resulting images are on screen, the nearest-neighbor versus anti-aliasing factor affects how smooth the resulting pixels look. You'll have to experiment with both and pick the one you think looks best for your game's art style.

---
Tags: adventure-game-studio
---


# Question
Title: Using a DirectX Vertex Shader to Modify the Vertex Data in VRAM?
I'm working on a GPU-side particle system in DirectX 11 where the vertex shader uses a vector field encoded into the color channels of a texture to modify the positions of the vertices before drawing them to the screen.

I'm trying to keep the computations on the GPU rather than calculating the updated particle positions on the CPU and send the new vertex data to the GPU every frame, so I've been investigating the possibility of having the vertex shader overwrite the vertex buffer in VRAM with the updated vertex positions each frame. So far, I haven't managed to find anything on the topic.

Would this be possible, and if so, how would I accomplish it?

# Answer
> 1 votes
Vertex shaders can't generally do that. They transform geometry, but do not write it back into the source buffers or into buffers at all (that you can access, at least).

You probably want to have a look a geometry shaders and the stream-output stage.

This way you can create a buffer for your data using the stream output bind flag, write yourself a geometry shader that does essentially what you were trying to do in a vertex shader (updates positions, dumps them to the buffer you created above). You can feed that buffer back into the start of the pipeline (input assembly) or later (you can read the buffer from shader code).

---
Tags: directx11
---


# Question
Title: How to get a game popular without a publisher?
I have just finished a game I had been developing last month, but whilst making the game I was pestered by the fact that I had no way of getting it to the public eye. I didn't want to pitch it to a publisher, as being tied to a publisher is the absolute last resort for me. So with little in the ways of funds for advertisement and supplementary materials, coupled with the fact that I am a fledgling to the industry to the highest degree and thus have nothing in the way of backing or accolades or any reputation at all. How does someone such as me get his work out there, and keep it as a work of his own merit and design? Am I just going to have to put my pride aside and join the veterans, or is there some way, any way at all, to make my way through? I really appreciate the help of anybody who answers.

# Answer
> 7 votes
**Option 1:**

Best way to market your own game? Talk to a company who publishes games. Pretend they're just a partner who takes a share just like anyone, and make a lot more money than you would have publishing on your own.

We sold about 50k copies of our IOS game last year. Really good game, 5 stars in almost all country specific app stores. Would have done way better with the $10000 marketing budget these types of games generally get from a publisher. 100% of a few bucks isn't as exciting as 50-70% of thousands. Lesson learned the hard way. Just a note, publishers won't touch your game, in my experience anyway, if it's been released.

**Option 2**

For the sake of answering your question, we sent the game out to about 100 game review sites in a few different countries. Had some videos posted up on youtube, did a "like me on facebook" contest, gave the right people a free copy to get them to play it, and broke even.

Maybe go for the latter option just to appreciate the value of someone who knows how to market. *They don't program games because they suck at it, I don't market games because I suck at it.*

# Answer
> 4 votes
Have you considered something like Steam?

If you could modify your game to suit their requirements, they could provide you with a solid base and you could focus more on the development itself without worrying about the business details (although business details are something to worry about).

Recently, a colleague and myself decided to develop a game and considered publishing it with Steam. We haven't done it yet, but it's a possibility for a small game studio/company such as our own, other small and big game studios/companies are doing it also, and it's something to start with.

An example of a bigger studio/company would be Runic Games with a game called Torchlight, but their developers are very experienced.

You could also check out GOG, I think they also provide this service.

**Update** (*to meet the needs for the discussion in the comments*):

From their FAQ on the site:

> 3: Do you take XNA, Flash or Adobe Air games?
>
> Yes, we accept all three types on Steam. Flash games need to be wrapped so that they launch from a stand-alone executable.

# Answer
> 2 votes
\[Edit\] There appears to be some confusion about what I mean by "marketing." When I say a good game will market itself, I mean a good game is likely to get featured in blogs and in app stores. **That is to say, the user has to spend $0 on advertising.** \[End Edit\]

The simplest way:

Make a good game.

A good game (or any good product) will market itself. "Good" is a very nebulous word. But from my view a "good" game has two requirements:

1) It is unique (you can clone another game, but you should bring significant improvements or new features to it).

2) It is fun. Fun is in the eye of the beholder, but generally, if your game is fun, at least a certain niche of people will enjoy it. A fun game is also functional, without frustrating bugs or design flaws.

A boring clone will fail. A fun clone probably won't stand out in the market, unless it is really well made and marketed (or free). A boring, unique game might stand out, but probably not for the right reasons. A unique, fun game will entice its users to spread the word, and news/review sites will be eager to talk about your anomaly.

Obviously, there is grey area on the line between good and bad, but your first few games will either be unfinished or not that great, because becoming a good artist, programmer, and game designer is not an overnight endeavor. There are very few cases where successful titles were the first thing to come out of a developer's efforts. Rovio was around for 7 or 8 years before Angry Birds was made. Notch was 30 before he made Minecraft, and had worked on many other games prior. The list goes on...

# Answer
> 0 votes
I'd say the real question to ask for determining whether or not you should self publish or join the veterans as you put it is "When does my project need to become profitable?"

I'm in a very similar predicament myself and this is what I'm using to make my decision. My game has been Greenlit on Steam and I've been approached by a mid level publisher who offered to cover Marketing, PR, Promotion, Testing and Customer support for a 50% revenue share which isn't a bad deal at all. I lose half the profit, but the game gets promoted from day 1 so it would likely equate to earlier sales which in turn would enable me to generate a profit much sooner than I would on my own.

However, I also don't have any timeline for when I need to be profitable. I'm the only designer, there's no budget aside from me living off of savings and paying rent and eating, so aside from starvation and homelessness, there's no real deadline that I need to aim for in regards to profitability.

I'm likely going to say no thank you to the publisher and just wait for the word of mouth to get around. It may take an extra year or so, but I'm confident that my game is good and will eventually sell well enough to keep me working on solo projects.

As to the question of how do you promote your game if you're self publishing? Same way you get your friends excited about anything you're interested in; Word of Mouth. Sadly this is the slowest and most time consuming way to promote your project, but its pretty much the only way if you have no budget.

Early on in development, you want to reach out to gaming publications - don't bother with the big names like Rock Paper Shotgun or Game Informer - they don't have enough time to write about every indie project that gets mentioned to them. Look to the smaller sites like ind13.com and indiedb.com Now you might wonder how writing articles or doing interviews with these guys will help you if they're relatively unknown themselves? Immediately they won't help you. They might generate a slight uptick in traffic to your website but otherwise they're not going to do much that you'll notice. They will however become a concrete backlink to your website as far as search engines are concerned so this will essentially act as your manual SEO optimization. Anything you mention in the article pertaining to your game and your game's "search terms" will help improve your ranking on google and others and over time this will help you to get noticed more. The more websites linking to yours, the greater your ranking. This will take more than a year to have any useful effect, but you're likely to be developing your game for more than a year anyway so you have time.

Same goes for talking about the game on various gaming forums, reddit, twitter etc. Make sure you always include a link back to your game's website when you talk about it and it will pay off in the long run. Also the word of mouth that you're generating will take more than a year to have a useful affect but its getting your game into the consciousness of as many people as you can. Eventually when you do land an article in RPS or GI or what have you, more people will think "Oh yeah, I remember hearing about that game" and you'll likely get a better response than a game being reported on for the first time.

Finally when your game is ready for release, (especially if you're on steam) send out a few hundred keys (or copies) to various twitch gamers, youtubers, reviewers and anyone else you think might be interested in the game and would like it. Don't ask for anything directly, just explain that you've made this game, and you think they'd like it and if they do, you'd love to hear their opinion. Again, go to the little guys first before you approach any big names. If 10 little guys are talking about your game, its more likely to catch the attention of one of the big ones.

I will say that someone people think you should be very direct when contacting potential promoters on youtube and twitch and ask them to post about or review your game. My theory is that they already get hundreds of people asking them for favors so if you're simply sending them a copy because you're a fan and they're awesome, they might appreciate it more. Leave it to them to decide whether or not they think its worth promoting.

---
Tags: marketing, publishing
---


# Question
Title: Unity2D - move rigidbody object with collision
How do I move and collide my object (position given by touch or click), by Using rigidBody2D.MovePosition i can only teleport my character, and by using velocity, my character keeps moving, I want him to stop at the position given

Ilustrations:

# Answer
This is called arrival. It's a steering behavior. The basic concept is:

1. Apply an acceleration towards the target position (alternatively, you can simply set the velocity if you're not using acceleration)
2. When within a defined range of the target object, start applying acceleration away from the object, this acceleration is scaled based on the distance to the object and the current velocity. (If not using acceleration, skip to step 3)
3. When within a "close enough" range, and below an acceptable velocity, stop all motion on the object. Optionally, you can also snap the position of the object to the target position.

You can find a good explanation of the implementation here.
> 1 votes

# Answer
You'll have to change the velocity after your object reaches the correct position. You could store the target position in your script, and you could check the distance to the target during Update. Once the object has arrived, set the velocity back to zero. Arrival should be determined by some non-zero minimum distance to the target, because the object is unlikely to land *exactly* on the target position. If you like, you could then move the object perfectly to the target position as one final step.
> 0 votes

---
Tags: unity, android, movement, touch, rigidbody
---


# Question
Title: Disney BRDF - where is metallic factor input into BRDF?
Burley states about *metallic* parameter:

"This is a linear blend between two different models. ..."

What are the two models? I can't see this described in the Frostbite or the Unreal papers either.

Is it simply a blend between the diffuse and specular terms or a scaling factor on the specular term?

Disney Paper

# Answer
If I'm reading this right, the answer seems to be right there in the continuation of that line:

> **metallic** \- the metallic-ness (0 = dielectric, 1 = metallic). This is a linear blend between two different models. *The metallic model has no diffuse component and also has a tinted incident specular, equal to the base color.*

(With the implication that the dielectric model is defined by *not* having those specific traits)

ie...

Dielectric Model:

* Has diffuse component
* Incident specular is not tinted

Metallic Model:

* Diffuse component = 0
* Incident specular is tinted by base colour
> 3 votes

---
Tags: shaders, graphics, pbr
---


# Question
Title: How to resolve combat of stacks of units to mitigate numerical advantage
I just started designing an strategy game where player's armies consist of stacks of units. For my design I was aiming to reproduce the following behaviour for a full combat of multiple turns (for simplicity assume both stacks are the same unit):

* 1 vs full stack: the single unit is killed, the full stack hardly notices.
* half stack vs full stack: the half stack is killed, the full stack sustain noticeable damage.
* almost full stack vs full stack: full stack wins but gets almost wiped out. If randomness is involved, any of both may win, although the bigger one has statistical advantage.

My first approach was to add up the stats and treat each stack as a single unit, resolve the combat and then calculate how many units are killed.

That didn't produced the expected results, as even the slight numerical advantage in one side produced it to win by a huge margin.

The reason is that after each turn, the bigger stack would kill more enemies than the smaller, widening the power difference for the next turn. This different increases exponentially until the smaller stack is quickly obliterated.

As a second approach I treated each unit in a stack individually for the combat (something that I wanted to avoid), which produces much better results. However now I have many choices about how to resolve the combat.

Should it be a series of 1 vs 1 or should I allow units to gang up on others?

Should I pair each evenly or randomly?

Should I leave extra units unpaired as "reserve", or all units should fight at least once?

# Answer
What you've described is the difference between Lanchester's linear and square laws. These are formulas estimating the rate of attrition between a battle between two military forces.

The **linear law** says that the two forces suffer a **constant rate of attrition**, regardless of the size of the forces. This is used as an approximation of **ancient combat**, between largely infantry formations with melee weapons. The reasoning is: it doesn't matter how many men you have in total, there is still a limited front line of actual men doing the fighting, so the larger force simply outlasts the smaller force while suffering the same casualties. So a full size force will wipe out a half size enemy but lose half their men. This appears to be the outcome you want.

The **square law** says that two forces **deal damage at a rate equal to the number of weapons firing**. At the extreme, every one can fire at and be fired by every enemy. This is used as an approximation of **firearms combat**. Unlike ancient combat, with modern firearms infantry can engage targets both close and far, so every one can potentially be in combat at the same time, greatly enhancing numerical advantages. So a full size force will be dealing twice the damage as a half size enemy, and over time the half size enemy will be losing men at a greater rate and deal less subsequent damage. The result is that the full size force will annihilate the enemy while suffering only a fraction of the casualties. This appears to be the model you currently have.

But if you read on the Lanchester laws, you'll notice that the same formula (which also includes a variable for firepower) applies to both linear and square cases, but with a different **exponent**:

* The linear law has the exponent at 1
* The square law has the exponent at 2
* For modern warfare, an exponent of 1.5 is often used

So you can try different exponents between 1 and 2 to see what makes sense for your game. One thing to note: when commanders like Hannibal attempt flanks, or when some RTS games talk about a "concave", they are effectively enhancing their exponent at the cost of the enemy's - allowing more of their forces to engage than the enemy:

> From https://gaming.stackexchange.com/a/18275/47716
> 7 votes

# Answer
Of course you expect the smaller army to lose most of the time, but they should still have a chance to do some damage. Which history shows is usually the case - quality matters more than quantity unless it's overwhelming.

There's many ways you can accomplish this but here are a few ideas:

1. Allow everyone in the small stack to attack, don't let the larger side take out half their force before they do anything. That is, even casualties should get a parting shot at their attacker - though perhaps one with reduced effectiveness. After all they were not standing still as they died.
2. If there is a wide numerical advantage, don't let all the units in the larger stack attack. Just let perhaps 2 units for each unit in the other stack attack at most. It's unrealistic for a whole huge army to engage a tiny force all at once anyway.
3. Give bonuses for terrain and for defending if they are the ones attacked.
4. I would choose each attacker in random order, perhaps with a stat like initiative involved in determining who goes when.
5. Consider some negative stat maluses for very large armies, or a hard limit on size of armies based on some kind of leadership or logistics stat. It's not easy to control a large army and ensure everyone does what they should.

I hope some of these ideas help a bit, but of course it's a bit subjective.
> 4 votes

---
Tags: game-design, strategy
---


# Question
Title: Best way to initialize values on 32-bit FP framebuffer in OpenGL
I have a framebuffer bound to 32-bit FP texture:

```
glGenTextures(1, &texColor);
glBindTexture(GL_TEXTURE_2D, texColor);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, w, h, 0, GL_RGBA, GL_FLOAT, (GLvoid*)NULL);
glBindTexture(GL_TEXTURE_2D, 0);

glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColor, 0);

```

What's the best way to initialize framebuffer to a value 1000.0?

The problem is that

```
glClearColor(1000.0f, 0.0f, 0.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);

```

clamps values to \[0,1\] interval, and clearing the texture texColor would require memory allocation of w * h * sizeof(float) bytes of memory and manual filling of that buffer with value 1000.0 which is slow (I would inject it using glTexImage2D).

I'm using OpenGL 3.2 Core profile.

Thanks, Josip

# Answer
> 1 votes
You can render a quad onto the framebuffer with a shader that will just set the color value to 1000.0.

Since you don't even need to set a texture really let alone compute lighting, this should not really take any noteworthy time to accomplish.

It's pretty easy to do but here is a tutorial that talks about rendering to a texture. Though really you don't even need to do all of those steps.

http://www.learnopengl.com/#!Advanced-OpenGL/Framebuffers

---
Tags: opengl, textures, frame-buffer
---


# Question
Title: Is there an existing algorithm to find suitable locations to place a town on a heightmap?
I've been experimenting with random generation of a "map" with the intention of building a basic sort of procedural map generator. Generating a reasonable heightmap using libnoise hasn't been that much of an issue.

I am considering using A\* or similar to plot two main "roads" across the terrain from top to bottom and left to right, intersecting in the middle of a town in some relatively flat section of the terrain.

I am unsure of the best way to go about locating the optimal point to place the town though. I created a "steepness" map as another map which looks at the points surrounding each point on the heightmap to determine the steepness and then sets 1 if steep and 0 if not to create a "mask" of steep and flat areas.

How then could I determine the largest rectangle area that will fit within those flat areas?

Or perhaps I need to re-look at this a different way and place the "town" first then build the terrain around it rather than trying to place it into an existing terrain.

# Answer
> 6 votes
Here's one (relatively exhaustive) method you can try:

1. Take your terrain heighmap (left)
2. Mask the areas that are too steep to build on (orange, center)
3. Propagate a distance field from the too-steep region (blue-green gradients, right) until you reach your maximum town radius:

(You can also use the Jump Flooding Algorithm to speed up this part)

The resulting gradient represents the maximum radius city that can be placed at each point. The highest overall peak in the gradient represents the placement point for the largest possible city this map can house (or, the one with the most padding around it)

# Answer
> 0 votes
If you do not want to alter the existing terrain that you generated, then a viable approach could be to use a flood fill algorithm.

Have your flood fill check for the largest fillable area that is inside of a specified height range.

This approach would require you to define at what height you would like your town to be placed.

If you are not opposed to modifying the terrain you generated, possibly utilize an erosion style algorithm, that will subtract data from higher areas, and place them at lowest areas near that original peak. You would more than likely have to taper off this effect at the edges of your area.

---
Tags: terrain
---


title: Level of detail for the map of stars

text:
# Question
Title: Level of detail for the map of stars
I have a large list of points (millions) in 2d. Let's say it's a star map. Each star has a radius and position in space.

I want to render this map at different level of details. From a single star to entire star system, galaxy or even universe. I also want it to be fast.

So I started with a quad tree approach: loaded every point into the tree. At any moment of time I can query a tree with a simple question: `Give me top N points in this region`

But what is a `top`? I thought to myself that quads can be compared based on total radius of points that they host. So, this gives me sorting order to work with, and the algorithm boils down to a mix of quad tree and a priority queue:

```
priorityQueue.push(rootQuad)

while priorityQueue.size < N {
  let node = priorityQueue.pop() // take the largest node
  for each child of node {
    if child.intersects(region) {
       priorityQueue.push(child)
    }
  }
}

```

After this algorithm is done, I can render each point either at its location (if it's a leaf), or at the node's center of mass (if it's intermediate node). It works very fast, and gives decent results.

However there is a problem with this approach. Let's consider a simple grid of points:

If I render each intermediate quad tree node at node's center of mass, then I get these artifacts, where two nodes are collapsed into one:

It almost feels like I should start from leaves, combine individual points into single cluster, until I get `N` clusters, but this would kill performance.

What would you recommend to do to avoid such artifacts?

# Answer
One obvious error in your current implementation is that you should combine nodes based on their **total area, and not total radius**. Otherwise you're overstating the visual effect by a squared factor - remember the area formula, pi\*r^2. But you'll still run into other artifacts.

An obvious one is that when you are zooming or refining your detail, there will be popping artifacts as one level of detail is abruptly replaced with the next. Most LOD algorithms deal with this by **fading between levels of detail** \- i.e. when you are at the threshold between levels, alpha blend between the two instead of having a hard threshold.

In my experience level of detail for point clouds where you replace small points with big points only works for continuous surfaces (and even then you get artifacts from the loss of surface texture, which is somewhat improved by texture mapping techniques like bump mapping). When you're dealing with discontinuous data, like your starfield, replacing multiple points with a single point is going to cause jarring effects like points shifting abruptly. You can also try one of two techniques:

* Replace with a single quad that approximates the total luminance of the underlying stars. This is a much better approximation than a single large star.
* Replace with a textured quad, where the texture is of a generic starfield. This is kind of related to the 3D impostors technique.

Experiment and see what works best. One thing you could try: the brightest stars are always visible; emulate that effect by having a priority queue of stars by brightness, always rendering the brightest N, and the rest in simplified form.
> 3 votes

# Answer
Try rendering the stars at full resolution, and building a mipmap.

A mipmap is a "pyramid" of images, each at a different scale. At the "top" of the (upside down) pyramid is the original image. The next level is the same image at half-scale. And so on.

GPU can produce mipmaps (opengl, directx I'd imagine too), though such a map is prolly too large to do it in one shot on the GPU (too large for a texture), but if you are doing quadtrees you should be able to figure out how to break it down to feed it to the GPU piecemeal. The lowest level of a mipmap would look like that section from far away. Precompute the entire mipmap if you can.

It should look decent, but if it doesn't look good, you'll want to do the same thing yourself; use a vision library like opencv (prolly to precompute them) and basically you do {1. blur, 2. subsample at half resolution} over and over until you have a 1x1 mipmap level. And you have produced the mipmap yourself. The choice of "blur" and associated parameter choices for each blur will affect how it looks at the end. Some examples are "gaussian filter" or "bilateral filter". There are lots of others.

Another thing to try would be to use opencv (or another lib) to directly do the rescaling; see if you can produce a mipmap this way, it might produce good results.

Fade between the two levels of the mipmap that are at the scale you want to draw on the screen (this is called trilinear interpolation).

Just to note, if you don't want to do the entire thing precomputed, you can take a section that you want to draw and only do that section. Keep in mind you might need to add some border to this section to take into account things that would normally be blurred in.
> 0 votes

---
Tags: 2d, algorithm, rendering, level-of-detail
---


title: convert clock input into 24 hour format

text:
# Question
Title: convert clock input into 24 hour format
I have stuck in a logical problem I have a third party package of DayNight. It takes hours input(24-hour-format) to show dayNight effects in scene

My code is to transform 12 hours clock cycle into 24 hours is

```
if (todsky.Cycle.Hour >= 0 && todsky.Cycle.Hour < 11.97)
            {
                Debug.LogError("1st");
                var degree = 360 - hourniddle.transform.eulerAngles.z;
                var degreeToMintues = degree * 2;       //multiply each degree with 2 to get correct minutes
                ConvertMinutesToHours(degreeToMintues); //
            }
            else if (todsky.Cycle.Hour > 11.97 && todsky.Cycle.Hour < 23.97)
            {
                Debug.LogError("2ndt");

                var degree = 360 - hourniddle.transform.eulerAngles.z; // as rotation is anti-clock getting rever degree
                var degreeToMintues = degree * 2; //multiply each degree with 2 to get correct minutes
                var MintuestTo24HoursMintueCoverstion = 720 + degreeToMintues; //add 720 mintues into current minute in order to get 24-hour-format
                ConvertMinutesToHours(MintuestTo24HoursMintueCoverstion);

            }
 void ConvertMinutesToHours(float mintues) {
        result = TimeSpan.FromMinutes(mintues);
        Debug.LogWarning(result.Hours + ":" + result.TotalHours + ":" + result.Minutes + ":" + result.TotalMinutes);
        todsky.Cycle.Hour = (float) result.TotalHours;
        Debug.LogWarning("setted hours : " + todsky.Cycle.Hour);
    }

```

But it is not working correctly . have made a clock GUI(360-degree) and as you know it only show 12 digits-format not 24. I am getting clock needle movement which can be change through mouse drag. Needle z position up to 320 degree which means one degree is equal to 2 minutes and i am taking it as input from GUI. I write below code to integrate my clock needle with my DayNight package in order to integrate GUI with package and passing hour parameter into the package but it not working correctly. Problem is that else condition is skipping.

# Answer
I'm not sure if I understand the question completely but here goes:

Converting the clock from 12h and 24h:

The 12 hour clock is basically the 24h clock limited to 12:

```
12h_time.hours = 24h_time.hours % 12;

```

To convert the 12h clock to 24h you need to know if it is morning or afternoon:

```
24h_time.hours = (morning?12h_time.hours:12h_time.hours+12);

```

Now from what I understand you have a GUI element clock that you want the player to be able to drag the hands and time will change accordingly. To achieve that, use 720 degrees scale. If the player keeps dragging the hands of the clock, just keep the internal measurement between 0 and 720 degrees. If the clock is in the lower 360 degrees, it's morning, else it's the afternoon.

You already seem to be able to draw the clock based on 2 degrees per minute; so this still applies and I guess no code sample is needed there.
> 0 votes

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


# Question
Title: How can I make sure multiple player scripts all get the same amount of execution time per game tick?
I'm looking for a way to allow players to write code in a high level language, but I need to be able to keep all script instances synchronized in terms of script execution time per game tick so that no player gets an advantage.

The purpose for this is a simulation in which there are many bots scripted by several people, and the bots are in competition. The idea is to have a level playing field by advancing the execution in a controlled way so that no bot can gain an advantage.

This also has to be synchronized in a meaningful way with the rest of the simulation/physics. Having control over granular execution steps seems like one way to do this, although I'd be open to other potential solutions. In other words, if i made up my own assembly language and associated interpreter, I could control execution granularly, but besides being a significant undertaking, assembly languages are far more difficult to work with then high level ones.

Here are some ideas I've come up with :

* If there is a way for each bot to run a simple OS/VM, that could work, provided the OSes can be instantiated, controlled/execution time metered, and interfaced with programmatically from .NET code, but I don't know of anything like that.
* A scripting engine like Google's V8 seemed like it would be awesome, but there's no way to ensure program A and program B can each be allowed equal execution time; line by line stepping doesn't work here, as a line from program A could read:

```
q=(((x+y)/z)-(a*b))/c;

```

while a line from program B could read:

```
q=3;

```

meaning running each line's program results in one (probably) executing for a longer time than the other.

# Answer
**High Level Languages Turn Into Assembly Languages**

I think you're overestimating the difficulty of building a high level language to provide to your players, you can quite easily build an interpreter to your simple bot scripting language that compiles down to a bytecode that runs on a virtual machine you can advance in fixed intervals in parallel with other virtual machines that control your game.

There's a wonderfully simple and common sense approach to building an interpreted language in the *Bytecode chapter of Game Programming Patterns* that should be able to get you started with building your own language or at least helping you decide if you need to build your own language for it. If you really want to, you could dive into a more complex language, learn compiler frontends and code generation with *Compilers: Principles, Techniques, and Tools by Aho, Sethi, and Ullman*; I have a personal fondness to the 1986 print, but any other version should be just as valuable.

**Once you have your language compiled down to your interpreter friendly assembly/bytecode just advance it at fixed intervals like anything else in your game loop; tweak as desired.**
> 0 votes

# Answer
What you are trying to do is far outside the usual use-case of off-the-shelf script engines. Scripting engines use lots of optimization tricks to run code as fast as they can. But that means the programmer can not know for sure how fast code will actually run. The runtime behavior could also change when you install some minor update to the scripting engine.

But when you want to have a competing programming game where managing execution time is a core gameplay element, then you want reliable and consistent execution speed.

For that reason I think the best option would be to write your own script interpreter for your own scripting language.

This allows you to define how many resources each instruction consumes by having the engine track the gameplay-relevant "virtual" execution time of scripts separately from the actual real-world execution time. Now you are able to freely balance the resource consumption of each instruction for a more accessible and balanced gameplay. You can simply say "each bot gets 100 virtual instructions per second, each arithmetic operation takes one virtual instruction". That way it becomes predictable for the player how much runtime their script actually takes.
> 1 votes

---
Tags: multiplayer, scripting, simulations
---


# Question
Title: Counting triangles and vertices in Unity's cube
I want to understand logic behind drawing triangles of primitives in Unity. When we spawn simple cube, variable mesh.vertexCount gives us value 24. Also when we list all vertices positions (from mesh.vertices) and triangles numbers (from mesh.triangles), we get:

```
0. (1.0, -1.0, 1.0) 0
1. (-1.0, -1.0, 1.0) 2
2. (1.0, 1.0, 1.0) 3
3. (-1.0, 1.0, 1.0) 0
4. (1.0, 1.0, -1.0) 3
5. (-1.0, 1.0, -1.0) 1
6. (1.0, -1.0, -1.0) 8
7. (-1.0, -1.0, -1.0) 4
8. (1.0, 1.0, 1.0) 5
9. (-1.0, 1.0, 1.0) 8
10. (1.0, 1.0, -1.0) 5
11. (-1.0, 1.0, -1.0) 9
12. (1.0, -1.0, -1.0) 10
13. (1.0, -1.0, 1.0) 6
14. (-1.0, -1.0, 1.0) 7
15. (-1.0, -1.0, -1.0) 10
16. (-1.0, -1.0, 1.0) 7
17. (-1.0, 1.0, 1.0) 11
18. (-1.0, 1.0, -1.0) 12
19. (-1.0, -1.0, -1.0) 13
20. (1.0, -1.0, -1.0) 14
21. (1.0, 1.0, -1.0) 12
22. (1.0, 1.0, 1.0) 14
23. (1.0, -1.0, 1.0) 15

```

(i-th element, vector from mesh.vertices\[i\], number from mesh.triangles\[i\])

Obviously we need only 8 vertices to create cube, but we need 6\*2=12 triangles, three vertices every - array of 36 vectors. So... what is the logic of Unity primitive?

# Answer
> 5 votes
In computer graphics, a vertex is usually more than just a position: it also includes texture coordinates and normal (facing direction) information (among other situational data, like vertex colours, blend weights, tangent vectors, etc...)

The vertex processing part of the graphics pipeline doesn't index these sets of information independently — all the information needed to build the triangles is indexed with just one array of indices. (At least that's the standard way — there may be more exotic techniques)

So to represent the same point in space but with different texture coordinates and normals, we need to duplicate the whole vertex, resulting in copies of the same position in the vertex position array. If you look at the uv and nornal arrays though, you'll find the vertices in these duplicated slots differ in other ways.

Bringing this together: while a cube contains 8 unique corner positions, if we look closely at any one corner we find 3 faces meeting along sharp edges. That means 3 surface normals are needed to represent that corner vertex, one for each adjacent face.

```
8 corner positions × 3 faces per corner = 24

```

So that's where the 24 number comes from. Each of the 8 unique vertex positions needs to be repeated 3 times to describe the different surface facing directions meeting at that point.

If we had only 8 vertices, we couldn't give each face meeting at a corner its own unique normal, so the cube would get shaded like a rounded blob, without the sharp edges we expect to see.

You may find 3D modelling software gives a different count. For editing a model, they'll typically treat shared vertices as a single object so it's easier to move parts around without creating gaps. Even these programs still usually split shared vertices into copies for each unique combo of vertex attributes on export, or the game engine does this on import, to make something friendly for GPU consumption.

# Answer
> 1 votes
**It doesn't count unique vertices (as defined by their positions), but vertices as they are used to generate triangles.**

Look at your list, vertex #0 and #13 are the same vertex, but as DM Gregory's answer will detail, have other different attributes like surface normals, so even indexed, the positions aren't enough to index (although in theory you could index positions and normals separately, it doesn't perform well in practice). Now another side of this is that you could collapse similar vertices that have very similar (read: indistinguishable) positions, normals, and other attributes and you could eliminate duplicates and index those. For example: a mesh of more natural shapes might have many vertices that have identical face normals and should be one vertex that is indexed.

---
Tags: unity
---


# Question
Title: How to save one color channel, taking only 1 byte per pixel?
How can I save only one color channel, such that it would only take 1 byte per pixel?

I only want to save the alpha channel and apply colors later using a custom shader. But all the formats I tried so far take more memory than necessary. For instance, 8x8 image should only take 64 bytes. Is there any image format that allows this?

# Answer
> 1 votes
Microsoft BMP files have a "monochrome" mode which uses just one bit per pixel (the file is still slightly larger due to meta-data).

Note that this only applies to the actual graphic files. When you have your graphics framework unpack the image files to textures, the required texture memory might be more than 1bpp.

---
Tags: sprites, image, spritesheet, color, file-format
---


title: UI 5: Slider Pressed

text:
# Question
Title: UI 5: Slider Pressed
I am using the UI slider from Unity 5 and would like to display a text every time the handle knob is touched/pressed.

My understanding is that my script should extend some Event System interface. From the unity doc either `ISelectHandler` or `IPointDownHandler` should be able to 'hear' if my knob is pressed. I am a noobie to the unity event system, so I hope that this question doesn't offend anyone if its pretty basic..

So far this is what I have:

```
public class SliderControl : MonoBehaviour, ISelectHandler {

    public Slider slider;

    void Start(){
        slider.transform.GetChild (2); // this gets the Handle Slide Area where the knob is
    }

    public void OnSelect (BaseEventData eventData) {
        Debug.Log ("Display some text");
    }
}

```

My questions are:

1. What exactly is a base event data in simple English?
2. How can I convert my slider knob into a BaseEventData type that OnSelect() can work with?

# Answer
Easiest way to do it by adding an `Event Trigger` component to the knob for `Pointer Enter` or `Pointer Down` and call a public method through it.
> 2 votes

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


# Question
Title: How do I add a smooth force my player's rigid body, to make them jump?
I am trying to add force to the player's rigidbody, when the screen is held. I've written the following code:

```
float PlayerForce=50.0f;

void FixedUpdate()
{
   bool PlayerActive = Input.GetButton ("Fire1");

   if (PlayerActive) {
       PlayerRigidBody.AddForce (new Vector2 (0, PlayerForce));
   }
}

```

This does not add a smooth jump effect. I've searched for smooth force effect, but I didn't find anything useful. How do I add a smooth force my player's rigid body, to make them jump?

# Answer
Use the `AddForce` like below and reduce `PlayerForce` value.

```
PlayerRigidBody.AddForce (new Vector2 (0, PlayerForce), ForceMode.Impulse);

```
> 1 votes

---
Tags: unity, rigidbody
---


# Question
Title: Camera relative movement is pushing into/off the ground instead of parallel
I'm building upon roll a ball tutorial in unity, and I have managed to rotate the camera around the ball just fine with the code below. But there's one problem.

In this code, when I add force to the ball, with `W` for example, the force will be added in the exact direction the camera is looking at the ball, meaning pushing the ball onto the ground, increasing friction and lowering speed. And if I press `S` the force will push the ball to the air, lowering friction and making the ball move fast.

So my question is, how can I achieve rotation without this issue?

Code for Camera (CameraController):

```
public GameObject Player;
private Vector3 offset;
public float cameraSpeed;
private Vector3 point;
static public Vector3 finalMovement;

void Start () {
    offset = transform.position - Player.transform.position;

    point = Player.transform.position;
    transform.LookAt(point);
}

void LateUpdate()
{
    point = Player.transform.position;

    offset = Quaternion.AngleAxis(Input.GetAxis("Mouse X") * cameraSpeed, Vector3.up) * offset;
    transform.position = point + offset;
    transform.LookAt(point);
}

Vector3 movement;
void FixedUpdate()
{
    movement = new Vector3();
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = Input.GetAxis("Vertical");
    movement = new Vector3(moveHorizontal, 0f, moveVertical);

    finalMovement = GetComponent<Camera>().transform.TransformDirection(movement);
}

```

Code for ball:

```
public float speed;
void FixedUpdate()
{
    rb.AddForce((CameraController.finalMovement) * speed);
}

```

# Answer
I often like to give myself a little convenience method:

```
Vector3 CameraRelativeFlatten(Vector3 input, Vector3 localUp)
{
    // If this script is on your camera object, you can use this.transform instead.
    Transform cam = Camera.main.transform;

    // The first part creates a rotation looking into the ground, with
    // "up" matching the camera's look direction as closely as it can.
    // The second part rotates this 90 degrees, so "forward" input matches
    // the camera's look direction as closely as it can in the horizontal plane.
    Quaternion flatten = Quaternion.LookRotation(
                                        -localUp,
                                        cam.forward
                                   )
                                    * Quaternion.Euler(Vector3.right * -90f);

    // Now we rotate our input vector into this frame of reference
    return flatten * input;
}

```

When I have an input in controller space, I can use this convert it to a direction in the world horizontal plane, relative to the camera:

```
Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

Vector3 worldSpaceInput = CameraRelativeFlatten(input, Vector3.up);

```

If we wanted, we could also use a local surface normal instead of `Vector3.up` to get our input parallel to an arbitrary tilted surface, instead of always in the XZ plane.

Since we're rotating the input vector, the length is preserved, so we won't just chop off the portion of a vector that was digging into the surface, slowing our forward-back movement relative to left-right.
> 2 votes

# Answer
So the problem you're having is that the Y movement is also used when applying the force. Easiest solution is to simply set the Y movement to 0 when adding the force:

```
rb.AddForce((new Vector3(
    CameraController.finalMovement.X,
    0,
    CameraController.finalMovement.Z).Normalize() * speed);

```
> 0 votes

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


title: Do games need installation these days?

text:
# Question
Title: Do games need installation these days?
I wonder why games need installation at all. I can understand that some software like a browser needs it so it can associate some file types with it and start an executable, or add the icon to the Programs/Features component on Windows. But what's the purpose of installing, say, a Steam game? The Steam itself handles installation/removal of a game, updating, starting etc. If I develop my own game launcher (which will use installation) what are the reasons for me to use also an installer for my games?

# Answer
> 81 votes
There are quite a few reasons you'd want to use an installer. Some of them, off the top of my head:

* Most games (and indeed, most applications) these days require the use of some supporting DLLs (such as a dynamically-linked C++ runtime or the Direct3D runtimes). Sometimes these DLLs *cannot legally* be distributed directly and must be installed via redistributable installers. This used to be the case for D3DX DLLs, for example. It's important to read and understand the licensing terms for your dependencies. If you have such a dependency, wrapping up its installation in your own installer can smooth the process out for end-users.
* A well-behaved modern program will not require elevated (admin) access to run. However, it might require such access to be *installed*, and an installer provides a reasonably simple process for doing so that users are more-or-less familiar with.
* Similarly, some games will want to generate registry entries to associate file types and the like, as you noted. This can also require elevation.
* If a game relies on system-wide installed versions of some of its dependencies (as above) it can benefit from security updates and hotfixes made to those dependencies more easily (the OS takes care of them, not the game developer). But installing those dependencies in system-wise locations *also* requires elevation, and can be very easy to get wrong if you ask a user (particularly a non-technical user) to do it manually.
* Finally, don't forget how easy it is, as somebody who is a tech-savvy user, to underestimate the non-tech-savvy view of computing. Sometimes "double-click to open" is the only skill you can assume (sometimes not even that much); double-clicking an installer launches a program the user can usually "okay, okay, okay" through. Double-clicking a .zip just extracts it ("well where did my game go?") or worse, opens it like a folder, where users will double-click on the .exe and it will fail to run correctly. Users don't always understand installers either, but it is closer to the paradigm they tend to get than "decompress archive and put files in 'the right spot.'"

As for Steam... Steam provides facilities for helping install and uninstall a game, but it does not do *everything* for you. It's also worth noting that not all games are distributed on Steam or exclusively on Steam, so relying entirely on Steam's installation services will mean those games end up duplicating work for non-Steam distribution channels.

# Answer
> 5 votes
Actually, when steam installs a game, there's still an installer. There are quite a few installer packages around, and to build an installer you use one of these packages and then write an install script which tells the installer software to:

* Move files to the local PC.
* Register COM dlls.
* Add registry entries, possibly depending on a complex script.
* Run any copy-protection algorithms
* Register Services.
* Set environment variables, possibly depending on a complex script.
* Run additional 3rd party installers (DirectX and the .Net Frameworks being the most well known examples)
* Install shortcuts on the desktop and the start menu.
* Register the uninstall procedure.

The decision what to do there is not made by Steam, it's made by the install script, which you need to write no matter which installer package you use, be it WiX, NSIS, or Steam.

Unix has similar steps. You can move much of that logic to the first start of the application, but the logic still exists, you're just splitting the installer into multiple pieces and place one piece into your game instead of an installer. There are pros and contras for doing so, which I'd be happy to discuss in another question.

# Answer
> 1 votes
The question is incredibly ambiguous, but I think OP is asking why games need to be installed and run through a "store" application on the desktop instead of just being standalone.

The answer is simple: the distributor can make more money by tracking what you do, and the Digital Restrictions Management (DRM) is more effective when performed through a remote server operation. The store gateway also serves your eyes and clicks to their salespeople and makes additional purchases easier.

If you're distributing your own game, there is no need for such a store application. Use a simple installer and make your game DRM-free.

---
Tags: installer
---


# Question
Title: Graph search with a high number of actions
I have implemented A\* to reach a goal state from a start state. My state is position X,Y, angle and others state variable. I have a number of actions. What I call actions is : A\* on a grid has 4/8 actions (straight, right, left, back).

My character has a lot of different actions. I started with 20 possible actions which will lead to different future possible positions. with my implementation of A\* it is working fine and I found a solution.

Now, I want to do the same thing but with my real number of actions. Which is around 1000... If I run my algorithm it may take forever...

This figure shows my problem :

The first red node is the start position. The green is the goal. When A\* will expand my children. I will have 1000 children nodes (note: the nodes are in a kind of same region the light blue envelope)). But then I have 1000 nodes to study and which can be extented by 1000 children each... and so on. So the number can be really huge.

Does anybody have a good idea to deal with this kind of high number of actions in a A\* ? Finding a good heuristic won't be enough I guess cause too many possibilities. Maybe using this light region ? Any ideas ?

Thanks. Let me know, If it is unclear or need more explanations.

# Answer
This is indeed a common and open problem in robotics and ai. When the search space is becomming too large, consider to use stochastic approaches. For planning or path finding, Rapidly Exploring Random Trees (RRT) are a promising method to efficiently find asymptotically optimal solutions.

The basic idea is to start at some initial configuration (i.e. foot on ground), randomly sample free space (i.e. possible foot positions), choose the closest sampled configuration (i.e. smallest movement needed to get to a certain foot position) and add that to your sequence of actions (i.e. foot movement from start to green).

Alternatively, you can use genetic algorithms in order to gradually approach a good solution. Some example.
> 1 votes

# Answer
If your grid contains so many nodes, One solution to avoid a freeze up on your pathfinding would be to switch to a different map representation, such as a hierarchical map, a quad tree, or navigation meshes that uses less nodes in order to speed up your search.

Another solution that could considerably improve performance would be to get rid of the closed list data structure and instead use an integer, lets say runID, to determine if a node is on the closed list. Lets assume that each node had an integer, called closedID, where we would compare that value to the runID as a way to check if it is on the closed list. If runID == closedID, then we can assume that the node is on the closed list. this could also be done with the open list when checking if a node is inside it (It won't replace the whole open list data structure, obviously). the runID would be incremented everytime you did a new search.

Another performance improvement would be to use manhattan distance instead of euclidean distance (assuming you are using it) for the heuristic. Using the sqrt() function for euclidean distance on large maps is expensive.
> 0 votes

# Answer
Your problem is still open, in the sense there is so much research about optimizing pathfinding and reducing its time complexity (however there is much advancement if positions are constrained in euclidean space: so travelling cost is equal to distance), I don't know the details of your game, but I think you don't need to be 100% precise, if you have to play with foot positions I may argue a more viable solution is to just take random positions as long as those positions will end up closer to goal, then when you are close enough to your goal enable precise pathfinding in order to search for a local position.

You can even develop a strategy (the same a player would do), in a sense that you choose euristics that will move foots to predetermined locations (in example 2 vertical lines) from wich you know you can incrementally adjust nodes in the path, effectively I think your problem resembles me more Inverse Kinematics than pathfinding. If you need further delucidations just ask in comments.

In example, if you are able to reach a state such that your foots are along a line, and starting location and goal location are simmetric to that line, you then just need to know that you have to do the same moves you used to reach that line, but you have to mirror back that moves (you halve the distance of computations, wich turns in much lesser time because O is not linear)

Another possible approach, just reduce granularity of your coordinates when you are far from goal (in example instead of having 10 different states for X, just use 3/4 different states for it).

And as all algorithms, just quickly discard branches in your search that are clearly wrong or too distant, some simple heuristic will suffice.

In example, If I'm correct your are examining possible moves, wich means there will always be a move that will bring your foot back in its previous position, just discard branches for that moves.
> 0 votes

---
Tags: c++, algorithm, path-finding, graph
---


# Question
Title: How can I create a copy of an object in Unity?
I'm new to unity.

How can I make some copies of my GameObject in Unity by scripting?

I have tried this by the way:

```
public GameObject stone_3;

void Start ()
{
  for (int i = 0; i < 10; i++)
    Instantiate(stone_3, new Vector3(i * 2.0f, 0, 0), Quaternion.identity);
}

```

I can't really understand why it's not working.

# Answer
There may be two reasons why it's not working.

1. You have not attached the script to any object which is in the hierarchy window.
2. You have not assigned a prefab in the `stone_3` variable field.
> 2 votes

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


title: OpenGL contexts

text:
# Question
Title: OpenGL contexts
I have several questions related to OpenGL rendering and the issues I encountered while making 3D enigne. Some of them were asked before, but the answers are old and possibly outdated or ambiguous.

1) Is there a way to make sure that an OpenGL context was initialized before creating a resource?

I know that SMFL executes a function that checks for the existence of an active context in a current thread and creates it if there wasn't one, yet that implies at least some, hopyfully inlined, functions every time such a resource is created. (static hell) There is also a method to enforce creation of OGL resources by context/window but at the same time forces you to pass reference around.

2) Is there a point of doing so? If we gonna throw exception anyway, I don't see one. There is also not-so powerful "don't do it" written in the docs.

3) Do I even have to take into consideration possibility of multiple windows/contexts? What about multithreading?

I've read a little about creating 2 threads, one for rendering, second for passing data. It seems to me that I would have to wait for the other thread to finish before letting another one permission to go.

Huge thanks in advance :)

# Answer
I think you miss the point of what an engine is a little bit.

Game engines are developed in order to make game creation easier, without having the users of the engine to take care of complex low-level APIs. Therefore I would manage OpenGL resources internally, inside the engine.

So, let's go through your points.

1. It depends on how you build your system. In my tiny render engine(s) I used to have factories (**Factory**-Pattern) which created the resources for me. Thus it wasn't even possible for me to create a resource without having the factory instantiated. For example, you could create a OpenGL context class, which is acting as a factory for resources as well.
2. I don't get this point. As someone who wants to develop a game engine, you should aim for making game creation easier and more streamlined.
3. I would take into consideration, that one would create 2 or more windows with a context. This doesn't necessarily mean that each window should have its own context. One context can be shared across multiple windows. However, you can render only to one window at one time.
4. About multi threading and OpenGL: Just don't. I assume, that you want to issue multiple *drawcalls* from multiple threads. A OpenGL context is bound to a certain thread, usually by the '\*MakeCurrent' calls exposed by the windowing systems. Multi threading won't buy you much using OpenGL. For more, just read here.

Disclaimer: I am not a professional graphics engineer. My complete knowledge is self-taught using the reference or sites like SO.

EDIT: I forgot the obligatory "Write games, not engines!"
> 1 votes

---
Tags: opengl, c++
---


title: Problem with a TinyOBJLoader Renderer

text:
# Question
Title: Problem with a TinyOBJLoader Renderer
I was working on implementing a renderer for SYOYO's tiny obj loader and when it came to testing time, it failed to render. Here is an image of the result:

I believe that i have made the error with my renderer, in which i have no idea of what is wrong.

Here is the code for the renderer:

```
void flushTerrain() {
            while (!pr_Models.empty()) {
                const Model3D* model = pr_Models.front();

                model->getVAO()->bind();

                glm::mat4 a;
                glm::translate(a, glm::vec3(model->getPosition()));

                model->getShader().setUniformMat4("ml_matrix", a);
                glDrawArrays(GL_TRIANGLES, 0, model->getShapeVerticies().size());

                model->getVAO()->unbind();

                pr_Models.pop_front();
            }
        }

```

and the code for the Model3D Constructor:

```
Model3D(std::vector<tinyobj::shape_t> shapes, std::vector<tinyobj::material_t> materials ,glm::vec3 position, Shader& shader) :
            pr_shapes(shapes), pr_materials(materials), pr_position(position), pr_shader(shader)
        {
            pr_VAO = new VertexArray();
            for (tinyobj::shape_t shape : pr_shapes) {
                pr_VAO->addBuffer(new Buffer(shape.mesh.positions, shape.mesh.positions.size(), 3), 1);

                pr_VAO->addBuffer(new Buffer(shape.mesh.texcoords, shape.mesh.texcoords.size(), 2), 2);
                pr_VAO->addBuffer(new Buffer(shape.mesh.normals, shape.mesh.normals.size(), 3), 3);
            }
        }

```

and finally, for the Buffer and VertexArray class:

```
Buffer::Buffer(tinyobj::shape_t data, GLsizei count, GLuint componentCount) {
        glGenBuffers(1, &pr_BufferID);
        glBindBuffer(GL_ARRAY_BUFFER, pr_BufferID);
        glBufferData(GL_ARRAY_BUFFER, count * sizeof(tinyobj::shape_t), &data, GL_STATIC_DRAW);
        glBindBuffer(GL_ARRAY_BUFFER, 0);
    }

void VertexArray::addBuffer(Buffer* buffer, GLuint index) {
        bind();
        buffer->bind();

        glEnableVertexAttribArray(index);
        glVertexAttribPointer(index, buffer->getCount(), GL_FLOAT, GL_FALSE, 0, 0);

        buffer->unbind();
        unbind();
    }

```

# Answer
Make sure: Number of vertexes=3\*Number of Triangles when using gldrawelement(GL\_TRANGLES,...
> -1 votes

---
Tags: opengl, c++, models
---


title: LibGDX Json not parsing full file

text:
# Question
Title: LibGDX Json not parsing full file
I'm trying to load a World with different Objects (World Objects and Entities). For that, I want to use Json. For less than two elements this works like a charm. But as I add more elements, some values are skipped on parsing. I'm using LibGDX for my game. Here is my code:

**level001.json**

```
{
  "id":1,
  "title":"Broken Home",
  "design":"tomschneider",
  "tiles_x":32,
  "tiles_y":32,
  "objects":[
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.BlackHole",
      "pos_x":10,
      "pos_y":10
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.BlackHole",
      "pos_x":10,
      "pos_y":15
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.SpaceStation",
      "pos_x":0,
      "pos_y":0,
      "i1":0
    },
    {
      "class":"net.sutomaji.space2.helperclasses.LevelStore_Object",
      "object_name":"net.sutomaji.space2.gamelogic.objects.SpaceStation",
      "pos_x":5,
      "pos_y":0,
      "i1":1
    }
  ],
  "entities":[

  ]
}

```

**Excerpt of Level.java**

```
Json json = new Json();
        LevelStore ls = json.fromJson(LevelStore.class, Gdx.files.internal("Worlds/level001.json"));

        System.out.println(json.prettyPrint(ls));

```

**System.out**

```
{
tiles_x: 32,
entities: [],
objects: [
    {
        object_name: net.sutomaji.space2.gamelogic.objects.BlackHole,
        pos_x: 10,
        pos_y: 10
    },
    {
        object_name: net.sutomaji.space2.gamelogic.objects.BlackHole,
        pos_x: 10,
        pos_y: 15
    },
    {
        object_name: net.sutomaji.space2.gamelogic.objects.SpaceStation
    },
    {
        i1: 1,
        object_name: net.sutomaji.space2.gamelogic.objects.SpaceStation,
        pos_x: 5
    }
],
title: "Broken Home",
id: 1,
design: tomschneider,
tiles_y: 32
}

```

So I am loosing positions (pos\_x etc.) and other values (i1) on parsing. I don't know why. Do you have any ideas?

LibGDX API Json

# Answer
I have no idea about how JSON of the libGDX parser works, but from what I can see, only keys with a value of 0 were removed. So in your code, if you cannot read the value from the JSON, put 0 as the default one.

Also, you can play with the JSON parser to have a better print if you want: https://stackoverflow.com/questions/23401431/libgdx-json-parsing
> 1 votes

# Answer
From the libGDX github wiki:

> Note: By default, the Json class will not write those fields which have values that are identical to a newly constructed instance. If you wish to disable this behavior and include all fields, call `json.setUsePrototypes(false);`.
> 2 votes

---
Tags: java, libgdx
---


# Question
Title: Dealing With Multiple requestAnimationFrame Calls
I am having issues with requestAnimationFrame calls stacking on top of each other. I am developing a platformer game, which has three separate functions that need animating (main menu, cutscene, in game). Currently, I have flags to determine when to run requestAnimationFrame. For example, I only call requestAnimationFrame in the runCutscene() method if !onMainMenu and !inGame. These flags are reset in the init() method, which decides which of the three methods to run.

Specifically, my problem occurs when I return to the main menu from the cutscene (at seemingly random times, I can not continuously replicate the error). The main menu appears to run at double its normal speed (which I assume is because of stacked requestAnimationFrame calls).

What is the most efficient way to call requestAnimationFrame? If I put the requestAnimationFrame call in the init() method, the game breaks. Thank you in advance.

# Answer
As you noticed, you should call requestAnimationFrame only once per frame. It means that you need to call it once upon starting your game, and then once at the end of the same function it calls. For instance:

```
requestAnimationFrame(draw);
function draw() {
    if (onCutScene) drawCutScene();
    else if (onMainMenu) drawMainMenu();
    else if (inGame) drawGame();
    else if etc... //Or use a gameState variable and a switch..case
    requestAnimationFrame(draw);
}

```

The inner functions should not call requestAnimationFrame again.
> 1 votes

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


# Question
Title: DirecX 11 R8G8B8 24bit format without alpha channel?
This is maybe a stupid question but I can't seem to find texture format for simple 24bit R8G8B8? There is only 32bit R8G8B8A8, but some of my textures don't have alpha channel.

Is there any way to do this, or I'll just have to create alpha channel on every texture?

# Answer
There's also DXGI\_FORMAT\_B8G8R8X8\_\* formats - explicitly no alpha, but still you must expand 24-bit image into 32-bit texture when loading data.
In Direct3D11 24-bit and 16-bit formats are gone for good.
> 1 votes

---
Tags: textures, directx, directx11
---


# Question
Title: Why am I having trouble, combining color attachments to implement bloom?
I'm trying to implement bloom in the same manner as this tutorial, but I am having difficulties. I have the blur buffer blurring correctly, but I can't seem to combine the two images.

---

Below, you will find my code. The commented-out lines just render one or the other buffer to the screen, so I know these are correct. For now, I am just trying to combine them together; not fix them with HDR. I just add together both textures, but no matter how I change things around, all I get is the one on the left.

```
blurShader.use();
glUniform1i(glGetUniformLocation(blurShader.program, "horizontal"), true);
glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[1]);

long blurCount = 5;

for(long i=0; i<blurCount; i++)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glActiveTexture(GL_TEXTURE0);

    // bind texture of other framebuffer (or scene if first iteration)
    glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[i%2]);

    RenderQuad();
    glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[i%2]);
}

glUniform1i(glGetUniformLocation(blurShader.program, "horizontal"), false);

for(long i=0; i<blurCount; i++)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glActiveTexture(GL_TEXTURE0);

    // bind texture of other framebuffer (or scene if first iteration)
    glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[(i+1)%2]);

    RenderQuad();
    glBindFramebuffer(GL_FRAMEBUFFER, pingpongFBO[(i+1)%2]);
}

glBindFramebuffer(GL_FRAMEBUFFER, 0);

//renderScreenQuad(colorBuffers[0]);
//renderScreenQuad(pingpongColorbuffers[1]);

// 2. Now render floating point color buffer to 2D quad and tonemap HDR colors
// to default framebuffer's (clamped) color range
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
bloomShader.use();
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, colorBuffers[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[1]);
glUniform1i(glGetUniformLocation(bloomShader.program, "bloom"), bloom);
glUniform1f(glGetUniformLocation(bloomShader.program, "exposure"), exposure);
RenderQuad();

```

---

```
#version 330 core
out vec4 FragColor; in vec2 TexCoords;

uniform sampler2D colorTexture; uniform sampler2D bloomTexture;
uniform bool bloom; uniform float exposure;

void main() {
    vec3 firstColor = texture(colorTexture, TexCoords).rgb;
    vec3 secondColor = texture(bloomTexture, TexCoords).rgb;
    FragColor = vec4(firstColor+secondColor, 1.0f);
}

```

---

```
#version 330 core
layout (location = 0) in vec3 position; layout (location = 1) in vec2 texCoords;

out vec2 TexCoords;

void main() {
    gl_Position = vec4(position, 1.0f);
    TexCoords = texCoords;
}

```

---

Basically, what happens is that the first image bound goes through, and is accessible. Then, the second is the same as the first! If I change the order in which I bind the images, then the other image becomes the one sent in.

```
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[0]);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[1]);
glUniform1i(glGetUniformLocation(bloomShader.program, "bloom"), bloom);
glUniform1f(glGetUniformLocation(bloomShader.program, "exposure"), exposure);
RenderQuad();

```

The above code is the section I'm talking about. Each of the `pingpongcolorbuffers` is attached to its own FBO. I am trying to send those in. Is there some reason that would limit me to sending in only one?

Here is the combined result, before HDR:

# Answer
> 1 votes
Even though you are binding the textures correctly with glActiveTexture and glBindTexture you are not telling GLSL which sampler uniform goes to which texture. What you should do is this:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, colorBuffers[0]);
glUniformi(glGetUniformLocation(bloomShader.program, "colorTexture"), colorBuffers[0]);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, pingpongColorbuffers[1]);
glUniformi(glGetUniformLocation(bloomShader.program, "bloomTexture"), pingpongColorbuffers[1]));

```

---
Tags: opengl
---


# Question
Title: In Game Maker Studio, how do I make a sound play only once when I jump on a block?
In my Game Maker Studio game, jumping on a musical block should play a note. Currently, if I step on it, the note keeps repeating.

How can I avoid that? I only want the note to play once.

# Answer
> 1 votes
The function audio\_play\_sound as a third parameter, 'loop'. If this is set to true, then your sound will loop. Try setting this to false.

audio\_play\_sound(index, priority, loop);

Reference: http://docs.yoyogames.com/source/dadiospice/002\_reference/game%20assets/sounds/audio\_play\_sound.html

# Answer
> 0 votes
Try putting a boolean condition before playing the sound then making it false when a collision happens.

Something like this:

```
if (place_meeting(x+1,y,objPlayer) || place_meeting(x,y+1,objPlayer) ||
    place_meeting(x-1,y,objPlayer) || place_meeting(x,y-1,objPlayer) &&
    noLooping == true) {

    audio_play_sound(index, priority, false);
    noLooping = false;

} else {
    noLooping = true;
}

```

# Answer
> 0 votes
try this--

if !audio\_is\_playing(snd\_xyz) { audio\_play\_sound(snd\_xyz,..,..) }

I also had this problem once, though i could not solve it completely. The above code did some good though

# Answer
> 0 votes
I solved this problem without using any additional variables, just collision checking function. Assuming that in the real world when someone jumps you hear a sound only in the very moment contact with the ground occurs, I managed to get the following code which checks for collision in the current position and in the previous one. Objects name are only indicative:

```
var curr_coll = place_meeting(x,y+1,oBlock);
var prev_coll = place_meeting(xprevious,yprevious+1,oBlock);

```

Variables `curr_coll` is a boolean value that tells us if there's a collision with a block underneath the player at the *current* position. As well, `prev_coll` does the same, but assuming the player position in the previous game step.

So, we can have four different cases (CC: `curr_coll`, PC: `prev_coll`):

* **CC = 0, PC = 0 :** no collision both currently and previously, so the player has jumped and is in mid-air;
* **CC = 0, PC = 1 :** no collision now, but collision detected in the previous step. This means the player has just performed a jump;
* **CC = 1, PC = 0 :** there's a collision at the current step, and no collision a game step before. So, the player was in mid-air and is currently hitting the ground. *Now* you can play the proper musical sound;
* **CC = 1, PC = 1 :** there's always a collision with a given `oBlock` or whatever object, so the player is walking on top of it.

That said, we can write our code to check for the needed values. You can use both a `switch` statement, or a chain of `if`s, depending on your purpose. If we want to just play a sound only when landing on a musical key, we can write:

```
if ( (curr_coll==1) && (prev_coll==0) )
{
    audio_play_sound(sndNoteD,1,false);
}

```

So, our full code will be:

```
/// Step Event for object 'oPlayer' ///
var curr_coll = place_meeting(x,y+1,oBlock);
var prev_coll = place_meeting(xprevious,yprevious+1,oBlock);

// Play sound if walk/jump on a musical block
if ( (curr_coll==1) && (prev_coll==0) )
{
    audio_play_sound(sndNoteD,1,false);
}

```

As commented in code, this code may work both for jumping on top of or walking onto a musical block. If you want to distinguish between walking or jumping, you need to perform a couple of more checks, but nothing hard.

---
Tags: game-maker, sound-effects
---


# Question
Title: Unity VR: How to draw camera on top of VRSettings.showDeviceView mirroring
We're using VRSettings.showDeviceView = true to mirror the VR display to the main window. We also have a camera that we'd like to draw over top of the main window's mirrored VR image. This other camera renders an overlay for people who are watching the mirrored VR view.

Right now the overlay camera has a depth of 5 and the VR camera has a depth of 0, but as far as I can tell I think the overlay camera of depth 5 is being overwritten by the mirror drawn by showDeviceView = true.

Anyone know an easy trick to get this behaviour?

Thanks for your time,

Allen

# Answer
You should be able to get the effect by disabling mirroring (VRSettings.showDeviceView = false), and then setting up an additional camera that displays to the main window. Make the second camera a child of the VR camera (with the same size, FOV, etc.), and then set up any overlay objects on their own layer that is not viewable to the VR camera.
> 1 votes

---
Tags: unity, camera, virtual-reality, overlay
---


# Question
Title: How can I pass a texture to a custom deferred lighting model in Unity?
I've replaced the `Internal-DeferredShading.shader` with my own shader, and it's working fine, but I want to add a uniform texture for it to sample from.

I've tried adding a texture as a property and assigning it a default value in the inspector but at run-time the shader still uses the default value given in the shader (e.g. `white`).

Is it possible to do this?

# Answer
> 0 votes
(Not 5 minutes after posting this I found a solution. Might as well share it here if someone else is curious about this in the future.)

It's possible to set the texture using Shader.SetGlobalTexture. For this to work properly I also had to remove the texture as a property of the shader.

I have the following script attached to an object in the scene and it's working perfectly:

```
[ExecuteInEditMode]
public class ChangeDeferredLightingTexture : MonoBehaviour {

    public Texture texture;
    public string shaderVariableName;

    void OnValidate() {
        Shader.SetGlobalTexture(shaderVariableName, texture);
    }
}

```

---
Tags: shaders, unity
---


title: Terrain Collision problem

text:
# Question
Title: Terrain Collision problem
I'm trying to implement terrain collision for my height map terrain, and I'm following this. The tutorial is for java but I'm using C++, though the principles are the same so it shouldn't be a problem.

To start off we need a function to get the height of the terrain based on the camera's position. WorldX and WorldZ is the camera's position (x, z) and heights is an 2D-array containing all the heights of the vertices.

```
float HeightMap::getHeightOfTerrain(float worldX, float worldZ, float heights[][256])
{
    //Image is (256 x 256)
    float gridLength = 256;
    float terrainLength = 256;

    float terrainX = worldX;
    float terrainZ = worldZ;
    float gridSquareLength = terrainLength / ((float)gridLength - 1);
    int gridX = (int)std::floor(terrainX / gridSquareLength);
    int gridZ = (int)std::floor(terrainZ / gridSquareLength);

    //Check if position is on the terrain
    if (gridX >= gridLength - 1 || gridZ >= gridLength - 1 || gridX < 0 || gridZ < 0)
    {
        return 0;
    }

    //Find out where the player is on the grid square
    float xCoord = std::fmod(terrainX, gridSquareLength) / gridSquareLength;
    float zCoord = std::fmod(terrainZ, gridSquareLength) / gridSquareLength;
    float answer = 0.0;

    //Top triangle of a square else the bottom
    if (xCoord <= (1 - zCoord))
    {
        answer = barryCentric(glm::vec3(0, heights[gridX][gridZ], 0),
        glm::vec3(1, heights[gridX + 1][gridZ], 0), glm::vec3(0, heights[gridX][gridZ + 1], 1),
        glm::vec2(xCoord, zCoord));
    }

    else
    {
        answer = barryCentric(glm::vec3(1, heights[gridX + 1][gridZ], 0),
        glm::vec3(1, heights[gridX + 1][gridZ + 1], 1), glm::vec3(0, heights[gridX][gridZ + 1], 1),
        glm::vec2(xCoord, zCoord));
    }

    return answer;
}

```

To find the height of the triangle the camera is currently standing on we use the baryCentric interpolation function.

```
float HeightMap::barryCentric(glm::vec3 p1, glm::vec3 p2, glm::vec3 p3, glm::vec2 pos)
{
    float det = (p2.z - p3.z) * (p1.x - p3.x) + (p3.x - p2.x) * (p1.z - p3.z);
    float l1 = ((p2.z - p3.z) * (pos.x - p3.x) + (p3.x - p2.x) * (pos.y - p3.z)) / det;
    float l2 = ((p3.z - p1.z) * (pos.x - p3.x) + (p1.x - p3.x) * (pos.y - p3.z)) / det;
    float l3 = 1.0f - l1 - l2;
    return l1 * p1.y + l2 * p2.y + l3 * p3.y;
}

```

Then we just have to use the height we have calculated to check for collision during the game

```
float terrainHeight = heightMap.getHeightOfTerrain(camera.Position.x, camera.Position.z, heights);
    if (camera.Position.y < terrainHeight)
    {
        camera.Position.y = terrainHeight;
    };

```

Now according to the tutorial this should work perfectly fine, but the height is rather off and at some places it doesn't even work. I figured it might have something to do with the translation and scaling part of the terrain

```
    glm::mat4 model;
    model = glm::translate(model, glm::vec3(0.0f, -0.3f, -15.0f));
    model = glm::scale(model, glm::vec3(0.1f, 0.1f, 0.1f));

```

and that I should multiply the values of the heights array by 0.1, as the scaling does that part for the terrain on the GPU side, but that didn't do the trick.

**Note**

In the tutorial the first lines in the getHeightOfTerrain function says

```
float terrainX = worldX - x;
float terrainZ = worldZ - z;

```

where x and z is the world position of the terrain. This is done to get the player position relative to the terrain's position. I tried with the values from the translation part, but it doensn't work either. I changed these lines because it doesn't seem necessary.

**Additional**

This is the vector where I store all the vertices in the grid with their respective x,y and z-values.

```
std::vector<glm::vec3> heightVertices(NumVertices);

```

To get the 2D-array for the getHeightOfTerrain function, I simply do

```
for (int i = 0; i < 256; i++)
    {
        for (int j = 0; j < 256; j++)
        {
            heights[i][j] = heightVertices[i].y;
        }
    }

```

And to get all the vertices for the terrain I use a BMP-file and carry on like below. If there would a problem in the code I assume it has to do with the vertices of the terrain, so I'll just list that part

```
    FILE *filePtr;
    BITMAPFILEHEADER bitmapFileHeader;  // For file
    BITMAPINFOHEADER bitmapInfoHeader;  // For image
    int imageSize, index;
    unsigned char height; // Color values

    filePtr = fopen(filename, "rb");
    if (filePtr == NULL)
    {
        printf("Cannot open file! \n");
        getchar();
        return false;
    }

    fread(&bitmapFileHeader, sizeof(BITMAPFILEHEADER), 1, filePtr);
    fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, filePtr);

    terrainWidth = bitmapInfoHeader.biWidth;
    terrainHeight = bitmapInfoHeader.biHeight;
    imageSize = terrainWidth * terrainHeight * 3;

    // Initialize the array which stores the image data
    unsigned char* bitmapImage = new unsigned char[imageSize];
    fseek(filePtr, bitmapFileHeader.bfOffBits, SEEK_SET);

    // Store image data in bitmapImage
    fread(bitmapImage, 1, imageSize, filePtr);
    fclose(filePtr);

    // Size of the image length and height (vertices of the terrain).
    heightMap = new glm::vec3[terrainWidth * terrainHeight];

    int k = 0;
    float heightFactor = 10.0f;

    // Read the image data into our heightMap array
    for (int j = 0; j < terrainHeight; j++)
    {
        for (int i = 0; i < terrainWidth; i++)
        {
            height = bitmapImage[k];
            index = (terrainHeight * j) + i;

            heightMap[index].x = (float)i;
            heightMap[index].y = (float)height / heightFactor;
            heightMap[index].z = (float)j;

            k += 3;
        }
    }

    delete[] bitmapImage;
    bitmapImage = 0;

    // Create vertices of the grid
    int cols = terrainWidth;
    int rows = terrainHeight;

    // Create the grid
    NumVertices = rows * cols;
    NumFaces = (rows - 1)*(cols - 1) * 2;

    std::vector<glm::vec3> heightVertices(NumVertices);

    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < cols; ++j)
        {
            heightVertices[i*cols + j] = heightMap[i*cols + j];
        }
    }

```

# Answer
You are offsetting the model as well as scaling its x and z coordinates, which I assume is why this is failing for you.

You really aren't providing enough information to help you more than that, since we don't know how your interface between the terrain and the rest of the game looks like.

I'd assume that if you account for the offset and the scaling along the x and z axis it will work unless you have another problem in your code.
> 0 votes

---
Tags: opengl, c++, collision-detection, mathematics, terrain
---


# Question
Title: How can i exclude "Y" from drag in unity?
I'm trying to make a moving object drag when no input is received, but i want the drag to only apply to X and Z variables, and not Y. Meaning i want it to fall at a normal speed, but when i stop giving it force in x and z directions, i want it to gradually and quickly stop going in those directions. How can i achieve this?

I've done this:

```
Vector3 input = new Vector3(Input.GetAxis("Horizontal") , 0, Input.GetAxis("Vertical");
If (input.x == 0 && input.z ==0) rb.drag = 3;

```

# Answer
> 1 votes
`Drag` of a `Rigidbody` is directed toward positive y-axis as it's supposed to be in a physical circumstances.

For moving and stopping a `Rigidbody` quick and gradually you should use it's `velocity` depending on `input`. As soon as there is no `input`, it will gradually stop.

Your code should be like:

```
void FixedUpdate()
{
 Vector3 input = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));

 rigidbody.velocity = input * 10f;// * Time.fixedDeltaTime; // Increase the value if using fixedDeltaTime
}

```

---
Tags: unity
---


# Question
Title: how to handle the virtual Z axis in 2D games?
I'm using this paper 2d framework of UE4 where a plane mapped with sprite texture is put in 3d world and therefore appears as 2D when viewed from sideways.

Its all good for games like NES mario where other than jumping you can only move along X axis.

However if you look at games like double dragon and Battletoads they have an isometric perspective and a virtual third co-ordinate axis which points outwards from the screen towards the player, you walk along this with d-pad up and down. It also works for objects in the scene such as a box or ladder which you can climb up and down along this axis, it also affects the game logic say like where your character's landing point would be when you jump.

how would you go about implementing this using 3d planes mapped to 2d textures without making some virtual co-ordinate system of your own?

# Answer
> 1 votes
Something very simple I used on Tiny Avengers and many other mini beat'em all was to link the Y axis to the Z axis.

The more the object is up the more in depth it will be.

So if your character is at 25 on Y it will also be at 25 on Z... which means that a crate placed at 20 on Y will be displayed in front of the player and will give an effect of depth.

Also I would suggest you to apply a slower speed movement for the Y axis than the one applied on the X axis.

# Answer
> 0 votes
The Battletoads solution is not quite isometric. It's drawn pseudo-isometric but the movement isn't. It's a regular square coordinate system except you move up and down slower to make it feel isometric-ish.

The world XY position of the toad is the position on the ground as marked by the shadow. During jumps the jump height (world Z) is added to the world Y coordinate of the Sprite to make screen Y (world X and screen X are the same). When a pig swings its axe at your shadow it compares the relative jump heights to see if it's a hit or not.

To complicate things, some interactions (like catching flies) are done in screen space. So, if the toad's screen XY and fly's screen XY line up then you catch it no matter your world coordinates.

If you're doing proper isometric then screenX=worldX-worldY and screenY=(worldX+worldY)/2+worldZ but the controls wont feel right on D-pad (check out the feel of Solstice)

---
Tags: 2d, mathematics, movement, axis
---


title: Java Game Optimizing

text:
# Question
Title: Java Game Optimizing
I'm trying to optimize my game. I've got object Handler that goes trought all objects and then render and tick them. If I have lot of objects in game game lags or don't start. Could you please help me? public class Handler {

```
public LinkedList<GameObject> object = new LinkedList<GameObject>();

private GameObject tempObject;

private Camera cam;

public Handler(Camera cam) {
    this.cam = cam;
}

public void tick() {

    for (int i = 0; i < object.size(); i++) {
        tempObject = object.get(i);

        tempObject.tick(object);

    }

}

public void render(Graphics g) {

    for (int i = 0; i < object.size(); i++) {
        tempObject = object.get(i);

        tempObject.render(g);

    }

}

```

# Answer
> 1 votes
First tip, don't use a linked list. At least not in this way. Use an ArrayList instead. If you absolutely have to use a linked list use an iterator.

Secondly it's probably a good idea to cull stuff on your screen. That should get you going for a while. Although I am willing to bet there are performance issues elsewhere as well.

---
Tags: java, optimization
---


# Question
Title: libgdx ActorGestureListener.pan() parameters not moving actor in smooth line
I override the `pan` method in `ActorGestureListener` to implement dragging actors in libgdx (scene2d).

When I move individual pieces on a board they move smoothly, but when moving the whole board, the x and y coordinates that is sent to pan is "jumping", and in an increasingly amount the longer it is dragged.

These are an example of the deltaY coordinates sent to pan when dragging smoothly downwards:

```
 1.1156368
-0.13125038
-1.0500145
 0.98439217
-1.0500202
 0.91877174
-0.984396
 0.9187679
-0.98439026
 0.9187641
-0.13125038

```

This is how I move the camera:

```
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    cam.translate(-deltaX, -deltaY);

```

I have been using both the delta values sent to pan and the real position values, but similar results. And since it is the coordinates that are wrong, it doesn't matter whether I move the board itself or the camera.

What could the cause be for this and what is the solution?

When I move camera only half the delta-values, it moves smoothly but only at half the speed of the mouse pointer:

```
cam.translate(-deltaX / 2, -deltaY / 2);

```

It seems like the moving of camera or board affects the mouse input coordinates. How can I drag at "mouse speed" and still get smooth movements?

(This question was also posted on stackoverflow: https://stackoverflow.com/questions/20693020/libgdx-actorgesturelistener-pan-parameters-not-moving-actor-in-smooth-line)

# Answer
> 1 votes
try this: for moving camera

```
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    camera.position.add((-x), (y), 0);
    camera.update();
}

```

for moving actor

```
public void pan (InputEvent event, float x, float y, float deltaX, float deltaY) {
    actor.setPosition(actor.positionX + deltaX, actor.positionY + deltaY);
}

```

# Answer
> 1 votes
I'm aware this is really late and you've probably already solved the problem but for future readers:

This forum post helped me: http://badlogicgames.com/forum/viewtopic.php?f=11&t=12343

If you move the camera while part way through a pan or ANY gesture the coordinate system being used for the x and y coordinates is changed and that's why you get the jumpy deltas alternating between +ve and -ve values.

The fix I used is to not use the pan() gesture and implement it like so:

```
private Vector3 prevDragPos;
addListener(new InputListener(){
        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            return true;
        }

        @Override
        public void touchDragged(InputEvent event, float x, float y, int pointer) {
            x = Gdx.input.getX(pointer);
            y = Gdx.input.getY(pointer);
            if(prevDragPos == null) prevDragPos = new Vector3(x, y, 0);

            getStage().getCamera().position.add(prevDragPos.x - x), y - prevDragPos.y, 0);
            prevDragPos.set(x, y, 0);
        }

        @Override
        public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
            prevDragPos = null ;
        }
    });

```

`Gdx.input.getX()` and `Gdx.input.getY()` don't get converted to camera coordinates so using them fixes the problem.

---
Tags: java, libgdx
---