# Question
Title: Unity3D Making timescale freeze and resume
So, I'm trying to make it where when a popup(Ui panel and text) appears, the game's time(timescale) would freeze. Then when the user enters input and clicks enter button, the popup would disappear and time would resume.

How could I make time follow this?

# Answer
> 2 votes
To Freeze Time (Game Time)

```
Time.timeScale = 0;

```

To restore Time (Game Time)

```
Time.timeScale = 1;

```

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


# Question
Title: How to make an enemy projectile head to the player's position with constant speed
How can I dynamically set the movement speed of the X and Y of the projectile so that it moves at a constant speed when the projectile heads at the player's position? I know this has something to do with vectors but I don't really have an idea how to do it. My current implementation of the speed is getting the difference of the x and y positions so what happens is that the projectile will be slower the nearer the player is to the enemy. I set the projectile's speed using the code below:

`projectile.moveSpeedX = Math.abs(position.x - targetPlayer.position.x);
projectile.moveSpeedY = Math.abs(position.y - targetPlayer.position.y);`

Below is the contents of the update(float delta) method of the projectile:

```
if(xdirection == LEFT) {
    position.x -= moveSpeedX * delta;
}
else if(xdirection == RIGHT) {
    position.x += moveSpeedX * delta;
}

if(ydirection == UP){
    position.y -= moveSpeedY * delta;
}
else if(ydirection == DOWN) {
    position.y += moveSpeedY * delta;
}

```

The movement will slow down when the player is near the enemy since the distance between them is small. The speed is the problem although this already makes the projectile head to the player's position.

# Answer
> 3 votes
IF I understood your question correctly (it's a bit un-detailed and I recommend editing it with more information and the piece of the code that you tried but is not working), you can solve the problem with many solutions.

A very simple one, in C#, is the following (consider that p0 is the starting point of your projectile and p1 is the end point, both in 3D space, i.e. of type vector3):

```
float speed = 200; //adjust the speed as you wish

float distance = Vector3.Distance(p0, p1);
Vector3 direction = Vector3.Normalize(p1- p0);

moving = true;

if(moving == true)
{
    projectile.transform.position += direction * speed * Time.deltaTime; //Time.DeltaTime may need to be replaced by whatever your platform gives you as a measure of the elapsed time since the last frame. This is important for making the velocity independent of frame-rate differences from one computer to another
    if(Vector3.Distance(p0, projectile.transform.position) >= distance) //this makes the projectile stop at the supposed end location. Of course, you could alter this for it to also stop in case it has collided with whatever stops your projectiles (like objects reprenting walls).
    {
        projectile.transform.position = end;
        moving = false;
    }
}

```

Conceptually, note that to move the projectile in the above code, at each iteration we take the present position of the projectile and sum to it a value that is given by direction * speed * Time.deltaTime. Direction is a vector you get by subtracting the start position of the projectile from the final position you expect the projectile to be. Speed is a constant you define. Time.deltaTime is the elapsed time since last frame. This is important to make sure that variation in frame rate from one computer to the other will not make the projectile looks faster/slower in each computer.

---

Or depending on the Engine you are using, for instance if it's Unity, you can do something like the following either inside a function that you call or in the Update loop:

```
    float step = speed * Time.deltaTime;
    projectile.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

```

---
Tags: movement, vector, projectile-physics, direction
---


title: Giving values to uniform in OpenGL

text:
# Question
Title: Giving values to uniform in OpenGL
First thing is that I know how to give values to uniforms in OpenGL. Second thing is that it is a question related to **optimization and performance**.

The habit for changing the uniforms, we preferred is like this:

```
//Consider that we have shaders having 'aValue' as uniform

//During initialization
GLint loc = glGetUniformLocation(program, "aValue");

//During a loop or when required to change uniform's value
if (loc != -1)
{
   glUniform1f(loc, 0.75);
}

```

But what if it is like this:

```
//'program' is a global variable

//Can be anywhere but not after destructing 'program'
void updateUniformf( const char* name, float value )
{
    glUniform1f(glGetUniformLocation(program, name), value);
}

//During a loop or when required to change uniform's value
updateUniformf("aValue", 0.75);

```

How much would such approach decreases the performance? Or would this approach even affects the performance? It will be appreciable to have some measurements or practical example rather than all theories. Of course, I need to know reasons as well.

Thanks for answering this question!

# Answer
Rules of thumb:

* Keep communications with the GPU at a minimum
* String comparisons are not known to be especially fast

Here are my test results:

* At 10000 uniforms per frame set using a pre-located uniform ID (as many characters as you need), we get 554 FPS on average.
* At 10000 uniforms per frame, with the uniform ID being looked up each time (7 characters), we get 227 FPS.
* At 10000 uniforms per frame, with the uniform ID being looked up each time (119 characters), we get only 99 FPS.

Bear in mind that the hardware components can affect these results significantly but the trend itself shouldn't change much.

tldr;

Always look up uniform locations once, at the beginning and then use those integral IDs to set the values. Do not look them up each time! String comparisons are not cheap.
> 5 votes

---
Tags: opengl, performance, optimization
---


title: Are metal slug art assets free use?

text:
# Question
Title: Are metal slug art assets free use?
I'm making a mobile game and I've gotten by with completely free art assets so far, but I have an explosion from metal slug. I love it and it's perfect, but I don't want to get sued. I've seen metal slug art assets posted around the internet on various clip art websites, but haven't found any statements outright saying they're free to use in one's own commercial application.

Could someone show me a link saying whether or not metal slug assets are free to use?

# Answer
The internet is full of copyright violations. Just because you see people posting 3rd party art assets doesn't mean that they are allowed to.

You might wonder "but they didn't get sued, why should I"?

Maybe SNK hasn't found out about the copyright violation yet. Maybe they can not locate the violator. Maybe it's not worth their time because the violators don't have any money. Maybe the paperwork is already on the way. But whatever the reason why that website is still online, you have no guarantee that these reasons also apply to you. SNK can decide who to sue and who to let go for violating their copyright.

The only way to be sure that an asset is safe to use is when you made it yourself. Even so-called "free" assets you find on websites can be dangerous because it happens all the time that people upload ripped assets to such websites (some people are even so audacious that they add an own copyright notice). When you hire artists to create assets for you, you should insist on a guarantee in the contract that their work does not violate 3rd party copyrights and that they take liability for that. I experienced it before that an "artist" tried to sneak ripped sprites into a project I took part in.
> 4 votes

---
Tags: sprites, legal, art, copyright
---


title: Raypicking / raytracing in OpenGL

text:
# Question
Title: Raypicking / raytracing in OpenGL
Alright, so before you down vote saying that OpenGL doesn't support rays for rendering, please read:

So I want to detect a quad in opengl 1.1( I don't want to use opengl 3.0). I wanted to detect it using OpenGL, but that doesn't seem possible.

But basically I have one choice, which is kind of "hacky". I create custom matrices and store the transformed vertices somewhere, then do a simple collision test.

What is the common way of doing ray-tracing in legacy OpenGL?

# Answer
> 1 votes
> I create custom matrices and store the transformed vertices somewhere, then do a simple collision test.

Thats one way, very expensive though, since you have to transform *all* the vertices of all the objects in question. Doing it the other way around is much cheaper. Transform the ray with the inverse object's matrix into the local object space and make the ray test in that space. Usually transforming the ray is way easier than transforming all your vertices.

Its even cheaper, if you use Bounding Objects (Aabb Axis-Aligned-Bounding-Boxes, Obb - Oriented Bounding Boxes, Bounding Sphere etc) for a first Hit Test. If that succeeds, do the actual Object Hit Test.

# Answer
> 0 votes
Picking in OpenGL can be done, by rendering the primitives you want to check for, assigning each one a unique color, based upon which you can look it up.

Then you can check what color is rendered for example on the center of the screen, this way getting the object pointed at.

This was done in older games, but is frowned upon, because it can be a huge performance hog.

---

Picking in an OpenGL based app, is usually done using external libraries to do the ray-casting. Usually a game has a Physics engine, which must be able to do a ray-cast, so most of the time the actual physics engine is used to do ray-casting.

One of such libraries is bullet.

Now if I understand you correctly, what you propose is simply the method used by a physics engine, it uses matrices to translate the object into world-space, then doing a ray-cast in world-space.

---
Tags: opengl, raycasting, raytracing
---


# Question
Title: Doesn't Unity5 support Expression Bodied Properties?
I wrote the following line in Unity5 using C#:

```
private static float Width => 0.015f;

```

Unity complained about the following issue:

```
Unexpected symbol `=>' in class, struct, or interface member declaration

```

Doesn't Unity5 support Expression Bodied Properties(a new feature in C# 6.0)?

I am really lost here...

# Answer
No, Unity doesn't support expression bodied members.

You'll find for most things, Unity is not at the cutting edge of C# / .NET features. That's because the version of Mono it uses under the hood to provide the Common Language Runtime across multiple platforms only handles up to about .NET 2.0-3.5 (circa 2005-2007):

This restriction also applies to using IL2CPP for iOS and WebGL builds, since it's still going through the same process to generate the intermediate language.

So, don't expect to use any .NET features introduced in the past decade, at least not yet. The Unity developers have announced that they intend to upgrade to more recent versions of Mono to allow the use of newer .NET features as Unity continues to evolve.

Fortunately, expression bodied properties are just syntactic sugar, and you can get the same compiled result today with only slightly more verbose source:

```
private static float Width { get { return 0.015f; } }

```

**Edit:** User Jaakko Lipsanen posted an answer to a related question which linked to a project to make many C# 6.0 features available for Unity through Visual Studio. It still compiles to ~.NET 3.5 IL under the hood, but supports C# 6.0 source code. I haven't worked with it myself yet, so I can't attest to how well it works, but if you prefer working in 6.0 it may be worth a look.
> 1 votes

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


# Question
Title: Fixing text on the screen for Oculus Rift
I would like to fix text to the screen for an Oculus Rift in Unity. The text should say something like "get comfortable and then press any key". It seems like OVRGUI.StereoBox should work for this and I've tried to copy an example I found on Github, like so:

```
public class TargetScript : MonoBehaviour {
    void OnGUI() {
            Debug.Log("Drawing Recenter dialog.");
            string loading = "LOADING...";
            OVRGUI guiHelper = new OVRGUI();
            guiHelper.StereoBox(300, 300, 300, 300, ref loading, Color.white);
            Debug.Log("Stereo Box should be visible.");
            Debug.Log (guiHelper);
    }
}

```

The log messages indicate that this code block is definitely being hit, but no text is visible on screen.

What am I doing wrong?

# Answer
When I had to do this in the past, I just parented the UI canvas for the text to the Camera. This should work for the first-party support for the Oculus available in Unity 5 now.

Alternatively, if you're using a plugin like the OVR plugin or similar, you should still be able to track down a suitable parent for the text's canvas.

e.g. The CenterEyeAnchor for the OVRCameraRig
(see https://developer.oculus.com/doc/0.4.4-unity/class\_o\_v\_r\_camera\_rig.html)
> 1 votes

---
Tags: unity
---


# Question
Title: Is reinforcement learning overkill for a vehicle steering bot?
I'm slightly familiar with the reinforcement learning (through this edx.org MOOC). Also I'm aware of reactive planning technique. I want to write a vehicle bot for a racing game, where cars have to complete laps and avoid collisions.

Is it sensible to use reinforcement learning for steering? Or should I stick with reactive planning?

# Answer
> 1 votes
In Artificial Intelligence for Games 2E the authors discuss racing games regularly and say that approaches built on steering behavior primitives (i.e. reactive planning) can be very well-suited to the domain. (I'm in the middle of reading it now, so I can't say whether they make the same claims for reinforcement learning.)

It of course depends on your exact needs, but I believe reinforcement learning is likely to be considerably more engineering effort than you need. You'll also have fewer resources available online for this particular application of reinforcement learning.

Of course, if you simply want to cut your teeth on reinforcement learning, it's certainly a possible pathway.

If you decide to stick with steering behaviors, you may find the source code accompanying the above-mentioned book a useful reference (and of course, the book itself). The steering-behavior-specific demos are the c03\_\* folders under https://github.com/idmillington/aicore/tree/master/src/demos. I haven't looked over the source code yet, so I can't say how accessible it would be without the book at hand.

---
Tags: ai, steering-behaviors, racing, bot, reinforcement-learning
---


title: Java map creation

text:
# Question
Title: Java map creation
So Im making a topdown 2d rpg in slick2d and lwjgl 2, and I wanna make a map, but not just random map, something like this:

The blue stuff is water and rivers, the gray in the middle is "the mountains" and such. How could I create such a map design, but a random one through code. If anyone has an idea of how this is done, please tell me, or even link a tutorial if you know a good one. Thanks.

# Answer
> 1 votes
The map in your screenshot is from Realm of the Mad God. It was generated from the url that Chris Mills-Price linked to. There's a flash demo on that page, a complete description of the algorithms used, actionscript source code, and links to Java code.

---
Tags: java, maps, slick
---


# Question
Title: Why is my gravity script repelling and not attracting?
I'm currently working on a small simulation of Newton's Law of Gravitation in Unity3d, and it seems to be working pretty well, except, it's doing the opposite of what I expected. Instead of attracting as it should, this script is repelling objects instead:

```
using UnityEngine;

/// <summary>
/// Gravity component.
/// </summary>
public class GravityComponent : MonoBehaviour
{
    public float gravityConstant;
    public Vector3 startingForce;
    public GameObject twinObject;

    /// <summary>
    /// Applies attraction to the object.
    /// </summary>
    public void ApplyAttraction()
    {
        Vector3 currentForce = this.transform.position - this.twinObject.transform.position;
        float attraction =
              ((this.gravityConstant * this.rigidbody.mass * this.twinObject.rigidbody.mass)
            / (Mathf.Pow(currentForce.magnitude, 2)));
        this.rigidbody.AddForce(currentForce * attraction);
    }

    public void Start()
    { this.rigidbody.AddForce(this.startingForce); }

    public void FixedUpdate()
    { this.ApplyAttraction(); }
}

```

While it is possible to "fix" this by making the result of the attraction calculation negative as seen below, this solution feels "dirty", as it's not truly following Newton's Law of Gravitation.

```
float attraction =
      -((this.gravityConstant * this.rigidbody.mass * this.twinObject.rigidbody.mass)
    / (Mathf.Pow(currentForce.magnitude, 2)));

```

What's the issue here? Is there a way to solve this issue without the above "dirty" fix?

# Answer
Firstly, while your variable may be named `currentForce`, it actually only contains the vector pointing from `this` to `this.twinObject`. Furthermore, with your addition, the subtraction actually points **toward** the first object. Think of vector a in this image to be your `this.transform.position` and vector b as your `this.twinObject.transform.position`.

So, since the vector is pointing **from** b **to** a, the vector is pointing in the opposite direction of the direction you actually want a to go in. You want to be going **toward** b.

To fix this just subtract b - a instead of a - b:

```
Vector3 currentForce = this.twinObject.transform.position - this.transform.position;

```
> 1 votes

# Answer
This line:

```
Vector3 currentForce = this.transform.position - this.twinObject.transform.position;

```

This gets you a vector pointing from `twinObject` toward yourself. By applying a force in that direction, you end up pushing yourself *away* from `twinObject`.

Think of it using one-dimensional numbers:

```
int difference = 5 - 2;
//difference is now 3
//difference points from 2 toward 5

```

Your solution multiplies `currentForce` by negative one, which flips the direction back to match your desired result. It's a minor kludge, but it works in a pinch. When I find myself doing that, I usually figure I've flipped the direction of a vector accidentally.

You can also fix this by flipping the operands for the subtraction:

```
Vector3 currentForce = this.twinObject.transform.position - this.transform.position;

```
> 1 votes

---
Tags: unity, physics, simulations
---


# Question
Title: DirectxMesh obj to cmo texture coordinates off
I'm having trouble getting the texture coordinates of the cmo to match how the mesh was unwrapped in blender. I am using the directxmesh to convert the obj to a cmo and the directxtk to load the cmo.

Relevant parts of code are as follows:

```
std::unique_ptr<DirectX::CommonStates> m_states;
std::unique_ptr<DirectX::IEffectFactory> m_fxFactory;
std::unique_ptr<DirectX::Model> m_model;

...

m_states.reset(new CommonStates(d3d11DeviceInterface.Get()));

m_fxFactory.reset(new EffectFactory(d3d11DeviceInterface.Get()));

m_model = Model::CreateFromCMO(d3d11DeviceInterface.Get(), L"unit.cmo", *m_fxFactory);

...

m_model->Draw(d3d11DeviceContextInterface.Get(), *m_states, local, view, proj);

```

The model and uv map in blender look like this:

Using the following directxmesh command: meshconvert unit.obj -cmo -y -nodds

the model looks like this in the program:

I thought this would be a simple matter of flipping the texture coordinates by adding the -fliptc switch to directxmesh meshconvert unit.obj -cmo -y -nodds -fliptc

But this changes the winding order resulting in backface culling on the wrong sides. Subsequently, I tried changing the culling face to clockwise with the -cw switch meshconvert unit.obj -cmo -y -nodds -fliptc -cw

Now the backface culling was happening on the correct faces but the texture coordinates were still wrong.

I'm rather lost as to what I have done wrong.

Edit: I seem to have figured out what is going on. The image seems to be flipped around the V axis. If I manually flip the image the coordinates match up to what is shown in blender. It's a shame I can't seem to find an option in blender to flip the UV coords along the V axis.

# Answer
> 2 votes
I looked and I totally boned up the implementation of `-fliptc`. It was flipping in U instead of in V, and you could only do it if you were also reversing the face winding.

I've updated the master branch of GitHub with some fixes. `-fliptc` has been removed. Instead I added `flipv` which inverts just the v texcoord without reversing the winding, and `-flipz` which negates the z for LH vs. RH. `-flip` still exists to reverse the winding independent of these other options.

Generally the issue is that with OpenGL-based editors, the upper-left of the textures is right side up but when you render that in Direct3D it is upside down because the Y origin is inverted in OpenGL vs. Direct3D. The fix is supposed to be a simple flip of the v texcoord which is what `-flipv` now does.

Depending on the winding order of your source and if you are going to render doing blackface culling of counter-clockwise triangles or clockwise triangles, you might need to reverse the winding of the triangles. That is what `-flip` does. I had originally made them dependent operations, but they are really independent. The `-ccw` switch in **meshconvert** just informs the normal computation which winding to use for the front (and this happens before any `-flip` if it is applied).

Finally, depending on if you are going to render with a RH vs. LH view coordinate system, you might need to invert the Z positions (and normals if present). The new `-flipz` switch does that.

---
Tags: directx11, 3d-meshes, obj
---


title: Animator has not been initialized

text:
# Question
Title: Animator has not been initialized
My animation is working but unity keep saying that my Animator has not been initialized error Here my Code:

```
using UnityEngine;
using System.Collections;

public class Player: MonoBehaviour {

public float maxspeed = 10f;
bool facingRight = true;

Animator anim;

bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;

void Start ()
{
    anim = GetComponent<Animator> ();
}

void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    float move = Input.GetAxis ("Horizontal");
    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
    if (move > 0 && !facingRight){
        Flip ();
    } else if (move < 0 && facingRight) {
        Flip ();
    }
}

void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

```

}

# Answer
> 1 votes
This has been discussed a few times in Unity's forums. This thread has a long discussion about the issue, and this and this Unity answers posts.

If you don't solve it and everything seems to work fine, I suggest submitting a bug to Unity. Remember this is a warning, so it is possible that even though you see it everything will work well. Usually it happens if you are accessing an animator that is disabled or immediately after enabling it. This doesn't seem the case from your code though. Another thing to try is to close Unity and reopen it, sometimes this goes away.

# Answer
> 0 votes
We had the same problem but finally we solved it. The problem was the gameobject which holds the Animator component must be active on the scene before you set the variables.

---
Tags: c#, unity, scripting, unityscript
---


# Question
Title: Game Design - Challenging a player in an RPG-like game without removing easy cards
I'm designing a card game that I'm implementing on the computer that mirrors some gameplay aspects of dungeon crawlers and RPGs. The player's object is to survive as long as possible from the onslaught of monsters, etc. in the dungeon, while getting stronger and more powerful. The way the dungeon is generated is by drawing one card from the "dungeon" stack per turn, this card represents a monster, animal, item, etc. found in the dungeon. As the player progresses through the game, he gains better abilities to fight the monsters and animals with. The issue becomes that the player then becomes too powerful to have any challenge (e.g. after progresses through the game for a while, the rats in the dungeon won't be a challenge). My question is, how can the player be challenged, assuming that any cards in the "dungeon" stack cannot be removed, and that the player must become stronger (e.g. not progressing is not an option)?

One solution I thought of would be a leveling system, where the player's progress is measured through levels, and upon attaining another level, certain, more challenging cards are mixed into the "dungeon" stack. This however would involve different card backs (theoretically not an issue in the digital implementation) which would give away the difficulty of the card the player is about to draw.

# Answer
> 1 votes
The core of the problem is that the monster cards are an additive difficulty `O(n)` or even less (`O(1)`?), while it seems the player's abilities increase faster, something like `O(n^2)`, `O(e^n)`, or `O(n^log(n))`.

The key is to figure out the curve you want both the player progression and the monsters to be at, and make them fit that curve. Don't just focus on the monsters - some overpowered or underpowered player abilities can also remove the player from the desired curve.

Various ways to increase monster difficulty:

* Increase stats of monsters based on strength of player
* Give different monsters ability to work together and complement each other
* Increase number of monsters per encounter based on player strength
* Add stronger monsters into packs of otherwise weak monsters if player is strong enough: `1 rat -> 2 rats -> 3 rats -> 6 rats -> 1 wererat -> 1 wererat + 3 rats -> ...`

# Answer
> 1 votes
You could have a variable modify the difficulty of all challenges, and that modifier goes up based on how many cards have been 'drawn'.

EX: Keep track of cards drawn and put your challenges in "pools". Thus any monster, X, will show up from card draws Y -\> Z.

This way keeps you from having to have a classic 'level' system, though one could argue the character's "level" would be the number of cards drawn by that point.

\[EDIT\]: To further explain - I'm not suggesting adding/removing challenges from the deck, but instead generalizing them and then having them be decided whenever the card is drawn. You would draw a "Monster" or "Monster type A", not a "Goblin" or "Dragon".

# Answer
> 1 votes
A possibility is that some of the dungeon cards include a global modifier to all traps and monsters. So you might draw that rat later on, but the dungeon has effectively leveled up that rat and given him better ways to hurt the player in the same sense that tabletop games offer templates to increase the strength of a monster.

---
Tags: game-design, game-mechanics, rpg, card-game
---


title: Collision box to slow

text:
# Question
Title: Collision box to slow
I've made the collision box for my player (and other blocks) and I'm now testing gravity and collision on the player. What I saw was that my collisionbox is updating slower than my player is moving.

It's not visual if he's just moving, but you can clearly see it when he's falling at a certain speed. (and it causes problems with the collision because the box updates slower)

This is for updating my collision box (and player):

```
public override void Update(GameTime gameTime, Rectangle clientBounds)
{
    // collision box for player
    if (left)
    {
        collisionRect = new Rectangle((int)position.X + 10, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
    else
    {
        collisionRect = new Rectangle((int)position.X + 8, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
    // for player
    position += direction
}

```

This is for updating my player:

```
public override Vector2 direction
{
    get
    {
        Vector2 inputDirection = Vector2.Zero;
        keyboard = Keyboard.GetState();

        if ((keyboard.IsKeyDown(Keys.Left)) || (keyboard.IsKeyDown(Keys.A)))
        {
            moving = true;
            walking = true;
            inputDirection.X -= 1;
            running = false;
            left = true;

            if (keyboard.IsKeyDown(Keys.LeftShift))
            {
                speed = speedMultiplier;
                inputDirection.X -= 1;
                running = true;
            }
        }

        if ((keyboard.IsKeyDown(Keys.Right)) || (keyboard.IsKeyDown(Keys.D)))
        {
            moving = true;
            walking = true;
            inputDirection.X += 1;
            running = false;
            left = false;

            if (keyboard.IsKeyDown(Keys.LeftShift))
            {
                speed = speedMultiplier;
                inputDirection.X += 1;
                running = true;
            }
        }

        if (!(keyboard.IsKeyDown(Keys.Right)) && !(keyboard.IsKeyDown(Keys.D)) && !(keyboard.IsKeyDown(Keys.Left)) && !(keyboard.IsKeyDown(Keys.A)))
        {
            moving = false;
            walking = false;
        }

        if (stopping)
        {
            inputDirection.X = 0;
        }

        if (falling)
        {
            inputDirection.Y += 1f;

        } else
        {
            inputDirection.Y = 0;
        }

        return inputDirection * speed;

    }
}

```

Or do I also need to use a get; for my collisionbox instead of updating it in `Update()`?

# Answer
> 1 votes
In your `Update()` method, you should be setting up the collision box after you add the vector `direction` to the player's `position`. Otherwise the collision box will always be at the player's position at the last update, not the current one. When the player has a high velocity (such as when falling), this will make it appear that the box is lagging behind.

```
public override void Update(GameTime gameTime, Rectangle clientBounds)
{
    // for player
    position += direction

    // collision box for player
    if (left)
    {
        collisionRect = new Rectangle((int)position.X + 10, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
    else
    {
        collisionRect = new Rectangle((int)position.X + 8, (int)position.Y + 14, frameSize.X + 2, frameSize.Y + 20);
    }
}

```

---
Tags: c#, monogame
---


# Question
Title: Simple way to detect collision between two bitmaps on android surface view
I'm looking for a standard way to detect collision between two bitmaps inside a surface view. I tried the intersect method with two rectangles, but it doesn't log.

```
practiseA = new Rect(500, 500, 500, 500);
practiseB = new Rect(500, 500, 500, 500);

public void isIntersecting() {
    Log.d("yeah", "hello");
    if (practiseA.intersect(practiseB)) {
        Log.d("collision", "yes");
    }
}

```

So can someone tell me what I'm doing wrong or give me a different method?

I saw this complicated algorithm but didn't understand what to feed it:

```
sqrt( ( ax - bx ) ^ 2 + ( ay - by) ^ 2) <= aR + bR

```

What's `aR` and `bR`?

# Answer
> 1 votes
Look at the classes in Rect, specifically .intersects(Rect a, Rect b) is boolean and saves having to do all the math yourself.

# Answer
> 1 votes
> I saw this complicated algorithm but didn't understand what to feed it:
>
> ```
> sqrt( ( ax - bx ) ^ 2 + ( ay - by) ^ 2) <= aR + bR
>
> ```
>
> What's aR and bR?

`sqrt( ( ax - bx ) ^ 2 + ( ay - by) ^ 2)` computes the distance between `a` and `b`, assuming they're objects with a 2d position.

`aR` and `bR` are probably the radii of `a` and `b`, so we can assume that `aR + bR` are the sum of these radii.

Thus we can assume that `sqrt( ( ax - bx ) ^ 2 + ( ay - by) ^ 2) <= aR + bR` checks if the two bodies `a` and `b` (which are probably circles because of the concept of radius) overlap (because the distance separating them is shorter than the sum their radii).

A more efficient option would probably be

```
( ( ax - bx ) ^ 2 + ( ay - by) ^ 2) <= ( ( aR + bR ) ^ 2 )

```

Because `sqrt` is generally more costly than squaring a value.

---
Tags: android, collision-detection
---


title: Stored Textures in C++ Projects

text:
# Question
Title: Stored Textures in C++ Projects
I have executed the following command in order to store a texture (PNG) file in a C++ header file: `xxd -i Texture.png Texture.h`.

How would I go about loading this texture into OpenGL?

```
glEnable(GL_TEXTURE_2D);
GLuint textureId;
glGenTextures(1, &textureId);
glBindTexture(GL_TEXTURE_2D, textureId);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

```

I realise that the function `glTexImage2D` should be used but am very unsure about which parameters to choose.

The specification describes the parameters as shown below.

```
void glTexImage2D(GLenum target, // GL_TEXTURE_2D
    GLint level, // 0
    GLint internalFormat, // GL_RGBA
    GLsizei width, // 2048
    GLsizei height, // 2048
    GLint border, // 0
    GLenum format, // What's this?
    GLenum type, // What's this?
    const GLvoid * data);

```

What are the `format` and `type` parameters for and what should they be set to in this case?

# Answer
> 4 votes
Normally you would load your images on-the-fly from a normal file then pass the decompressed pixels to OpenGL, but I'm also fond of embedding resources into the executable `:)`. For an extreme example, see my PS2 game. The whole thing consists of a single 4 Megabytes executable, all assets built-in.

What I did, and you can also take the same approach if you want, is:

* Dump the binary contents of an image file (PNG, JPEG, etc) into a C-style array that you can compile with the rest of the application. You can write a simple tool to do that quite easily if you want. I use `bin2c`, which is pretty good and free.
* You still need to decompress your image data to raw RGB\[A\] pixels for OpenGL. A good public domain, single-file library that you can use is STB Image.
* Then just pass the address of the data array that was embedded with the help of `bin2c` to STB Image and the library will decompress the data and return a new pointer to the pixels that you can pass to OpenGL.

This is a viable setup for limited amounts of data, but very impractical for larger projects. Each time you change an image you have to do the whole cycle of `bin2c` -\> recompile. It's fun as an experiment, but I can tell from own experience that near half way through the project I mentioned above I was regretting my choice of embedding everything, but in that specific case I had to do it due to external factors.

---
Tags: c++, assets, storage
---


# Question
Title: Store and retrieve different objects on a tile
(I hope the title is clear enough, if not feel free to suggest a better one)

I'm trying to make a simple tile-based map for a college project in Java. But I'm stuck on how to literally place things on my map. On the programming side of things, I still haven't got into graphics on this. As of now I have:

A "Robot" class, which implements an "Attackable" and "Spawnable" interface, the robot can attack and moved

A "Obstacle" class, the obstacle too can be attacked, so it implements Attackable, Spawnable, but it also can be pushed by a robot (methods by the class itself).

A "Station", which is nor attacable nor can be pushed, so it only implements Spawnable and other specific methods.

A "GameWorld" class which hold the map (a 2D array of Tiles) and various methods. A "Tile" class (which is arrayed to create the map). It has a boolean "Occupied" (which doubles as a collision too). Previously it stored just a single Attackable variable, because both Obstacles and Robot can be attacked, so I just tought it would be easy to just store them as such on the map for when I need to attack something, and then use some other reference to Robot instances when I need to move the robots and have a reference to the station in GameWorld in order to use that. But then I remembered that the Obstacles need to be moved too, so it wouldn't really work.

Now I'm thinking about having two maps, basically, an AttackableMap\[\]\[\] for the attackable object (which would store both robots and the obstacles) and a ObstaclesMap\[\]\[\] for the obstacles alone (with tiles occupied by robots set as occupied). Which would obviously mean having two tile classes, one to hold each kind of object.

But it feels cheap, I think. It uses a lot of memory and I think it might be hard to render at a later time. But having only one map would mean having to check what kind of object I'm getting and I'd have to do loads of casts and I want to avoid that.

So, I think, there must be a better way to do this. How do other people do it then? So basically my question is... How can I store different "things" on a tilemap in a better way? Is there some technique widely used?

What I've come up with feels rigid, if I wanted to add another kind of object that can be placed on the map (like a mine) I would need to create another map entirely, another tile, write new methods... There must be some flexible (and not too complex) way to have some freedom in this aspect.

# Answer
Right now you have an array of `Tile`s that has an `Occupied` boolean value, and previously had an `Attackable` value. You are suggesting that you have multiple arrays of tiles, one to store the `Attackable` things and another to store the `Obstacles`. I do not think that this is the best approach for you to take.

You need to make the decision about whether a `Tile` can ever have more than one object in it. For example, what if a `Robot` had the ability to move through walls? Or if there was a power-up that the player could pick up that gave them that ability? So let's assume that it is theoretically possible for more than one object to be on a `Tile`.

In this case, you could give the `Tile` an array of objects, and when a `Robot` or `Obstacle` moves to that tile, it could be added to that array, and removed from the array of the previous tile. In order for this to work, all of the movable things would need to inherit from the same class, such as a `Moveable` or `Character` class, and the array of the `Tile` would be an array of this type. That way, any subclasses of that type will be able to enter the `Tile` array.

When you want to check whether a tile is attackable or occupied, you could have a method of the `Tile` class that searches through the array, looking for a `Robot` or an `Obstacle` or whatever you need.

There are lots of different ways to solve this problem, but since you are concerned about the inflexibility of your current approach, I think this is a valid way to program it.
> 0 votes

---
Tags: software-engineering, tilemap, tiles
---


title: Calculating delta time

text:
# Question
Title: Calculating delta time
I'm trying to calculate deltaTime, but it's not correct.

What's wrong in my code?

```
//declared outside
private long timeSinceStart = System.nanoTime() / 1000;
private long oldTimeSinceStart = 0;
public static long deltaTime = 1;

while(running)
  timeSinceStart = System.nanoTime() / 1000;
  deltaTime = timeSinceStart - oldTimeSinceStart;
  oldTimeSinceStart = timeSinceStart;

```

# Answer
`System.nanoTime()` returns the time in nanoseconds.

In order to get it in milliseconds, do `System.nanoTime() / 1000000`.

Here is an example how to calculate delta time properly.

```
long last_time = System.nanoTime();

while(running) {
    long time = System.nanoTime();
    int delta_time = (int) ((time - last_time) / 1000000);
    last_time = time;
}

```
> 5 votes

---
Tags: java, android
---


# Question
Title: Game speed on different devices isn't same
I have an app, in which I have constant int speed = 5; On each update, the game object (player) is moving 5px ahead. Problem is, that I can't handle that on different devices - older devices is having fx. 20fps (so 20 updates per second), and other one have 60fps. Then, my object is moving faster or slower, than it should.

I tried some screen width divisions, but didn't managed to work it.

I also tried to stick to some FPS (25) and skip frames if necessary. But on my tablet and phone, it just run on its own; it works like there isn't any frame skip code at all.

# Answer
> 1 votes
Firstly you should find delta time and then multiply your movement velocity on that.

```
position.x = velocity * deltaTime;

```

---
Tags: java, android
---


# Question
Title: How can I move the camera directly under a certain plane?
I am attempting to render a "reflection" of a scene for water:

To create this illusion, I need to render the scene from below, and then ignore all geometry below the water line.

As such, I need to move the camera below the water, and invert the pitch.

I have one problem: My entire framework is based on the fixed-function pipeline. Basically, I need to call the correct glTranslatef() calls and glRotatef() calls to be able to simulate the camera being in the new position, and then render the scene.

Unfortunately, I have so far failed to achieve this. Calling the glRotatef() function obviously just rotates the entire scene, so I am struggling to just simulate the camera rotation.

The water is at a height of 300. I believe I may be moving the camera down correctly by calling `glTranslatef(0, -(2 * (camera.y() - 300)))`, but it has been impossible for me to get them to both work.

# Answer
I am not sure if this will be helpful for you but there is a really simple way how to achieve a reflection in water.

Using fixed pipeline all you need is to make water transparent (using `GL_BLEND`) and then render the scene upside down (using `glScale(1,-1,1)`). To prevent rendering objects above the water you can use `glClipPlane`.

For example:

```
glScalef(1,-1,1); //everything is now rendered upside down
double plane[4] = {0.0, 1.0, 0.0, 0.0}; //water at y=0
glEnable(GL_CLIP_PLANE0);
glClipPlane(GL_CLIP_PLANE0, plane); //preventing rendering objects above the water
RenderSceneAgain(); //renders scene once again
glDisable(GL_CLIP_PLANE0);
glScalef(1,-1,1); //everything is now rendered normally again

```

Its really one of the simplest way to achieve reflections and because you have to render your scene twice you can expect performance drop.
> 1 votes

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


# Question
Title: Why does SDL_RenderCopy result in a blank screen?
I'm trying to render a texture(picture), but `SDL_RenderCopy` keeps the window's background black.

Here's the relevant code:

```
SDL_Rect rect; rect.x = 0, rect.y = 0;
while(!quit)
{
    SDL_RenderCopy(g_renderer, g_texture, NULL, &rect);
    SDL_RenderPresent(g_renderer);
    // Window stays dark although i've rendered via RenderCopy
    SDL_Delay(500);

    while(SDL_PollEvent(&event) != 0)
    {
        if(event.type == SDL_QUIT)
            quit = true;

        else if (event.type == SDL_KEYDOWN)
            move_picture(event.key.keysym.sym, rect);
    }
}

```

If I change the `SDL_RenderCopy` function call to:

```
SDL_RenderCopy(g_renderer, g_texture, NULL, NULL);

```

The picture is visible in the center of the window, but its not the result I'm looking for, as I would want the image to render to the position I set to my rectangle.

After a couple of searches I've found that this is a known behavior. I've tried changing the way I'm loading a texture from `CreateTextureFromSurface` to `IMG_LoadSurface`, but the rendering still doesn't work.

# Answer
You need to set the size of your destination rectangle. Currently you're rendering a 0x0 portion of the texture. So change your code to also include the size of the preferred result. See https://wiki.libsdl.org/SDL\_RenderCopy for more info.

Assuming your image you're trying to render is 32 wide and 32 tall, you would need to set the size of the rect like this: `rect.w = 32; rect.h = 32;`. Then as you're using `NULL` as the source rectangle, SDL will stretch the texture to the size you want.
> 3 votes

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


title: 2d Tile Based Collision Response

text:
# Question
Title: 2d Tile Based Collision Response
Right now I am trying to make a 2d collision response system for a platformer, and the algorithm I have for it works quite well. The only problem is that if the player is standing exactly on a tile, he cannot move. I think this is related to the fact that the manager is checking if he is colliding on the X axis, instead of the Y Axis.

I have thought of making one big AABB for a check, using all applicable tiles, but I feel as if there is a simpler way. I don't really understand normals, so I have not tried anything with them yet.

Right now, I am getting the centers of both objects, the distance inbetween them, and the minimum distance between them, returning the overlap. And then applying the overlap to the players position. It looks like this

```
sf::Vector2f centerA(
  AABBFirst.left + (AABBFirst.width  / 2),
  AABBFirst.top  + (AABBFirst.height / 2));
sf::Vector2f centerB(
  AABBSecond.left + (AABBSecond.width  / 2),
  AABBSecond.top  + (AABBSecond.height / 2));

sf::Vector2f distance(centerA.x - centerB.x, centerA.y - centerB.y);
sf::Vector2f minDistance(
  (AABBFirst.width  / 2) + (AABBSecond.width  / 2),
  (AABBFirst.height / 2) + (AABBSecond.height / 2));

return sf::Vector2f(
  distance.x > 0 ? minDistance.x - distance.x : -minDistance.x - distance.x,
  distance.y > 0 ? minDistance.y - distance.y : -minDistance.y - distance.y);

```

I apologize if this question has already been asked and answered before, I have not found the proper terms to search for.

# Answer
Collision problems are a little bit complicated but here:

My answer to another question similar to yours: Link
> 0 votes

---
Tags: collision-detection, collision-resolution
---


title: Unity Controller navigating UI

text:
# Question
Title: Unity Controller navigating UI
I want players to be able to use a controller to navigate our game's menus. We use Unity's new UI, and in the EventSystem have specified a controller axis for our vertical axis. However the selection from the controller is extremely sticky. The joystick must be held down for a second in order for it to move its selected item down.

I've tried fooling around with the Gravity, Dead and Sensitivty levels but haven't found anything suitable. Could someone recommend some standard settings so the input is not stick7?

I've been using a Xbox controller with a wireless adapter for PC as my controller.

# Answer
> 1 votes
Changing the EventSystem's following values:

Input Actions Per Second: 2

Repeat Delay: 0.3

This makes it more responsive, but is not ideal because it involves changing the EventSystem present in every scene. If someone has a better solution, I'd be happy to hear it.

---
Tags: input, unity, controllers, xbox-controller
---


# Question
Title: How to show specific item in question on trigger entry? (Unity & c#)
So I have multiple, random objects on a plane, and when my player walks into them, I want them to be 'picked up'. The player can only hold one object at a time, and needs to return the item to the base before he can pick up another. Using the OnTriggerEntry function in a collider script, a set of commands are called when the player touches the object. Within the function, the 'itempickup' function from the player script is called using 'col.transform.SendMessage()'. How do I tell the itempickup function which specific object was 'picked up' in the trigger script? That is, is there a variable of some kind that acts as an ID for game objects? Thanks :)

# Answer
> 0 votes
For very simple and limited(in numbers) you could give each of your items tag.
Alternatively, you can take advantage of the `OnTriggerEnter(Collider other)` method signature - the one of the colliding object will be `this`(.gameObject) and the other one is `other.gameObject`. This way you can access attached components directly, including all scripts. So assuming you have something like `Hands` script on player and collider script on the item you could do something like:

```
//on player
public Hands {
  public Item ItemHeld { get; private set; }
  public void EquipItem(Item item) { /*some logic e.g. drop old assign new item*/  }
  public void DropItem() { /*some logic*/}
}

//on item
public Item {
  public string name;
  public OnTriggerEnter(Collider other) {
    if(other.gameObject.tag == "player")//or just assume it is always player
      other.gameObject.GetComponent<Hands>().EquipItem(this);
  }
}

```

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


# Question
Title: XNA Platformer - Where should tile collision handling be?
I've started using XNA and am working on a simple 2D platformer (single level). However, I am stuck as to where the collision detection should be handled. Here is my current project structure:

* The level is a child class of `GameScene` which is a base class for different screens (menus and such)
* The game is based off of a structure where everything is tile-based
    + Therefore, everything inherits from `Tile` which in turn inherites from `DrawableGameComponent`

Currently I have a character (`Character`) and a block tile (`Block`), but there will be different other tiles as well. There are several types of blocks that the player cannot walk through, and should stop moving (in the necessary dimension) upon collision.

I know how to detect collisions; my problem is determining where the Collision detection code should go for player movement. I was told that all collisions should be handled by a separate collision manager which would be passed the (list) of objects to check and then resolve all collisions.

However, the way I was implementing this was to check for collisions, and if they occurred, I would have to check on which side the collision occurred, and then backtrack the character to a position directly flanking the other tile. Here is a (very brief - not all code) example:

### Character\_Block\_CollisionManager.cs

```
public class Character_Block_CollisionManager : GameComponent
{
    private Character character;
    private List<Block> tileList;

    public Character_Block_CollisionManager(Game game, Character character, List<Tile> tileList)
        : base(game)
    {
        this.character = character;
        this.tileList = tileList;
    }

    public override void Update(GameTime gameTime)
    {
        //Checks for collisions and updates the objects accordingly
        foreach (Tile tile in tileList)
        {
            //Get intersection bounds of character and current tile
            Rectangle characterBounds = character.CollisionBounds;
            Rectangle tileBounds = tile.CollisionBounds;

            //Get horizontal and vertical differences in position between character and current tile
            float xDiff = characterBounds.X - tileBounds.X;
            float yDiff = characterBounds.Y - tileBounds.Y;

            //Track the post-collision location of the character (character cannot be displayed inside a wall)
            Vector2 postCollisionLocation = character.Position;

            //Check for a collision
            if (tileBounds.Intersects(characterBounds))
            {
                //Find the intersection rectangle between the two tiles
                Rectangle intersectionRectangle = Rectangle.Intersect(tileBounds, characterBounds);

                if (intersectionRectangle.Width > intersectionRectangle.Height)
                {
                    //A collision has occurred on either the top or bottom of the current tile
                    if (character.Position.Y + characterBounds.Height / 2 > tile.Position.Y + tileBounds.Height / 2)
                    {
                        //A collision has occurred on the bottom of the current tile
                        postCollisionLocation = new Vector2(character.Position.X, tileBounds.Y + tileBounds.Height + characterBounds.Height / 2);
                    }
                    else
                    {
                        //A collision has occurred on the top of the current tile
                        postCollisionLocation = new Vector2(character.Position.X, tileBounds.Y - characterBounds.Height / 2);
                    }
                }
                else
                {
                    //A collision has occurred on either the left or right of the current tile
                    if (character.Position.X + characterBounds.Width / 2 > tile.Position.X + tileBounds.Width / 2)
                    {
                        //A collision has occurred on the right of the current tile
                        postCollisionLocation = new Vector2(tileBounds.X + tileBounds.Width + characterBounds.Width / 2, character.Position.Y);
                    }
                    else
                    {
                        //A collision has occurred on the right of the current tile
                        postCollisionLocation = new Vector2(tileBounds.X - characterBounds.Width / 2, character.Position.Y);
                    }
                }

                //Update the position if the character to reflect the collision
                character.Position = postCollisionLocation;
            }
        }

        base.Update(gameTime);
    }
}

```

### Level.cs

```
public class Level : GameScene
{
    private Tile[,] map = new Tile[32, 18];

    private Character character;
    private List<Tile>tileList;

    private CharacterCollisionManager characterCollisionManager;

    public Level1(Game game, SpriteBatch spriteBatch)
        : base(game, spriteBatch)
    {
        //Create character here...

        this.Components.Add(character);

        tileList = new List<Tile>();

        //Create blocks here...

        tileList.Add(block1);
        tileList.Add(block2);

        foreach (Tile tile in tileList)
        {
            this.Components.Add(tile);
        }

        characterCollisionManager = new CharacterCollisionManager(game, character, tileList);
        this.Components.Add(characterCollisionManager);
    }
}

```

This does work, but also means that I need to know which side the collision occurred on in order to reposition the character. One approach I have heard a lot about is the approach of creating a temporary player location based on movement and then checking said temporary location for collisions. If collisions will occur, calculate the distance to a collision on each axis and move the player that distance. Otherwise, proceed as normal.

This seems all very good in theory, but I am now stuck with the problem of not knowing where to implement this logic... Here are the possibilities I see:

* `Player` class
    + Here is where it seems to need to be in order to have access to player position and therefore be able to calculate a temporary position and check it for collisions (this would be in `Character` Update())
    + However, it wouldn't have access to any of the other tiles to check against, so this seems pointless
* `CollisionManager` class
    + Here is where it seems to need to be in order to have access to all the other tiles and calculate collisions.
    + **Clarifying Edit:** It seems that this will mean I can't create a tempory player position (based on input) and check it for collisions, as the position will have already been completely calculated in the `Player` `Update` method, which will thus have already been moved (possibly into a collision situation).
    Rather than this, I want to test the temporary position for a collision and if one occurs, change the temporary position to the closest it can get without a collision. Finally, I would update the Player's position to be the temporary position. However, as I see it this can only be done from the `Player` class (as the collision manager does not have access to the `Player` `Update` method).

That's basically all I've been able to come up with, which doesn't seem like much. I'm sure other people have done similar things, but have not been able to find a tutorial in this manner. Trust me, I have looked (I wouldn't have posted otherwise). Other tutorials/questions will often have some necessary code/pseudocode, but I've not found one that tells me **where** to put the code and **why**. If someone could please do this for me I would greatly appreciate it!

Let me know if I should add anything else!

# Answer
> 0 votes
You should definitely do this in the `CollisionManager` class. However, your question seems to allude to something inhibiting you from doing this, although I'm not sure what. If you're worried about good code design, then it's fine to use `Get` and `Set` methods to retrieve and set the positions you need when detecting and resolving collisions. This doesn't violate encapsulation.

A `CollisionManager` would also be extensible, meaning when you go to write other collision stuff, you can modify and generalise your `CollisionManager` rather than cluttering lots of other classes with collision logic. If you find an issue down the line with some collision code, it's much easier to change it once in the `CollisionManager` rather than lots of times in each individual class which implements collision detection/handling.

Edit: Ok, I see what you mean now. You're describing continuous collision detection. I had discrete collision detection in mind! I'm not used to this type of collision detection, so I'm not going to be of much help. I guess you could work the character's position at the next update based on current velocity, etc. and pass that to the `CollisionManager`, but I'm sure there are better ways of doing it.

You do have the option of using discrete collision detection, which is when you update the world, then check to see if anything has collided. If they have, you separate them, then render the scene. It's very easy to implement, and given that your game's a simple platformer, I can't see any major downsides to implementing it this way. It's up to you though!

---
Tags: c#, collision-detection, xna-4.0, tilemap, platformer
---


# Question
Title: What's a simple way to send statistics from my game back to me?
For example, I set up my game to keep track of how many times people play x, y, and z game modes, and also to keep track of how often players reach a certain point. What's a simple way to send this data to me so that I can see it?

# Answer
For Unity, I would just recommend using their analytic service, which allows you to store String data (not just numeric data like many services) so you can capture things like which game mode or level was most played, user hardware specs, basically anything.

https://unity3d.com/services/analytics

The API is also very simple to use and integrate, much simpler then most other services I've tried.
> 1 votes

# Answer
The simplest solution would be to setup a web server that saves the data.

Make the client send data once in a while via http.

Save the data in a database like MySQL, and create a page to view the data. Remember to add security if you're sending anything critical.

And since the legal aspect of apps is getting more and more complex, make sure you have your users agree to that fact in the ToS, and make sure you review your app with a competent lawyer.
> 0 votes

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


# Question
Title: Proper way to draw 1000 billboards that always face the camera
I have up to 1000 visible `GameObjects` with trivial plane meshes, which are essentially sprites/billboards and which should always face in the relative direction `-camera.forward`.

**There are so many ways to do this that I have trouble sorting the good ways from the bad ones.**

1. The straightforward way is to use a geometry shader, but that isn't supported on most devices, so that's out.
2. Using a script is nice, easy, simple, and wasting performance.
3. Using a vertex shader and passing in center coordinate of the billboard through properties feels clean but is wasting even more performance because it breaks batching.
4. Doing it in a vertex shader and passing in center coordinate of the billboard through through `uv2` feels brittle and wrong, but will be the most performant.

Ideally, someone has a better solution. If not, maybe someone can make a convincing argument for one of the approaches?

Related: Rotate object to always face camera, Efficient billboarding sprites in Unity 5

# Answer
> 3 votes
Quite simply put, Evorlor is right. Use the script, only look at the shader if performance becomes an issue, not when it's simply a concern.

I implemented a scripted solution (option #2) with a default renderer first. It took about 10 ms per frame, with 1000 meshes with 10 triangles each. As it turns out, almost all of the performance cost in this case came from the Unity batching process. This cost will be exactly the same if using a shader.

Because the number of vertices rarely changes in my case, by batching the billboards on my own, in script, the time got down to 3 ms. Performance cost was down 70%, even though I rotated all vertices independently every frame in script just to make sure the load from the script stayed the same. Of course it's even more silly because I only need to do one single rotation and can replace the 999 remaining ones with vector additions - which then gets the time below 2 ms. So in the very best case a shader can save 2 ms of the original 10 ms, because that's all that remains.

In the end the performance cost came from an unexpected place, as usual, and a shader wouldn't have helped performance at all.

---
Tags: shaders, camera, unity, billboarding
---


# Question
Title: Shaders: packing 4 textures into a single RGBA - slower?
I'm experiencing something really strange on an iOS mobile device. I have 4 textures, and after some profiling it seems, that doing four separate grayscale texture reads is faster, than reading the same textures from a single packed texture:

```
#ifdef COMBINED_METALLIC_ROUGHNESS_AO_EMISSION_TEXTURE
    fixed4 mraeTex = tex2D(_MetallicRoughnesAOEmissionTex, IN.uv_MainTex);

    fixed metallic = mraeTex.r;
    fixed roughness = mraeTex.g;
    fixed ambientOcclusion = mraeTex.b;
    fixed3 emission = mraeTex.a * albedo;
#else
    fixed metallic = tex2D(_MetallicTex, IN.uv_MainTex).r * _Metallic;
    fixed roughness = tex2D(_RoughnessTex, IN.uv_MainTex).r * _Roughness;
    fixed ambientOcclusion = tex2D(_AmbientOcclusionTex, IN.uv_MainTex).r;
    fixed3 emission = tex2D(_EmissionTex, IN.uv_MainTex).rgb;
#endif

```

It seems, that the second option is faster for some reason. Isn't a single texture read supposed to be faster, than doing 4 separate texture reads? Am I missing something?

Thanks!

# Answer
> 2 votes
According to PowerVR "Swizzling the components of lowp vectors is expensive and should be avoided". Source: https://stackoverflow.com/questions/7251772/what-exactly-constitutes-swizzling-in-opengl-es-2-0-powervr-sgx-specifically

---
Tags: shaders, glsl, opengl-es2
---


# Question
Title: Activate and Deactivate Collider with Click
I'm having some trouble working with this, it's basically a sword that points toward your mouse position, and when you Left-Click, a Trigger Collider is activated and then deactivated, but I can't get it to work.

Here is my code :

```
void Attack()
{
    //Activates the Sword Collider
    polygonCollider2D.enabled = true;
    //Debug Line
    Debug.Log("Collider Active");
    StartCoroutine(Wait(0.1f));
    polygonCollider2D.enabled = false;
}

IEnumerator Wait(float seconds)
{
    yield return new WaitForSeconds(seconds);
}

```

I did it this way hoping that the `Wait` method would give the game enough time to react to an active collider, and using some `Debug.Log()`. I know that the collider actually activates, but it does not react to other colliders.

I keep wondering if this is the proper way of working with this. If it's not, do let me know.

# Answer
Add the `polygonCollider2D.enabled = false` line after the `yield return` in the coroutine instead. In your code this line is executed immediately because a coroutine is executed over multiple frames based on what it yields. Whatever is after the `yield return` statement will be executed after `seconds` seconds, but while the coroutine is waiting control is returned to the coroutine caller so that it can continue execution and isn't blocked. So this statement is executed immediately, since while coroutine `Wait` waits, control is returned to `Attack` and it executes the last statement.
> 4 votes

---
Tags: unity, 2d, collision-detection
---


title: Bouncy Ball stops without enough force

text:
# Question
Title: Bouncy Ball stops without enough force
I am building a 3D Pong clone and want to implement a frictionless bouncing ball.

These are the steps i took:

1. Create a box in which the ball can bounce, consisting of standard cubic objects.
2. Create a ball using a spherical object
3. Add a Rigidbody to said ball (Mass: 1, Drag: 0, A.Drag: 0, no Gravity)
4. Add a bouncy Physics Material to the balls Sphere Collider (D.Friction: 0, S.Friction: 0, Bounciness: 1, Fraction Combine: min, Bounce Combine: max)
5. Add a script to the ball that adds force to the ball on start:

Script Snippet:

```
void Start() {
    this.getComponent<RigidBody>().addForce(0, 0, 100);
}

```

When i play the scene, the ball will fly towards the wall and then stop. If i change the added force to (0,0,101) it works as intended. If i lower the mass of the ball and use the old force (0,0,100) it also works. But it will always stop at the wall, if the added force is \<= mass\*100.

What am i missing?

# Answer
> 2 votes
A guy on my development team actually found the source of the problem:

Unity has an internal Bounce-Threshold. If the velocity towards one axis does not reach this Threshold the velocity will be set to 0. This is a nice feature for normal game physics, as bouncing objects will come to a rest faster, but you can't build a perfect bouncing ball without lowering the value.

You can find the Bounce Threshold in the Physics Manager ( Edit \> Project Settings \> Physics ).

---
Tags: physics, movement, unity
---


# Question
Title: Moving a UI element with an object on-screen [Gamemaker]
I have an `oPlayer`object, and an `oTutorial` object which has a DrawGUI event for displaying text on-screen.

Currently I have the text appearing at the top-left of the screen, but I would like the text to follow the `oPlayer` object around the room.

I have tried to set the x & y values in the DrawGUI event to the player's , but this does not have the desired effect; I imagine because the DrawGUI event doesn't occur every step.

Can anybody help?

# Answer
If you want draw text in `Draw GUI` event, just add `Draw GUI` event to the player and place code like this:

```
var posx = x - view_xview[0];
var posy = y - view_yview[0];
draw_text(posx, posy, "Your text");

```

`Draw GUI` occur every step, like any other Draw's event. And GUI layer has independent resolution and coords (see functions `display_set_gui_size` and `display_set_gui_maximise`).
> 0 votes

---
Tags: game-maker
---


# Question
Title: Generating Formulas for glDrawElements with Tile Grids
`glDrawElements` can be used to save you from uploading a lot of vertices to the GPU.

Many 2D games use tiles, which are rendered in grids.

I have done some experimenting with the indices array. For a 3x3 grid of tiles, the indices for `glDrawElements` are as follows:

* 0 1 2 2 1 3 -|- 2 3 4 4 3 5 -|- 4 5 6 6 5 7
* 1 8 3 3 8 9 -|- 3 9 5 5 9 10 -|- 5 10 7 7 10 11
* 8 12 9 9 12 13 -|- 9 13 10 10 13 14 -|- 10 14 11 11 14 15

Already, calculating this is incredibly tedious and the grid is only a 3x3 one.

The proportion of vertices used with `glDrawElements` for power of two grids is `(s + 1)^2 / s^2 * 6`, where `s` is the grid width or height. Here are some grid sizes and savings:

* 10x10 : \<0.2
* 30x20 : \<0.18
* 50x50 : \>0.17
* 100x100 : 0.17

How could one generate an array of indices in the correct order for a grid of tiles, of either width `w` and height `h` (or size `s` for power of two grids if that's more simple)?

# Answer
Well if you want to generate the indices it really depends on how you store the vertices. But lets say you store it like I show below. So vertex 0 is the bottom left and vertex 24 is the upper right.

The bottom triangle 015, notice the pattern that 1=0+1 and 5=0+(4+1). So you can iterate through all the bottom left vertices and calculate the indices. Generally speaking with this format, give me any number V representing the bottom left vertex in the tile and your three indices are {V,V+1,V+(w+1)} for the bottom triangle. For the upper triangle you notice a similar pattern {V+1,V+(w+2),V+(w+1)}. Make sure you don't go outside the grid.

Example code.

```
int[] ind = int[w*h*6]; // The indices
int j = 0;

// Remember to draw all triangle counter-clockwise
for (y = 0; y < h; y++) {
    for (x = 0; x < w; x++) {
        int v = y*w+x;

        // Bottom triangle in tile
        ind[j]   = v;
        ind[j+1] = v+1;
        ind[j+2] = v+w+1;

        // Top triangle in tile
        ind[j+3] = v+1;
        ind[j+4] = v+w+2;
        ind[j+5] = v+w+1;
        j += 6
    }
}

```

Now just pass the ind\[\] array to OpenGL as an element buffer. If you store the vertices in a different order you will have to change the formulas a bit, but the idea is the same. Hopefully this is what you wanted.
> 1 votes

---
Tags: opengl, algorithm, memory-efficiency, efficiency, automation
---


# Question
Title: Can I remove Unreal Engine Splash Screen and put my own?
In Unity, I can change the splash screen if I buy the Pro version.

Can I do the same with Unreal?

# Answer
> 2 votes
https://www.unrealengine.com/eula

Check section on attribution. It appears you do not have to show the Unreal logo at startup, just mention you used the engine in the credits.

> 11. Proprietary Notices and Attribution
>
> You agree to retain and reproduce in all copies of the Licensed Technology the copyright, trademark, and other proprietary notices and disclaimers of Epic and third parties as they appear in the Engine Code and the Content.
>
> You agree to place the following notices in the credits for any Product (replacing xxxx with the current year):
>
> "\[Product name\] uses the Unreal® Engine. Unreal® is a trademark or registered trademark of Epic Games, Inc. in the United States of America and elsewhere"
>
> "Unreal® Engine, Copyright 1998 - xxxx, Epic Games, Inc. All rights reserved."
>
> No other license or right in the Epic Trademarks is granted under this Agreement. All use of the Epic Trademarks will inure to the sole benefit of Epic. You agree not to engage in any activity that could tarnish, dilute, or affect the validity or enforceability of the Epic Trademarks or cause consumer confusion or diminish any goodwill relating to any Epic Trademarks. If you wish to make further use of the Epic Trademarks, please go to https://www.unrealengine.com/branding-guidelines-and-trademark-usage.
>
> Epic may use your trademarks, service marks, trade names, and logos used with any Product, as well as publicly released screen shots and video content from the Product, in connection with Epic's marketing, advertisement, and promotion of the Unreal® Engine in any and all media without restriction.

---
Tags: unreal-4
---


# Question
Title: How to pass rendered frames from OpenGL to DirectX 11?
I have a dll that does some rendering using OpenGL. I need to render it to a texture and use that texture in direct x 11. My current attempt has been to render the OpenGL to a texture on one process, and then use Cuda to encode the texture to a h264 video stream, and then decode that stream on another process using cuda / directx 11. However, I'm wondering if there is an easier way to get a portion of a scene rendered OpenGL to DirectX11.

# Answer
The ideal way to do this would involve OpenGL and D3D sharing the texture memory on the GPU. But there is unfortunately no practical way to do that (as far as I am aware).

Thus, you're going to have to shuffle the texture data around on the CPU. The process is fairly straightforward though. Once your render-to-texture has completed in OpenGL, map the texture to the CPU (via `glGetTexImage` or something fancier), which gives you access to the pixel data of the texture.

With that mapped information you can use `CreateTexture2D` and/or `Map` to create a D3D texture using the same pixel data.

If you're going to do this repeatedly you'll want to make sure you create both textures with the appropriate flags to suggest dynamic updates to the API.
> 5 votes

# Answer
Really the ***most*** elegant solution would be to replicate the functionality in Direct3d 11, but presumably this is unfeasable for you because of reasons™. You could also consider whether using the dll is more trouble than it's worth, there are no easy solutions here.

If you really, **REALLY** need this you could :

* Look into memory-mapping like Josh Petrie suggested
* Use the underlying DXGI layer which is the infrastructure Windows uses for drivers to the hardware. I don't know enough to present a complete solution but can at least point you in the right direction.

Either way will probably require some serious low-level hacking so think really long and hard if you want to take that plunge.
> 2 votes

# Answer
You might want to look at the DX\_Interop OpenGL extensions. Since the extensions were contributed by NVIDIA, they might not be available on every card, but since you mentioned using CUDA, you should be covered.
> 0 votes

---
Tags: opengl, directx, directx11, cuda
---


# Question
Title: Reading XML working in my computer but not in my Android phone
Following code works perfect in my computer but when I try to run it in my Android Phone, it does not work.

```
string path = @"Assets\Layout\XML\file" + select.ToString() + @".xml";
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Name>));
StreamReader sr = new StreamReader(path);
List<Name> listnames = (List<Name>)xmlSerializer.Deserialize(sr);

```

How can I make the code work in my Android Phone?

PS: It is C# , Unity.

# Answer
> 0 votes
I almost gave up but finally solved it. Unity converts everything to binary variable so that the first thing you need to do is to convert all xml files you have to txt and copy them to "Assets/Resources" folder.

Then, you can use following code:

```
    TextAsset asset = Resources.Load("file" + select.ToString()) as TextAsset;
    Stream s = new MemoryStream(asset.bytes);
    BinaryReader br = new BinaryReader(s);

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Name>));
    StreamReader sr = new StreamReader(s);
    List<Name> listnames = (List<Name>)xmlSerializer.Deserialize(sr);

```

# Answer
> 1 votes
What you are trying to do is "load an asset". Here's how:

http://docs.unity3d.com/Manual/AssetDatabase.html

```
using UnityEngine;
using UnityEditor;

public class ImportAsset
{
    [MenuItem ("AssetDatabase/LoadAssetExample")]
    static void ImportExample ()
    {
        Texture2D t = AssetDatabase.LoadAssetAtPath("Assets/Textures/texture.jpg", typeof(Texture2D)) as Texture2D;
    }
}

```

`AssetDatabase.LoadAssetAtPath` is the thing you need to use.

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


# Question
Title: Can I use a BlendState object to emulate a draw call's blending color?
I'm working on a lighting system for a tile-based game.

What I want to do is draw my tiles to the screen, then draw a single Texture2D object (my light map) over top of them. However, doing it in two steps results in the tiles looking "painted" and washed out.

To get this effect working, I called `Texture2D.GetData()` and then used that `Color` as the blending color when calling `SpriteBatch.Draw()` on each tile, which results in them being "tinted" correctly. This works, but it's a fair bit slower, and won't scale up for huge maps/view areas.

So, is it possible to use a BlendState object to do what I am doing above?

# Answer
I found the solution I was looking for. Since my light map used transparency, I simply used:

```
ColorSourceBlend = Blend.Zero;
ColorDestinationBlend = Blend.SourceAlpha;
ColorBlendFunction = BlendFunction.Add;

```

Had to adjust a few things to support it, but it works great.
> 1 votes

---
Tags: xna, alpha-blending
---


title: MonoGame Pipeline

text:
# Question
Title: MonoGame Pipeline
I've been having some problems with the pipeline in MonoGame. I'm using Visual Studio Community Edition 2015 with MonoGame 3.4. I used the installer rather than NuGet if that helps with the problem. Originally the templates went into another users folder and I had to copy them out. I have all of the templates installed in the correct area but when I double click the Content.mgcb icon on the right side of the screen it opens up this file:

```
#----------------------------- Global Properties ----------------------------#

/outputDir:bin/Windows
/intermediateDir:obj/Windows
/platform:Windows
/config:
/profile:Reach
/compress:False

#-------------------------------- References --------------------------------#

#---------------------------------- Content ---------------------------------#

```

Thanks!

# Answer
> 4 votes
What it looks like you're seeing is the file opening as a plain text in Visual Studio. I often open the file this way because I find it handy to be able to edit stuff outside the GUI.

As mentioned by @tandersen, if you right click the `Content.mgcb` file in Solution Explorer you can choose "Open With..." to get the following dialog.

If you can't see the MonoGame Pipeline Tool in the list you'll need to "Add..." it manually. This can be a little tricky because it installs into an odd folder by default.

On my machine the `Pipeline.exe` is located here:

```
C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools

```

Once you've added it and "Set as Default" it should open by double clicking the `Content.mgcb` file.

---
Tags: monogame, xna-content-pipeline
---


title: Movement with Vector Math

text:
# Question
Title: Movement with Vector Math
After reading This SO post on Vectors, I'm still pretty confused on how to use vectors to move my entities at any angle. The SO post assumes only 90 degree angles:

```
if up pressed:
    direction = direction + Vector(0, -1)
if down pressed:
    direction = direction + Vector(0, 1)
if left pressed:
    direction = direction + Vector(-1, 0)
if right pressed:
    direction = direction + Vector(1, 0)

```

Once I have the vector length (are "length", "speed" and "magnitude" all the same thing?), and vector direction (angle), how do I actually move the entity towards the player target at the specified angle and speed?

So, for example:

```
Point a (Player x, y): is at (2, 3)
Point b (Target x, y): is at (6, 8)

```

Vector between a and b is:

```
x2 - x1 =  6-2 = 4
y2 - y1 =  8-3 = 5

```

Vector x,y = (4, 5)

Vector length = sqrt (x^2 + y^2) = 6.4 "units"

Vector direction = atan(5/4) = 51 degrees down and to the left

So I know the speed/length/magnitude is 6.4 "units", and the angle is 51 degrees, but now how do I apply this data to make point B actually move towards point A at that angle and correct speed?

# Answer
> 4 votes
1) First of all, let me roughly clarify a few concepts. You said:

> Once I have the vector length (are "length", "speed" and "magnitude" all the same thing?), and vector direction (angle), how do I actually move the entity towards the player target at the specified angle and speed?

Yes, length and magnitude of a vector can be both terms used with the same meaning. However, technically, a vector is not an angle: it forms angles in *relation to something else*. In your example image, the line segment going from point B to point A forms an angle of around 51 degrees in relation to the X axis.

A vector is given by a point in space (in your case, 2D space). When we *think of* or *use* a vector as a direction, it means that it represents the direction going from the origin (0,0) to that given point in space. Not a specific angle. So, in your example, the vector (4,5) that you calculated *is* the direction from point B to point A. And actually, as you will se, that is all we need.

In what regards speed, that's a totally different thing. By you mixing that together with length and magnitude, it is apparent that you are confounding speed and velocity, which are two different concepts. Speed is just a scalar number that represents the amount of distance walked in a given time, i.e. length divided by elapsed time. Velocity is a vector given by the direction of the movement divided by elapsed time. Hence, the current speed of a movement is the length of the velocity of that movement. For more details, see: http://www.physicsclassroom.com/class/1DKin/Lesson-1/Speed-and-Velocity.

2) That said, the way I find to be the simplest to move an object using vector math is the following. You need 4 pieces: direction, length, speed and frame delta.Time.

In detail: you have to calculate the vector direction (not the angle) and normalize it, have to use the scalar speed that you desire, and have to apply a frame-to-frame delta time for consistency across different computers. You put all that in a loop that loops while the distance between moving char and destination point (in your case, point A) is lower than the total distance between points A and B. And voilá!

Let's do it. If the movement goes from point B to point A, then the vector **direction of the movement** is equal the location (position) of point A in the space minus the location (position) of the point B in space. I will use C# for the following examples, but you will get the idea:

```
Vector2 movement_direction = A.transform.position - B.transform.position;

```

Then, we normalize that vector. What does normalize mean? It only means that we take the vector "movement\_direction" and force its length/magnitude to become equal 1. That's pretty simple to achieve: you just divide the vector by its length. See more here: http://www.fundza.com/vectors/normalize/. For that, we will need to get the **direction lenght**, just as you did:

```
float direction_length = Math.sqrt (Math.Pow(movement_direction.x,2) + Math.Pow(movement_direction.y,2) );

```

Then, let's normalize the direction of the movement:

```
Vector2 movement_direction_normalized = movement_direction  / direction_length;

```

Now, you just choose the **speed** you want for your movement and you retrieve from your game engine the so called frame **delta.Time**, which is the time elapsed between the last frame and the current frame of the main game loop.

The final formula for the movement becomes, at each frame of the main loop while the movement is still going on:

```
movingchar.transform.position = movingchar.transform.position + (movement_direction_normalized * speed * Time.deltaTime;

```

It means that, at each iteration of the loop while movement is in place, you take the current location of the moving char and sum to it the result of the multiplication between the normalized direction of the movement, the speed of the movement and the frame delta.Time.

Note that you should execute the formula (i.e. update the movement) in a loop that keeps working until the updated distance between the moving character is smaller than the initial distance, i.e. smaller than the distance between points B and A.

Also note that including delta.Time is crucial, because that is the way you guarantee that you movement will have the same speed no matter how fast is the computer running the game. Otherwise, the speed would vary because of the difference in how fast computers calculate each frame of your game.

# Answer
> 1 votes
Once you have the vector (`V` in your diagram), you can simply normalize it (that is, make its length 1.0), then multiply it by the speed you want and add it to point `B`.

To normalize the vector divide the components by the length. In this case, that would mean the normal vector is `(4/6.4, 5/6.4)` = `(0.625, 0.78125)`.

It's not clear to me what you're trying to accomplish, so I don't know how best to tell you to calculate the speed. If you set it to `6.4`, then the target will be in the player's position on the next frame. (But the player may have moved by then.)

Once you know the speed you want, you can move B by doing the following:

```
b.x += speed * v.x;
b.y += speed * v.y;

```

That assumes you put the normalized vector into `v`.

---
Tags: game-design, movement, vector
---


# Question
Title: How to determine lowest PC requirenments for my game to run
so I've created my first game in UE4 (4.9.2 version) and want to publish it. But i really don't know how to determine lowest possible environment my game runs on.Also I am unsure what other files apart from actuall build I should redistribute. I am building game via file-\>package project-\>window.

1) How to determine minimum required DirectX version?

2) How to check what other dll's I need to include into installer (apart from actuall build)? For example will I need to install VC redistributable packages? If so then which ones? The same goes with directx.

3) How to determine minimal windows version? This is limited by directx compatibility right? If my game runs on DirectX10 or higher then all OS versions with at least direct10 will be OK?

4) This may seem as stupid question but in which version 64 or 32 bit I should distribute my game? 32 is always better because anybody can run it right?

thanks for Your answers ;)

# Answer
> 5 votes
First thing: as @ZEKE has suggested in the comments to your question, you should check: How do I determine my games minimum hardware/software requirements? Also, in the end of the day, only experimenting can really give you final answers to that, as @Abstract-Sky has replied in the other answer.

However, you can certainly have some pointers. Here, I will be answering to your original question, the one that brought multiple sub-questions - not to the edited version, because mentioning only "lowest possible environment" becomes just too vague. But, of course, I am only thoroughly answering to **part** of your sub-questions, because as @zehelvion has well put in the comments, it becomes hard to handle when multiple different stuff is mixed together in the same question.

So:

> 1) How to determine minimum required DirectX version?

By default, the minimum requirement of UE4 games as of 2014 was DirectX10, because the engine required SM4.0 GPU. So, if you don't use any external libraries or plugins or functions that are specific to DirectX11 or 12, it's very likely that for your game DirectX10 will be also the baseline. So start by checking that.

> 2) How to check what other dll's I need to include into installer (apart from actuall build)? For example will I need to install VC redistributable packages? If so then which ones? The same goes with directx.

That's impossible to answer without knowing in much more detail what have you used, implemented and included in your game. I think this one deserves a separate question with plenty of details about your game.

> 3) How to determine minimal windows version? This is limited by directx compatibility right? If my game runs on DirectX10 or higher then all OS versions with at least direct10 will be OK?

Not necessarily. Windows Vista had DirectX10 and still Epic never supported that OS officially. So, it's unclear whether UE4 games would run on that without problems. I've read Epic staff mentioning that UE4 games could work under Vista, but that would be a case for empirical verification in a case-by-base basis. So if you want to aim Vista, there might be some hope.

What is often said to be the minimal system for a game using UE4 is Windows 7 sp1. However, again, if you installed or included any external library or plugins, you will have to double-check that all those also work back to Windows 7 sp1. But if your concern is to go even backward, for Windows XP compatibility, there might be also hope. Epic staff has mentioned in the past (see for instance this forum thread: https://forums.unrealengine.com/showthread.php?1310-Unreal-Engine-4-etc) that they were looking into giving compatibility to a version of OpenGL that would make it work even in Windows XP. In the UE4.2 release, they announced a preview of that compatibility: https://www.unrealengine.com/blog/unreal-engine-42-release

But by default, it's Windows 7 sp1 if nothing external from your game requires Windows 8 or 10.

> 4) This may seem as stupid question but in which version 64 or 32 bit I should distribute my game? 32 is always better because anybody can run it right?

Well, ultimately that's an opinion based one - therefore hard to answer. But I can give you one of the basic trade-offs: 32bits systems generally can regularly use only up to 2.75 to 3.5Gb of RAM memory, no matter how much total RAM is present in the machine. See this: https://en.wikipedia.org/wiki/3\_GB\_barrier

So first of all you have to have that in mind. If you consider an OS as memory hungry as the Windows 7 & 8, think of performance and make sure to profile how your game runs under those systems with a 2.75Gb RAM constrain.

---

Lastly, if you were happy enough to have come to the point of finishing a game for delivery, I think that you should certainly write UE4 for technical details on compatibility. Specially if you are interested in older Windows versions (i.e. XP and Vista).

# Answer
> 2 votes
The Unreal Engine documentation has a page specifying the hardware and software requirements to run the engine here (you're looking for the "running the engine" parts). Besides that, if you want to know if your game can run on machines with inferior specs, I think only experimentation can tell.

---
Tags: unreal, requirements
---


title: Pygame freezing on QUIT

text:
# Question
Title: Pygame freezing on QUIT
I'm having problems with quitting a Pygame application (6502 based computer emulator).

The part regarding exit looks like this:

```
while True:
  do_something_200_times()

  for event in pygame.event.get()
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()

```

I'm also using pygame.mixer to play sounds as they appear, but I'm not sure that's related. I'm also using pygame.time.set\_timer to update screen in regular intervals and play sound if buffer has filled enough. Is it possible the event queue overfills? How would I determine if this is the case?

It simply freezes in 40-50% cases, and attaching strace -p to the python interpreter gives:

```
Process 21326 attached
futex(0x7f5a32f839d0, FUTEX_WAIT, 21329, NULL

```

Also, I'm getting occasional pulseaudio related crashes, is this combination known to be buggy?

Any ideas and suggestions are more than welcome! Thanks!

EDIT: it freezes when I click the window's close button (x)

# Answer
> 2 votes
```
RUNNING = True
while RUNNING:    # Loop while RUNNING == True
    do_something_200_times()

    for event in pygame.event.get()
        if event.type == pygame.QUIT:
            RUNNING = False    # Set RUNNING = False and end the loop

pygame.quit()    # Quit pygame and allow the program to end

```

Instead of creating an infinite loop, assign it's execution to a variable, in this case RUNNING. Then, when an exit event is raised, you can just set the variable, RUNNING, to false. That will end the loop where Pygame can be exited after the loop and allow the program to end naturally without raising any exceptions and without having to use the sys module.

---
Tags: python, pygame
---


# Question
Title: Is there software that allows remote and collaborative work? How is it called?
I am currently not in the game development industry and develop my own games using GameMaker, but as a high school student I don't really have the time to make proper titles and actually make money from them. But, I have been thinking. Is there a program/website that, just say you were doing a long distance development with multiple team members in different parts of the world/country, you can upload all your work and with the click of a button anyone else in the "group" automatically downloads it. So for example:

* You are a coder working on the physics engine.
* There is another coder (somewhere else in the world) that is in your group and is programming the player that relies of the physics engine.
* You make a change to the physics engine
* Instead of having to email your partner the updated coding file and him having to download it, you save your file to a program that automatically uploads it to a server
* Every 5 minutes (or whatever) the server checks if either person has uploaded any new files and automatically downloads them and overwrites them
* So in turn your partner stays with continuously updated code and so do you. This could work with any aspect of a game (or any group project).

So is there anything like this? If so, is there a name for it?

# Answer
> 2 votes
There is this wonder invention, its called source control.

Many of us use github or visual studio online, if you want auto updates there are a ton of examples for writing about 10 lines of code in a python script or similar to auto fetch and compile sources from a repo, virtually all open source builds do that these days for software that runs on nas or media centers.

On top of that there's then project management tooling like, jira (seems to be the most popular from what i've seen, when used with something like jenkins (an automated build tool) and bitbucket (atlassian's version of github) you can a pretty good continuous integration (CI) workflow for your CI builds.

Pick your poison and do some research.

---
Tags: terminology
---


# Question
Title: How can I get projected coordinates of vertex on screen
I want to check picking for faces and for that I need projected X Y coordinates of my vertexes in -1 to 1 range:
For that I multiply my vertex array with matrices and then get projected triangle coordinates from it and check if mouse is inside of that triangle ,but something goes wrong:
Here is my code

```
    for (int i = 0; i < m_vertexCount; ++i)
{
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &worldmatrix);
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &viewmatrix);
    D3DXVec4Transform(&m_Pverts1[i], &m_Pverts[i], &projectionmatrix);
}
z = 0;
for (int i = 0; i < m_faceCount; ++i)
{
    x1 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y1 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z1 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;
    x2 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y2 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z2 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;
    x3 = m_Pverts1[m_verts[z].x - 1].x / m_Pverts1[m_verts[z].x - 1].w;
    y3 = m_Pverts1[m_verts[z].x - 1].y / m_Pverts1[m_verts[z].x - 1].w;
    z3 = m_Pverts1[m_verts[z].x - 1].z / m_Pverts1[m_verts[z].x - 1].w; ++z;

    //code .. //
}

```

Where `m_Pverts` is array of vertexes `m_Pverts1` is empty array for transformed vertexes and `m_verts[].x` is array of vertex indexes: `x1,y1,z1,x2,y2,z3,x3,y3,z3` must be X Y projected coordinates of triangle and Z depth:
Other code is checked and works right:

What I am doing wrong ??

# Answer
I get the solution of my problem: Instead of using `worldmatrix` `viewmatrix` and `projectionmatrix`
i must use `wvpwatrix` which is multiplication of that three matrices

```
D3DXMATRIX wvp;

wvp = worldmatrix*viewmatrix*projectionmatrix;

for (int i = 0; i < m_vertexCount; ++i)
{
    D3DXVec3TransformCoord(&m_Pverts1[i], &m_Pverts[i], &wvp);
}

```

But I dont know why is it working??
> 0 votes

---
Tags: directx, matrix, directxmath
---


# Question
Title: LibGDX hexagonal tilemap getting adjacent tiles
How do I get all adjacent tiles to a hexagonal tile, my tile map is using a staggered co ordinate system with an odd stagger index and I am using libgdx java.

```
if (x % 2 == 0) {
            hexAdj[0] = new Vector2(x    , y + 1);
            hexAdj[1] = new Vector2(x + 1, y + 1);
            hexAdj[2] = new Vector2(x + 1, y    );
            hexAdj[3] = new Vector2(x    , y - 1);
            hexAdj[4] = new Vector2(x - 1, y    );
            hexAdj[5] = new Vector2(x - 1, y + 1);
        }else{
            hexAdj[0] = new Vector2(x    , y + 1);
            hexAdj[1] = new Vector2(x + 1, y    );
            hexAdj[2] = new Vector2(x + 1, y - 1);
            hexAdj[3] = new Vector2(x    , y - 1);
            hexAdj[4] = new Vector2(x - 1, y - 1);
            hexAdj[5] = new Vector2(x - 1, y    );
        }

```

# Answer
> 1 votes
I think the simplest way would be to convert your coordinates to cube coordinates, then use a lookup table with the offsets to get the coordinates for the adjacent tiles, and then convert the coordinates back.

```

Vector3 coordsToCube(Vector2 coords) {
    Vector3 cube = new Vector3();
    cube.x = coords.x - (coords.y - ((int) coords.y & 1)) / 2
    cube.z = coords.y;
    cube.y = -cube.x - cube.z;
    return cube;
}

Vector2 cubeToCoords(Vector3 cube) {
    Vector2 coords = new Vector2();
    coords.x = cube.x + (cube.z - ((int) cube.z & 1)) / 2;
    coords.y = z;
    return coords;
}

static Vector3[] offsets = new Vector3[] {
   new Vector3(+1, -1,  0), new Vector3(+1,  0, -1), new Vector3( 0, +1, -1),
   new Vector3(-1, +1,  0), new Vector3(-1,  0, +1), new Vector3( 0, -1, +1)
}

Vector3[] getAdjacent(Vector3 cube) {
    Vector3[] adjacent = new Vector3[6];
    adjacent[0] = new Vector3(cube).add(offsets[0];
    adjacent[1] = new Vector3(cube).add(offsets[1];
    adjacent[2] = new Vector3(cube).add(offsets[2];
    adjacent[3] = new Vector3(cube).add(offsets[3];
    adjacent[4] = new Vector3(cube).add(offsets[4];
    adjacent[5] = new Vector3(cube).add(offsets[5];
    return adjacent;
}

```

---
Tags: java, libgdx, tilemap
---