title: Camera view/projection issue

text:
# Question
Title: Camera view/projection issue
I made a simple OpenGL program but I can figure out why the camera is not working, here it's a little fragment of the Camera class:

```
public Matrix4f getView() { // initializes the view matrix
    return new Matrix4f().lookAt(
            new Vector3f(0f, 0f, 1f), // camera position at 0,0,1
            new Vector3f(0f, 0f, 0f), // camera target at 0,0,0
            new Vector3f(0f, 1f, 0f)); // up axis set to "worldUp" (0,1,0)
}

public Matrix4f getProjection() {
    return new Matrix4f().perspective(
            (float) Math.toRadians(fieldOfView), // the fov has a value between 0f and 180f, by default I set it to 90°
            viewportAspectRatio, // the aspect ratio is equal to 1024 / 960 (screen height / screen width)... even if I've not understood what is it...
            0.1f, 1000f); // I've not really understood what near and far planes are...
}

public Matrix4f getMatrix() { // with this function I obtain the final camera matrix
    return getView().mul(getProjection());
}

```

And it's how I handle the camera Matrix in GLSL, created using `camera.getMatrix()`:

```
gl_Position = camera * model * vec4(position, 1.0);

```

Without the camera all is fine: here's the program running using `gl_Position = model * vec4(position, 1.0);`:

*(Yeah, it's a cube)*

But using the camera in the way I showed you before, increasing the FOV, I get this:

Could anyone look at my code and tell me where I'm wrong? I would be really happy... D:

# Answer
> 1 votes
I solved, the problem was on `getMatrix`. Has *Jon* say I had to flip `getView().mul(getProjection())` to obtain `getProjection().mul(getView())`. At first I though that this would not change anything but I was wrong. Thank you *Jon*!

---
Tags: camera, lwjgl, opengl-es3
---


title: When shouldn't I use object pooling?

text:
# Question
Title: When shouldn't I use object pooling?
Are there any cases where I should *not* use object pools but instead rely on `Instantiate` and `Destroy`? (Or more generally, outside of Unity, creating objects on a per-instance basis instead of with a pool)?

# Answer
It depends why you were using object pooling in the first place. Pooling mainly addresses problems with objects that are expensive to construct and which benefit from locality of reference.

Whenever you have objects that *aren't* expensive to construct and/or *don't* need to have high locality of reference, there might not be a lot of benefit to using a pool, and indeed you may start to incur some disadvantages:

* Pools generally work on a fixed-block-size principle, and if that fixed size greatly exceeds the number of concurrently alive instances, you're wasting memory.
* Similarly, if you can't reasonably bound the maximum number of instances, you're left with either not being able to use a pool, or use one that "grows" by allocating another fixed-size block. This starts to undermine some of the initial advantages of using a pool.
* If the cost of resetting a "released" slot in a pool (so it can be used by a future instance) is higher than the cost of initial construction, that's a mark against using a pool for such objects.
* If you're using a pool for improved locality of reference you generally want to swap released objects with the last used slot so you have a clear separation in the pool between "alive" and "dead" slots. If the cost of that swap is high, or if some other aspect of the object semantics require the ordering within the pool to be preserved, pools might be a poor choice.
> 10 votes

# Answer
Yes, when you don't need it.

This means that you should use object pooling when you profile and realize that a part of your code would benefit from object pooling.
> 1 votes

---
Tags: unity, object-pools
---


# Question
Title: How can I apply effects to a character based on the tiles it occupies?
A mechanic of my game is that when a `Character` (Actor) steps on some specific tiles, they should be affected by status effects like slow, poison, burn, etc. These effects lasts only while the `Character` is on the effect tile. The character may be a lot larger than the tile. How can I achieve this?

# Answer
> 2 votes
Presumably you have some structure that describes properties of a tile:

```
class Tile {
  int sprite;
  int movementCost;
  ...
}

```

To that data structure, add a list of effect references which point to the effects to apply to a character while that character is on the tile.

Since a character is potentially larger than a tile, it can potentially "occupy" more than one tile for the purpose of having effects applied. It should be fairly easy to get the range of tiles covered by a character of known width and height given the character's current origin tile position and the width and height of a tile (`ceiling(characterWidth / tileWidth)` tells you how many tiles the character covers along the X axis; Y can be computed similarly).

With that information you can collect the set of tiles covered by any given character, and then:

```
foreach (tile in tiles) {
  foreach (effect in tile.effectsToApply) {
    character.applyEffect(effect);
  }
}

```

Optionally, you can check if an effect is already applied to a character in the inner loop and skip it if you'd prefer tiles not to "stack" their effects.

---
Tags: java, game-design
---


# Question
Title: How can I better structure my code to reduce coupling between input and graphics?
I've been working through a few OpenGL tutorials, and decided to give myself the exercise of trying to draw a grid, with the added requirement of being able to press the `-` and `+` keys to change the dimensions of the grid. I've achieved what I set out to, however, it's left me with a few questions on how to go about separating some of the logic.

My biggest concern is to do with the input handling. Right now, I'm handling it like so:

```
Grid grid;

void key_callback(GLFWwindow* window, int key, int scanCode, int action, int mode)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);

    if (key == GLFW_KEY_MINUS && action == GLFW_PRESS)
        grid.DecrementGridSize();

    if (key == GLFW_KEY_EQUAL && action == GLFW_PRESS)
        grid.IncrementGridSize();

    grid.Build();
    glBufferData(GL_ARRAY_BUFFER, grid.Size() * sizeof(Vector3D), grid.Data(), GL_STATIC_DRAW);
}

```

There are several things I don't like about this:

1. This is at the top of my `main.cpp` file, so `grid` is global, purely so it can be used in the input handler.
2. I've coupled the glBufferData() call with the input handling.

I'm not sure how to go about solving point 1, as I'm inexperienced with C++, but, for 2, I've considered the idea of having a separate `Update()` method that would be called at the end of the handler, rather than calling `glBufferData()` directly. `Update()` would then take care of updating the contents of the buffer.

The problem I see with that is how you would pass the data from `grid` to it. In my simple program, passing one set of vertices is absolutely no problem, but I'm not sure how you'd handle doing that when you have a whole bunch of different objects with their own vertices. I assume there are different patterns that already exist for handling this, so I'm more looking for some phrases I can Google really.

What can I do to improve the situation?

# Answer
> 3 votes
> This is at the top of my main.cpp file, so grid is global, purely so it can be used in the input handler.

In general, the solution here is "don't make it global," and to pass instances needed to functions that need them. In this simple program you probably don't need to worry about it too much. Think of more as something you should think about for the future.

One way to refer to this concept is "dependency injection," which may give you something useful to search for (be wary though, as the phrase is also used to describe hideously over-complex "enterprise" engineering patterns as well; all I'm really talking about is the straightforward idea of passing instances of dependencies to objects or functions that require them).

In the case of GLFW you can't modify the input callback signature, so consider looking into attaching data to the user pointer of the window to remove the global variable reference.

> I've coupled the glBufferData() call with the input handling.

Fundamentally, the input causes the action (the action in this case is regenerating the buffer). You'll never be able to decouple those unless you remove the functionality. You can place layers of abstraction in between them, sure, and in some cases that's desirable. Maybe not so much in this simple program; this key handling code is basically part of the "top level" game layer of abstraction, which *is* going to know about every other system in the game somehow already, or that system would never be instantiated/ticked/whatever.

You've already (apparently) got a start on the idea of keeping logical data (grid) and render data (the grid's buffer) distinct. This is a good direction, but I'd suggest that you focus on is continuing that separation rather than worrying so much that your input handling code is triggering a graphics rebuild.

For example, `glBufferData` operates on the currently bound buffer, and I don't see where you set that here. That means either you're setting it in `grid.Build` or you're setting it at the start of the program and expecting it to remain set. *That* is bad, as it will cause you no end of pain when you start adding more than one buffer to your program. Spending time getting OpenGL buffer management correct early can save you a lot of trouble in the long run. Consider building an abstraction around the *renderable* grid that makes it just as easy to update the render buffer data, but does it without making assumptions about which buffer is currently bound, et cetera.

# Answer
> 1 votes
I think simple layers of abstraction would do the trick. Create an `InputModule` that produces `InputEvent`s that are handled by objects that have registered to the `InputModule` as event handlers, listeners or such.

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


# Question
Title: What causes regions of improperly-lit terrain when my pixel light count is below 4?
My Unity3d game has a strange bug where if you have the pixel light count set below 4, these strange boxes appear on the terrain. Because this game is going to be for mobile, if I set the pixel light count too high, won't run fast enough.

The screenshot will show you what I mean:

You can see this box on the left of the image where light is entering, I want light to enter all around the coin. How can I fix or prevent this?

# Answer
> 3 votes
* You have 1 pixel light in the scene for every coin, I see four coins in the scene.
* You have your quality settings set to 1 pixel light.

This means that every mesh will pick the *nearest* 1 pixel light to use for illumination and ignore the rest. The nearest light to the plane on the left of the image is the light we can see. For the other three planes, that light is not the nearest.

---
Tags: unity, lighting
---


# Question
Title: How to create a dynamic Map in Unity (Augmented Reality)
I created a dynamic map with a LineRenderer. The LineRenderer gets a new position assigned, for each movement my 'character' does. It works good, but I expect it to get a really bad performance at some point. Could you recommend a better solution to create a dynamic map with the free version of Unity. My code looks like this at the moment :

```
        if (lastPosition != target.transform.position) {
            path.SetVertexCount(positionCounter + 1); //Path is the LineRenderer
            lastPosition = target.transform.position;
            path.SetPosition(positionCounter++,new Vector3(lastPosition.x,0,lastPosition.z));
        }

```

The LineRenderer lies on a layer, which can only be seen by my orthographic mini map camera. Btw. I need it in a dynamic way, because it's an augmented reality app, which has no terrain which I could display on the map or stuff like this. I have to create the stuff which should be displayed.

# Answer
> 2 votes
**Caveats**

1. I recommend anyone using `LineRenderer` to look into Vectrosity on the Unity asset store. I use it for any line drawing I do in any of my projects, period. It's great.
2. Before you implement a convoluted solution to address the performance impact of your current solution, prove that it's a problem with profiling. AR/VR is new, unfamiliar, and *uncomfortable* for most players. They are not likely to play any game for multiple hours yet (expect 15-30 minutes), so you don't need to consider that kind of long-term stability/performance.

If you're producing a brisk 1 point per second and you have a player stay for a massive 10 hours you're only at 36,000 points. Even if none of those are culled, that shouldn't cause extreme performance issues.

---

OK, so lets assume in spite of the above you're observing real performance issues that are definitely caused by the `LineRenderer`. Here are some ways to address that.

**Cull Mercilessly**

First, you need to make sure you're not rendering anything unnecessarily. I believe Unity will cull the parts of the line that aren't in the frustum, though I haven't explicitly tested that recently. If you zoom into the cube in Vectrosity's Demo #3, there appears to be culling, though whether that's Vectrosity, the demo, or Unity, I haven't checked just yet.

If it does not cull for you, then you may benefit from doing your own. There are many ways to accomplish this, but mostly they hinge around determining which points should be visible (perhaps using QuadTrees/Octrees) and re-creating your line periodically to show only those points. You don't need to maintain an object that can't possibly be visible.

Likely, this also involves breaking your line into multiple LineRenderers. I.e. if a player walks down one side of a street and then later the other side of the street, you shouldn't be trying to render everything between those two paths.

**Compress Aggressively**

A second approach is line "compression" - removing unnecessary points. Players generally won't care too much about having a perfect record of their path, so you can remove points from your line once you recognize they're not helping.

A good starting point for this is the Ramer-Douglas-Peucker algorithm.

**Is It Really Necessary?**

The easiest way to optimize any task is to realize you don't need to do most of that task. If you don't think the player *really* needs to know their long-term history, you could simply keep track of the past X points and only draw those.

I realize this is all pretty high-level. If you'd like more detail on any of these, or if I totally missed your actual question, let me know. :)

---
Tags: c#, unity, maps, augmented-reality
---


# Question
Title: Is knowing physics necessary for game development?
Is knowledge of physics necessary to design quality games? How important is it? Be realistic and explain a few novice examples of how's mandatory.

What kind of physics is necessary, non-calculus-based or calculus-based? Do I need to know Physics III (modern, heat, light, waves)? In summary, what part (and level) of physics must one know?

# Answer
> 4 votes
As stephelton said in the comments to your question, vector math is extremely important for pretty much any 2D or 3D game. However, physics knowledge isn't necessary for a lot of simple games. There are physics-like concepts you should understand a bit about, like collision, but you won't need calculus or physics classes for that as long as you keep it simple. A lot of things you may want to do can be simulated simply enough that players won't care much, like friction, or sliding, or gravity. A decent grasp of physics will likely help in many situations though.

# Answer
> 2 votes
You can write complete games without any physics knowledge depending on the type of the game. For example puzzle games rarely have any physics. If you want to have physics simulation you can use existing physics engines, but then you need some basic knowledge of the physics, e.g. about mass, inertia and impulses. You don't need to do the math, but you need to understand the concepts. Knowing the underlying math helps even more.

On the other hand in game development you can utilize almost any kind of physics if you want to and you have an idea where to use it. This can include rigid bodies, soft bodies, lighting, heat simulation, water pressure or theory of relativity for a game in space. It's up to you, but no physics knowledge is mandatory in general. Math is important though. You can hardly avoid that, as it's everywhere.

# Answer
> 1 votes
Physics isn't really necessary unless you want to have physics in your game. While a good general knowledge of physics is recommended, it's not necessary if you're using someone else's physics engine (which I would recommend). Also, calc based physics will get you farther. And, you really only need to know mechanics but the other things don't hurt. All in all though, it depends on what you're doing.

# Answer
> 1 votes
It depends.

There are many areas of game development, just as there are many areas of physics.

First, you will only need to know physics for games that require physics, obviously!If you're making an MMO, for example, you probably wont need physics.

But, as soon as there is any falling, velocities, acceleration and things like that involved, you'll need physics. Mostly, it's just movement stuff, m1v1 + m2v2 = m1v3 + m2v4, dS = V\*dT, and your regular formulas you already know. I doubt that you will need anything more complicated from that, at least for now.

What is the problem, though, is applying physics. Collision detection isn't really an area of physics (or at least until you get to the subatomic level), but you still need it in your physics engine.

# Answer
> 0 votes
There anything that you need to know in order to develop games. It depend what's your better knowdledge, that you should make some kind of game of another. Or depends of your traits, you should make a part of another in a game studio.

How do you see yourself?

* Programer \[gameplay programmer, graphics programmer, network programmer... etc\]
* Artist \[2d artist, 3d modeller, ...et\]
* Designer \[level designer, script...etc\]
* Musician

# Answer
> 0 votes
Having something that behaves close to our real world makes the rules of your game easier to learn for your player, feel more natural, and brings the player to the fun/challenging part more rapidly.

The first time I wanted to have a character jumping in a game, I started using sin(x). The result was kinda akwards: as soon as you jumped off a cliff, you'd end up travelling up and down, as if you'd be riding a curious deltaplane. The good approach is much simpler and simply require that the speed is increased at every frame by a constant (gravity acceleration) as stated in Newton Laws. Knowing physics makes you find the right solution faster.

It is probably not *required* to know physics in details when you're doing a game, but it definitely helps, especially if there are some 'virtual reality' features in your game. A game like "From Dust" (Eric Chahi) is essentially physics simulation gamified, while "Another World" only need high-precision capture of real-life motion (so and requires little to no actual understanding of what happens).

It is very likely that inertia and the other bodies motion related fields will be quite helpful to produce something that is pleasant to the eye, even if you're just moving items on a chessboard. Knowing that friction exists helps using it as a game mechanic, even if you don't exactly use their academic version. Same for energy conservation. In fact, I believe we could very much use game development as a way to **teach** physics.

I'd be very surprised if you ever use Maxwell or Einstein theories, though. But who knows ? Ludum dare could prove me wrong.

---
Tags: physics
---


# Question
Title: Which three points to use to calculate a frustum plane?
So I have a view frustum I'm going to be using for frustum culling. I have a method that finds the cross-product of three points but since each side of the frustum has four corners I don't know which three to use and in which order.

Point numbers:

##

My question is, does anyone know what order and which points to use?

# Answer
> 1 votes
It's not that you can't point the normals randomly inward/outward, as long as you test them appropriately. It's easier to point them either all-in, or all-out so that the dot products of a contained point are either **all** positive or **all** negative. This makes an generic, iterative `if` test possible.

The cross-product of two *vectors* is a third vector, perpendicular to both; it is also the normal of the plane that contains both inputs.

For the front face, you can do:

```
 cross(normalize(5-7), normalize(6-7))

```

The in- or out-wardness of the direction produced doesn't matter. You can simply breakpoint this, once, see if the calculated normal is positive or negative, and then adjust the `if (dot)` within the iterative plane test accordingly. I viewed the front face from the "outside" along its normal and chose counter-clockwise points, starting at the "top-left" corner. Pick a point on the face, call it "top-left", then wind counter-clockwise around the face's normal. Your hand-drawn diagram has everything you need.

---
Tags: mathematics, optimization, frustum, frustum-culling
---


# Question
Title: When to use multiple parts for a mesh, and when to build detail in?
I am always running into the decision whether or not to make a mesh one connected mesh or to add small details as just separate parts to the model. Is there a best practices for this? Does it matter for games either way?

# Answer
Fewer meshes equate to fewer draw calls, so generally you should try to go for as few as possible.

Split them when:

* one mesh would be so large that you'd need 32-bit index buffers to address (as this is generally *too* large)
* the sub-mesh uses different textures/shaders/materials
* the sub-mesh is somehow optional and might be detached or attached from the main mesh often (or similar reasons; basically you want to avoid having to update the main mesh's vertex buffer)
> 3 votes

---
Tags: 3d, models, 3d-meshes
---


# Question
Title: Why do I get 3 lines of log at Monitor.exe when using Debug.Log in Unity?
* I'm debugging a real device.
* In a `GUILayer.Button` I've put a single `Debug.Log()` message, like in this code

Code:

```
if( GUILayout.Button( "Click to Test." ) )
{
    Debug.Log( "XAVI Clicked!" );
}

```
* But in `monitor.exe` I get 3 lines, like the following ones:

* To filter out messy messages from other applications, my filter is "tag:unity".
* The APK is compiled with `Development Build` unchecked.

**Problem:**

I expected to see only one log line, with the text `XAVI Clicked!` but I also got a blank line and a line referencing a filename that I don't know what is it.

Those 2 lines are a consequence of "logging", not a consequence of "clicking the button", as if I remove my log sentence, then I do not receive my log but also I don't receive those phantom two lines (zero log lines then).

**Questions:**

1. Is there any way I get rid of those lines I don't want to see?
2. Is there any way I can create my own filtering tag inside the Unity?
3. How do you handle if you want to see exclusively your logs but not "extra logs" placed by the system?
4. Is there any reason that I should keep watching those lines? Are they carrying meaningful intormation? What do they tell to me that is relevant to me?

Thanks.

# Answer
> 1 votes
Those other lines are your callstack. It's just how Unity does things -- as far as I know you can't change it.

If you want to filter them out, what you can likely do is add a prefix to your own debug logs and filter off of that instead of just relying on the tags.

---
Tags: android, unity, debugging
---


# Question
Title: How do you use SoundManager for multiple player games over the network?
I have created a basic sound manager according to this unity tutorial (https://unity3d.com/learn/tutorials/projects/2d-roguelike/audio). However, I need it to work for multiple players over the network, and it doesn't make sense for them all to be playing the same sounds. E.g. If a player loses, it should play the gameover sound, but the other player(s) should remain in the game and continue playing the game sound. But the current behavior is that once a player loses, everyone gets the gameover sound.

By the tutorial, I currently use a single instance within the SoundManager class. I think I need multiple SoundManager instances, each associated with a client. What's the best thing to attach the SoundManagers too? Or is there a different best practice for managing sounds for multi-player games?

Here's the code for my sound manager:

```
using UnityEngine;
using System.Collections;

public class SoundManager : MonoBehaviour {

    public static SoundManager instance = null;

    public AudioSource effects;
    public AudioSource music;

    void Awake ()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy (gameObject);
        DontDestroyOnLoad (gameObject);
    }

    public void playSoundEffect(AudioClip clip) {
        effects.PlayOneShot (clip, 1f);
    }

    public void setBackgroundMusic(AudioClip clip) {
        music.clip = clip;
        music.Play ();
    }
}

```

# Answer
> 2 votes
This turned out to be much easier than I imagined. Don't know if this is a best practice, but you can just attach the sound manager to an empty game object and get a client instance of it via `GameObject.Find("Name of your sound manager").GetComponent<SoundManager>()`. You can do this inside of `public override void OnStartLocalPlayer ()`. Get rid of the instance variable inside the class.

---
Tags: unity, multiplayer, sound, audio, unity-networking
---


title: About HLSL array packing policy

text:
# Question
Title: About HLSL array packing policy
This is not a question but a confirmation if I'm correct about the behavior of HLSL arrays.

I'm working with a standard lighting vertex shader, HLSL plus C++, DirectX11.1 API. For storing my lights data I've setup a simple declaration, padded accordingly to match the packing requeriments of constant buffers:

```
  // C++ side
struct LightBase {
            DirectX::XMFLOAT3   pos, color;
            DirectX::XMFLOAT3   color;
            float               intensity;
            float               isOn;
    };
    struct CBUFFER_LIGHT {
        LightBase   light[MAX_LIGHTS];
        float       numActiveLights;
        float       _padding[3];
    };

```

The shader declares a "matching" cbuffer as:

```
// HLSL vertex shader
    struct LightBase {
        float3 pos;
        float3 color;
        float  intensity;
        float  isOn;
    };
    cbuffer lights : register (b3) {
        LightBase light[MAX_LIGHTS];
        float numActiveLights;
    }

```

Now, as I expected, it didnt work due to the HLSL memory organization policy regarding arrays. e.g; if I set the buffer from C++ with the following data:  I get the following data when accessing struct members of light\[0\] from shader:

See how `light[0].color` and other struct members got messed up? Seems that HLSL will organize your arrays in Vector4 elements *regardless of the real type of the array element*.

So the array data passed from C++ which is `{ -7, -1, -100, 0.44, 0.66, 0.88, 1.0, 1.0 }` will be organized by HLSL as follows:

```
A[0] = { -7, -1, -100, 0.44 }
A[1] = { 0.66, 0.88, 1.0, 1.0 }
A[2] = { ...}

```

So `A[0]` contains .xyz for position and .x for color struct member. `A[1]` contains .gb for color member, intensity and isOn data.

But calling `light[0].color` from the shader will still try to address `&light + sizeof(float3)+sizeof(float3)` as defined in the cbuffer, but ***you will get incorrect results due to array organization policy of HLSL*.**

If HLSL and DirectX are so fond of FLOAT4 values, it's not better to use all float4 variables and access members (.xyzw) as needed? Thanks.

# Answer
The rules are a bit convoluted but the essence is that if a vector element would wrap into the next register, it's put at the beginning of the next register.

Your CPU-side and GPU-side definitions do not agree on actual member offsets, you need to manually pad your type on the CPU side according to the rules if you want to use a struct.

You can achieve a tighter packing by organizing your buffer elements such that they logically group up in chunks of 4.

```
float3 pos; float intensity;
float3 color; float isOn;

```

Encoding things in clunky float4 tends to be reserved for the case when you encode things in multi-component textures:

```
float4 pos3_and_intensity;
float4 color3_and_isOn;

```
> 3 votes

---
Tags: shaders, hlsl, data-structure, memory
---


# Question
Title: Having trouble creating multiple sprites from one class
So I am trying to make more than one sprite using a single class but I cannot seem to get the sprites to be drawn at all or drawn in different places (they are all just on top of one another).

In my Game1 I have:

```
    Flag flag;
    List<Flag> GameFlags = new List<Flag>();

```

then in LoadContent:

```
flag = new Flag();
tempTexture = Content.Load<Texture2D>("FlagTexture");
tempRectangle = new Rectangle(50, 500,tempTexture.Width / 3, tempTexture.Height / 3);
flag.SetSprite(tempTexture);
flag.SetRectangle(tempRectangle);

for (int i = 0; i < 2; i++)
        {
            GameFlags.Add(flag);
            flag.spriteRectangle.X += 100;
        }

```

Then in Draw:

```
 foreach (Flag flag in GameFlags)
        {
            spriteBatch.Begin();
            flag.Draw(spriteBatch);
            spriteBatch.End();
        }

```

The effect I am after is having 2 sprites spaced out by a specified amount of space. Image if the underscores were spacing and the zeros were sprites in the following:

0\____________________________0

Any help and advice is appreciated.

Thanks in advance,

TeaBelliedTitch.

# Answer
```
for (int i = 0; i < 2; i++)
    {
        GameFlags.Add(flag);
        flag.spriteRectangle.X += 100;
    }

```

Is this not adding a reference to the same object? So you have a list of references to one thing as opposed to a list of things or references to things
> 1 votes

---
Tags: c#, xna, sprites, xna-4.0
---


# Question
Title: How do I find the location of a GameObject in C#
I'm making an elevator script. Essentially I'm wanting to find the difference between two empty objects so that I can move the elevator between them.

To be able to do this, I need to be able to get the location of both GameObjects in my script. From a bit of searching, I haven't been able to figure it out.

How would I go about doing this?

# Answer
> 4 votes
Basically its all the game of terminologies, probably you couldn't find anything because of it.

Actually the basic term is **Transformation** which includes three basic attributes of any object, i.e. **Translation**( position ), **Rotation** and **Scaling**.

Have a look in detail from these answers

Right terms are so important because of there generality.

For example lets take a term *Gameloop* that is a general term. So you can search it for any game engine through this term, but if you know only Unity's `Update` method then it'd be much difficult for you find it for any other game engines. That is how the general terms work.

So your term *location* is not suitable though, you should use *position* instead when you are searching.

In Unity `gameObject.transform.position` will give you the global position of `gameObject` through its `transform` component.

I think that is the thing you want to know. Let me know if I did miss anything.

# Answer
> 3 votes
To get the position of a gameobject in the world, you can retrieve a Vector3 (x,y,z) of it's Position from the Transform component that's added by default to every gameobject, as seen in the inspector:

`gameObject.Transform.position` returns the absolute world position. *Note that this is the same as `GetComponent<Transform>().position` on your gameobject.*

`gameObject.Transform.localPosition` returns the position relative to that gameobject parent's position - if your gameobject has a parent whose position is not 0,0,0 this will return the Vector3 value of what you see in the inspector, rather than the absolute world position.

---

If you're not sure how to reference the two gameobjects in your script, the simplest and most basic way is to create two GameObject variables in your script and expose them in the editor (since they are serializable):

```
public GameObject OriginPosition;
[SerializeField] private GameObject _destinationPosition;

```

*Above: Two ways of exposing a variable to the Unity Inspector*

*Above: The result, now you can simply drag and drop GameObjects into these slots.*

```
UnityEngine.Debug.Log(OriginalPosition.Transform.position);
UnityEngine.Debug.Log(_destinationPosition.Transform.position);

```

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


# Question
Title: XNA How do I detect if my mouse if hovering over a specific sprite?
How do I detect if my mouse if hovering over a specific sprite?

For example I'm making a custom button and I want to check if my mouse is hovering over it so I can make animations.

# Answer
You need two things:

1. Get the position of the mouse cursor
2. Get the position and size of your sprite texture (`Texture2d` has a very handy propery that does just that)

The second point depends of your implementation but you could have a `Sprite` class that holds a reference to a `Texture2d` and a `Vector2` for the position.

The `Bounds` property of `Texture2` returns a `Rectangle` which has a Contains method that does exactly what we need. So from here we can write a very simple function that returns true when a point is located within a given sprite.

```
bool IsPointOverSprite(float x, float y, Sprite sprite)
{
    return (sprite.getTexture().getBounds().Contains(pos.X, pos.Y);
}

```
> 2 votes

---
Tags: xna
---


# Question
Title: How to make score counter independent of framerate
I have a score counter, but I've noticed that the lower the framerate is, the slower it counts. How can I make it so it ignores the framerate?

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

public class Score : MonoBehaviour {
    private Text scoreText;
    private static int score;
    private static int finalScore;
    private static bool count;
    public static int scoreMultiplier;

    private void Start() {
        scoreText = GetComponent<Text>();
        count = false;
        scoreMultiplier = 1;
    }

    public static void StartCounting() {
        count = true;
    }

    public static void StopCounting() {
        count = false;
    }

    public static void Reset() {
        count = false;
        score = 0;
    }

    public static IEnumerator MultiplyBy(int scoreMultiplier) {
        Score.scoreMultiplier = scoreMultiplier;
        yield return new WaitForSeconds(6f);
        Score.scoreMultiplier = 1;
    }

    private void Update() {
        if (count) {
            score += scoreMultiplier;
        }

        // Slice the score so the number doesn't get too big
        finalScore = score / 4;

        scoreText.text = finalScore.ToString("00000");
    }
}

```

**Edit: Fixed by adding `Time.deltaTime` and putting it in `FixedUpdate` instead of `Update`**

```
private void FixedUpdate() {
    if (count) {
        score += scorePerSecond * Time.deltaTime * scoreMultiplier;
    }

    finalScore = Convert.ToInt32(score);
    scoreText.text = finalScore.ToString("000000");
}

```

# Answer
> 2 votes
You have to use the frame time, and make your score based on time instead of on frames:

Here is the pseudo-code:

```
float scorePerSecond = 1000.0 // A parameter of some sort
float score = 0.0

update( )
  if ( count )
    score += scorePerSecond * deltaTime * scoreMultiplier;

```

In this example, `deltaTime` is assumed to be in seconds. In Unity, the `deltaTime` seems to be fetched by using `Time.deltaTime`. Also, note that the score is now a floating point value (because everything else is calculated in floating point values). You'll have to convert that to int before displaying to the user.

Everything in your game that happens over time should be done in that fashion.

---

Edit based on comments.

Alternatively, you can use Unity's `FixedUpdate` method to have the update done on a more precise basis. (In Unity, menu *Edit* \> *Project Settings* \> *Time* to set your fixed timestep; thanks @Chris.)

You then have 2 options.

You can either still use the delta time provided by Unity:

```
float scorePerSecond = 1000.0 // A parameter of some sort
float score = 0.0

fixedUpdate( )
  if ( count )
    score += scorePerSecond * deltaTime * scoreMultiplier;

```

This method will 'shield' you from when Unity is not able (for a reason or for another) give you the rate you request, but the extra multiplication (when compared to the next method) can introduce a small fixed point manipulation error.

Or you can use a pre-computed 'by frame' value, based on the framerate that you set Unity's value.

```
int scoreMultiplier; // A parameter of some sort, assume that the frame rate is fixed at 30 hz
int score = 0

fixedUpdate( )
  if ( count )
    score += scoreMultiplier;

```

No floating point error is introduced here, and you can use integers.

# Answer
> 0 votes
`MonoBehaviour` has a method called `FixedUpdate`, I suggest you to use it instead of `Update`. Multiplying by frames' delta time gives results that are dependent of the framerate, which is unstable and thus unreliable.

---
Tags: unity, frame-rate
---


# Question
Title: how to add an onclick event to a button?
If I will draw a button with canvas with any programming language (java,javascript....) I want to know how to add the events to what I've drawn for example If I will draw a button piture then what I have to do to be able to make an onclick event to that button in my case I'm trying to make a javascript application but In canvas it's a drawing so how could we add a button ? Please comment with any idea you have ?

> Example : When I run my game the player will find a welcome page with a start button drawn with Photoshop or something like that and it has been drawn by a canvas so how could I add a MouseListener to that button ?

# Answer
> 1 votes
The straightforward method is to keep a list of trigger areas and on each onclick event on the canvas compare the cursor location to the areas and trigger the correct event handler.

How you express those areas is up to you, in extremis you can assign a handler to each pixel using a second bitmap where the exact color of the second bitmap is an index to the handler.

# Answer
> 0 votes
You could try having 2 layers stacked on top of each other with a default button underneath your canvas drawn one

---
Tags: java, events
---


# Question
Title: Physics Object on Client moving too quickly in comparison to the Server: Should be a copy
I have a client server scenario. On the Server a force is applied to a 2d object. I want the client to copy the movements of the server but not through constant positional updates. My current approach is to send the objects name, position and speed to the client for the client to apply those to its own object and therefore copy the server. The speed is calculated by subtracting the last known position from the current one and working out the magnitude:

```
physicsManagerScript.SendInfo (transform.name, transform.GetComponent<Rigidbody2D>().position, (transform.GetComponent<Rigidbody2D>().position-lastPos).magnitude);

```

The position and speed are received via RPC and each go into a list on the client and then the client object applies these via Vector3.MoveTowards:

```
transform.position = Vector3.MoveTowards (transform.position, receivedPos [index], receivedSpeed [index]/Time.deltaTime);

```

My problem is that even though the same magnitude is applied on the client as the server, the clients object moves very quickly in comparison to its server counterpart. The server object bounces around and eventually slows, however when it is moving slowly the client object flashes to its new position. I dont understand why this is happening when it should be moving at the same speed as the server object. Any help would be greatly appreciated.

\**Additional Info

I have an invokerepeating method on the server that every second sends the name, position and magnitude to a physics manager script. This physics manager script then RPC's the client sending the correct position and magnitude to the correct name of object. The client object places the received position and magnitude into seperate lists. Vector3.MoveTowards is then used to move the client object to its new position at a new speed. However the speed it moves at is very quick in comparison to the server, when i want it to copy the server. This is for a distributed physics project, ie the server handles the physics and sends down the appropriate info without the client using any physics.

# Answer
Doing some more research into finding out the speed a physics object is moving that I came across someone who found the magnitude of the velocity instead of finding the magnitude of the last known position from the current position. This changes my line to

`physicsManagerScript.SendInfo (transform.name, transform.GetComponent<Rigidbody2D>().position, transform.GetComponent<Rigidbody2D> ().velocity.magnitude);`

This seems to fix my issue!
> 0 votes

---
Tags: c#, unity, client-server, unity-networking
---


# Question
Title: OpenGL: why do I have to set a normal with glNormal?
I'm learning some basics of OpenGL but I'm wondering why there is a call `glNormal` to set the normal of vertices.

If I create a simple triangle like this:

```
glBegin(GL_TRIANGLES);
    glVertex3f(0,0,0);
    glVertex3f(1,0,0);
    glVertex3f(0,1,0);
glEnd();

```

Shouldn't the normals be defined implicitly by the type of the geometric primitive? If I don't set a normal will OpenGL calculate it?

# Answer
Calling `glNormal` multiple times between `glBegin/End` allows you to set a normal per vertex instead of per primitive.

```
glBegin(GL_TRIANGLES);
    glNormal3f(0,0,1);
    glVertex3f(0,0,0);
    glNormal3f(0,0,1);
    glVertex3f(1,0,0);
    glNormal3f(0,0,1);
    glVertex3f(0,1,0);
glEnd();

```

For a more complex mesh consisting of multiple triangles you would want the normal at one vertex depend on the other triangles of the surrounding geometry and not just the normal of the triangle it belongs to.

Here is an example of the same geometry with:

* on the left **per-vertex normals** \- so each vertex of a face has a different normal (for this sphere it means all normals point outward from its center), and
* on the right **per-face normals** \- each vertex gets the same normal value (since you specify it only once, or because it uses the default normal value of `(0,0,1)`):

The default shade model (`GL_SMOOTH`) causes the normals of the face's vertices to be interpolated across the face. For the **per-vertex normals** this results in a smooth shaded sphere, but for the **per-face normals** you end up with the characteristic faceted look.
> 32 votes

# Answer
The short answer is that you don't actually *have* to set a normal at all. Normal vectors are only used if you're performing OpenGL lighting (or perhaps some other calculation that may depend on them), but if that doesn't apply to you (or if you're using some other method to do lighting, e.g. lightmaps) then you can quite happily omit all glNormal calls.

So let's assume that you are doing something where specifying glNormal makes sense and look at it some more.

glNormal can be specified per-primitive or per-vertex. With per-primitive normals all that it means is that all of the normals for each vertex in the primitive face in the same direction. Sometimes this is what you want but sometimes it isn't - where per-vertex normals come in useful is that they allow each vertex to have it's own facing.

Take the classic example of a sphere. If each triangle in a sphere had the same normal then the end result would be quite faceted. That's probably not what you want, you want a smooth shading instead. So what you do is average the normals for each triangle that shares a common vertex, and get a smooth shaded result.
> 4 votes

# Answer
No, GL does not calculate a norm for you. It cant't know what the normal should be. Your primitives don't mean anything outside of rasterization (and a few other places). GL doesn't know which faces (triangles) share a vertex (calculating this at runtime is very expensive without using different data structures).

You need to preprocess a mesh's "triangle soup" to find common vertices and calculate normals. This should be done before the game runs for speed.

There are also cases like hard edges where geometrically there is a shared vertex at the corner, but you want separate normals so it lights correctly. In the GL/D3D rendering model, you need two separate vertices (at the same position) for this, each with a separate normal.

You'll need all this for UVs and texture mapping, too.
> 4 votes

# Answer
**Minimal example** that illustrates some details of how `glNormal` works with diffuse lightning.

The comments of the `display` function explain what each triangle means.

```
#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

/* Triangle on the x-y plane. */
static void draw_triangle() {
    glBegin(GL_TRIANGLES);
    glVertex3f( 0.0f,  1.0f, 0.0f);
    glVertex3f(-1.0f, -1.0f, 0.0f);
    glVertex3f( 1.0f, -1.0f, 0.0f);
    glEnd();
}

/* A triangle tilted 45 degrees manually. */
static void draw_triangle_45() {
    glBegin(GL_TRIANGLES);
    glVertex3f( 0.0f,  1.0f, -1.0f);
    glVertex3f(-1.0f, -1.0f,  0.0f);
    glVertex3f( 1.0f, -1.0f,  0.0f);
    glEnd();
}

static void display(void) {
    glColor3f(1.0f, 0.0f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();

    /*
    Triangle perpendicular to the light.
    0,0,1 also happens to be the default normal if we hadn't specified one.
    */
    glNormal3f(0.0f, 0.0f, 1.0f);
    draw_triangle();

    /*
    This triangle is as bright as the previous one.
    This is not photorealistic, where it should be less bright.
    */
    glTranslatef(2.0f, 0.0f, 0.0f);
    draw_triangle_45();

    /*
    Same as previous triangle, but with the normal set
    to the photorealistic value of 45, making it less bright.

    Note that the norm of this normal vector is not 1,
    but we are fine since we are using `glEnable(GL_NORMALIZE)`.
    */
    glTranslatef(2.0f, 0.0f, 0.0f);
    glNormal3f(0.0f, 1.0f, 1.0f);
    draw_triangle_45();

    /*
    This triangle is rotated 45 degrees with a glRotate.
    It should be as bright as the previous one,
    even though we set the normal to 0,0,1.
    So glRotate also affects the normal!
    */
    glTranslatef(2.0f, 0.0f, 0.0f);
    glNormal3f(0.0, 0.0, 1.0);
    glRotatef(45.0, -1.0, 0.0, 0.0);
    draw_triangle();

    glPopMatrix();
    glFlush();
}

static void init(void) {
    GLfloat light0_diffuse[] = {1.0, 1.0, 1.0, 1.0};
    /* Plane wave coming from +z infinity. */
    GLfloat light0_position[] = {0.0, 0.0, 1.0, 0.0};
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_SMOOTH);
    glLightfv(GL_LIGHT0, GL_POSITION, light0_position);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glColorMaterial(GL_FRONT, GL_DIFFUSE);
    glEnable(GL_COLOR_MATERIAL);
    glEnable(GL_NORMALIZE);
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-1.0, 7.0, -1.0, 1.0, -1.5, 1.5);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(800, 200);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    init();
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

```

**Theory**

In OpenGL each vertex has it's own associated normal vector.

The normal vector determines how bright the vertex is, which is then used to determine how bright the triangle is.

When a surface is perpendicular to light, it is brighter than a parallel surface.

`glNormal` sets the current normal vector, which is used for all following vertexes.

The initial value for the normal before we all `glNormal` is `0,0,1`.

Normal vectors *must* have norm 1, or else colors change! `glScale` also alters the length of normals! `glEnable(GL_NORMALIZE);` makes OpenGL automatically set their norm to 1 for us. This GIF illustrates that beautifully.

Bibliography:
> 2 votes

# Answer
You need the glNormal to implement some features coder-dependant. For instance you might wish to create normals dat preserve hard edges.
> 0 votes

---
Tags: opengl, normals
---


# Question
Title: How to make a custom inspector component
I have a script component, but I want to know how I can add things like sliders buttons etc.

I wrote a grid system that generates at the start of my script but I want to run it in editor when I push a button to not to force calculations, lessen load times for my game and even see result of my work in editor. How can I do that?

# Answer
It depends on what you need.

For instance if you need to display a slider in the inspector you need to declare your slider

```
using UnityEngine.UI;

[Range(0, 100)]
public Slider sldr;

```

to Add a buttom you could follow this simple tutorial.

**EDIT**:

As per your edit and Byte32 suggestion would be usefull to you to check also for this basic Custom Editor tutorial.
> 2 votes

---
Tags: unity
---


# Question
Title: Is it possible to use Metal and SceneKit at the same time?
All the tutorials that I've found online speak about using Metal alone, without any other supporting library. But I don't understand if it's possible to create a SceneKit game and then use a Metal layer just to make some optimizations.

# Answer
Yup! As of iOS 9, you can set a SceneKit SCNView to use a Metal renderer on devices that support it by initializing it with the `SCNPreferredRenderingAPIKey` key in the options dictionary, as described here. Something along these lines should work:

```
let sceneView = SCNView(frame: someFrame, options:[SCNPreferredRenderingAPIKey: NSNumber(unsignedInteger: SCNRenderingAPI.Metal)])

```

That’s pretty much all you need to do; the way you interact with the rest of the API remains unchanged.
> 3 votes

---
Tags: ios, swift, scenekit
---


# Question
Title: How can I destroy a game object across the network in Unity?
How do I go about destroying a game object across the whole network in a multiplayer scene in Unity? I can only get it to destroy on the local client and not for everybody else connected. I'm instantiating the object client side at runtime. Any pointers?

# Answer
> 1 votes
Unsurprisingly, the way clients and servers communicate it with messages. Two ways of doing this is with either event messages or action messages. For example, in a first person game, a client might send the server one of two messages:

1: Event message:

* Client: "I am at position XYZ and have fired my gun in direction Rx,Ry,Rz."
* Server message to everyone: "Player Lime has just been killed, user ABC receives 12 points."

Following the server receiving the client's message, it checks whether a hit actually happened and then updates all clients with its decision. If possible, then this is the correct way to do multiplayer. It is however much more expensive to run, as the server needs to "play" the game and make all decisions.

2: Action messages

* Client: "I just fired my gun at Lime, did 12 damage to him and killed him"
* Server to client: "Ok."
* Server to all other clients: "Player ABC just killed Lime."

In this case you are only relaying what happened to the server, which replies with an event message to all clients. This is however easily exploitable, but cheaper to run, since the server simply relays messages to everyone and informs them of what is going on.

Now I'm assuming that the thing which surrounds this gameobject's destruction, involves more fluff than just "the GameObject gets destroyed". It's probably either death or destruction or map pruning or something. So if you're using the event driven approach, then write a method which handles all the events from this event (including the GameObject's destruction). When a message for that event arrives, fire the method. Then ensure the message is sent to all clients. Each of them should proceed to run their own version of this method, destroying their own copy of the GameObject.

If you're using the other approach, then make a simpler method which just destroys the object. The rest of it actually remains the same.

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


# Question
Title: What might cause edges of an FBX model to appear curved?
I'm developing an importer/exporter using the FBX SDK. One model I've been using for testing really has me scratching my head:

http://www.turbosquid.com/3d-models/maya-tower-bridge/328242

When I look at the model with my own viewer, with some other 3rd party ones (like the Clockstone one), or based on the screenshots on TurboSquid, all the edges of the bridge look straight. But when I open it with Autodesk FBX Review, it looks all "bulgy":

The scene is composed entirely of meshes and I tried a variety of calls on the mesh parts to see if anything would be returned that didn't just look like default values. All to no avail.

Any perspective would be much appreciated!

# Answer
> 1 votes
I feel like I should add and accept an answer so people won't waste time reading this in an "unanswered question" list.

See the comments on the question. Essentially what I was seeing in FBX Review when looking at this file was actually due to a bug, which in v1.3.1.0 appears to be fixed.

---
Tags: fbx
---


# Question
Title: Audio not playing until after button release when it should be playing while it's pressed
I am trying to play the sound of a car accelerating while a user has a certain button pressed, however, the audio clip isn't playing until after that button is released. Can anyone explain to me where I'm going wrong?

**C#**

```
using UnityEngine;
using System.Collections;

public class MoveCar:MonoBehaviour{
    //Car's idle speed
    private float idleSpeed = 0.0f;
    //Car's current speed
    private float speed = 0.0f;
    //Car's top speed
    public float topSpeed = 165.0f;
    //Car's acceleration rate
    public float acceleration = 10.0f;
    //Car's braking power
    public float deceleration = 15.0f;
    private Rigidbody playerCar;

    void Start(){
        playerCar = GetComponent<Rigidbody>();

    }

    void Update(){
        if(Input.GetKey(KeyCode.W)){
            AudioSource accelerate = playerCar.GetComponent<AudioSource>();
            float horizontal = Input.GetAxis("Horizontal");
            float vertical = Input.GetAxis("Vertical");
            if(speed <= topSpeed){
                accelerate.Play();
                speed = speed + (acceleration * Time.deltaTime);
                Vector3 movement = new Vector3(vertical, 0.0f, horizontal);
                playerCar.AddForce(movement * Mathf.Clamp(speed, idleSpeed, topSpeed));
                Debug.Log(Mathf.Clamp(speed, idleSpeed, topSpeed));
            }
            else{
                speed = topSpeed;
                Debug.Log(Mathf.Clamp(speed, idleSpeed, topSpeed));
            }
        }
    }
}

```

Here's my editor windows

# Answer
Input.GetKey returns true whilst the key is pressed, you're looking for Input.GetKeyDown; this will only fire once. The reason yours isn't working is because it's constantly running those lines of code, which causes the audio to always be 'starting'. If you combine Input.GetKeyDown and Input.GetKeyUp you'll be able to achieve what you're looking for (make sure loop is on);

```
private AudioSource accelerate;

public void Start()
{
    accelerate = playerCar.GetComponent<AudioSource>();
}

public void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
        accelerate.Play();

    if (Input.GetKey(KeyCode.W))
    {
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        if (speed < topSpeed)
        {
            speed = Mathf.Clamp(speed + (acceleration * Time.deltaTime), 0f, topSpeed);
            if (speed == topSpeed)
                accelerate.Stop();
        }

        Vector3 movement = new Vector3(vertical, 0.0f, horizontal);
        playerCar.AddForce(movement * Mathf.Clamp(speed, idleSpeed, topSpeed));

    }
    else
        speed = Mathf.Clamp(speed - (acceleration * Time.deltaTime), 0f, topSpeed);
}

```
> 1 votes

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


title: Keeping Players in Groups

text:
# Question
Title: Keeping Players in Groups
**tl;dr** How can one enforce that groups of players stay together in units in Minecraft?

I'm developing a plugin for a Minecraft server. It's based off feudalistic societies, like Ancient Europe or Japan. I understand that many ancient societies had advanced battle tactics (like this and this, for example). I think this is very interesting, and would add some more interest to a server.

However, Minecraft isn't particularly well suited for this kind of play. Generally, in battles, all the players just run willy-nilly and charge the enemy. There are no units of players, much less the units combining in a smart way to defeat the enemy. How can one enforce players staying together in one unit or group? Keeping each player in a certain position no matter what is not an option, since the players cannot PvP. Once players are grouped into units, I assume they will take up certain battle strategies and use them in a smart way.

# Answer
It's not Minecraft alone that's not well suited for that kind of play, it's the whole first person genre. I'm not sure of any FPS games that take the approach of requiring formations. That level of cooperation is very difficult to communicate, organize and enforce. It's a strategy for a highly trained military unit. Overall, this can easily make the game more work than fun. It becomes even more difficult when you try to balance tactics like strict formations against strategies like guerilla warfare. There's a reason these types of tactics aren't used anymore.

However, if you do want to enforce this behavior, your best bet is likely to give players in formation significant benefits to their health and attack power. While penalizing players who attempt to attack when not in formation.

Further, you'll want to provide explicit in-game markers that inform players where they should be standing, which way they should be facing, etc. in order to stay in formation. That includes having one player that would likely be leading the formation and directing the rest of the players in the formation.
> 0 votes

---
Tags: server, minecraft-modding, plugin
---


title: Playing multiple sounds in Unity5

text:
# Question
Title: Playing multiple sounds in Unity5
I have multiple `AudioClip`s that I have attached to a `GameObject` and I'm trying to play them when certain conditions are met. Each clip is in an array and I have each array item attached to a variable. I'm also getting the `GameObject`'s `Audio Source`. My problem is, I can't get the clips to actually play, how do I get them to do so?

**C#**

```
private Rigidbody playerCar;
private AudioSource engine;
public AudioClip[] carSounds = new AudioClip[3];
AudioClip accelerate;
AudioClip toppedOut;
AudioClip idle;
private bool accelerating;
private bool idling;
private bool maxed;

void Start(){
    playerCar = GetComponent<Rigidbody>();
    engine = playerCar.GetComponent<AudioSource>();
    carSounds = playerCar.GetComponents<AudioClip>();
    idle = carSounds[0];
    accelerate = carSounds[1];
    toppedOut = carSounds[2];
    idling = true;
}

void Update(){
    if(idling){
        engine.PlayOneShot(idle);
        accelerating = false;
        maxed = false;
    }
}

```

**Editor**

For further clarification, here is the exact error Unity is giving me.

`ArgumentException: GetComponent requires that the requested component 'AudioClip' derives from MonoBehaviour or Component or is an interface.
UnityEngine.GameObject.GetComponents[AudioClip] () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineGameObjectBindings.gen.cs:100)
UnityEngine.Component.GetComponents[AudioClip] () (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineComponentBindings.gen.cs:183)
MoveCar.Start () (at Assets/Scripts/MoveCar.cs:28)`

Line 28 is `carSounds = playerCar.GetComponents<AudioClip>();`

# Answer
Big edit:

From chatting and working with Robert on this, to resolve this issue, the solution seems to be:

1. Remove the `carSounds = playerCar.GetComponents<AudioClip>();` line because `GetComponents<AudioClip>()` will always return a null array because AudioClips aren't components that can be added to GameObjects. This was overwriting the AudioClips that had already been assigned in the Inspector tab.
2. PlayOneShot just doesn't seem to work. Perhaps an issue with Unity?
3. Add in extra code to assign engine's AudioClip and tell it to Play.

Working code:

```
if (idling) {
    engine.loop = true;
    engine.clip = carSounds[0];
    if (!engine.isPlaying) {
        engine.Play();
    }
}

```
> 2 votes

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


# Question
Title: When should I extrapolate and when should I interpolate?
I'm having trouble understanding when to extrapolate and when to interpolate. In gaffer on games, he said to interpolate but then in another article it recommended extrapolating the player. So my question is when is it better to extrapolate and when is it better to interpolate?

# Answer
You interpolate when you *know* the 'before' and 'after' values.

> For example: in a point-and-click game, player is currently at position X, and from his interface, he clicks on spot Y. You must *interpolate* the displacement between X and Y because you **know** the two values.

You extrapolate when you guess what's going to be future value, based on what you already know.

> For example: in a first-person-shooter game, player is at position X and he's been depressing the UP arrow on his keyboard for the last second, you can **suppose** that he'll be doing this again for the next second because that's basically the most frequent behaviour in your game; so you *extrapolate* the position that he'll be next frame. The server sends it to the other game clients, this accounts for the delay in the transmission from the server to the players.

**Extrapolation is used mainly for movement prediction. It is not needed by the game *server*, but the game clients need it to display a somewhat realistic and current vision of the state of the game in order to give a smooth visual experience to the players.**
> 32 votes

# Answer
Interpolation is done when you have both a start and end value, and you want to estimate what happens between this start and end value. An example would be to move a player from Position A to Position B in a fluid motion.

Extrapolation, is done when you have a start value, but do not yet have data for the end. You can then extrapolate based on what data you have. For example, based on a player's previous movements, you can determine where he is probably going to be in the next frame.
> 15 votes

# Answer
Always interpolate when you can.

When you don't have enough information to interpolate then you need to extrapolate.

It really is that simple, don't over-think it :)

To explain a bit more:

In general interpolation is better because interpolation is always right. To extrapolate you have to guess. Then you have to deal with what happens when you guess wrong, which leads to rubber banding or popping and all sorts of systems to deal with handling all of that and disguising it.

What happens if you extrapolated a bat position and showed it going to the right place and bouncing the ball, then realize afterwards that you were wrong and it didn't bounce the ball? There is no good way to handle that scenario.
> 2 votes

# Answer
You interpolate to find states between known values, and you extrapolate to find future states.

Think of the problem in terms of state variables, like positions and velocities. In the best of all scenarios, every computer which needs to work with state has access to the state data for the time they want to work on. For example, a collision algorithm to see whether laser-rifle shot X interesets player A's head, the best of all cases is when the algorithm knows the exact position of every object at the time the laser was fired.

In the real world, we are not always so lucky. Sometimes the truth information we receive is more sparse. For example, if player A is a remote player on another computer, you may not know exactly where they're going when you fire the laser and need to calculate the shot. In this case, you need to create an estimator for A's position, typically with interpolation or extrapolation.

The difference between the two is whether you have data that is bounded on both sides, or only one side. Let's say that Player A has already announced their truth position for t=0 and t=1. Player B shoots a laser at t =0.5. In many situations Player A's announcement of their position at t=1 can occur before Player B pulls the trigger. Why? In many games, the responsiveness of the controls is less than perfectly instantaneous. In a racing simulation, much of the player's position is bounded by the physics of a moving vehicle. You may choose to announce a "future position" because you know you really can't steer all that much in a short period. If you have information in the future, you can interpolate between the two values.

What if you aren't lucky enough to have a t=1 value? What if Player A wasn't in a position to announce their future location, and you're stuck deciding whether you hit or missed with only the information from t=0? In this case you have to extrapolate. In extrapolation, you use what you know about the motion to extend beyond any data you have. You might know that Player A has a certain velocity, so presume that if you multiply that by time, you can get a position at each time.

The difference is in the behaviors. Interpolation requires you to have an upper and a lower bound, which you do not always have. However, in nearly all situations it has vastly better results than extrapolation. Extrapolation can easily lead to unrealistic movements. Consider the case of a player who is sidestepping left and right to avoid being shot while advancing. At any given point, their velocity is along a diagonal, so if you extrapolate, the player may appear to run off to the side when, in fact, they never do. If you only do interpolation, the values tend not to stray outside realistic values.

Interpolation and extrapolation are two extremes in the world of filtering. There are many many many many many filters out there for handling data like this which mix and match properties between interpolation and extrapolation. Accordingly, don't be surprised if you see algorithms that are not clearly interpolation or clearly extrapolation. Those two are just the tip of the ice berg.
> 2 votes

# Answer
Interpolation is using known data to calculate a datum within the bounds of the data set (inter- being the 'inside' prefix). Extrapolation is calculating a datum outside the bounds of the existing data (extra- being the 'outside' prefix). Both are used to synthesize additional data, with the exact method of calculation defining the expected reliability of the data generated.

Or to put it into a very simple diagram:

```
A - - - - - B - - - - - C - - - - - D

```

Given the data points `A` and `C` you can interpolate `B` and extrapolate `D`.

---

The accuracy of an interpolation or an extrapolation is entirely dependent on how well you can account for every variable in the calculation. If you know all of the variables and have an equation that accounts for all of them, then you can interpolate or extrapolate with equal ease.

For game mechanics the limiting factors will be the points at which the variables are influenced in unpredictable ways, either by the player or some random or pseudo-random element.

For example, the movement of a ball in Breakout (in its simplest form) can be extrapolated all the way up to the point where it could potentially interact with the player's paddle. All of the variables can be accounted for up to that point and so you can precisely model the actions of the ball. When it reaches the point where player interaction is possible then there are a number of possible outcomes and no way to accurately model which of those is going to be the case until it actually happens. This is the predictive limit of the game physics model.

Interpolation is simpler in games because you are working with known points and don't have to wonder if the conditions will change. Further you have full control over the variables involved and can use any rules you define to determine the path of an object. The more complex the rules the harder it may be to interpolate.

For object movement with simple collisions in a gravity-free playing space (like Breakout or Pong) the mechanism for interpolation along a line on the path is a simple linear interpolation of the points, and the same calculation can be used to extrapolate the line to test for future collisions. Once a collision is detected you can extrapolate the effect of that collision on the objects involved.
> 1 votes

# Answer
The short answer: you interpolate when you have to estimate a value between two known values (i.e.: in one hour the value is 1, in 3 hours it's three, to interpolate the value at 2 at the most likely value 2, with the given values). Extrapolate is when the unknown is outside what you know, so when 1 and 2 are known you can make an educated guess on 3.

Interpolate: in between Extrapolate: outside

The long answers here are most likely way more accurate and scientifically correct, but I hope my simple explanation can make sense to some
> 0 votes

---
Tags: interpolation, extrapolation
---


# Question
Title: timeScale=0 doesnt stop all prefabs in unity
As expected timeScale=0 can be used for stopping the game or pausing but when i make timeScale equal to 0 some prefabs still move and they can shoot bullets but addforce doesnt effect to bullets and they stop there. I know i can fix the problem on handling code of my prefabs but they are a lot. is there a good way to do the trick in my game? thank you for helping

# Answer
> 3 votes
With the exception of `FixedUpdate`, which isn't called with `timeScale = 0`, all other Update methods will get called, and have their code executed.

So setting `Time.timeScale = 0` doesn't necessarily guarantee an object won't move, but if you're keeping your game framerate independent through the use of `Time.deltaTime` then `timeScale = 0` should stop most things.

For example, the following would stop movement, because if `Time.timeScale` is `0`, then `Time.deltaTime` would return `0`, resulting in no translation.

```
transform.Translate(Vector3.forward * Time.deltaTime);

```

Also, physics aren't updated either when `timeScale = 0`. See http://docs.unity3d.com/ScriptReference/Time-timeScale.html for more info.

But ultimately, if you need something to stop (both in terms of movement and executing other actions) you'll need to add a check to your Update methods that return on pause.

```
void Update() {
    if (IsGamePaused) {
        return;
    }
    // All other script logic...
}

```

# Answer
> 1 votes
Unfortunatly, you have to check if you're paused or not in **every single script**, because setting the time scale to zero won't pause the execution of all your script (which is great, of course... to handle things the user can do **while** in pause for exemple).

---
Tags: unity, unityscript
---


title: How can I clear the screen in Xcode?

text:
# Question
Title: How can I clear the screen in Xcode?
so I am following a tutorial to make a snake game in my Xcode console. But the tutorial i am following is using windows and therefore the "system("clear")" command isn't working with my mac, and all of my research seems to show that there is no way to do that in Xcode

my question is, don't many games need to have their screen cleared constantly? how would games that are being designed in Xcode clear their screens if there is no easy way to do this?

# Answer
The `system()` standard library function invokes the host operating system's command processing facility. For Windows this is essentially the console you get when running `cmd.exe` which lets you run DOS-like commands such as `cls` to clear the screen. Other than the function's existence, everything about `system()` is platform-specific.

If you're using Xcode, you're using a Mac, which means you have Terminal.app or similar, which will use some shell (bash, by default). `clear` is the program for most \*nix environments to clear the screen. However, when running the program under Xcode's debugger, the `TERM` environment variable isn't set and the `clear` program won't know what to do. So it won't clear anything, even though the program would if you ran it directly from the terminal.

All the `clear` program does, generally, is either print a bunch of newlines or print a bunch of ANSI escape codes to manipulate the cursor and write over the console output buffer. You could do the same; the newlines in particular would be easy enough.

As for your second question: *Most games don't use terminals* for their main interface and so have no need to clear the terminal. Even games that do, like Nethack, use libraries like `ncurses` to interact with lower-level terminal APIs and "draw" to the terminal. If that's what you're going for you should investigate those sorts of third-party libraries.

Most games use the underlying OS APIs to create windows and draw into those using platform-appropriate APIs.
> 1 votes

---
Tags: c++, xcode
---


# Question
Title: Using Variable to Reference Different C# Script
I had a question about using a variable to access different scripts. I have a Rhythm game I'm working on, and I have different scripts named Rudement1, Rudement2, Rudement3, ect... One of my other scripts has something like this,

```
public GameObject HighHatFlare;
public int RudementNumber = TrainingMenuScript.TrainingMenuInt;

// Use this for initialization
void Start ()
{
    Rudement1.NoteCreated = Rudement1.NoteCreated + 1;
}

```

What I'm looking to do is use this same script but modify it to to something like this:

```
public GameObject HighHatFlare;
public int RudementNumber = TrainingMenuScript.TrainingMenuInt;

// Use this for initialization
void Start ()
{
    Rudement(RudementNumber).NoteCreated = Rudement(RudementNumber).NoteCreated + 1;
}

```

The goal is that I can continually use this script and it will modify itself as I use different "Rudement" scripts. I figured it some type of "RudementNumber" or 'RudementNumber', but I can't figure it out. Can someone help me with this?

A rudement is a basic sticking pattern that you learn at a very beginning level of drumming. Also spelt "Rudiment" I was always told to spell it with an "e" because of its French roots (not relevant).

In this context it could be replaced by the term "level". Each rudiment is a different level and therefore has different amounts of notes. The base script between each level is identical, but the note patterns are different.The script above is attached to each note to give them a numeric order as they are created. It is running under a mono behavior. I think that at it's simplest I'm wondering if you can reference a script name via a changeable string with the intent to pull a variable from it. As the level changes so does this string to pull the amount of NotesCreated from the new level.

# Answer
> 1 votes
Whenever you create anything with identifiers named `Foo1`, `Foo2`, `Foo3` etc., it is very likely that what you should actually be doing is using an array or `List`.

Which one is the ideal solution for your case is hard to tell because you aren't saying much about what you already have and where you want to go software-architecture wise. Also, I have no idea what a "Rudement" is. But I suspect that your "Rudement"'s are actually all subtypes of a common base-type. In that case you should have one base-class Rudement and either several instances of it which differ by their private variable values or several derived classes which implement certain methods differently.

In either case you can have a static array of "Rudements" in your base-class where you store these instances. Your Rudement class would then have a

```
public static List<Rudement> rudements = new List<Rudement>();

```

A public static list is visible everywhere in your project and can be accessed with `Rudement.rudements`. Any rudement which is created should add itself to that list with `Rudement.rudements.Add(this);`. You can then address certain rudements with `Rudement.rudements[index]`.

This should get you going, but keep in mind that this is just one of several solutions to this general problem. There is never just one solution to a software design question and maybe a different one will suit you better.

# Answer
> 0 votes
make this variable static than you can access in any other script like public static #type of variable# myrudment in other script you can access like this name of the class in which you declared that variable #name of the class#.myrudment

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


title: How to convert font size to pixels?

text:
# Question
Title: How to convert font size to pixels?
I'm trying to add text to my game using SDL\_TTF, and it's working pretty well.

Except for one thing :

My text's SDL\_Surface needs a width and a height, if I don't give it one it will automatically set it to 0, making the text invisible.

However, if I insert a value like 100 width and 100 height, it will stretch the image.

I need to know how I would convert ANY font size on the font **arial** to pixels in width and height.

# Answer
> 1 votes
`TTF_RenderText_Solid(font, const char* text, {r, g, b});` renders a surface with text on it. You could just use something like

```
SDL_Surface* text = TTF_RenderText_Solid(arial, "hi", {r, g, b});
int textWidth = text->w;
int textHeight = text->h;

```

You don't even need to make a blank surface for this method.

---
Tags: sdl2
---


# Question
Title: Cryengine crashes at loading CryRenderD3D11
Starting the CryEngine Launcher, creating a new project runs a loading screen that always crashes on CryRenderD3D11.

How can i fix that?

The Editor.log file is:

```
BackupNameAttachment=" Build(184) 19 Mar 16 (17 04 53)"  -- used by backup system
Log Started at Sat Mar 19 17:04:53 2016
Built on Mar 15 2016 14:54:28
Running 64 bit Windows version
Executable: M:\Videogiochi\CryTek Engine\CRYENGINE Launcher\Crytek\CRYENGINE_5.0\bin\win_x64\Sandbox.exe
FileVersion: 5.0.0.184
ProductVersion: 5.0.0.184
Added MOD directory <%engineroot%> to CryPak
Added MOD directory <%engineroot%/engine> to CryPak

Total number of logical processors: 4
Number of available logical processors: 4
Total number of system cores: 2
Number of cores available to process: 2

Processor 0:
  CPU: Intel Intel(R) Core(TM) i3-4150 CPU @ 3.50GHz
  Family: 6, Model: 12, Stepping: 3
  FPU: On-Chip
  3DNow!: not present
  MMX: not present
  SSE: present
  SSE2: present
  SSE3: present
  Serial number not present or disabled

Processor 1:
  CPU: Intel Intel(R) Core(TM) i3-4150 CPU @ 3.50GHz
  Family: 6, Model: 12, Stepping: 3
  FPU: On-Chip
  3DNow!: not present
  MMX: not present
  SSE: present
  SSE2: present
  SSE3: present
  Serial number not present or disabled

[Error] [CVARS]: [DUPLICATE] CXConsole::AddCommand(): console command [hmd_recenter_pose] is already registered
Loading Config file system.cfg (m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\system.cfg)
<17:04:53> OnSysSpecChange(4)
<17:04:53> [Warning] Config file VeryHighSpec.cfg not found!
<17:04:53> Loading Config file %ENGINEROOT%/editor.cfg (m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\editor.cfg)
<17:04:53> [Warning] Config file game.cfg not found!
<17:04:53> Loading Config file project.cfg (project.cfg)
<17:04:53> GameDir: Assets
<17:04:53> Loading Config file game.cfg (assets\game.cfg)
<17:04:53> creating CVarGroups from directory 'assets/Config/CVarGroups' ...
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_full.cfg (assets\config\cvargroups\sys_spec_full.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_gameeffects.cfg (assets\config\cvargroups\sys_spec_gameeffects.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_light.cfg (assets\config\cvargroups\sys_spec_light.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_objectdetail.cfg (assets\config\cvargroups\sys_spec_objectdetail.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_particles.cfg (assets\config\cvargroups\sys_spec_particles.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_physics.cfg (assets\config\cvargroups\sys_spec_physics.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_postprocessing.cfg (assets\config\cvargroups\sys_spec_postprocessing.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_quality.cfg (assets\config\cvargroups\sys_spec_quality.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_shading.cfg (assets\config\cvargroups\sys_spec_shading.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_shadows.cfg (assets\config\cvargroups\sys_spec_shadows.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_sound.cfg (assets\config\cvargroups\sys_spec_sound.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_texture.cfg (assets\config\cvargroups\sys_spec_texture.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_textureresolution.cfg (assets\config\cvargroups\sys_spec_textureresolution.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_volumetriceffects.cfg (assets\config\cvargroups\sys_spec_volumetriceffects.cfg)
<17:04:53> Loading Config file assets/Config/CVarGroups/sys_spec_water.cfg (assets\config\cvargroups\sys_spec_water.cfg)
<17:04:53> creating CVarGroups from directory 'Engine/Config/CVarGroups' ...
<17:04:53> [Warning] <ThreadConfigInfo>: Active platform identifier string "pc" not found in config "config/engine_core.thread_config".
<17:04:53> [Warning] <ThreadConfigInfo>: Active platform identifier string "pc" not found in config "config/engine_sandbox.thread_config".
<17:04:53> Windows 10 64 bit (build 10.0.10586)
<17:04:53> User name: "Luca"
<17:04:53> System language: Italian
<17:04:53> Windows Directory: "C:\WINDOWS"
<17:04:53> Local time is 17:04:53 03/19/16, system running for 37 minutes
<17:04:53> 16323MB physical memory installed, 12072MB available, 134217727MB virtual memory installed, 26 percent of memory in use
<17:04:53> PageFile usage: 43MB, Working Set: 52MB, Peak PageFile usage: 43MB,
<17:04:53> Current display mode is 1600x1200x32, (Unknown graphics card)
<17:04:53> IBM enhanced (101/102-key) keyboard and 8+ button mouse installed
<17:04:53> --------------------------------------------------------------------------------
<17:04:53> [Warning] Config file %USER%/game.cfg not found!
<17:04:53> Loading Config file system.cfg (m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\system.cfg)
<17:04:53> OnSysSpecChange(4)
<17:04:53> Loading Config file VeryHighSpec.cfg (assets\config\veryhighspec.cfg)
<17:04:53> Loading Config file %ENGINEROOT%/editor.cfg (m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\editor.cfg)
<17:04:53> Loading Config file game.cfg (assets\game.cfg)
<17:04:53> Loading Config file project.cfg (project.cfg)
<17:04:53> [Warning] Config file user.cfg not found!
<17:04:53> Stream Engine Initialization
<17:04:53> GameName: CRYENGINE SDK Example
<17:04:53> BuildTime: Mar 15 2016 14:54:28
<17:04:53> [Warning] Editor only supports DX11. Switching to DX11 Renderer.
<17:04:53> Physics initialization
<17:04:54> Initializing CryPhysics...
<17:04:54> Initializing CryPhysics done, MemUsage=972Kb
<17:04:54> [Warning] Cannot open Pak file assets\localization\english_xml.pak
<17:04:54> Localized language content(english) not available or modified from the original installation.
<17:04:54> [Warning] Cannot open Pak file assets\localization\english.pak
<17:04:54> Localized language content(english) not available or modified from the original installation.
<17:04:54> [Warning] Cannot open Pak file assets\localization\english.pak
<17:04:54> Localized language content(english) not available or modified from the original installation.
<17:04:54> [Error] <Localization> No localization files found!
<17:04:54> <Audio>: AudioSystem initialization
<17:04:54> Initializing CryAudioSystem...
<17:04:54> Initializing CryAudioImplSDLMixer...
<17:04:54> <Audio> <0.231>: CryAudioImplSDLMixer loaded
<17:04:54> Initializing CryAudioImplSDLMixer done, MemUsage=5476Kb
<17:04:54> Initializing CryAudioSystem done, MemUsage=6128Kb
<17:04:54> Renderer initialization
<17:04:54> Initializing CryRenderD3D11...
<17:04:54> CRenderer sizeof(Vec2f16)=4 sizeof(Vec3f16)=8
<17:04:54> Initializing CryRenderD3D11 done, MemUsage=3804Kb
<17:04:54> Initializing Direct3D and creating game window:
<17:04:54> D3DX_SDK_VERSION = <UNDEFINED>
<17:04:54> Direct3D driver is creating...
<17:04:54> Crytek Direct3D driver version 2.00 (Mar 15 2016 <14:54:30>)
<17:04:54> Creating window called 'CRYENGINE SDK Example' (1280x720)
<17:04:54> [HMD] HMD Renderer not initialized - stereoOuput [0] hmdDevice [ null]
<17:04:54> Flushing pended shaders...
<17:04:54> Finished flushing pended shaders...
<17:04:54> System Shutdown
Closing PAK file: assets\textures.pak
Closing PAK file: m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\engine\engine.pak
Closing PAK file: m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\engine\shadercache.pak
Closing PAK file: m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\engine\shadercachestartup.pak
Closing PAK file: m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\engine\shaders.pak
Closing PAK file: m:\videogiochi\crytek engine\cryengine launcher\crytek\cryengine_5.0\engine\shadersbin.pak

```

# Answer
The ATI Radeon 4800 HD Series GPU supports up to DirectX 10. Cryengine requires DirectX 11 minimum in order to work. So the GPU can't work with Cryengine
> 1 votes

---
Tags: cryengine
---


# Question
Title: Accessing a database with a php script from Unity mobile game
So I am attempting to keep track of some user data in my game that I am creating in Unity 3d. I am using Unity's WWW class to do this. I am following this tutorial: http://wiki.unity3d.com/index.php?title=Server\_Side\_Highscores

I am not sure why but I keep getting a 404 error even though the file is on the server. I am using godaddy to host my website and I have the php script that I am trying to access in there so that it can use it to query the database. I am using "http://www.mysite/myscript.php?" followed by the values that I want to push to the database, as the tutorial shows to do.

No matter what I do I end up with a 404 and it doesn't make any sense as I know that it is there in the path I am attempting to connect to. If I type out the path to the php file in a browser it will take me to a page that gives an error about the hash not existing (since I am not passing one unless it is in my game) so I know that the file is there.

**3/18/16**

Here is my php script to add the values to the database.

```
<?php
    $server = "MyServersIP";
    $user = "MyUser";
    $pass = "MyPassword";
    $db = "MyDB";

    $conn = mysql_connect($server, $user, $pass);

    mysql_select_db($db);

    $Username = mysql_real_escape_string($_GET['Username'], $db);
    $Fuel = mysql_real_escape_string($_GET['Fuel'], $db);
    $IAPCar1 = mysql_real_escape_string($_GET['IAPCar1'], $db);
    $IAPCar2 = mysql_real_escape_string($_GET['IAPCar2'], $db);
    $Score = mysql_real_escape_string($_GET['Score'], $db);
    $Level = mysql_real_escape_string($_GET['Level'], $db);
    $Wins = mysql_real_escape_string($_GET['Wins'], $db);
    $Losses = mysql_real_escape_string($_GET['Losses'], $db);
    $Ads = mysql_real_escape_string($_GET['Ads'], $db);
    $LicensePlate = mysql_real_escape_string($_GET['LicensePlate'], $db);
    $hash = $_GET['hash'];

    $secretKey = "mySecretKey";

    $real_hash = md5($Username . $Fuel . $IAPCar1 . $IAPCar2 . $Score .     $Level . $Wins . $Losses .
    $Ads . $LicensePlate . $hash);
    if ($real_hash == $hash)
    {
        $query = "INSERT INTO Player values (NULL, '$Username', '$Fuel', '$IAPCar1', '$IAPCar2',
        '$Score', '$Level', '$Wins', '$Losses', '$Ads', '$LicensePlate');";
        $result = mysql_query($query);
    }

    mysql_close($conn);
?>

```

Here is the code I use to call the php script:

```
public string setValues = "http://www.mysite.com/Set_Values.php?";
private string secretKey = "SecretKeyFromThePhpScript";
public void SetValues(string username, int fuel, bool iapCar1, bool iapCar2, int score,
    int level, int wins, int losses, bool ads, string licensePlate, bool firstTime)
{
    string hash = Md5Sum(string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", username, fuel, iapCar1, iapCar2,
        score, level, wins, losses, ads, licensePlate, secretKey));
    string url = string.Format("{0}username={1}&fuel={2}&IAPCar1={3}&IAPCar2={4}&Score={5}&Level={6}" +
        "&Wins={7}&Losses={8}&Ads={9}&LicensePlate={10}&FirstTime={11}&hash={12}", setValues, username, fuel, iapCar1, iapCar2,
        score, level, wins, losses, ads, licensePlate, firstTime, secretKey);

    WWW www = new WWW(url);
}

```

# Answer
> 0 votes
The solution to my issue turned out to be that I had a typo in my url that I used. Also I needed to change $db to $conn where I am getting the values and assigning them to variables.

---
Tags: unity, c#, databases, php
---


# Question
Title: Finding the last GO in a set of generated objects?
I currently generate the maptiles using Tags purely, which works great but doesnt satisfy my needs. I want to delete tiles that i dont need(since my player will only be going to the right) but I have a problem with checking when to delete old tiles so that i can generate new ones. My idea would be checking how close the player is to the last tile given and then delete the first, but i cant do that with tags since tags are given in the order that unity finds the GOs with that tag and not from left to right AFAIK. What would be the best way to get the last ground tile? (the one that got generated last).

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

public class MapGenerator : MonoBehaviour

{
    private GameObject[] groundTiles;

/// <summary>
///  Represents the minimum amount of active tiles needed
/// </summary>
public int ActiveTiles;

void Start()
{
}

void Update()
{
    groundTiles = GameObject.FindGameObjectsWithTag("ground");

    if (groundTiles.Length < ActiveTiles)
        SpawnTile();
}

public void SpawnTile()
{
    GameObject tile = (GameObject)Instantiate(groundTiles[groundTiles.Length-1]);

    Vector3 tmpVec = tile.transform.position;
    tmpVec = tile.transform.position;
    tmpVec.x += 1;
    tile.transform.position = tmpVec;
}

public void DespawnTile(int tileIndex)
{
    List<GameObject> tmp = new List<GameObject>(groundTiles);
    tmp.RemoveAt(tileIndex);
    groundTiles = tmp.ToArray();
}
}

```

# Answer
> 0 votes
Two main ways come to mind: Either you make the `groundTiles` array contain a fixed number of GameObjects, which you instantiate in the Start() method and then don't destroy, but move. So instead "Spawning" or "Despawning" objects, you are actually always reusing the same ones. (This is called **pooling**, if you would like to look it up.) Alternatively you can Spawn an object, add it to the `groundTiles` array and, when destroying GameObjects to despawn them, you remove either the first or last item of the array and shift all the items in the array over by one. (Whether you are destroying the first or last item depends on your implementation).

**Pooling:**

I'll only provide the pooling code (which will probably need some tweaking), as it is the correct way of doing this. Instantiating and destroying objects is fairly resource intensive and destroying in particular can be fairly unpredictable. Copying arrays is also very resource intensive. And while the code below can be improved in many ways, it can be a starting point for you.

```
public GameObject TilePrefab; //Prefab for the tile, assign in editor
int Tiles = 10; //Number of tiles to have at any one time (pool size)
float TileWidth = 10; //Width of tile, will need tweaking depending on your tile size.

void Start()
{
    groundTiles = new GameObject[tiles];
    for(int i = 0; i < tiles; i++){
        groupTiles[i] = instanteate(TilePrefab);
    }
}

void Update()
{
    for(int i = 0; i < tiles; i++){
        float dX =  groupTiles[i].transform.position.x - Player.transform.position.X;  //Get how far away the tile is from the player along the X axis
        if(dX < -40){    //Distance from the player at which tiles despawn.
            groupTiles[i].transform.Translate(Tiles * TileWdith, 0, 0); //Move the tile forward
        }
    }
}

```

# Answer
> 0 votes
Add to `groundTiles` when you spawn a tile, instead of repopulating it every update. Then you can just use the array to find the last generated when you want to delete one.

---
Tags: unity
---


# Question
Title: The tolareable lag range in a multiplayer game
I am programming a multiplayer game. I calculate the ping in ms as :

```
ping = the_time_i_recieved_pong - the_time_i_sent_ping

```

I implemented client-side prediction and interpolation algorithms. When I test the game with my friends, it works quite fine for those who have a ping under 100ms, but after 120ms it becomes unplayable as they have told me. So my question is wheter I should try to improve the client's game experience under a latency more than 120 ms or not ( is a lag \>120ms considered tolerable ? )

Thank you all !

**NOTE :** My game is a fast-paced game so the lag compensation matters.

# Answer
Lag tolerance is very subjective - what works for one game might not work for another. That being said, if your play testers say things become unplayable, that's strong evidence that it's a problem for your specific game.

What to do about it is another matter. Before you go too deep into optimizing code, refactoring systems or working up some sort of interpolation system to approximate data that didn't arrive on time, it might help to get a better idea of what's really going on. I recall a story\* in which the Halo: Reach devs added a 'I just saw lag' button to the development build to help pin down what was leading to the player's perception of lag. They used this in conjunction with system log files to focus on fixing things that were most damaging to the player experience.

\*As noted on pg 318 of "Designing Games A Guide to Engineering Experiences" by Tynan Sylvester.
> 0 votes

# Answer
Explain multiplayer game.

In fps games, 100 milliseconds can change the outcome of your shots.

In civizilation-type games, you can have up to 1000 milliseconds without even noticing it, and up to 2000, without being seriously frustrated.

In games, where everyone does his thing, like in simcity 5 (let's assume simcity 5 is one of them, and it doesn't kicks you the moment your net goes out). A player can be offline for a long amount of time, and only send the information after he goes online again.
> 1 votes

---
Tags: multiplayer, interpolation, lag, movement-prediction, latency
---


# Question
Title: Does marking a GameObject as static actually improve performance?
I'm currently working on a small game that will include somewhat large levels. Each level will have a somewhat large amount of `GameObject`s lying around as props. I was told by a friend of mine that marking the `GameObject`s that the map is comprised of as static will improve performance. However, I am aware that this can greatly increase the amount of space the built game takes up on the disk. Does the performance boost gained from marking `GameObject`s as static outweigh the cost of increased build size? Is there even a performance increase at all?

# Answer
Definitely maybe; this depends on things like the overall number and complexity of the objects involved.

**Not static:**

Draw a 100-vertex model with 1,000 different (constantly-changing) transforms.

* Approximately 17,200 bytes (1,200 bytes uploaded once)
* New transforms uploaded every frame (approximately 16,000 bytes)
* More objects creates more overhead (during render), linearly
* Additional math every frame (transforming normals for lighting, etc.)

**Static:**

Since this object won't move ever, copy and transform the 100 vertices, 1000 times, into a single vertex buffer. Then, draw the new 100,000-vertex model with one transform. Multiple draw calls may be required to process the entire model but will require few state changes in-between. Since it's already in world-space, the GPU can skip a transform; the normals are already in world-space, for lighting, as well.

* Approximately 1,200,000 bytes (uploaded once)
* Performance penalty, once, during baking
* More objects creates "no" additional overhead (during render)

**Vertex:**

The "vertex" I used is a single `float3` each; if we also include UV's (`float2`) and normals (`float3`), the size of each vertex becomes 32 bytes:

The non-static method's memory footprint increases from 17.2KB to 19.2KB (1.1X).

The static method's memory footprint increases from 1.2MB to 3.2MB (2.6X).

The memory size of an additional, non-static, object is 64 bytes for a float4x4 matrix. The actual size Unity uses may be different, but the important point is that it is approximately fixed.

The memory size of an additional, static, object is (VertexCount x VertexSize). This method is not feasible for excessively complex and/or numerous objects.
> 3 votes

---
Tags: unity, performance
---