# Question
Title: What is the difference between a Sprite and a Texture?
I have an assignment due for University, and my task is to discuss textures used within video games, and how they have evolved.

My main question is, what is the fundamental difference between using a sprite, or using other texture methods?

Having done a little research myself, I seem to be inclined that Sprites store images in a single file, and can be used for animations etc.. and were commonly used with older video games, generally using sprites as all of their game visuals. Now, with modern games, sprites I believe tend to be less used as technology advances and other textures are available such as bump mapping. Although sprites are still used today to accommodate features such as a health bar or long distance textures.

But what are the main advantages of using textures, over sprites?

# Answer
At the end of the day, sprites and textures are just images - blocks of raster colour data (although sometimes we push the bounds a bit to put non-image data into them). The distinction is largely in how we use them.

We usually call an image (or a part of an image that contains many separate pieces) a "sprite" if its intended rendering purpose is to be drawn straight to the 2D grid of the screen, without perspective distortion. So what you see in the running game is basically what you see in the image file itself (apart from colour tinting/palette swapping/transparency effects). This applies to the background tiles and characters / interactive objects in 2D games, "billboard" cards like particles and older styles of tree & shrub rendering, and also to the user interface elements and icons in 3D games too.

Conversely, if we're using an image to provide surface detail for the polygons of a 3D object that might be drawn in perspective, we usually call that image a "texture." That name has carried over to other uses of image data to modulate rendering of something else, even if they're no longer about texture in the sense you could feel with your fingertips - things like reflections, distortion maps, overlays, masks, or any general-purpose use of images we don't feel like naming more specifically tends to get lumped under "texture" in our loose nomenclature.

That makes the bounds between the two fuzzy and not particularly strict. If I have an image containing a sequence of fire and smoke plumes to use in drawing billboarded particles for an explosion effect, I might call that a "spritesheet" or a "flipbook texture" interchangeably. Or if I have a tileset image comprising all the background tiles for a 2D game, I might call that a "texture atlas" today, by analogy with atlas textures developed for 3D games, even though its data and use in my 2D game is indistinguishable from what someone else would call a spritesheet. If I have a rectangle of geometry whose purpose is to present a single image to the screen, I might call that a "textured quad" or a "sprite" depending on what I want to emphasize about its use.

(Note here in this last example that "sprite" stands for both the source image segment in our game assets, and the instance of a rendered game entity that uses this image segment - another way we use this terminology a bit inconsistently)

You'll find some engines and libraries encode this distinction in rendering intent into their own nomenclature. For instance, in Unity, you can choose to import an image asset as a "Sprite" - this enables an extra set of options that are commonly desired for UI images or 2D game assets, like spritesheet slicing & packing, and the ability to reference parts of the image as discrete entities in your scene and object setup. In these cases "Sprite" often means "an image (texture) *plus metadata*" - but it's still rendered the same as ordinary textures under the hood. The extra packaging is a convenience so we don't need to micromanage UV offsets and the like everywhere we want to use the image; instead these frameworks conceptually pack that data in as part of the asset entity itself.
> 39 votes

# Answer
A sprite is a relict from the history of computer games. Think 8-bit Ataris around ca. 1980. A little image, usually with a coverage bitmask (or a special "transparent" color) that has a position on the screen and is combined onto the screen in some particular way. With holes where there be "holes" in the sprite, as per the coverage map. Usually in a "just works" way, and in a way that easily allows for the illusion of stuff moving around, usually by saving and restoring the overwritten original screen pixels.

Used to be that sprites were a hardware feature on computers, used to be you could draw/undraw them with screen contents being saved automatically, used to be you could only have a very limited number of them (and non-overlapping, yay!), and used to be that they're pretty darn small (like 16x16) and limited.

The mouse cursor is what comes closest to a sprite nowadays (and used to be it *was* an actual sprite on some systems until some ~10-15 years ago).

Nowadays, no such thing really exists, but the word remains. A sprite is basically a small 2D image that you draw (composite) somewhere. Usually by drawing a small textured quad.

A texture, on the other hand, is the concept of a readable image used in somewhat more modern graphics APIs. Or, more precisely, a region of memory ("buffer" in terms of modern APIs) with some associated extra data such as size, which can be sampled from via some means. Usually, but not necessarily by a shader running on a graphics processing unit. Usually, but not necessarily, with normalized coordinates, and usually but not necessarily with filtering (and mipmapping, and some particular border mode, and, and, and...).

Thus, a texture may be the source of the data what you use to draw a sprite.
> 7 votes

# Answer
It's sortof an apples and oranges comparison. A texture is just an image, while a sprite is an image *and* how it's used.

We still use sprites for 2d games, and they show up in 3d games in particle effects. Nowadays, sprites generally refer to a certain kind of textured quad, or (rarely, I think) a single triangle. Even UI elements are often still textured quads - which I would call sprites.

It used to be the case that sprites were preloaded into memory and blitted (byte-for-byte mem-copied) to points on screen (literally, screen memory), like stamps. In a way, we still do that. For sprite animations, we often alter the sample coordinates of the source texture to copy segments from textures to be rendered onto quads. Shader effects, such as bump mapping, sample from textures in the same way and thus are still usable for, say, glow effects in sprites.

More particular to 2d games, it's a stylistic choice. One could, for example, compose hand drawn or painted characters in a game using sprites. The South Park games would be an example of that, technically.

So, you can't really use *just* a texture in place of a sprite.
> 4 votes

# Answer
Here is a simple and short answer. I usually think of the sprite as the entire object itself alongside whatever functions and textures to have applied to it. As for texture, I pretty much consider it just a image that could be applied to something.
> 3 votes

---
Tags: textures, sprites, terminology
---


# Question
Title: How to pass array of dozens of floats to OpenGL 3.0 vertex shader?
I use PyOpengl and Python 3.

I have 50 thousand vertices. Position of each vertex could be calculated in vertex shader as

```
#version 300 es

uniform v_coefficients_weights[COEFFICIENTS_AMOUNT];
in vec3 v_coefficients[COEFFICIENTS_AMOUNT];
in vec3 v_initial_position;
out vec3 v_position;

void main() {
    v_position = v_initial_position + v_coefficients * coefficients_weights;
}

```

Amount of coefficients varies between 0 and 199 — it's not a problem for me to generate 200 vertex shaders to cover each situation. I need to change position of vertices tens of thousands times per application calls as fast as it's possible, so I cannot calculate them once on start.

Though, I cannot provide arrays for each vertex because documentation says:

> Attribute variables cannot be declared as arrays or structures.

I see following solutions of this issue:

* (will **not** work) hardcode suffices of variables names to emulate arrays:
    + use vectors with names like coefficients\_000, coefficients\_001, ..., coefficients\_199;
    + use matrices to have 4 vectors in each of variable — will it be better than previous solution with vectors (maybe performance of matrices product is faster than 4 products of vectors)?
* calculate vertices positions by myself using C/NumPy;
* calculate vertices positions by myself in parallel using OpenCL;
* (will **not** work) store all coefficients in `uniform int v_coefficients[COEFFICIENTS_AMOUNT*VERTICES_AMOUNT]` and access needed ones according to vertex number, which will be stored in `in int vertex_id`;
* store coefficients in textures (proposed by @HolyBlackCat).

Are there any other solutions of my issue? Is there optimal solution in proposed above? Will I go out of memory if I will use 200 float 3-vectors for each vertex?

I imagine the solution with hardcoded indices as:

```
#version 300 es

uniform v_coefficients_weights[COEFFICIENTS_AMOUNT];

in vec3 v_coefficients_000;
in vec3 v_coefficients_001;
...
in vec3 v_coefficients_199;

in vec3 v_initial_position;
out vec3 v_position;

void main() {
    v_position = v_initial_position
        + v_coefficients[0] * coefficients_weights_000
        + v_coefficients[1] * coefficients_weights_001
        + ...
        + v_coefficients[199] * coefficients_weights_199;
}

```

# Answer
The best solutions appeared to be

* Store coefficients in texture (proposed by @HolyBlackCat). OpenGL allows to save array of `float`s there.
* Calculate all needed values before passing to GPU. I've faced a performance issue when stored array in texture.
> 0 votes

---
Tags: opengl, shaders, glsl, vertex, vertex-attribute
---


# Question
Title: Blender assets management and workflow for Unity project
I'm trying to decide how to manage my 3D assets, and even how I should construct a world for my game.

I should maybe explain, my game is basically a single explorable world set in a school. It's quite large. Every room and building enterable (possibly transitionless), and a large outdoor area (sports field, playground, etc.) I plan to make much of it modular (walls, floors, etc.) The world is somewhat tiled. I've create several different blocks for walls (Straight, cornered, T shaped, cross shaped, door, etc.) which I can place sequentially to create rooms and buildings. I have some blocks lined up in a row in Blender. Now I'm wondering what to do with these pieces...

Issue 1)

Should I use Unity to place my assets to create my world, or do I create another blender file with all my assets linked? I'm tending towards the latter because I feel I can do a lot more within Blender, but it doesn't appear very easy. However in order for the game to function I'd imagine I'd have to cut up my world into pieces. Problematically I'd also like to use Unity's terrain tool, so if I'm creating a single world object in Blender I'm not sure how I'd do this.

Issue 2)

I'm not very experienced in 3D game development, I've mainly worked with Flash up until recently. In Flash, you can create movieclips which nest other movieclips. Preferablly I'd like a system as close to this as possible within Blender or Unity.

So for instance, I'd like to have a 3D asset of a table. Without affecting the original asset, I want to place objects on the table like books and whatnot, and then control this as a single instance called 'Table with books', maybe duplicate it elsewhere, if I change the position of the books on one it should update all other instances.

In Blender, I use alt+D to duplicate an object and link it to the original, however it's very easy to duplicate an object without selecting it's children and creating a variety of differently childrened duplicates, which in a vast world which is hard to keep track of, would become a massive headache to deal with. I can just imagine spending hours upon hours correcting a single silly mistake I produced and repeated without noticing for several days.

Within Blender I've tried making each wall object it's own group, however they're all in one file and have different xyz positions. I don't want to separate them into dfferent files, in order to create seamless walls I need to have them all in one place. When I create a group instance with shift+A, the origin is of the original group object's xyz position:

I know there's an offset option in the groups panel where I could set it to -2,4,0 to counteract this but I don't like this at all. If I move 10 original grouped objects I have to update each of their offsets! I suppose I could create an empty axis for each wall object, but this also seems an odd way of doing things.

Issue 3)

Walls are 2 sided objects, the design of one could be different on either side, one could be pink on one side with a skirting board, the other side could be exposed brick work. How would I do this? Lets say I use Unity to position all my assets (which I'm now assuming is probably the right way), ideally I'd like to select a load of walls faces and change their design with a combo box of styles and a color picker in the inspector (a script would be necessary obviously).

---

Sorry, that's a lot of questions for a single post, I hope someone can point me in the right direction.

# Answer
> 1 votes
> Issue 1: Should I use Unity to place my assets to create my world, or do I create another blender file with all my assets linked?

Both strategies can work depending on what's more comfortable for you. When you create the world in Unity it will be easier to control it *from* Unity (add, move or remove objects at runtime). But neither will give you an usability experience as you are used to from Flash.

A third option you could try is building your level editor into your game which behaves the way you want it to. That way you can write a specialized editor which is more easier to work with than either the Unity editor or Blender. The initial cost of creating that edit mode might or might not amortize depending on how much level building you expect to be doing.

> Issue 2: Edit one thing and have it affect all the duplicates of it

This can be easily done in Unity through prefabs. When you change a prefab, you also change all instances of it. Prefabs can have children which can in turn also be prefabs. So you can have a classroom-prefab with a desk-prefab child which in turn has a book-prefab child. You can then place that whole object-tree with a single drag&drop, edit it, and then either "Apply" it to make your changes apply to all other classrooms, or don't to have them as independent modifications.

The prefab system is a really basic concept of Unity which is covered in most basic tutorials, so forgive me if I don't write yet another detailed explanation of *how* to use it.

> Issue 3 Walls are 2 sided objects

Not necessarily :)

Each polygons of a 3d model has a surface normal which says from which direction it is visible. When viewed from the other direction, the polygons are invisible. Blender doesn't show this, but Unity does when you import the model. So when you have two adjacent rooms wall-to-wall you can have the walls of both rooms on the exact same coordinates. When both walls have surface normals facing inside the room they belong to, the player always sees the texture of the correct side.

# Answer
> 0 votes
To design walls you should use cubes in blender and not planes.

For issue 2 you should use prefabs , for better understanding of prefabs : https://docs.unity3d.com/Manual/Prefabs.html

For issue 1 i would suggest you to make different components of your scene in blender individually.(if you want a table in the scene make a table in one project, and buildings in the other.) after you have made your scene components individually you can assemble them in the Unity3D scene editor.

# Answer
> -2 votes
Personally, I've had a lot of success with modelling stuff such as walls, chairs, or the like in Autodesk Inventor, exporting that to an stl file, importing that into Blender, and exporting that to fbx.

It's a messy pipeline, but it's helped me out a lot, especially when designing things like beakers or test tubes for visualizations. I've found that the extra precision you get when working with Inventor, due to the availability of dimensions and measurements, is a huge help when designing either a game world or objects to populate it.

Obviously, some things won't be doable through this pipeline - like a human form, or a really irregular shape like a crumpled up piece of paper. For those, I would recommend either Maya or just Blender.

Hope this helped!

---
Tags: unity, blender, assets, gameobject, asset-workflow
---


# Question
Title: Unity3D (2D) - Make sure Item Dragged Is Top Item Visually
I am using Unity 5 and making a 2D game in which many sprites will be stacked on top of each other and can then be moved by dragging. Sometimes when the users goes to drag from a pile, ones that aren't on the top are dragged instead. Is there any way to make sure that the one that is dragged is the one on top? Thanks

# Answer
Here's an idea: move them a tiny bit on the z-axis, or whichever axis the camera is oriented on. Then make it so that they block raycasting to things behind them - putting the sprites at minimally different positions on the z-axis should allow for the colliders to block the raycasting to anything behind it.
> 1 votes

# Answer
Take a look at this tutorial on Sprite Sorting Layers

In short, you can use the Sprite Renderer component and modify the layer properties to achieve the effect you want.
> -1 votes

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


# Question
Title: How to simulate car drivetrain (in Unity)?
One of my hobby projects involves cars. Up until now I had a quick and dirty "one class" implementation of engine+gearbox+wheels, but I thought that this is ugly, and I want to go a bit more realistic. Sadly I couldn't find much on Google (either wrong search terms or there really isn't anything that is what I want). It seems like

Setup in scene: Four wheelcolliders attached to a big boxcollider.

Things that I want in the system:

Separate classes for engine, clutch, gearbox, differential and wheels (and whatever else does stuff with torque). Throttlecontrol with revlimiter (works!), steering (works too!), brakes (not yet made, but also not very complex and will likely work).

* **First thing I tried:**

Mainly this rotates around how I tell the engine that the wheels are actually using or giving (engine braking) power to the system. so first I created all the classes each with their own `updatemethod` (not called directly by mainloop, but from a fixedupdate of a controllerclass). `updatemethod` of engine calculates engine torque from throttle, torque curve (animation curve) and engine friction. This is then used to speed up the virtual crankshaft which has its own inertia. But before speeding up the shaft, I decided to put some feedback torques on the engine torque, so if the wheels can't keep up, the engine can't speed up, or even slows down. Such a feedback torque is added for example by the gearbox, which in turn also has feedback forces from the differential and with that the wheels. The wheels calculate the torque needed to spin up to the speed of the shaft coming out of the gearbox and then it propagates all back to the engine over a few updates.

Problem was, the torque feedback didn't really do engine braking, but catapulted it to several million RPM in a split second. Dividing the feedback torque by 1000 did work, but then the car didn't move at all. So this is fail number 1.

* **Fail number 2:**

Okay screw this, I thought, and tidied up all the stuff. This doesn't use several `updatemethod` anymore, but recursive updating. Basically I call update on the engine, which in turn then calculates what torque it has available. With that it tells the transmission that it has `t` torques at `r` RPMs. The gearbox changes the values according to the current gear and then again puts the values into the differential. The differential SHOULD split the torque between its outputs. To do this I calculate how much torque the output (in this case wheels) would need to speed up to `r` RPMs. I do this for each output and make a list of it for each output. I also save the sum of these values. With this I can get a value of `0...1` for each output, that determines how much torque each output gets in its `updatemethod`. Its basically an intelligent differential that gives the output which needs more torque, more torque. I guess modeling a real differential would involve some more complex stuff. Now the torque is at the wheels and gets put into the motorTorque property of the wheelcollider. Up until here it works. If I throttle up and then let go of it the wheels start turning backwards. It's basically another feedbackloop just like with the first try. So also fail

* **And fail 3:**

Instead of returning the torque that's left, I tried backpropagating the RPMs to the engine instead. So I apply torque, and get RPMs back. But again everything tries to move the car in the opposite direction that I want it to go.

Here is where I'm out of ideas. I want a relatively realistic drivetrain, that is modular and can do enginebraking. A bought asset will most probably not solve my problem, and I also want to understand how it works, and not just use it.

Does anybody have experience with how to properly model a drivetrain?

If I forgot to mention something, please ask.

# Answer
> 1 votes
One suggestion I could think of is to restructure how you think of the math, and also working from the outside in.

So first, have it so that your input directly controls the wheels - not very realistic, but it will allow for you to see what happens with the physics of the wheels spinning against the ground without an excessive amount of variables determining how they spin. Once you've dialed in the parameters necessary to make realistic wheel physics, then we can start to focus on the internals of the vehicle.

First off, when it comes to the gearboxes that the wheels are attached to, I would recommend starting simple. Only use a gear ratio calculation to determine how fast the wheels go based on the input - no feedback yet, not until the whole system has some sort of functional framework.

The drive shaft should just be 1:1 for early testing purposes - assume a perfect system for now, and we can dial in different values later.

For the engine, I'd recommend making it little more than a fancy calculator - give it input, and it outputs a value that determines how quickly the driveshaft spins, and how that spins the gearboxes.

Then, use a gear ratio to drive the wheels. I would recommend not giving the components such as the gearbox, engine, and driveshaft collision, or any physics at all - I would recommend just animating them according to how quickly they should be spinning. Their collisions could end up making the car behave in ways you don't particularly want it to.

Moving forward, you can start to rely on the Unity physics engine a little more - but to be perfectly honest, I would recommend only giving physics to your wheels, and just calculating the final torque imparted upon them.

---
Tags: unity, simulations, car, torque
---


# Question
Title: Could a Peer-To-Peer network architecture be good for my fighting game
I am looking forward to developing a **2D spaceship-fighting, brawler game** and I have so many ideas about it. I am going to make a single-player component anyway, but the core of this game would certainly be its multiplayer. For this game, I was **inspired by Brawlhalla** and its dynamic play-style. In my game, there has to be real-time action features such as attack, dodge, getting hit, killed, so a reliable networking needs to exist. I have thought initially about a client/server architecture, but a peer-to-peer connection would be in my opinion more easily for me to implement. I have read this article and it proves encouraging for me to go on with this **simulation solution**.

Let me describe my concept:

A client initializes a room and using **sockets, IP, port** and the other players would after connect to him. Therefore, there is always a Master Client that handles the new connections and gives signal to other clients about a new existing player. Then, as the game is running, the byte data-packets would stream each player's input, his position, his ship rotation, his ship status and so on, so that each of the other clients could run a perfect simulation of the initial client. In other words, this data packets would trigger all the actions on each client. As network protocol, I am thinking about TCP/IP and should someone be willing explain to me in more practical terms the difference between this and UDP, I would be thankful.

I have even computed how much data it would take to transmit over a second: assuming a **byte\[256\] array** that holds all the data at one time multiplied by the number of calls per second (**about 32 times**) multiplied by the number of clients the data should be broadcasted to (**3-4**) results in about **32 kb/s**. It might be a dummy result, i might have left a lot of things out, but again, I am ready to learn.

As a note, I do not intend to make at this moment a professional multiplayer system, but rather, I would like to learn more about this programming part of applications and I think this is a very good project idea to enhance my skills. Of course, I am opened to any advanced tips, solutions, materials and should I add anything else about my concept, please let me know.

How is my theoretical model so far?

# Answer
> 2 votes
You have multiple problems with your current implementation.

First of all, the biggest problem with peer-to-peer (or P2P for short) networking is, that it isn't designed for games. Due to it's nature, nobody has authority over the data being sent and received. If one of the players decides to cheat (always assume this), then there's nothing you can do against it. If you try to look up some guides to P2P networking in games, they'll have a sentence along the lines of "...assuming a reliable and non-cheating peer".

Second, your current approach isn't a P2P one. It's just a dynamic-host-based authoritative one. Instead of having a separate server software running somewhere separately from the game, you just couple it together with the client and make one of the players run it. The difference can be seen on the following image (from left to right: authoritative, dynamic-host and P2P):

As a general rule of thumb: only choose the second option, if 1.) running separate dedicated servers is out of the question (e.g. it's too expensive), 2.) releasing the server software doesn't solve the first problem (E.g. running a server for a mobile game doesn't really work) 3.) you don't care about cheating. The only positive thing you can say about it over the other two solutions is the reduced cost on the developer's side. It makes one of the users run the server, which can cause performance problems. It relies on every user having a good internet connection, which never happens irl. The server has to survive even after the host user leaves, which means the other users have to check the host server every X milliseconds and if it doesn't respond, they have to choose the next best user to host the game. This can take up to 500 ms during which nothing happens.

Three, your calculations about the necessary internet speed doesn't matter nowadays. The games rarely cap the upload and download speeds of users, latency is the problem. The biggest advantage of P2P is the small latency. It basically halves it relative to the authoritative solution.

So, first you should definitely design an actual P2P network if you still want to use it (look up how a P2P network usually looks like). You'll still have problems with cheating though. There are simply no solutions to that.

And to answer your question about TCP vs UDP briefly (for a longer answer, see here): TCP and UDP are very similar with 1 difference: TCP makes sure the packets (the blobs of data) always arrive and in the order they were sent. This makes it lot slower. UDP on the other hand doesn't try to do these. If a packet arrives, but it got damaged, then it simply throws it away. As a general rule of thumb: if speed matters in your game and UDP is available, use it.

---
Tags: unity, multiplayer, socket, peer-to-peer
---


# Question
Title: Difference between linear and logarithmic z-buffer
I've searched about this topic for awhile and i couldn't find it on google. I've come across several ways to avoid z-fighting which are linear z-buffer, logarithmic z-buffer and reversed z-buffer. I decided to leave reversed z-buffer for now as i'm not planning to use OpenGL 4.5. The thing is i don't know the difference between linear and logarithmic z-buffer.

By "linear" i mean this:

```
float fz = gl_Position.z * gl_Position.w;
gl_Position.z = (fz - near) * 2.0 / (far - near) - 1.0;

```

And by "logarithmic" i mean this:

```
float w = gl_Position[3];
float C = 0.001;
gl_Position.z = (2 * log(C * w + 1) / log(C * far + 1) - 1) * w;

```

If i understand those codes correctly, the linear try to map all of the z value evenly. So does the logarithmic one. Sure both of them are totally different but i have tried both and see no or if any minimal differences, both eliminate the z-fighting. So there must be something i missed or don't understand.

**edit:** As Jimmy said, logarithmic is better than linear. Please add why logarithmic is better than linear z-buffer as i want to know why it is better and not just which one is better.

# Answer
> -2 votes
A logaritmic z-buffer provides more accuracy for objects near the camera in exchange for a drop in precision for far away objects. In comparison a linear z-buffer provides uniform precision for all distances and it's a bit faster.

You should try to find which algorithm fits your game best. e.g If you are developing a game with closeup elements like a FPS a logaritmic z-buffer may be the best for you.

---
Tags: opengl, glsl, depth-buffer, vertex-shader
---


# Question
Title: 2D SAT Collision - Triangle and Square Problem
So I was just doing an example 2D SAT collision detection problem on paper when I encountered something unexpected. I ran the algorithm on a triangle and a square, and the result of the algorithm was that there was a collision, when indeed there was not. Take a look at this:

*grey lines are the axes, red marks are extremes of projection endpoints (from both shapes) on each axis*

I was under the impression that the SAT algorithm checked for overlapping vertices on all unique axes generated by both shapes sides' normals, and if no gap is found on any axis, then there is a collision. It looks like that does not work in this example. Can someone explain what I am missing? Maybe I'm understanding the algorithm wrongly.

# Answer
> 1 votes
Figured it out thanks to @DMGregory 's comment. The slanted axis in the picture shouldn't be there. The axes should be parallel to the normal of each side of both shapes, not perpendicular. This idea goes the same for any 2D convex polygon.

*grey lines are the separating axes of this triangle and are also normal to the sides of the triangle, as indicated by the yellow arrows*

---
Tags: 2d, collision-detection, separating-axis-theorem
---


title: Calculating collision of polygons

text:
# Question
Title: Calculating collision of polygons
Say I have a multitude of 2D polygons floating about on a plane. These polygons can have any side count and aren't necessarily regular.

Assuming I know absolutely everything about the polygons (area, collision point, location, velocity, rotation, angular velocity... etc) how to I calculate what happens to two polygons after collision?

I.e. what will their resultant velocities and angular velocities be after collision?

If not an exact solution, what resources could help me learn how to accomplish this?

# Answer
This is kinematics, which allows us to deal with each kind of motion (rotation, translation) separately.

First of all, let's look at the what the new direction and velocity of the 2 object is going to be. We need the normal of the side the collision happens on to get the direction. Given the normal (yellow), the direction of object A (green object, green vector) and object B (red object, red vector) is (black is the original velocity) (the red object is considered static in this example. To get the dynamic-dynamic collision's result, do the same calculation twice and add the direction vectors together):

Basically you get the new velocity of object B by projecting object A's original velocity on to the negative version of the normal and you get A's new velocity by dividing B's new velocity from A's original velocity. To get the result, as I wrote above, do the same with A being static and add the resulting velocity vectors together.

This should solve the translation problem, now onto rotation.

Every object has angular momentum, even if it doesn't rotate. It can be expressed as

```
L = m * v * r * sin(theta)

```

where m is the mass, v is the velocity of the dynamic object (again, if both of them are dynamic, simply do these twice), r is the distance of the center of masses and theta is the angle between the vector pointing from the dynamic body to the static body and the velocity vector. You can simplify this to get an angular velocity:

```
ω = m * v / (1/3 * M * r * sin(theta))

```

where M is the mass of the static object. Now take this angular velocity and add it to the current angular velocity of the static object and you're done.

Sources:

angular momentum: https://en.wikipedia.org/wiki/Elastic\_collision

angular velocity: https://www.khanacademy.org/science/physics/torque-angular-momentum/torque-tutorial/v/ball-hits-rod-angular-momentum-example
> 2 votes

---
Tags: physics, collision-resolution
---


# Question
Title: How to synchronize the speed of spawned object and spawning time interval?
I want a stream of enemies coming from the top of the screen one behind other in a line, with their speed (speed of the whole stream i.e. every enemy) increased over time.

When I simply increased their speed, a continuous stream of balls (which will be my enemies) is lost since objects are spawned at a fixed time interval irrespective of the varying speeds of the spawned balls.

To maintain the continuous flow of balls what I wanted is to generate balls rapidly as the speed increases. So there should be a direct relationship between spawning interval and speed of the stream.

How can I do that?

# Answer
> 5 votes
This is a simple application of the distance-velocity-time triangle:

(Image via BBC "Bitesize Maths")

```
float timeBetweenSpawns = spaceBetweenBalls/ballSpeed;

```

This relies on your units being consistent between the three variables. So if `timeBetweenSpawns` is measured in seconds then the `spaceBetweenBalls` should be measured in world units and the `ballSpeed` measured in world units per second.

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


# Question
Title: What is the clearest way to present several numbers in a very limited space?
I'm building a mobile incremental game and as, is typical for the genre, I've got a ton of changing values to show to the user. They serve both as a way to show them their progress, but also to help them make better decisions as the game goes on.

I have five values I want to show, the amount of "Harvesters" and "Salesmen" the user has, and then how many resources they're adding or removing from the resource pool, along with the net result. Say if you're harvesting 10 resources a second, and you're selling 2, you're netting +8/s.

In the following images, blurred to focus on the area in question, you can see the different styles I've tried out. This is the first style, where everything is shown to the player, but is exceptionally busy:

The second style is just the net change, but is missing the quantities of the two types of workers (ie 10 harvesters and 5 salesmen)

Finally the third style is a mix of verbosity and information, but does not show the net difference (ie +123/s).

I'm a fan of the first style because it shows the player everything, and as the programmer I'm happy to look at piles of numbers that represent the fruits of my labour, but the player might not want to see all of that. I've considered adding a toggle setting that goes between the styles if you press it, but I'm hoping there's some sort of happy medium here.

The highlighted parts of the image is all the space I have, but I can incorporate icons if it would help.

My question is between the three of these (or some totally different style), how can I convey the same amount of information clearly and cleanly?

# Answer
I don't think anyone can give you a suggestion of precisely how this should be done, as it's pretty subjective and more of a design thing that needs to fit the theme and style of your game.

But that said, I'm going to suggest that you represent the data visually, and not numerically. As a primary user experience element, give the user clear feedback about what kind of numeric level(s) they are at, and how they are changed, but not actual details.

But then also let the user, via specific actions, request the actual numbers if they care to know the details.

Specifically in your images, you're showing a blurred out game background with unblurred numbers. My suggestion is you have an on-screen visualization of the information shown at all times, with no game blurring. And if the user clicks on the visualization, show the actual numbers at whatever complexity you feel is sufficient. Which would be the first case, which you've said you like best. Go for it.

Look at sparklines for example, of a very non-numeric representation of data, which tells the user what they wish to know. It might not be what you want, but they are a neat way to show the idea of visualizing data without numbers.

Or think of a shooting game, where red flashes show on the screen when the player is damaged, with the intensity of the flash showing the damage amount, and the screen location showing the direction the damage came from. At the same time, allow the user to view the actual damage details if they wish to.

And per my comment, most definitely look into the work of Edward Tufte \- this is the kind of stuff he's all about.
> 2 votes

---
Tags: mobile, ui-design, user-experience
---


# Question
Title: Fixed timestep updates with a variable timestep update
Many suggest that a game loop looks something like this. See:

http://gameprogrammingpatterns.com/game-loop.html

http://www.koonsolo.com/news/dewitters-gameloop/

https://gafferongames.com/post/fix\_your\_timestep/

```
while (1) {
    lag += Chronograph.getDelta();
    while (lag >= msPerTick) {
        update(msPerTick);
        lag -= msPerTick;
    }
    render(lag);
}

```

However, is it equally viable to have a game loop as follows?

```
while (1) {
    lag += Chronograph.getDelta();
    while (lag >= msPerTick) {
        update(msPerTick);
        lag -= msPerTick;
    }
    update(lag); // 0 <= lag < msPerTick
    lag = 0;
    render();
}

```

I'm posing this question because my game should only be drawing sprites in the render call. Everything else should be handled by updates, particularly when sprites advance frames. In other words, the logic for advancing sprite frames should be handled by updates and rendering shouldn't have any affect on the state of my sprites.

# Answer
> 1 votes
The reason we do fixed timestep updates in the first place is to ensure our realtime game simulations stay consistent.

Take a simple object falling under gravity of -9.8 m/s^2 under Euler integration, at 60 and 30 fps:

```
t @30fps  vy        py          t @60fps     vy       py
------------------------------------------------------------
0.00      0.00      0.00          0.00      0.00      0.00
                                  0.02     -0.16      0.00
0.03     -0.33     -0.01          0.03     -0.33     -0.01
                                  0.05     -0.49     -0.02
0.07     -0.65     -0.03          0.07     -0.65     -0.03
                                  0.08     -0.82     -0.04
0.10     -0.98     -0.07          0.10     -0.98     -0.06
                                  0.12     -1.14     -0.08
0.13     -1.31     -0.11          0.13     -1.31     -0.10
                                  0.15     -1.47     -0.12
0.17     -1.63     -0.16          0.17     -1.63     -0.15
                                  0.18     -1.80     -0.18
0.20     -1.96     -0.23          0.20     -1.96     -0.21
                                  0.22     -2.12     -0.25
0.23     -2.29     -0.30          0.23     -2.29     -0.29
                                  0.25     -2.45     -0.33
0.27     -2.61     -0.39          0.27     -2.61     -0.37
                                  0.28     -2.78     -0.42
0.30     -2.94     -0.49          0.30     -2.94     -0.47
                                  0.32     -3.10     -0.52
0.33     -3.27     -0.60          0.33     -3.27     -0.57
                                  0.35     -3.43     -0.63
0.37     -3.59     -0.72          0.37     -3.59     -0.69
                                  0.38     -3.76     -0.75
0.40     -3.92     -0.85          0.40     -3.92     -0.82
                                  0.42     -4.08     -0.88
0.43     -4.25     -0.99          0.43     -4.25     -0.96
                                  0.45     -4.41     -1.03
0.47     -4.57     -1.14          0.47     -4.57     -1.11
                                  0.48     -4.74     -1.18
0.50     -4.90     -1.31          0.50     -4.90     -1.27

```

So with only a single object moving for half a second, we already have a 3% relative error between our two framerates. In more complicated game systems, these differences can snowball, even when you compensate with more sophisticated integrators like RK4.

This happens because many common game systems and features - especially player input - are non-linear. The behaviour of the feature over a span of time isn't just its behaviour at the start of the interval times a duration, it arcs or jumps or changes in ways that are more difficult to model.

If we allow our game behaviour to shift based on its rate of updates, then players on different devices could get different (and possibly unfair) experiences, or the gameplay could change in the middle of an action if our framerate fluctuates. If we tune our game for 60 fps then need to drop to 30 on some devices (or tune if for 30 then want to upgrade to 60), we have to re-adjust all our tuning numbers to ensure it still feels the same.

Switching to a fixed timestep, as you've seen many gamedevs recommend, provides strong protection against these inconsistencies, by decoupling the simulation rate from the rendering framerate. Now whether we do one, two, more, or no simulation steps in a frame, each step's math comes out the same according to its sequence, rather than the particular instant it happened to run in this session.

If you add a variable-length update at the end, all those nice consistency guarantees go out the window, and we're back in the realm of potentially divergent gameplay depending on how fast our game renders in a particular context.

But maybe that doesn't matter - not every game will be adversely affected by this type of variability. If your game is turn-based, or works on discrete rather than continuous states (like tiles on a game board), then there are far fewer opportunities for your simulation to diverge based on how quickly or slowly it's updated - just watch for chains of dependency in your features, and cases where they can give different results if they get updated in a different order.

If that's the case though, and you have an update function that can scale to arbitrary timesteps, without caring about fixed timestep guarantees, then you might as well skip the loop entirely and just step forward in one go:

```
while (1) {
    lag += Chronograph.getDelta();
    update(lag);
    render();
}

```

The only real reason to chop-up your update then is if you have some steps that become unstable, unreliable, or more costly over long timesteps, so you want to enforce a maximum step duration or break into sub-steps to avoid those issues specifically.

Lastly, if you want the game simulation consistency guarantees of a fixed timestep, plus the visual responsiveness of a variable timestep, you can have your cake and eat it too, like so:

```
while (1) {
    lag += Chronograph.getDelta();
    while (lag >= msPerTick) {
        oldState = newState;
        newState = update(oldState, msPerTick);
        lag -= msPerTick;
    }

    renderState = interpolate(oldState, newState, lag/msPerTick);
    renderState.applyVisualFeedback(lag);
    render(renderState);
}

```

Here you interpolate smoothly between the last two states according to the "spare change" you have left after the fixed timestep loops. This ensures your motion is smooth and doesn't show a "beat frequency" or stutter due to mismatches between the rendering and update rates.

Then you can apply some just-in-time visual state updates, like animations, particle effects, etc. - stuff that doesn't affect the underlying rules of the game simulation, but are important to present to the player in a fresh state that accurately reflects the current moment.

By keeping these tweaks limited to a rendering-only state, we don't pollute the game simulation loop with inconsistencies based on the framerate, while still showing the player the freshest information available at the time of rendering.

---
Tags: interpolation, timer, timestep
---


# Question
Title: FPS drops when I maximize the game tab in Unity Editor
I have a simple unity scene with some primitive objects like cubes and spheres. Most of the objects are static and I made backed GI for lighting, The light is a point light. I also used unity post-processing asset for the depth of field.
`FPS` in normal game window size is about `500` but when I maximize the Game tab, `FPS` goes around `30`. Why does this happen?

**FPS 500**

**FPS 30**

# Answer
> 2 votes
Most likely reason is that you have VSync turned on for your game. VSync (vertical synchronization) will only ever work for a game if it's in exclusive full screen (which is what you're doing by maximizing). You can change this setting by using the QualitySettings option for VSync. Taken directly from the link I've provided. This `Example()` function should only ever be used when VSync option is wanted as turned off.

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Example() {
        QualitySettings.vSyncCount = 0;
    }
}

```

You can also turn it on or off in the default Quality Settings here (using menu: **Edit \> Project Settings \> Quality**).

Both pictures taken from Unity's linked pages, since Unity sometimes likes to change the current manual and deprecate links or images.

There's also one more setting that could affect target framerate. Try setting it to a high value.

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Awake() {
        Application.targetFrameRate = 300;
    }
}

```

---
Tags: unity, performance, lighting, lightmap
---


title: Multiple Object Collision SDL

text:
# Question
Title: Multiple Object Collision SDL
I figured this is would be the correct place to ask the following ...

1) How would I go about making multiple object collision detection (Bullets For Example)?

2) How would I make it efficient enough so that I can have many objects be able to detect collision of other objects.

The only idea I currently have is for each bullet to iterate through the other game objects and check collision individually. But that could/would have a terrible impact on time, considering that there can be many objects in the scene. I have also considered multi threading, but I really don't know how to apply it in game programming. Any Suggestions?

# Answer
My approach is to throw everything into a quadtree, update the items inside the quadtree as they move, and then each object checks the objects returned by the quadtree. The advantage of a quadtree in general is that it reduces the number of collision checks required by dividing the playarea into smaller chunks, hence quickly ruling out entities that are far away.

Your collision loop could look something like this:

```
for (Entity* entity : entities)
{
    std::vector<Entity*> collisions = quadTree.Get(entity->Bounding);
    for (Entity* collision : collisions)
    {
        // Handle collisions per-entity.
    }
}

```

With the help of the quadtree, it shouldn't be a problem to iterate over some stuff multiple times.

Quadtree isn't a must, basically any way to do spatial hashing will probably suffice.
> 1 votes

# Answer
The problem you describe is solved by what is largely known as Broadphase collision detection.

Your basic problem is this:

If you have 1000 objects in your scene that all need collision checks, then using a pure brute force attack, you need to perform one million checks. And it gets exponentially worse, the more objects you add. In CS terms, this is known as an intractable problem, with O(n^2) complexity.

So, how do we solve this problem? We introduce a way of reducing the number of collision checks which are performed each update. We do this by eliminating objects which cannot possibly collide by means of very cheap tests (usually circle/circle, or AABB/AABB tests).

How those tests are run is a matter of debate, but there are several options, each with strengths and weaknesses:

1. Quad/octree spatial partition trees
2. Binary space partition trees (BSP)
3. Spatial grid
4. Sweep and prune.

The list is not exhaustive, but is a good starting point.

Quad/Octrees partition space recursively, and statically, and are very good at handling many static objects, but are poor at dealing with moving objects which have to be removed and reinserted into the structure.

BSP trees are also recursive, but require reconstruction when dealing with moving objects.

Both resursive options are at their best performance when the scene they model is static, quadtrees especially so, as their "collision" test is actually logical rather than mathematical, i.e. if two objects share a tree node, then they are close, and therefore worth the cost of further testing in your narrowphase.

Spatial grids are the most simple, conceptually, and basically divide up your game world into equal sized "cells". They can handle moving objects pretty well, but need to be updated each frame, i.e, the position of each object needs to be tested against the boundary of the cell it's currently in, and potentially moved to a new cell. Again, when collecting potential collisions, if two objects occupy the same cell, you test them further.

Sweep and prune is a different beast entirely, and is very good at handling moving objects.

The basic idea is that you have two/three sorted lists of "end points" which represent the min/max extents of each object on a given axis (X/Y/Z). These end points contain an id for the object that "owns" it. The lists are sorted every frame, and because they are unlikely to from one frame to the next, sorting is fast.

To build up pairs of potential collisions, there must be logical id overlaps. ie if you move through the list two at a time, and the two ids don't match, you cache the pair. If the pair exists in all lists, then it needs further narrow phase testing.

This is a very broad overview of common solutions, so I would recommend analysing your game to see which one suits your needs, and then researching it.

It is, however, worth noting, that in many case, a combination of these approaches can sometimes be beneficial.
> 1 votes

---
Tags: c++, algorithm, sdl
---


# Question
Title: SDL 2.0 OpenGL not drawing anything except background
My 'hello triangle' compiles well, no errors, but doesn't drawing anything. Here's my code:

**main.cpp**

```
#include "src/App.h"

int main( int argc, char* args[] )
{
    App app(600, 400, false);
    app.Run();
    return 0;
}

```

**App.h**

```
#ifndef APP_H
#define APP_H

#include <SDL.h>

class App
{
public:
    explicit App(size_t win_width, size_t win_height, bool fullscreen_mode)
            : m_window_width(win_width), m_window_height(win_height),
            m_fullscreen(fullscreen_mode) {
        };

     void Run();

private:
    void Draw();
    void Update(double dt);
    void Resize(size_t width, size_t height);
    void ProcessEvents();

private:
    size_t m_window_width;
    size_t m_window_height;
    bool m_fullscreen;
    bool is_done;
    SDL_Window* m_window;
    SDL_GLContext m_glcontext;
};

#endif // APP_H

```

**App.cpp**

```
#include "../App.h"
#include <SDL_opengl.h>
#include <cassert>

void App::Run()
{
    SDL_Init(SDL_INIT_VIDEO);
    m_window = SDL_CreateWindow("Okno gry",
                                SDL_WINDOWPOS_CENTERED,
                                SDL_WINDOWPOS_CENTERED,
                                m_window_width, m_window_height,
                                SDL_WINDOW_OPENGL | (m_fullscreen?SDL_WINDOW_FULLSCREEN:SDL_WINDOW_RESIZABLE));

    m_glcontext = SDL_GL_CreateContext(m_window);
    Resize(m_window_width, m_window_height);
    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);

    glClearColor(0, 0, 1, 0);
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_EQUAL);

    is_done = false;
    size_t last_ticks = SDL_GetTicks();
    while(!is_done)
    {
        ProcessEvents();

        size_t ticks = SDL_GetTicks();
        double delta_time = (ticks - last_ticks) / 1000;
        last_ticks = ticks;

        if (delta_time > 0 )
        {
            Update(delta_time);
        }

        Draw();
    }
    SDL_Quit();
}

void App::Draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glBegin(GL_TRIANGLES);
    {
        glColor3f(1, 1, 0);
        glVertex2f(1, 1);
        glVertex2f(0, 1);
        glVertex2f(0, 0);
    }
    glEnd();
    SDL_GL_SwapWindow(m_window);
}

void App::ProcessEvents()
{
    if (is_done) return;

    SDL_Event event;
    while (SDL_PollEvent(&event))
    {
        if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED)
        {
            Resize(event.window.data1, event.window.data2);
        }
        else if (event.type == SDL_QUIT)
        {
            is_done = true;
            break;
        }
    }
}

void App::Resize(size_t width, size_t height)
{
    m_window_width = width;
    m_window_height = height;

    glViewport(0, 0, static_cast<int>(width), static_cast<int>(height));
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, 1, 0, 1, -1, 10);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void App::Update(double dt)
{
    //printf("%d", dt);
}

```

Can anyone help? I don't know why it's not running.

# Answer
Based on this page, I would say that you need to set your attributes *before* you create your context. From what I can see in your code, the attribute setting lines are doing nothing, and so the deprecated code is disabled. This would prevent your triangle from being displayed.
> 1 votes

---
Tags: opengl, c++, sdl, c, sdl2
---


# Question
Title: In a visual novel game, What makes a story immersive?
I am planing to make a Visual Novel Game using RenPy and was wondering, how do I make the story immersive to the players playing?

In this Horror Game, there will be drama, thrill and mystery to solve. You are playing as one character and interacting with a couple NPCs.

So what I am really asking is how do I make the charcter’s in the game likable and hate able to give off that feeling of “you are inside the story and not just watching a movie”. Is it the story, is it the dialogue or is it the graphics? or just something else that I am missing.

# Answer
There are many theories about how to maintain immersion in games, and no single ingredient that does it all. But here's one framework I've found useful personally:

It's a psychological theory of motivation called Self Determination Theory. It says that humans (players) are motivated by three core drives: Autonomy, Competence, and Relatedness.

* **Autonomy** is an alignment between what you're doing and what you personally value. Few things will sap a player's investment in a story faster than a long sequence of actions they don't care about but have to do/read through anyway.

In games, autonomy is often mistaken for "choice," but giving tons of wide-open choices is basically throwing eggs at the wall, hoping one of them lands on what the player cares about. Instead it's more effective to identify a few *core values* the player is likely to be pursuing, and drive key moments around threats or opportunities related to those values. Even stronger is when you can put those values in *conflict*, so the player needs to reflect and make very personal choices about which to prioritize. This promotes a "*volitional*" mode of play, where players are drawn into actively striving toward goals they care about, even when real choices are sparse.

It may seem like a silly example, but play deep enough into *Hatoful Boyfriend* and you'll find that some of the most deeply immersive parts of that visual novel are almost entirely linear. They work by building the player's investment early in the game, and establishing high stakes targeting those values, so the player is motivated to push through the available path.

Giving players *in-game tools to express* what they value and why can help cement this feeling of autonomy, even when the player has to take actions contrary to those values. Just including a reluctant yes option when "no" isn't available, or conversations where the player can express their conflict, can let the player feel listened to, and allows them to act in a way that's consistent with what they care about even when they have to make compromises or bump into the boundaries of what the written possibility space allows.
* **Competence** is a feeling of control and capability, that your skills are up to the tasks you're pursuing, and that you are growing and learning over time. Traditionally this is an area where games have excelled through their tight loops of challenge, action, and reward, driving the player to learn, apply, and master their mechanics, and progression systems that show you measurable growth even during learning lulls.

It can be more difficult to create a sense of competence in a visual novel game though. Because the options available to the player at each juncture might be totally unique, they can have a hard time predicting the consequences of each option and making deliberate, meaningful choices. Every time you hit "oh, wait, that's not what I expected that choice to do!" you've put the player in a position of not feeling competent.

Ensuring your story and world have what Emily Short calls *systematic mechanics* can help with this: *rules and conventions* your player can learn over time and apply to inform new choices in scenes they've never seen before. The developers at Inkle for example conceived of 80 Days as a board game at its foundation, where the player can exercise their competence, with the story layered on top providing context, nuance, and richness. This lets the player *choose with purpose*, and develop a mental model of how to make progress toward their goals.
* **Relatedness** is a feeling of connection with other people, of belonging in a community, or being a part of something bigger. It's strongest when used with other real players, but it's possible to cultivate strong relatedness with non-player characters too. Most normal writing advice applies here, about creating characters with depth and motivations, so they don't appear one-dimensional.

In games we also have the ability to shape *interactions* and *dependencies* on the characters - giving the player the opportunity to rely on another character for support, or make sacrifices to help them, can help foster strong relationships. One reason Aeris's death in Final Fantasy 7 was felt so keenly by so many players was that she served as the player's primary healer, so the narrative loss of the character was backed-up with an "oh shit, what now?" sense of dread from their practical gaming instincts too.

Once you're structuring your game around these core drives, you can also subvert the theory and selectively deny the player one of these axes to create emotional turning points.

For more on applying self-determination theory in games, I recommend checking out the work of Scott Rigby and Troy Skinner of Immersyve. They've developed a model based on SDT they call PENS (Player Experience of Need Satisfaction) and they've given many presentations exploring how these aspects drive play. (Granted, they also want to sell their services, so take this with the requisite grain of salt too)
> 11 votes

---
Tags: game-design, storyboard, visual-novel, renpy
---


title: Adding Log4Net to Unity

text:
# Question
Title: Adding Log4Net to Unity
I would like to add `log4net` library as a logging tool to visual studio project which created by `Unity`, Is this possible?

I dragged the `log4net` DLL to assembly references in `Visual Studio`. so the DLL added to the project, but when I want to import it in code with `using log4net`, it doesn't find the library!

# Answer
> 2 votes
Yes, I found the solution, So it's absolutely possible to use `log4net` or any other managed library with `Unity`. But I made a mistake, I should be followed the Unity manual page which said:

> Usually, scripts are kept in a project as source files and compiled by Unity whenever the source changes. However, it is also possible to compile a script to a dynamically linked library (DLL) using an external compiler. The resulting DLL can then be added to the project and the classes it contains can be attached to objects just like normal scripts.
> **the DLL file can simply be dragged into the Unity project like any other asset.**

So I just needed to add the `log4net` DLL to asset folder and it would be accessible through `Visual Studio`.

---
Tags: unity, c#, visual-studio
---


# Question
Title: Unity3d - Immediately force transition without waiting until current animation ends
I created a animation Controller and attached it to the Animator component of my main camera. My Animation Controller looks like this:

I am building a Main Menue. If the user presses on the buttons, then the camera is animated to different places in the world.

Each transition is linked with a condition, e.g. the Transition going from `CameraIdle` to `ToLoadscreen` has a condition called `GoToLoadscreen` which is a boolean parameter, the camera is only getting animated to the Loadscreen, if its value is true.

However, the transition is only starting after the current animation `CameraIdle` finished playing, as you can see in the next picture, `CameraIdle` is still getting played even though the parameter `GoToLoadscreen` is set to true.

How can I force the transition?

# Answer
> 9 votes
You can force the transition to immediately happen, by clicking on the transition and unchecking `Has Exit Time`.

Now the transition is immediately forced and you don't have to wait until the current animation `CameraIdle` is finished.

---
Tags: unity, animation, animation-states
---


title: Opponent car logic in race games

text:
# Question
Title: Opponent car logic in race games
I'm developing a race game in Andengine. I have created a car which player is controlling. But since this is a race game, there should be 3 or 4 car which snatch with the player's car. My question is: How do the opponent cars move along the path? How their logic works? Must I know certain path?

# Answer
> 2 votes
In racing games it's often best to use both track relative coordinates as well as Cartesian world coordinates. This makes it easier to reason about overtaking and optimal lines the cars should follow.

A great article to read would be Shawn Hargreaves' postmortem on the MotoGP AI

You can also try to use follow and flock algorithms like Open Steer

If you are more interested in how to determine the optimal curve that (AI) drivers should follow on a track you could research flow fields. You can find more info about those in the links in this answer on this same website.

# Answer
> 1 votes
I outline one simple implementation:

Assume your track is a series of points joined together and the last point joins the first to form a cicular track.

loop through all the points and find the nearest point to your car. Take this point and minus the previous point to get a normalized track forward vector; take the car position minus the previous point to get a "car vector"; do a dot product to get the perpendicular distance from the track vector.

The perpendicular distance represents how far away the car is from the center of the track. Now you know the distance and on which side of the track the car is on, you can steer (change the rotation/direction) the car back onto the track.

# Answer
> 0 votes
I'm not a high level programmer, I just know some basic java, however I am a racer. Racing games such as Forza have a very good AI, but other games that have racing as a secondary feature don't. When constructing this "dot track" based on coordinates of the track and world, I'd recommend watching ViperConcepts on YouTube and trying to liken the line you create for your track to his recommended racing line. In my experience of real life racing vs Forza, the main problem, even in the best "simcade" games, such as Forza, GT, Project Cars, etc... the main thing that I notice detracts from the realism is the fact that the AI are very predictable and they usually don't take themselves out, pass eachother, or make mistakes. They don't have much aggression as far as overtaking or defending/blocking. I assume your game won't be competing to be the next Forza, but I'd definitely love to play a game where the AI are a little bit more of a mess maybe, rather than a parade. In real life, I've ended up on the podium with a damaged engine, just by keeping my nose out of trouble. I want to say good luck with your game and I hope it manages to capture some of these elements!

---
Tags: logic, racing, car
---


# Question
Title: Is Unity 2017 random number generator deterministic across platforms given the same initial seed?
Is unity engines random number generator deterministic across platforms given the same initial seed or should I implement my own?

I know there have been some modifications to the random number generator recently.

Answers are appreciated, I don't have the devices on hand to perform any tests and I haven't yet found a direct statement on the matter.

# Answer
While I haven't had time to do any extensive testing, initial research suggests that the random number generator used is deterministic across different platforms. The exact implementation used is: Unity PRNG. See also: Unity Random Seed On Different Hardware.
With the Unity `Random` class, the exact state of the PRNG can be saved, see: Unity Random Sate.
> 8 votes

# Answer
Thomas answered the question as asked. The more important question is as follows:

> Is the Unity 2017 random number generator guaranteed to deliver the same numbers across all current and future platforms given the same seed, and is it also guaranteed to deliver the same numbers as future releases of Unity?

There is a rather high likelihood for this being the case, but that isn't the same as a guarantee. So the answer, unfortunately, is "**no, it is not**". A guarantee would need to be explicitly stated in the documentation of Random, but *currently* there is no such thing.

Personally, even if there were such a guarantee, I'd recommend not to trust it - even with a guarantee there's still a chance of the implementation being changed by accident (a bug), or simply being deprecated and later removed. At some point you also might want to reuse the generator outside of the Unity framework. Instead of relying on Unity, just copy a random number generator someone else wrote(make sure you're allowed to use the code), and write a test to verify it satisfies your requirements for randomness.
> 7 votes

# Answer
Using Unity 2017.2.0f3, UnityEngine.Random appears to give the same results across multiple platforms. Tested on Windows 10, macOS 10.12 Sierra, and Android 7.

To test, I trimmed down a SeedFactory class I've created:

```
using UnityEngine;

public class SeedFactory {

    private Random.State state;

    public SeedFactory (int seed) {
        Random.InitState(seed);
        state = Random.state;
    }

    // Set Unity's global Random state with this SeedFactory's state, get a random int,
    // then set our SeedFactory's state with the new state.
    // (this allows us to use multiple SeedFactories for multiple paths of determinism
    // if desired)
    public int GetRandomInt (int minInclusive, int maxExclusive) {
        Random.state = state;
        int randomInt = Random.Range(minInclusive, maxExclusive);
        state = Random.state;
        return randomInt;
    }

}

```

And a MonoBehaviour to run the test:

```
public class SeedTest : MonoBehaviour {

    void Start () {
        SeedFactory seedFactory = new SeedFactory(123456789);
        string result = "";
        for (int i = 0; i < 20; i++) {
            result += seedFactory.GetRandomInt(int.MinValue, int.MaxValue) + ", ";
        }
        Debug.Log(result);
    }

}

```

And the results have all been the same:

```
Windows Editor:
217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178,

Windows Standalone:
217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178,

macOS Standalone:
217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178,

Android:
217814258, 711215697, 1793372675, -1318111305, -513578644, 1776128467, -1503243711, -285471819, -1800526065, -1845985472, -2061970588, 188207569, 1858341351, -1139513088, 2136219157, 1255727479, -2070068486, 459175680, 1151694536, 1232856178,

```
> 4 votes

---
Tags: unity, c#, random, cross-platform
---


# Question
Title: Unity3d - Find out if current animator animation is playing?
I need to call a function immediately after animator animation finished playing, I know I could solve this by adding an event to my animation, but I try it without.

How can I find out if the current animator animation is playing?

On normal legacy animations I solved it by writing a coroutine:

```
public static IEnumerator playAndWaitForAnim(Animation anim, string clipName, Action callback)
{
    anim.Play(clipName);

    //Wait until Animation is done Playing
    while (anim.IsPlaying(clipName)) {
        yield return null;
    }

    //Done playing. Do something below!
    callback();
}

```

Which I use like this:

```
StartCoroutine(AnimationHelper.playAndWaitForAnim(
    myAnimation,
    "ToSettings",
    () => {
        Debug.Log ("Finished playing");
    }
));

```

But how does this work with mecanim animator animations?

# Answer
Might not be best but you can add bool parameters in layers in animator and then assign the condition to transition then with these bools so you can check with a script which animation is playing or not , here is example of my code i used recently :

```
// when animation starts
if (AnimationState == true)
    {
        anim.SetBool("TurnRight", true); /* this will make the animator
TurnRight paramter to ture so animation will play */
        //Do something

if (AnimCounter == Timing) /* this if is used to make the TurnRight false
mean that animation must stop or go to another transition also some
variables like AnimCounter and Timing i used to stop the animation at
propriate time */
        {
            anim.SetBool("TurnRight", false);
           //Do something when animation ends

        }
    }

```

with this as long as the TurnRight bool is true i know that is still playing.

This code might not do the exact thing you want but it can gives you some idea or at least lighten something for you to do your work.
Hope it helps.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: How do I prevent modders from creating malicious code?
Let's say I have both a game and a modding system for it. The modding system loads DLL files containing custom features and allows mod creators to override certain functions to change game mechanics. This is all well and good until some mod creator decides to put a keylogger or a virus in one of those DLL files. What can be done to prevent this problem? Is there any way to allow a high level of customisability in a modding system while still maintaining a strong level of security for the end user?

# Answer
You cannot prevent it (in situations which are equivalent to running arbitrary native code supplied by others).

You can:

* curate the mods
* screen submissions with a scanner
* restrict your API as much as possible
* select a language that is safety oriented
* sandbox foreign code

All of these increase safety to varying degrees. But none of them are a guarantee.
> 4 votes

# Answer
As others have stated in the comments, the easiest way is to either embed an interpreter in your game (for example, Lua scripts are fast-ish, and there are a number of good implementations scattered across the web for various languages) or create a simple text parser and read files. For example, you could roll your own text format for simple scripts, embed lua for mire complex scripts and gui-related tasks, and load object definitions from JSON or XML.

For example, in my strategy game;

1.) Unit types are defined in xml - safe\[1\].

2.) GUI layout is defined in xml - safe.

3.) I use a custom parsed scripting language for simple events.

4.) Lua is used for gui interaction. I have removed the io, and os functions effectively rendering these scripts safe.

\[1\] - As others have stated, these approaches aren't necessarily "safe" just "safer" than including compiled dll's.
> 1 votes

---
Tags: modding, security, dll
---


title: Simple square vertex lifting shader

text:
# Question
Title: Simple square vertex lifting shader
I am trying to rebuild the fur effect in Viva Pinata.

Here each square becomes a pattern of fur

I imagine the process to be like this...

U lift one end of the triangles.

Now I need to achieve "lifting one end of square". I can do either vertex, fragment, geometry shader. However I am clueless when it comes to determining which vertex is "end of square", so that I know which vertex to lift up.

# Answer
> 4 votes
This is actually an illusion. The vertices are not lifted: There aren't enough vertices in the model to create the pinata effect.

Here are the tricks:

* The normal map has squares in it to create the illusion of bumps
* The diffuse map as ambient occlusion baked-in to create the illusion of high-detail self-shadows or an ambient occlusion map is used.
* The shadow calculation gets distorted by either the normal map or a displacement/height map to create more illusion of pinata-like bumps so the shadows aren't straight-edged.
* "Fins" are added to the model to create the fluffy paper look you see on the sides where opacity is controlled by the fin's normal relative to the view (camera).

Additionally:

* The diffuse texture can be displaced (parallax mapping) according to the view direction and a height map to create a higher sense of depth.

Shells are not needed for the pinata effect but look up "3d Fur effect" and/or "shell and fins" for example of generating fins

---

A very minimalistic example (fins and baked ambient occlusion only):

Create your pinata color pattern:

Add some ambient occlusion:

--\>

Take your 3D model (A simple cube in this example so we can see how its done) and **extrude the edges**. These are the "fins".

Create a texture for those fins that reproduces how the pinata paper looks sideways:

Apply this texture to the fins

Voila.

Left to do: Add normal map and parallax mapping or an extra shell.

---

Shells are extra copies of your original geometry extruded along the vertex normal that are rendered with a mostly transparent layer to create the illusion of depth.

Usually a shader is created that takes a height map and the diffuse texture to make every texel below the height threshold of each shells transparent.

--\>

By creating an extra layer above the original mesh a slight illusion of depth is created:

The more shells are created, the better the effect.

---
Tags: shaders, glsl, gpu, cg, geometry-shader
---


# Question
Title: String table or a tree for virtual filesystem
I am developing a binary file format to store my game's assets and I am thinking about how to implement the "file table". One option to would be to create a structure for file entries like this:

```
    struct Entry
    {
        uint16_t nameLength; //< This basically stores the whole path e.g "dir1/file1.txt"
        char*    name;
        uint64_t dataSize;
        uint64_t dataOffset;
    };

```

Or i could use a method, which I think is more elegant and is based off the ISO 9660 filesystem, however I think it may have a performance impact on traversing the file tree.

```
    struct Entry
    {
        uint16_t entrySize; //< This is used for going to the next entry (next = current + current.entrySize)
        uint8_t  entryType; //< 0 for file, 1 for directory + may be extended later
        uint16_t nameLength; //< Now this only stores the concrete file/directory name
        char*    name;
        uint64_t dataSize;
        uint64_t dataOffset;
        Entry*   children; //< Actually an array where entrySize is used for iterating
                            // and the last entry is a "null entry" which has entrySize = 0
    };

```

So which one of theese will be better considering that the resource files are "read only" and cannot be modified, only created again? Or is there a solution better tailored for virtual filesystems?

Because in the first case the system only needs to traverse all the entries lloking for "dir1/file1.txt", but in the second case it will have to first search for "dir1" in the root entry, and the for "file1.txt".

I hope that I was clean enough.

# Answer
The tree approach will only provide a benefit in one specific scenario: Obtaining all files within a specific directory subnode. If that's your most common access pattern, then this structure might be useful.

If you want to get a single file by its full path and name, then you will be far better off if you create a separate `std::unordered_map<std::string, Entry*>` which maps filenames (with complete path) to `Entry`s. An unordered\_map is (practically always) internally implemented as a hash table, so finding an entry in it by key is a constant time operation. Finding one in your tree can potentially take much longer, especially if you happen to have many directories in the hierarchy which have a lot of entries which come before the one you are looking for.

Note that an unordered\_map can also be used to speed up tree traversal if you put the entries for the directory nodes into it, because it will make it faster to find the directory node from which you want to find the children.

Possible drawback: Hashmaps have quite a lot of memory overhead compared to other data structures. But I suspect that this overhead will be nothing compared to the memory taken by the actual file data in your virtual filesystem.
> 0 votes

---
Tags: c++, assets, filesystem
---


title: Convert char array to std::string

text:
# Question
Title: Convert char array to std::string
I have this code:

```
char shaderName[128] = "";//the name of the file
char text[1024 * 16] = "";//the content of the file
std::ofstream myfile;//the file
myfile.open(shaderName + ".shader");//i want to concatenate the file name with the .shader extension
myfile << text;//put the content of the text array in the file
myfile.close();//close the file

```

This gives me an error. It tells me i can't convert a char array to a string or const char\*. I want to be able to concatenate the nameof the file with the `.shader` extension. I also tried to cast `shaderName` to an `(std::string)` or a `const char*`

EDIT:

```
ImGui::Begin("Shader Writer");

char text[1024 * 16] = {""};

char shaderName[128] = {""};

ImGui::InputTextMultiline("##source", text, IM_ARRAYSIZE(text), ImVec2(-1.0f, ImGui::GetWindowHeight()), ImGuiInputTextFlags_AllowTabInput | (false ? ImGuiInputTextFlags_ReadOnly : 0));

    ImGui::Text("Shader Name: ");
    ImGui::InputText("", shaderName, IM_ARRAYSIZE(shaderName));

    ImGui::SameLine(0.0f, 2.0f);

    if(ImGui::Button("Create", ImVec2(50, 20)))
    {
        char shaderName[128] = "";

        std::ofstream myfile;

        std::string name(shaderName);
        std::string FileName = name + ".shader";

        myfile.open(FileName.c_str());
        myfile << text;
        myfile.close();
    }

    ImGui::End();

```

The InputTextMultiline() function let's you modify,write,read a text. The "text" in this case is a char array(this function outputs a char array). Then we have another InputTextMultiline() function which also returns a char array. In order to use this data returned by these functions, i need to convert them to strings(or maybe to const char\*,even tho i think std::strings is better).

Here is a rapresentation of what these functions do:

# Answer
> This gives me an error. It tells me I can't convert a char array to a `string` or `const char*`. I want to be able to concatenate the name of the file with the .shader extension. I also tried to cast shaderName to an (`std::string`) or a `const char*`.

You can't concatenate C-style strings using `+`. If you want to use `operator+` you'll have to use `std::string`. Otherwise you'll have to use `strcat()`.

```
std::string shaderName = "";
...
std::ofstream myfile;
myfile.open(shadername + ".shader");
...

```

Note that `open()` does not accept `std::string` until C++11; prior to that you'll need to concatenate the name into a local variable and use `c_str()`:

```
std::string fileName = shadername + ".shader";
...
myfile.open(fileName.c_str());

```

If you must use `strcat` instead:

```
char shaderName[128] = "";
strcat(shaderName, ".shader");
myfile.open(shaderName);

```

It is your responsibility to ensure `shaderName` is large enough to hold the resulting buffer.
> 1 votes

---
Tags: c++, filestream
---


title: Proper updating of GeoClipMaps

text:
# Question
Title: Proper updating of GeoClipMaps
I have been working on an implementation of gpu-based geo clip maps, but there is a section of the GPU Gems 2 article that I just can't seem to understand, specifically this paragraph, and more precisely the bolded part:

> The choice of grid size n = 2k−1 has the further advantage that the finer level is never exactly centered with respect to its parent next-coarser level. In other words, it is always offset by 1 grid unit either left or right, as well as either top or bottom (see Figure 2-4), depending on the position of the viewpoint. **In fact, it is necessary to allow a finer level to shift while its next-coarser level stays fixed, and therefore the finer level must sometimes be off-center with respect to the next-coarser level.** An alternative choice of grid size, such as n = 2k−3, would provide the possibility for exact centering

Let's take an example image from the article:

My "understanding" of the way the clip maps were updated was that you floor the position of the viewpoint to an int, and as such get the center vertex point. If this is not the same as the previous center point, you update the entire map. Now, this obviously is not the case. What I am failing to understand is this:

If you look at the image above, if the viewpoint was to move one unit to the right, then the inner ring (the one just around the view point + white center square) would end up getting a 1 unit space on both the left and right side of itself. But there is nothing in the paper that deals with this. What I mean is that it would end up looking like this:(excuse my crummy cut-and-paste editing of the above image):

This is obviously not a valid state. So, would the solution be that a clip ring (layer) can only move in increments of the ring/layer it's contained within? Wouldn't this end up being very restrictive? I feel like I am missing some crucial understanding of parts of the algorithm, but I have been over both this paper and the original paper from 2004 and I just can't see what I am not getting.

# Answer
> 1 votes
I think you have the right idea.

> So, would the solution be that a clip ring (layer) can only move in increments of the ring/layer it's contained within?

Yes

> Wouldn't this end up being very restrictive?

No, this system the innermost level can always move in 1-unit increments. Then each ring at level n out from the innermost one needs to be updated once every 2n increments.

Not having the half-blockwidth strips makes generating the patch strips easier as well.

### Animated Demo

Here is what the sliding windows should look like, as far as I can tell from the paper. Note that there isn't any of the "half-edge strips" in your example, and the innermost block is still able to move in smooth 1-unit increments.

---
Tags: terrain, terrain-rendering, gpu
---


# Question
Title: Proper use of async, await and task.delay for a game loop
I'm currently in the process of making a game loop in a console application. I'm trying to make the game loop wait at the end of its loop for `(1000*10000/fps) - ElapsedTicks` to put a cap on game loop speed. For reference 1 millisecond is 10,000 ticks.

If the `ElapsedTicks < FrameTimeTicks` I execute `await Task.Delay(FrameTimeTicks - ElapsedTicks)` but this ends my console application.

The code responsible is the await Task.Delay so I assume I'm not using it properly.

My code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApp1
{
    class Program
    {
        static byte fps = 30;
        public static byte Fps { get { return fps; } set { fps = value; } }
        //user specified fps

        static long frameTimeTicks = (1000 * 10000) / Fps;
        static long FrameTimeTicks { get { return frameTimeTicks; } }
        //amount of ticks desired in one frame

        static bool draw = true;
        public static bool Draw { get { return draw; } set { draw = value; } }

        static long elapsedTicks;
        static long ElapsedTicks { get { return elapsedTicks; } set { elapsedTicks = value; } }
        //ticks elapsed in one game loop

        static void Main(string[] args)
        {
            GameLoop();
        }

        static void UpdateGame()
        {
            int a = 0;
            a++;
        }
        static void Render()
        {
            Console.WriteLine("@");
        }

        public static async void GameLoop()
        {
            Stopwatch gameLoopTicks = Stopwatch.StartNew();

            while (true)
            {
                gameLoopTicks.Restart();

                if (Console.KeyAvailable == true)
                {
                     char KeyPressed = Console.ReadKey().KeyChar;
                }
                UpdateGame();
                if (Draw == true)
                {
                    Render();
                }
                ElapsedTicks = gameLoopTicks.ElapsedTicks;
                if (ElapsedTicks > FrameTimeTicks)
                {
                    Draw = false;
                }
                else
                {
                    Draw = true;
                    await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
                }
            }
        }
    }
}

```

I Have also tried this variation but to the same result, my console application ends.

```
public static async void GameLoop()
    {
        Stopwatch gameLoopTicks = Stopwatch.StartNew();
        async Task PauseGameLoop()
        {
            //Console.ReadKey(); execution ends here!
            await Task.Delay(TimeSpan.FromTicks(FrameTimeTicks - ElapsedTicks));
            GameLoop();
        }

        while (true)
        {
            gameLoopTicks.Restart();

            if (Console.KeyAvailable == true)
            {
                 char KeyPressed = Console.ReadKey().KeyChar;
            }
            UpdateGame();
            if (Draw == true)
            {
                Render();
            }
            ElapsedTicks = gameLoopTicks.ElapsedTicks;
            if (ElapsedTicks > FrameTimeTicks)
            {
                Draw = false;
            }
            else
            {
                Draw = true;
                await PauseGameLoop();
            }
        }

```

Task.Delay MSDN, await MSDN. Am I tackling this problem the wrong way ? This post is why I chose this method. Thanks for the help!

# Answer
> How do keep the program from exiting when there's an active async function running?

You GameLoop is async but your Main function is not. By default, starting a Task starts it on pooled thread. The minimal changes to avoid exiting Main are to return a `Task` and wait on it in `Main`:

```
static void Main() {
   GameLoop().Wait();
}

public static async Task GameLoop() {
      .. same as before ..
}

```

---

A bigger issue will be that the resolution of the timer in Task.Delay is (system-dependent) probably only around 15ms, so you're not going to get very stable framerates. In fact, the resolution of sleeping a thread in general is going to be too low.

> How to get consistent sleep times if Task.Delay isn't high-resolution enough?

For most consistent results, You'll want to look into implementing a fixed-timestep game loop where you just render as fast as possible (or perhaps spinwait any extra time away) or use VSync to naturally limit your loop speed.

The Go-to article on how to implement a fixed-timestep game loop has been Fix your Timestep, and there have been plenty of previous fixed-timestep questions asked here.

We take a page from the standard fixed-timestep pattern and wrap a main loop around a time-delta generating function. When that delta goes above our desired `frameTime` we call `Update()`. The rest of the loop consists of either a Thread.Sleep(1) if your platform has a high-resolution sleep timer or an empty loop while you're waiting for enough time to pass, to get a spinwait. In theory, you could use unsafe / unmanaged code to call the equivalent of `_mm_pause` to reduce your power consumption in the spinwait, but that's outside the scope of this answer.

```
using System;

class Program {
    public Program(double fps) {
        DesiredFPS = fps;
        frameTime = TimeSpan.FromSeconds(1.0 / fps);
    }
    double DesiredFPS;
    TimeSpan frameTime;
    // counts how many times we've looped while waiting
    int spinCounter = 0;
    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();

    // this is the function we run at the desired FPS
    void Update() {
        Console.WriteLine("{0}   {1}", spinCounter, sw.Elapsed);
        spinCounter = 0;
    }

    void MainLoop() {
      sw.Start();
      var last = sw.Elapsed;
      var update_time = new TimeSpan(0);
      while (true) {
        var delta = sw.Elapsed - last;
        last += delta;
        update_time += delta;
        while (update_time > frameTime) {
            update_time -= frameTime;
            Update();
        }
        spinCounter++;
        // On some systems, this returns in 1 millisecond
        // on others, it may return in much higher.
        // If so, you should just comment this out, and let the main loop
        // spin to wait out the timer.
        System.Threading.Thread.Sleep(1);
      }
    }

    static void Main() { new Program(30.0).MainLoop(); }
}

```
> 1 votes

---
Tags: c#, game-loop
---


title: Limiting Framerate and Input

text:
# Question
Title: Limiting Framerate and Input
So I have been learning HTML5 canvas recently and ran into a bit of a snag. I created a proof of concept that builds a block based 2d map that you can move a character inside of using arrow keys. This works well because everything is free moving (character moves 1 pixel per frame, so the movement is fluid and looks good).

I am trying to fork off of this code to create another concept that forces grid based movement (like in a typical roguelike). I have updated my movement code to move in chunks equal to tile size.. but the issue is that the refresh rate is so fast that it just seems like the character is moving at super speed.

Here is a snippet of my code that handles animations:

```
function gameLoop() {
        ctx.clearRect(player.x,player.y,PLAYER_SIZE,PLAYER_SIZE);
        getInput();
        ctx.fillStyle = '#000000';
        player.draw(ctx);
        window.requestAnimationFrame(gameLoop);
}

```

Is using requestAnimationFrame() for this sort of movement not a good idea? Is it better to just setInterval() for this sort of thing? I found a article via Google that talks about using variables for time, delta, fps, etc to limit the framerate... but Im not sure I understand how to do that in conjunction with requestAnimationFrame(). Should I somehow hold my gameLoop() from hitting requestAnimationFrame() until some time interval is hit? That seems like it would just be a waste because I would need to force a loop of some kind... doesnt seem too elegant

# Answer
> 1 votes
First, the properties of `window` are exposed globally, which means that you don't need to put it before `requestAnimationFrame`. `requestAnimationFrame`=`window.requestAnimationFrame`.

Now onto your problem. You shouldn't limit the framerate, it makes the game less responsive. Instead try limiting the player's movement. What you need is a delay between the movements.

So, you need to store the time the last move happened. This is relatively easy, just store the value you get from `Date.now()` in variable. If the current time minus the last time the player moved is bigger than or equal to the delay between moves, then move the player and set the variable to the current time again.

There's still a slight problem woth this though. It restricts the movements of the player, even when he repeatedly presses the keys. To solve this, set the "last move" time to 0 when the user releases the keys.

# Answer
> 1 votes
when your `gameloop` function is called by the animationFrame event, it is given a parameter that shows how many milliseconds have elapsed since the previous frame.

You can use this to normalize the speeds, and to implement a fixed timestep game loop (for example, like the one described at http://isaacsukin.com/news/2015/01/detailed-explanation-javascript-game-loops-and-timing)

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