# Question
Title: Lerping character moving up and down slope tiles
So, when interpolating position against a standard 'horizontal' platform, everything works great. What happens is something like this..... (Question continues after graphic)

Now, the question I have is, how do we correctly interpolate the player's sprite (blue circle) against a 45° tile? When I attempt to do this, what happens, is that when the player is going *up* the slope, it is slightly embedded in the tile and when coming *down* the slope, it floats slightly above the tile.

In the example above, the sprite effectively 'stops' moving along the Y Axis, so therefore, interpolation along that axis stops, however when interpolating the position against a slope, the sprite moves in an X and Y direction, so never stops. I think this is causing the issue, if my logic is correct, some more graphics follow to illustrate what I mean....

What am I doing wrong? How do I interpolate my sprite while making sure it's 'on' the slope at all times?

**For moving up a slope**

**When moving down slope**

**Summary**

When interpolating against a horizontal platform, although the sprite isn't rendered **on** the platform in the frame straight after collision has been resolved, it is rendered on the platform during subsequent frames because the difference between the old and new positions has become 0 as it is no longer moving. However against a slope, again, the initial frame is incorrect but then the sprite moves again, so the next frame is also wrong etc so it never 'settles'. Note it *does* move at the slope's angle just not *on* the slope.

I'm trying to work out how to get my two points along the 45° slope and interpolate between them (ie, along the slope)....

# Answer
I finally found out what was happening and the solution was actually really simple.

In my logic update, I was stepping Y first (applying gravity etc) and then moving my characters along the X. (This worked fine for levels with no slopes).

The solution was simply to reverse this.

For example, when stepping Y first, the sprite was being pushed down into the slope, and resolved to sit on it, then the sprite was moving out (X) and this was where it was being rendered - away from the platform.

See **The guide to implementing 2D platformers** for the article which led me to the resolution. See this quote from the above article:

> Decompose movement into X and Y axes, step one at a time. If you’re planning on implementing slopes afterwards, step X first, then Y. Otherwise, the order shouldn’t matter much.

So for anyone who may be experiencing similar problems, remember, **when you have slopes in your game, it's important to step X first, then step Y**. After doing this (at least in my case), the sprite adhered perfectly to the slope. It was never an issue with the interpolation as I initially thought.
> 0 votes

# Answer
Without checking if your player is inside a platform in your render logic, you cannot prevent this.

You can mitigate this by minimizing the distance the player moves between physics updates. This is accomplished by limiting the player's velocity (duh.) This helps because the less distance you interpolate over, the less you're assuming about the player's path between updates.

All this makes a lot of sense right? All you have is a bunch of points you know are correct, and you're just guessing at the path between points. The more distance between those points, the more error prone your guess will be. Working on a better interpolation routine isn't going to help much, because any interpolation is, by definition, a **guess**. That leaves either just guessing, as you are now, or running collision logic to get the correct position.

If you insist on running collision logic in your render routine, look into calculating the minimum translation vector. This is all you need to shift your player outside the bounds of the ramp. Running collision logic twice might be ok CPU-wise for a single body. Although it is still violates separation of concerns, a common software design guideline, as your display (render routine) will be dependent on your logic (physics system.)

If you try simulating many bodies like this, you will waste a lot of CPU. I do not suggest this approach for many bodies.

Edit:

Here's the only issue I see you having. If drawing a line as thick as your player between 2 physics updates would cause the player to intersect a platform, linear interpolation could put a player in a platform.

The problem you're describing above, of the player floating above, or appearing in a platform should not happen if your code is correct, and something similar to my illustrated condition does not occur.

So, I think your code is incorrect, likely in the render routine. Maybe your player graphic isn't aligned with the physics coordinates correctly? Maybe your linear interpolation is a little off. Maybe your physics object is a little smaller or bigger than your player graphic?

Regardless, I don't think the problem is with your interpolation. If you want more help, post code. We've gone as far as we can with what you've provided.
> 1 votes

# Answer
I think you should interpolate between two collision resolved frames. If so, the ball would touch the slope because the linear interpolation of two frames where the ball touches the slope would produce a ball, center of that is lying on imaginary line that connects the centers of two balls at collision resolved frames. This is true, if the slope is linear.

So, you need to:

* Update ball speed. It would change due to the gravity or user input.
* Update ball position.
* Resolve collisions.
* Back up frame.
* Render interpolation of the two last backed up frames.
> 0 votes

---
Tags: collision-detection, collision-resolution, interpolation, lerp
---


# Question
Title: My pool balls often jump around when there are two or more balls colliding/touching
I'm working through the book 'Introduction to Game Physics with Box2D' and I've created a little pool game with the example code. Despite the name, there is NO box 2D used in this particular exercise.

The example in the book can be seen in this video by the author which only consists of the cue ball and 8-ball. This all works well.

I've written my own version from scratch (using SDL instead of DirectX), using the code in the book as a guide. When I limit it to two balls, everything works great.

When there are more than two balls, things are sometimes problematic in a way I can't predict. Breaking can be fine on one run, or it can cause the balls to 'jump' and flicker as they move presumably looking for empty space. Generally, problems occur when there are more than two balls in a collision.

I've read around and it seems that I need to perform more 'iterations' to get closer to the correct result, but the code that I'd learned will work the same regardless of the number of times it is performed - it sets the positions of any overlapping balls so that they are barely touching. I've tried changing it so it 'pushes' the balls slightly in the direction of the collision normal, with no success.

Here's the relevant code:

```
bool BallManager::ballBounce(Ball& ball1, Ball& ball2)
{
    float r = static_cast<float>(ball1.diameter_ + ball2.diameter_) * 0.5f;

    // Calculate direction of relative velocity.
    Vector2 v = ball2.velocity_ - ball1.velocity_;
    Vector2 vhat = v.normalized();

    // Calculate relative displacement along normal to collision tangent.
    Vector2 c = ball2.position_ - ball1.position_;

    Vector2 n = c.normalized();

    // Relative distance along normal to tangent.
    float cdotvhat = dot(c, vhat);

    // Balls don't collide, exit early.
    float discriminant = cdotvhat * cdotvhat - c.lengthSquared() + r*r;
    if (discriminant < 0.0f)
    {
        return false;
    }

    // The distance we want to move ball2 back by.
    float dist2 = cdotvhat + sqrt(discriminant);

    float relativeVelocity = 0.0f;
    if (ball2.velocity_.length() > 0.0f)
    {
        relativeVelocity = ball1.velocity_.length() / ball2.velocity_.length();
    }

    // The distance we want to move ball1 back by.
    float dist1 = dist2 * relativeVelocity;

    // Move balls in reverse direction of velocity to point of impact.
    Vector2 v1hat = ball1.velocity_.normalized();
    Vector2 v2hat = ball2.velocity_.normalized();
    ball1.position_ -= dist1 * v1hat;
    ball2.position_ -= dist2 * v2hat;

    // Adjust ball velocities after reflection.
    Vector2 vDiff = ball1.velocity_ - ball2.velocity_;
    vDiff = dot(vDiff, n) * n;
    ball1.velocity_ -= vDiff;
    ball2.velocity_ += vDiff;

    // Finally, move balls again to where they should have bounced to.
    v1hat = ball1.velocity_.normalized();
    v2hat = ball2.velocity_.normalized();
    ball1.position_ += dist1 * v1hat;
    ball2.position_ += dist2 * v2hat;

    return true;
}

```

At the moment I'm mainly looking for a pointer in the right direction or suggestions since I'm new to physics programming.

# Answer
I've managed to get it working, thanks to @UnholySheep for convincing me that I was on the right track which helped me through some head scratching. Things move smoothly now, and the balls don't stick together either.

I've changed my `ballBounce()` function to return a `bool` if there is still a collision/overlap so that my main game loop will iterate again, up to a specified limit.

(EDIT: I've made it a lot simpler, and more accurate - the balls are pushed by the penetration depth, which works in 1 step for several balls) I've also changed the function to push the balls by a tiny amount instead of placing at the edge of the other ball, because even though that worked for two balls, it causes multiple colliding balls to 'jump' to the next empty space instead of moving naturally.

Here is the changed function:

```
bool BallManager::ballBounce(Ball& ball1, Ball& ball2)
{
    Vector2 c;
    float cdotvhat = 0.0;
    float discriminant = 0.0;
    bool collision = ball1.checkBallCollision(ball2, c, cdotvhat, discriminant);
    if (!collision)
    {
        return false;
    }

    float relativeSpeed = 0.0f;
    if (ball2.velocity_.length() > 0.0f)
    {
        relativeSpeed = ball1.velocity_.length() / ball2.velocity_.length();
    }

    float penetrationDepth = (ball1.getDiameter() + ball2.getDiameter()) * 0.5f - c.length();

    Vector2 n = c.normalized();

    // Adjust ball velocities after reflection.
    Vector2 vDiff = ball1.velocity_ - ball2.velocity_;
    vDiff = dot(vDiff, n) * n;
    ball1.velocity_ -= vDiff;
    ball2.velocity_ += vDiff;

    // BALL_RESTITUTION is 0.9f.
    ball1.velocity_ *= BALL_RESTITUTION;
    ball2.velocity_ *= BALL_RESTITUTION;

    ball1.position_ -= c.normalized() * (penetrationDepth * 0.5f);
    ball2.position_ += c.normalized() * (penetrationDepth * 0.5f);

    return collision;
}

```

The method `checkBallCollision()` is just a refactoring of code from the old version of `ballBounce()`, because I experimented with checking for overlaps in various parts of my code:

```
bool Ball::checkBallCollision(const Ball& otherBall, Vector2& c, float& cdotvhat, float& discriminant)
{
    float r = static_cast<float>(getDiameter() + otherBall.getDiameter()) * 0.5f;

    // Calculate direction of relative velocity.
    Vector2 v = otherBall.getVelocity() - getVelocity();
    Vector2 vhat = v.normalized();

    // Calculate relative displacement along normal to collision tangent.
    c = otherBall.getPosition() - getPosition();

    // Relative distance along normal to tangent.
    cdotvhat = dot(c, vhat);

    // Balls don't collide, exit early.
    discriminant = cdotvhat * cdotvhat - c.lengthSquared() + r*r;
    if (discriminant < 0.0f)
    {
        return false;
    }

    return true;
}

```

Finally, (leaving out a few layers of abstraction), here's an excerpt from my main loop (EDIT: I've made changes based on @Roy T.'s suggestions, as well as the well-known GafferOnGames article):

```
const unsigned int FRAMES_PER_SECOND = 60;
const unsigned int MILLISECS_PER_FRAME = 1000 / FRAMES_PER_SECOND;

const unsigned int PHYSICS_TICKS_PER_SECOND = 100;
const unsigned int MILLISECS_PER_PHYSICS_TICK = 1000 / PHYSICS_TICKS_PER_SECOND;

bool quit = false;

unsigned int lastTickStart = g_timer.time();

while (!quit)
{
    input();

    const float dt = static_cast<float>(MILLISECS_PER_PHYSICS_TICK) / 1000.0f;
    float accumulator = 0.0f;

    unsigned int newTime = g_timer.time();
    unsigned int frameTime = newTime - currentTime;

    accumulator += static_cast<float>(frameTime) / 1000.0f;

    bool unresolvedCollision = true;
    while (accumulator >= dt)
    {
        unresolvedCollision = update(t, dt);
        accumulator -= dt;

        t += dt;
    }

    const double alpha = accumulator / dt;

    renderFrame(alpha);

    currentTime = newTime;

    int delayTime = MILLISECS_PER_FRAME - (g_timer.time() - currentTime);
    if (delayTime > 0)
    {
        SDL_Delay(static_cast<unsigned int>(delayTime));
    }
}

```
> 2 votes

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


# Question
Title: TypeLoadException when running a Monogame Windows Phone 8 game
Using Monogame, I'm trying to port a game to Windows Phone 8, but I'm having issues getting a basic example to run.

When I create a basic Mono project and run it on my phone (to check everything's OK), it compiles the game, and deploys it to my phone, but when the app starts running, the debugger throws this error:

I tried adding a reference of that `.dll`, but that doesn't solve it. This is the first time that I use Monogame, so please bear with me.

# Answer
I believe you are running into the same issue as below. It is fixed in the development branch.

**MonoGame 3.2 installer installs Windows (DX) framework assembly into WindowsGL**

You can check by following these steps.

> Install MonoGame 3.2, then inspect Assemblies/WindowsGL/MonoGame.Framework.dll in ildasm. The assembly manifest is referencing SharpDX instead of OpenTK. The assembly is a copy of Assemblies/Windows/MonoGame.Framework.dll.

Checking out the original branch, building the project, and then running the installers should fix your issue. Additionally reinstalling WindowsGL should solve the issue.
> 0 votes

---
Tags: xna, monogame, windows, windows-phone-8, debugging
---


# Question
Title: IDXGISwapChain::ResizeBuffers - should I recreate the depth/stencil buffer too?
When I resize the buffers via IDXGISwapChain::ResizeBuffers(), it is required to release any references to views to the back buffer. That of course makes sense, because the back buffer texture is about to be changed.

But nothing mentions whether I should change the depth/stencil buffer at the same time. I'm guessing it's not a requirement because D3D can scale before outputting, but is it a good idea anyway?

Thank you

# Answer
Although you don't strictly need to resize your depth/stencil buffer, you will need to do so if you want to use it in conjunction with the back buffer render target. This is because the depth/stencil buffer must match the size of the render target. If you are doing deferred rendering, or some other technique that doesn't require a depth buffer bound when rendering to the back buffer, then you can omit the resize; but otherwise you should resize both to match the new window size.
> 3 votes

---
Tags: directx, directx11
---


title: Unity Plugin DLLNotFoundException

text:
# Question
Title: Unity Plugin DLLNotFoundException
I am using a plugin DLL that I created in Visual C++ Express 2010 on windows 7 64 bit Ultimate Edition. The DLL functions properly on the machine that it was originally created on.

The problem is that the DLL is not functioning in the Unity3d Editor on another machine and giving an error that basically states that the DLL is missing some of its dependencies. The target machine is running Windows 7 Home 64 bit (if this is relevant)

Results from the error log of Dependency Walker:

Error: The Side-by-Side configuration information for "c:\users\dewayne\desktop\shared\vrpnplugin\unityplugin\build\release\OPTITRACKPLUGIN.DLL" contains errors. The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log or use the command-line sxstrace.exe tool for more detail (14001). Error: At least one module has an unresolved import due to a missing export function in an implicitly dependent module. Error: Modules with different CPU types were found. Warning: At least one delay-load dependency module was not found. Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.

The Visual C++ Express 2010 project and solution file can be found here: https://docs.google.com/leaf?id=0B1F4pP7mRSiYMGU2YTJiNTUtOWJiMS00YTYzLThhYWQtMzNiOWJhZDU5M2M0&hl=en&authkey=CJSXhqgH The zip is 79MB and also contains its dependencies.

The DLL in question is OptiTrackPlugin.dll

# Answer
> 1 votes
Which C runtime is the plugin DLL built with? If you use the 'DLL' runtime (Multithreaded DLL, I think it's called; I don't have Visual C++ in front of me), you'll also need the matching CRT distributable installed on the target machine (you're building a DLL which references the DLL version of the C runtime, in other words). If you use the non-DLL runtime (just called Multithreaded), then the C runtime will be statically linked to your DLL (as such the plugin DLL will be bigger but won't have the CRT DLL dependency).

# Answer
> 0 votes
If the DLL is not a .Net assembly (i.e. cannot be loaded in the References folder) put it in the root folder (not the assets)

---
Tags: c++, unity
---


# Question
Title: Getting the Halo property of a point light in Unity
I am adding point lights in my scene ( max 6 ) and I want to be able to enable its Halo property via script. However in the documentation reference, they haven't mentioned how to enable the halo property of a light source via script.

This is what I have so far.

```
GameObject lightObj = new GameObject("Light");
lightObj.AddComponent<Light>();
lightObj.light.color = Color.blue;
lightObj.transform.position = city.transform.position + new Vector3(-6.0f,0,0);

```

Point Lights have a property "Draw Halo" on the Inspector but how do I enable it via script?

# Answer
From what I can tell from the Halo class documentation, lights do some magic behind the scenes to automatically create a Halo component, but hide it from the hierarchy (much like how AudioSource.PlayOneShot() will automatically create and destroy new AudioSources while hiding them from the hierarchy). It seems the Halo component is not exposed. However, there is a workaround.

In my tests (using Unity 4.5.5) using the answers found in this Unity forum thread, I could not access the automatically created Halo via script, but if I added the Halo component to the light manually (Component -\> Effects -\> Halo) then I could access it via script according to the answer given by Thundergod44, which I'll quote (with minor modifications) below:

```
//It's possible with C# and System.Reflection:

var haloComponent = lightObj.GetComponent("Halo");
var haloEnabledProperty = haloComponent.GetType().GetProperty("enabled");
haloEnabledProperty.SetValue(haloComponent, enable, null);

```

You'll need to replace "enable" in that last line above with a boolean value. Enabled is true, disabled is false.

Admittedly, I'm pretty inexperienced with lights/halos and reflection, so you may have better luck getting things to work with the automatically created Halo component than I did. But I can confirm that manually adding a Halo component will allow you to work around this seeming oversight by Unity to expose the Halo component.

A tangential fact that I found to be an interesting explanation as to why I couldn't figure out how to add a Halo component via script is that GetComponent("Halo").GetType() returns *Behaviour*. That's a type I'd never seen before. You'll need to know this if you wish to use strong typing when declaring variables or getting the component. e.g.:

```
Behaviour haloComponent;

void Awake() {
    haloComponent = (Behaviour)lightObj.GetComponent("Halo");
}

```
> 1 votes

---
Tags: unity, lighting
---


# Question
Title: How can I stop explodable objects from creating new ones during cleanup?
I have a problem with the handling of explosions in my game.

Currently, I have an entity create an explosion when it is destroyed (in the destructor). The issue with this is that when I change states, all my game objects are deleted. This causes explodable objects to create explosions when my EntityManager is already deleted.

I'm still pretty new to game development and I believe my design is very poor. How can I solve this problem?

# Answer
> 4 votes
Constructors and destructors in C++ are about the lifetime of the object. Your problem is that you are mixing up the lifetime with the desired behavior of the object.

The solution is to decouple them.

Give the appropriate entities an "OnDestroy" function, which is called by your game logic when the entity should be (according to the rules of the game) destroyed.

Leave your destructor to do what it should do: anything necessary when (according to the rules of the *language*) the object itself should be excised from your program's memory.

Then you create your explosions in OnDestroyed. When you transition between game scenes, that causes the entities to be deleted, cleaning up and invoking the destructor, but it doesn't need to call the OnDestroyed method, so no new entities will be created.

---
Tags: architecture
---


# Question
Title: How to calculate ray polygon intersection?
I'm in a class where we are creating a ray tracer from the ground up in C++. I'm at a point where I can't seem to wrap my head around the math that is required to calculate the point at which a ray intersects a polygon.

We have some direction for how to do this, but all of the class materials as well as my Googling of the subject have not helped.

These are the functions we must complete:

```
bool polygon::Intersect(const ray &R, intersection &inter)
{
    // To Do: If you have implemented the "CalculateNormal" method
    // below, should already be calculated and placed in the member
    // "n".
    //
    // Now, using n, you need to calculate the intersection of the
    // ray with the plane containing the polygon.  Then, once you
    // have that point, you need to loop through each edge in the
    // polygon and make sure the point is to the left of that edge.
    //
    // If it is to the left of every edge, then fill the structure
    // inter with all of the data for the intersection and return
    // true, if not, return 0.
    //
    // Don't forget to check to see if the t you calculate for the
    // ray is > 0.

    return false;
}

void polygon::CalculateNormal(void)
{
    // To Do: Use the edges of the polygon to calculate the normal
    // of the polygon. You should be careful to take care of the
    // case where two edges give you a zero normal.  Place the
    // normal into the member "n" so that the intersection method
    // can use it when called.
    //
}

```

Could someone please explain this in a bit further detail?

Note: I am not asking for anyone to write the code or do my homework for me, but instead help me understand what exactly is going on here.

Thank you.

# Answer
> 5 votes
To find the normal, you can use the cross product of three of the points in the polygon. Create two vectors from those three points and find the cross product of those.

To find the intersection of the ray with the polygon, you will first need to ensure it intersects with the plane of the polygon. To do this, you will need to do some algebraic manipulation of the equation of the plane as seen here.

Your ray should be defined as R0 + tV = P, where R0 is the origin of the ray, V is the direction of the ray, P is an arbitrary point on the ray and t is an arbitrary parameter.

The plane has the equation P . N + d = 0, where P is an arbitrary point on the plane, N is the normal of the plane (calculated earlier) and d is the vector offset from the origin.

We want to substitute the ray equation into the plane equation (replacing P) to get: (P0 + tV) . N + d = 0 and find the value of t:

t = -(P0 . N + d) / (V . N)

then you substitute that value of t back into your ray equation to get the value of P:

R0 + tV = P.

Finally, you want to go around each adjacent pair of points in the polygon checking that P is inside the polygon, which is done by checking that P is to the same side of each line made by the points.

When the instructions say to check that the point "to the left of every edge", imagine that you rotating the polygon and testing the edge that is the right-most. That might help you understand why we test that the point is always on the left of the edge.

---
Tags: c++, intersection, raytracing
---


# Question
Title: What scoring system should I use in my game?
I'm trying to determine how good a player is getting throughout his gameplay and hopefully adapt the level of the game to his expertise. Currently I have a scoring system. For example, if the player collects tokens he gets scores, if he's hit by a monster he looses score etc.

I'd like to log this score based on time(time = the amount of time passed since player started playing), and compare previous plays to the current gameplay score at any given time. If i see that the player's score is much higher than usual I'll adapt the gameplay to challenge him, and the other way around of course.

As to the question. I'm trying to understand what module would be best for:

1. Building the previous score per time values. For each gameplay I'll have to update the previous score per time with the new score with some mean. I'm just not sure which one I should use? (should I keep separate values of last two game plays and all the rest, and then give more weight for last games when calculating the means?)
2. How should I detect significants? What would be the best way to detect player is playing much better or worse?

Also, if anyone could refer me to good tutorials, essays, etc. I will be very greatful.

Thanks

# Answer
I think what you are looking for is Statistical Change Detection.

I remember we studied such things in our Bachelor degree, for applications such as detecting when a machine is behaving slower than usual.

Although I have been unable to find any paper explaining our method, it would work like this:

In order to detect an statistical relevant change in a process, you keep a record of the last X measures of your process (on this case score). Then, you compare the value of the last measure with the average of all of them. If this value is above or below 2 times the standard deviation of the series, then an statistical change has occurred.

The problem with this method is that it is very sensible to anomalies. Just let your friend play one game and you can suddenly jump in difficulty. In order to avoid this, it is advisable to compare the average of the last Y values, with Y significantly smaller than X, with the total average.

To put a concrete example, you could store the last 20 scores obtained by your player. Then, you compute the average and the standard deviation. Finally, you compute the average of the last 3 played games. If this average is more than 2 times the standard deviation from the total, you can safely deduce that your player has improved significantly, and then increase difficulty.

Playing around with the parameters such as the number of scores stores, the number of last scores used for the measure and how many standard deviations to use for the comparison can be used to tune the sensitivity of the system.
> 3 votes

---
Tags: scoring
---


title: Server to client update rate

text:
# Question
Title: Server to client update rate
I am building a game that uses client-server architecture and have the following question regarding server to client updates.

Currently the server is doing 60 ticks per second and is sending updates to the connected clients after every step, this means information about every entity that is in the world. Since my game is rather slow and rts based, a lot of the entities do not change state after every step and do not need to be updated. So to reduced server load I added an update queue. Only entities that require an update are added to this queue and it is executed after each step.

Looking at this approach I wonder if there are any significant disadvantages to it. One I could think of is that maybe as the time goes by and the game gets more complicated all the entities will need to be updated on every step anyway and that might be just a waste of time to implement.

# Answer
> 1 votes
You're worried that if you optimize something now, it might turn out to be wasted effort in the future.

But more importantly, if your system is working now, as-is, then it's wasted effort here in the present!

That said, minimizing server-client traffic is generally a good idea, especially if the clients are out in the real world, on unknown networks, and so on. In that case you'll also need to deal with recovering state from short outages and crashes, so at least sometimes you'll probably need to send the entire state.

But for now, if it works as-is, stop, and move on to the next bit.

---
Tags: networking, multiplayer, mmo, server, client-server
---


# Question
Title: Can we use credit card/prepaid voucher payment systems in Android and iOS?
We already have a credit card gateway with a local bank. We also have a prepaid card voucher in the market.

In our game, a user will create an account within our portal. The user will "recharge" his account via credit or prepaid (voucher) cards. Then the user will buy services and subscriptions.

My question is: can I put our credit and prepaid card gateway in our Android and iOS apps in order to recharge a user account that belongs to our portal?

# Answer
Apple's guidelines are very strict. Relevant points include:

> * Apps utilizing a system other than the In-App Purchase API (IAP) to purchase content, functionality, or services in an App will be rejected
> * Apps offering subscriptions must do so using IAP, Apple will share the same 70/30 revenue split with developers for these purchases, as set forth in the Program License Agreement
> * Apps that link to external mechanisms for purchases or subscriptions to be used in the App, such as a "buy" button that goes to a web site to purchase a digital book, will be rejected

For Android, it may matter which store you sell through; you didn't specify. Google Play's content policy says, of in-app purchases:

> * Developers offering virtual goods or currencies within a game downloaded from Google Play must use Google Play's in-app billing service as the method of payment.
> * Developers offering additional content, services or functionality within another category of app downloaded from Google Play must use Google Play's in-app billing service as the method of payment, except:
>     + where payment is primarily for physical goods or services (e.g., buying movie tickets, or buying a publication where the price also includes a hard copy subscription); or
>     + where payment is for digital content or goods that may be consumed outside of the app itself (e.g., buying songs that can be played on other music players).

So basically, For iOS the answer is definitely no. For Android in the Play store, the answer is also no. In both cases, you can't charge users directly via your own payment portal. You'll have to use the in-ecosystem IAP mechanisms available to you and convert that into appropriate tokens for representing purchases on your back-end.

I'm having a harder time finding the relevant guidelines for other potentially-applicable Android stores, such as the Kindle store (the guidelines are here, but they don't seem to explicitly call out that you *must* use the Amazon API for purchasing -- only that Google's API will not work).
> 3 votes

---
Tags: android, ios, in-app-purchase
---


# Question
Title: Copying a texture's colors to a new texture to create a new sprite
Let `mySprite` be some .PNG sprite:

```
Texture2D tex = mySprite.texture;
Sprite sprite = Sprite.Create(tex, new Rect(0,0,tex.width,tex.height),new Vector2(0.0f,0.0f),1.0f);

```

The resulting sprite can be used by a `SpriteRenderer` just fine. Now, let's do something a bit more redundant:

```
Texture2D tex = mySprite.texture;
Texture2D tex2 = new Texture2D(tex.width,tex.height);
Color[] colors = tex.GetPixels(0,0,tex.width,tex.height);
tex2.SetPixels(colors);
Sprite sprite = Sprite.Create(tex2, new Rect(0,0,tex.width,tex.height),new Vector2(0.0f,0.0f),1.0f);

```

All I am doing is create a new texture, copy the original texture's colors, and then used this new texture to create my sprite. However, when I use this sprite with a `SpriteRenderer`, all I get is a grayish rectangle.

What is wrong with this code?

# Answer
Found the issue. You have to use

```
tex2.Apply();

```

For the `SetPixel()` changes to take effect.
> 1 votes

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


title: get View from LibGDX for Android

text:
# Question
Title: get View from LibGDX for Android
I am making a LibGDX app, and I need to get the view to put to an Android app. Here is the code to get the view:

```
package jangkoo.game.shadowfiend.android;

import jangkoo.game.shadowfiend.ShadowFiendGame;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class LibGdx extends AndroidApplication {
    private static final String TAG = "LibGDx";
    public View view;
    Bundle savedInstanceState;
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        if(savedInstanceState == null)
        this.savedInstanceState = getIntent().getExtras();
        Log.e(TAG,savedInstanceState + "");
        super.onCreate(savedInstanceState);

        AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
        view = initializeForView(new ShadowFiendGame(), config);

    }
    public LibGdx(){
        onCreate(new Bundle());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        }
}

```

And I want to get the libGDX.view from this,for a class that doesn't extend AndroidApplication.

```
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    interstitialAd = new IntestialAds(this);
    inflater = LayoutInflater.from(this);
    config = new AndroidApplicationConfiguration();
    libGdx = new LibGdx();
    Log.e(TAG,libGdx.view + "");
}

```

However, the onCreate function has nullpointer exception. How can I handle this?

# Answer
I don't know if this is the Problem, but your LibGdx.onCreate() is calling LibGdx() which calls the onCreate() again.
> 1 votes

# Answer
If you mean by view the screen size / viewport , you could use the ScreenViewport function of libgdx.. ScreenViewport (LibGDX API)
> 1 votes

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


# Question
Title: Animated examples of different interpolations formulas: any link?
I remember having spotted a link to a huge page with different equations to non linear interpolation curves, for example if you want to stop a car smoothly, etc.

Those can sometime be useful to emulate some real-world acceleration/velocity behaviors without the help of a physics engine, which can really simplify the code.

Any idea where this page is ? I can't manage to give google the right keywords...

EDIT: I just searched on my previous laptop bookmarks, and I found it: http://sol.gfxile.net/interpolation/

# Answer
I found it mate. http://sol.gfxile.net/interpolation/
> 3 votes

# Answer
If you had searched for "easing formulas" it would've been the first result.

http://www.gizma.com/easing/
> 10 votes

# Answer
This might be the one: http://hosted.zeh.com.br/tweener/docs/en-us/misc/transitions.html
> 2 votes

# Answer
There is a realtime WYSIWYG interpolation editor: http://inloop.github.io/interpolator/
> 1 votes

---
Tags: mathematics, physics, simulations
---


# Question
Title: Find a position within one radius, but outside other radii
I have an **Object A** which will attempt to stay within a certain distance of another **Object B**. I would like **Object A** to also try to stay outside a certain distance of one or more other **Objects R**.

The idea behind this question is the desire for a companion AI to follow the player around and provide support, but also try to stay out of the attack range of enemies.

Using the image above as an example, we'll say the distance/radius within which we want to stay to **Object B** is represented by the blue circle. The distances/radii we want to stay outside of for **Objects R** are represented by the red circles.

How can I find any point (perhaps the closest point? or the point least crowded by red circles?) in the blue circle that is not overlapped by a red circle?

Furthermore, approximately how expensive would it be to calculate these kinds of details?

And how would the answer(s) to the questions above be affected if we used spheres instead of circles (3D instead of 2D)?

I use Unity and C#, so please keep that in mind if you provide specific code examples. Thank you.

# Answer
This is an interesting problem. I can think of two mechanical (brute-force-ish) approximate approaches. My math-fu is not strong enough to opine if an analytic solution is practical here. I hope there is such an approach! But here’s my “just get it done” suggestions.

**By Gridded Area, approximate**

We only care about the blue area. Represent that to the desired resolution, as a 2 dimensional array of “blue” or “not blue”, and start it with your circle. Then knock out red circles one by one. Any blue left is not in red (within the grid resolution).

*Improvement 1.* skip red circles that don’t intersect, dist(center1,center2) \> (radius1 + radius2).

*Improvement 2.* instead of just Blue or Not-Blue, store a “distance from red center”, and when knocking red areas out, also fill in the whole blue area with the minimum distance to any of the red centers. Now the highest remaining blue cell is the “least crowded”.

*Improvement 3.* Keep the blue cells in a linked list, and knock out ones that are in red. For each new red circle, just walk the still-living blue cells.

Could work in 3d, but the resolution is even more expensive. The spheres would be sets of cubes, minecraft-style.

**By Polygon, approximate**

Represent your circles by N-gons, with whatever number of sides is “good enough”. Use boolean operations to carve away the blue area. Remaining blue polygon is blue, but it might have no sides left, meaning no safe blue area left. http://en.wikipedia.org/wiki/Boolean\_operations\_on\_polygons has some notes on this, and links to boolean-operation libraries.

Could work in 3d, but, those boolean ops are even more expensive.

**By Spring Forces**

If the red circles/spheres are not necessarily absolutely solid, or if they represent zones of danger, another approach would be to apply forces of various kinds. If your companion object A tries always to move towards B, but is forced away by R, it will tend to find a way to get to B. This will work best if everything is moving, since "unsolvable" positions may get another chance. Something nonlinear pushing away from the the R circles, from gentle nudges far away, to "impenetrable" when A is at their actual physical boundary, would be appropriate.

**To conclude…**

If this is for game collisions, the grid or polygons may be good enough, especially for a low resolution or low polygon sides. (If this were an abstract math question… my answers would be unsatisfying.)

For a game AI, though, perhaps some variation on the "spring forces" might serve better, giving the object some lively and persistent motions. The simplest force would have your "companion" object A just follow a greedy path, and aim straight for B until it hits any of R, and then stop or slide around the Rs.
> 2 votes

# Answer
Try to get the sphere equations with respect to world space for each sphere like a sphere with radius r and centre (a,b,c) in WorldSpace Coordinates will be represented by the equation (x - a)^2 + (y - b)^2 + (z - c)^2 = r^2 then find the common portions and subtract the equations to get the blue part and any solution of the remaining equation will be a point. But you better write it down on paper and work out the math first instead of trying to write the program itself. Regarding the performance part, it really depends on how well you are able to solve the equations. Good Luck.
> 0 votes

---
Tags: c#, unity, collision-detection, ai, collision-avoidance
---


# Question
Title: Android appstore developer account, to not charge then change
The idea of charging for my early releases doesn't sit well with me, but at some stage, I will want to devote more time to games dev activities, when I will need it to be rewarding.

On the Play Store site a lot of options become locked once the app is published. Can this be revised at a later date? Thanks, I'd rather not worry about money already.

# Answer
> 3 votes
You can change the price at any time, or make it free if you like. Also, you have the option of uploading your app under a different name. This is done often as demo/pro versions, where one is free and the other is paid.

# Answer
> 0 votes
Personally, I'm no real fan of "cripled" or ad-riddled "lite" versions of games and other tools.

How about you don't worry about this for now. If you'd like to give your game away for free to build a fanbase, try out the whole process, test new things, and possibly establish your own setting/game world/community, go on and do so. Don't worry about earning money with it now, if you don't have to! That's the big power/advantage of small, *independent* developers.

Then later on, once you've got an established fan base and know you can dedicate more time to it and make some money by selling the game, create a sequel or expansion, that gets your players a significant update/boost over the previous free version, and start selling it (at a reasonable price). You could even do this using in-app purchases then - just like DLC on consoles or PC.

This way you won't have people complaining about a free game going pay to play and at the same time you don't intentionally (or unintentionally) criple the experience of people who are potentially interested in trying (or even buying) your game.

Don't forget that things such as nag screens or "whops, you can't continue playing unless you pay me" messages are everything but user friendly and might turn off many potential fans.

---
Tags: android, monetization
---


# Question
Title: Cover Screen with Snowing Effect in Libgdx
Oddly enough I cant find clear instructions on this theme (I only found rain and the method is very particular) so I ask, how do I implement a whole-screen snow-falling effect?

The methods i can think off the bat are:

-Using LibGDX's Particle System: But it seems like it will be overkill for some reason, i need the snow all over the screen and i have the idea that particle system is only optimized for ephemeral occasional particles (correct me if im wrong)

-Draw a giant animation that fills the entire screen Well, it also seems quite overkill... and it sounds hackish and dirty.

Id like a smooth effect, like a snowstorm, I cant think of any optimal method nor I have great experience in particles to be honest. So, any ideas?

P.S: The game is mainly for android, which is why Im so worried about an optimal solution

# Answer
The particle system solution is likely the one you want as creating and maintaining 100+ sprites with varying positions and gravity is exactly what a particle system does. Only it will handle object re-use for you automatically which will help make it as efficient as possible.

Just create a line emitter that covers the entire width of your viewport. Place it slightly above the top of the camera viewport so that spawned snowflakes appear to drift into the frame. Give the particles a downward gravity and give them some horizontal jitter to simulate a drifting movement. Give each snowflake a random scale to simulate some sense of depth. You could even base the strength of gravity based on that scale to give a proper parallax. Maybe even lower the opacity of each particle based on how low the scale is to increase the sense of depth?
> 6 votes

# Answer
Im using LibGDX particle system for a snow effect. Here's the draft file. This will need some tuning but it's a good start.

In this effect the png get some light blue tint.

You can simply import it

```
ParticleEffect snowEffect = new ParticleEffect();
snowEffect.load(files.internal("snow_effect"), [files.internal("particle.png")][2]);
snowEffect.start();

```

have to call the start method ...

and in the render loop you should call

```
snowEffect.draw(batch, deltaTime);

```

This will update then draw the effect.

There's a simple draw without the delta time, in that case you have to call the `effect.update(deltaTime)` before it.

PS: you need to position it to the top of the screen and match the width.
> 3 votes

---
Tags: java, android, libgdx, particles
---


title: Confusion over GLViewport

text:
# Question
Title: Confusion over GLViewport
I'm hoping someone can help me understand the **GLViewport** and what happens when we resize it

This will illustrate my confusion....

So, here I have a quad stuck in the middle of the screen. If I have my GLViewport match the device's width and height, I get what is on the first (left hand) picture. Exactly what I would expect.

* Device resolution, 2560 x 1600
* Viewport resolution 2560 x 1600
* Quad size 200 x 200 (Note, the image above is not to scale!!! :-))
* Quad shape, appears as square

Now, for the 2nd (right hand) picture...

* Device resolution, 2560 x 1600
* Viewport resolution 2560 x 1200 (and centered vertically)
* Quad size (200, 200)
* Quad shape, appears as rectangle

My question is, why is the quad displaying as a rectangle now and not a square? I've confirmed by logging that my quad is 200 x 200 pixes - surely the size of the physical pixels stays the same? They can't change. So what is going on here?

I thought (clearly incorrectly) that when I scaled the viewport, it literraly just chopped off pixels.

Would appreciate if someone could explain how this works.

**Edit**

Currently, I'm setting my viewport like this:

```
width = (int) Math.min(deviceWidth, deviceHeight * 1.702127659574468);
height = (int) Math.min(deviceHeight, deviceWidth / 1.702127659574468);

ratio = width / height;
GLES20.glViewport(offsetX, offsetY, width, height);

Matrix.orthoM(mProjMatrix, 0, -ratio, ratio, -1, 1, 3, 7);

```

offsetX and offsetY are just so that when there are letterboxes, the viewport is centered.

# Answer
To understand what's going on, you have to understand the rendering pipeline:

Your geometry (the quad) is initially defined in world space, think of this as some global coordinate system. Inside of the vertex shader those are transformed to normalised device coordinates (NDC), a virtual coordinate system defined so, that everything from -1 to 1 will get drawn to the screen. Note, that NDC is ranging from -1 to 1 in X and Y, and it's totally independent of the devices aspect ratio and resolution. This transformation from world space to NDC is done by the model, view and projection matrix (in a simple form, just one matrix for everything or the geometry was even defined in NDC to begin with!).

The rasterisation unit needs to know where and how large it should raster and this is what you define with the glViewport call: where to start are the first two parameters, the size are the second two. The hardware will then convert from NDC to pixel coordinates by a simple scale and shift - and this is what you see in your example: a scale in the Y axis.

So to make sure your quad gets rendered in the correct aspect ratio, you also need to adjust the projection matrix to include the expected aspect ratio of the glViewport call.
> 13 votes

# Answer
In your call to glViewport you are specifying less pixels in width and height. Your projection matrix is defined in terms of pixels. That's why you will have to calculate a new projection matrix after a glViewport call.
> 0 votes

# Answer
For first picture:

1. We are creating projection matrix. For example, the parameters used are: Left1, Right1, Bottom1, Top1, Near1, Far1. Here, Aspect\_Ratio\_1A = (Right1 - Left1) / (Top1 - Bottom1);
2. Then we are doing a view port transformation. For example, the parameters used are: Width1, Height1. (I am not mentioning shift parameters for simplicity). Here, Aspect\_Ratio\_1B = Width1 / Height1;

For second picture:

1. We are creating same projection matrix with same parameters as before. So: Aspect\_Ratio\_2A = Aspect\_Ratio\_1A;
2. This time the view port transformation is having different parameters: Width2 and Height2. Here, Aspect\_Ratio\_2B = Width2 / Height2.

We note that Aspect\_Ratio\_1B and Aspect\_Ratio\_2B are different. Specifically they are:

Aspect\_Ratio\_1B = 2560 / 1600 = 1.6 Aspect\_Ratio\_2B = 2560 / 1200 = 2.13

So, if we summarize what we are doing for the second case is:

We are projecting the image onto a plane with Aspect\_Ratio\_2A and before showing it to user, we are scaling it to Aspect\_Ratio\_2B. Other users are asking us to correct our projection matrix in such a way that the Aspect\_Ratio\_2A = Aspect\_Ratio\_2B.

We can also read Robert's comments a couple of times to have a better understanding.

Also, I cannot agree that the red quad in the second picture has a 200 by 200 pixel size when drawn on the screen. Since we know, a pixel is a square, if the quad has one of the sides longer than the other, the longer side takes more pixels to be drawn for sure. I, personally, do not know what logging is, but may be it doesn't return screen pixel size.
> 0 votes

---
Tags: opengl, opengl-es2, viewport, aspect-ratio, scale
---


# Question
Title: Installing Unreal Engine 4 in Ubuntu -- setting OAuth
https://wiki.unrealengine.com/Building\_On\_Linux

When I run ./GenerateProjectFiles.sh I get this:

Github build Checking / downloading the latest archives

Please set OAUTH\_TOKEN You can generate an access token at https://github.com/settings/tokens/new It must have repo scope

I have the token, how do I "set" it?

# Answer
This is actually something that's not specific to Unreal Engine 4. OAuth is an authorization token so you don't need to log in with credentials. You first need to generate this token using your credentials. As your error message shows, you need to set your token. Before you set the token, you need to generate it. You do that at the link provided in your error.

Now that you have a token, you need to set it. As stated in the instructions found in your first link:

> Create a new personal access token here: https://github.com/settings/tokens/new and set OAUTH\_TOKEN environment variable to it.

Information for setting an environmental variable can be found here. Basically:

```
OAUTH_TOKEN=pathToToken

```
> 2 votes

---
Tags: unreal
---


# Question
Title: List of 3 letter English words to disallow from entry for public kids game
I saw this post about a profanity filter for an mmo chat.

In my case I've got a game played in public, mostly by kids. The only text they can enter is their initials A-Z, 2 or 3 letters.

With only 2 letters I think I'm safe. But, I'd prefer 3. Alas, 3 letter nicknames would allow for such names as `ASS`, `FUK`, `COK`, `DIK` and `SHT`, `CNT` etc. although the last few are more open to interpretation than the first. I'd just like not to get negative feedback from parents or other adults. I saw the lists linked to above didn't include `FUK` so I'm wondering whether anyone knows of a list that only includes 3 letter words, maybe left over from arcade machines or something.

Note: I've displayed the game in public before with adults with a 20 letter limit and without fail 1 or 2 people will put `8======D~` or some short rude sentence. While I don't care with adults, the next event will be 5-15yr old kids, their parents, and also adults without kids. So if there is a list of 3 letter words to avoid I'd allow 3 letters. If I can't find such a list I'll probably just go with 2 and avoid the problem.

Anyone know of such a list?

# Answer
> 6 votes
Note that in addition to vulgarity other words may be inappropriate, for example "KKK" or "LSD".

It may also pay to consider any local sensitivities for demographics you are targeting, for example if releasing a "gun game" in the United Kingdom or Ireland I would consider "IRA", for Chicago would consider "CPD"

---

Kenneth Hurley has a *very* comprehensive list of bad words included in the ElementalEngine2 repository on GitHub.

The author has indicated these can be used freely.

---

Another good source of candidates for consideration is the blacklists used by vehicle licensing agencies when issuing license plates. The lists as provided by the DMVs of a number of US States have been collected by Government Attic and published here (California is a good example).

# Answer
> 17 votes
If the kids are supposed to enter their initials, I don’t think you should block any combination. On LinkedIn, there are 25 professionals named Carol O’Keefe. How about Andrew S. Schwartz?

If you want kids to be able to choose an online identity without allowing profanity, you could consider a pre-determined combination of icons, animal pictures, colours, etc. instead.

# Answer
> 1 votes
The bad words and Elemental Engine2 is completely open source BSD/Mit like licensing. You can do with it what you want to, commercial, private, etc.

If you don't like the original license for some reason, just let me know

---
Tags: leaderboards, community-management
---


# Question
Title: Trigger scene loading in one device from another device using Unity WWW class
I have a master device and client device. I want to load a scene in the client device by pressing a button in the master. My method is, when the button is pressed in the master device, a data is stored in a server using the WWW class and in the client device it is checked whether the data is there, through a coroutine.

But, in the client device, the coroutine is not waiting for the trigger from the master. Instead it continues the execution. Because in the `yield return` statement, it says downloading is complete. Can I make it to wait for a trigger from the server?

# Answer
Eventually found out. Turns out it was very basic. This is probably not an efficient way, but it serves the purpose.

The problem was the `yield return` statement returns a value immediately without waiting for confirmation from the master device. To solve this, take the value and check if it is indeed the value we require, if not call the coroutine again with fresh WWW object.

For example:

```
void Start()
{
    CallCoroutine();
}

void CallCoroutine()
{
    WWW w = new WWW(URL);
    StartCoroutine(RequiredCoroutine(w));
}

IEnumerator RequiredCoroutine(WWW w)
{
    yield return w;

    if(w.error == null)
    {
        // extract value from the json (value which was set through master device)
        if(value == requiredValue)
        {
            // load scene
        }
        else CallCoroutine(); // start again
    }
}

```

Hope this helps someone. :)
> 1 votes

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


title: How can I view an R32G32B32 texture?

text:
# Question
Title: How can I view an R32G32B32 texture?
I have a texture with `R32G32B32` floats. I create this texture in-program on D3D11, using `DXGI_FORMAT_R32G32B32_FLOAT`. Now I need to *see* the texture data for debug purposes, but it will not save to anything but dds, showing the error in debug output, "Can't find matching WIC format, please save this file to a DDS".

So, I write it to DDS but I can't open it now! The DirectX texture tool says "An error occurred trying to open that file".

I know the texture is working because I can read it in the GPU and the colors seem correct.

How can I view an `R32G32B32` texture in an image viewer?

# Answer
> 2 votes
The only way I could find to view a 96 bpp texture was using NVIDIA's DDS plug-in direct download 64-bit, 32-bit.

It's important to use the right bitness of the plug in, otherwise it won't work (which is what I found before)

# Answer
> 4 votes
How about using PIX for Windows? That's probably the easiest way to view your texture.

As a bonus, you can right click your texture and "Save Picture As..." to shelve it for later, if that's something you need as well (though I'm not sure this will handle a R32G32B32 format).

# Answer
> 4 votes
The DDS file format changed between dx9 and dx10. dx9 had been supporting a lot of new features via kludges, these new features were finally added as full types with the switch to DXGI. What this means is that most existing DDS viewers do not support any of the new texture formats or even files saved from DirectXTex. (The new semi-open source microsoft library for manipulating DDS files. )

DirectXTex has a command line tool called DDsView.exe that can view all file formats.

# Answer
> 0 votes
From what I can tell the old DX texture tool doesn't support this format - it's certainly not available in the list of formats to convert to. What *is* available, however, is R32G32B32A32 float, and I've tested a little and determined that it can indeed convert to, save as, and subsequently re-open using it, so you could try converting to that format before saving.

---
Tags: textures, directx11, gpu, floating-point
---


# Question
Title: c# Unity - Matrix output incorrect on vector rotation
I have a input Vector (1,1,0) when I run it through a Unity Matrix4x4 class with a rotation of 90 degrees around the Z axis the output is (-0.9999999,1,0) which is nearly correct but strange. But (2,0,0) with the same degrees and axis rotation I get (1.192093e-07,2,0). The Y vector coordinate is correct, but why on earth is X set to 1.192093e-07? I cant explain why this is happening. I thought it would be set to (0,2,0).

The code I am using

```
using UnityEngine;
using System.Collections;

public class test : MonoBehaviour
{
public Vector3 translation;
public Quaternion rotation;
//public Vector3 eulerAngles;
public Vector3 input;
public Vector3 output;
public Matrix4x4 m;
// Use this for initialization
void Start ()
{
    //transform.rotation = Quaternion.Euler(60F, 0, 45F);
}

// Update is called once per frame
void Update ()
{

    input = new Vector3 (2, 0, 0);
    rotation = Quaternion.AngleAxis(90, Vector3.forward);
    m = Matrix4x4.TRS (Vector3.zero, rotation, Vector3.one);
    output = m.MultiplyPoint3x4(input);

    }
}

```

You can see Vector forward is the Z axis. I have scale as (1,1,1) and no transformation set. I have Unity set to 2D view. I have a main camera with a Orthographic view, clipping plane near is 0 and far is 1000 and its depth is -1, its vector is (0,0,0).

When I use (2,0,0) as the input this is the result of the matrix

\[E00\] = 5.960464e-08 \[E01\] = -0.9999999 \[E02\] = 0 \[E03\] = 0 \[E10\] = 0.9999999 \[E11\] = 5.960464e-08 \[E12\] = 0 \[E13\] = 0 \[E20\] = 0 \[E21\] = 0 \[E22\] = 1 \[E23\] = 0 \[E30\] = 0 \[E31\] = 0\[E32\] = 0 \[E33\] = 1

# Answer
Floating point math is not perfect. You're trying to compress an infinite set (all real numbers) into an *extremely finite* space (32 bits).

Consequently, not every number can be accurately represented, and some numbers will suffer from rounding error. Basically, as you do increasingly more math on some particular value, you increase the chance(\*) that the resulting calculation will drift in some form. This is why, for example, you don't want to represent successive rotations of objects by doing something like:

```
transform = transform * rotation;

```

Even if you have pure rotations in there, over many successive frames you may introduce enough error in the computation results that you start to observe distortion in the final model due to the fact that your error is introducing, effectively, scaling or shearing terms.

The math you're doing involves several multiplies, adds, and transcendental functions (sine and cosine). It's not unreasonable that certain inputs will result in errors carried through those computations that result in a technically-mathematically-incorrect answer.

The values you are reporting seem sufficiently close as to be considered normal, in practice, however. If this is not actually causing observable problems in your game, I wouldn't worry about it.

(\*) I say "chance" lightly; for a fixed set of inputs, a computation will be deterministic on a particular machine, but when you don't know the potential inputs it becomes much harder to determine if you'll get rounding error and such, so the amount of practical observed error can appear "random."
> 1 votes

# Answer
When you create a rotation matrix or quaternion from an angle, you are actually taking the sine and cosine of a numeric value *in radians*. Your value in degrees is being converted to radians, so 90 degrees becomes π/4.

π is not something that can be represented accurately in floating point. This is where the accuracy loss is coming from.

If you take the sine or cosine of that slightly inaccurate angle, the result is slightly inaccurate, and any transformations you do with it will also be slightly inaccurate.

As Josh Petrie says - this inaccuracy usually does not matter, so long as you avoid accumulating the error.

If you need an exact rotation by 90 degrees, you can manually construct an exact transformation matrix for that *specific* case (because `sin(90°) = 1` and `cos(90°) = 0`).
> 0 votes

---
Tags: c#, unity, matrix, vector
---


# Question
Title: Generate race track using freeform curves
I am trying to generate a race track in Vertex Shader(constraint) and only using B-Spline/Bezier/Hermite curves. My problem is that when i try to widen the obtained curve by translating another instance of it (lets say translate the x value), at certain turns, the road gets thinner.

As input, i can only have a certain number of control points/knots with which to generate a 2-degree closed(start point = end point) curve B-spline. The closed curve (translated on Z) is shown in the picture attached. The camera is positioned right above it. Every vertex from the curve has Y = 0, seeing how the track is flat without any height(no perspective view).

Is there any possible way to keep the road's width on all its sections?

# Answer
This is a known issue. One of the best and most suitable solution would be to use a library like this one Clipper

There are other known ways that are more complex and not open source yet.

http://www.angusj.com/delphi/clipper.php

Another solution would be to form the track as a spline from Béziers and then convert it to a rigid spline by sampling points along the path. You then use this point with the vector of their approximate direction of flow which could be computer by deducting the previous point from the next point on the road to compute where the left and right sides of the road need to be. To get a smoother result, apply a Bézier on the resulting borders like this: How do I generate a smooth random horizontal 2D tunnel? and add a bit of noise too.

In this step you extend the sampled points on the spline into egdges by picking two points in a 90 degree angle from the direction of the spline.

@Trilarion
> 2 votes

# Answer
Instead of simple shift, you need to widen the track by calculating a perpendicular in every point and shifting the contours along it inside and/or outside.
> 1 votes

---
Tags: curves
---


title: How to spawn multiple enemies?

text:
# Question
Title: How to spawn multiple enemies?
I can store it in an array, ok, but after how can i paint it? Because if i do
enemy = new Enemy();
enemy2 = new Enemy();
i create two istances of the object, but afer how can i paint it?
I use:
g2d.drawImage(Enemy.getImage(), Enemy.getX(), Enemy.getY(), this);
But obviously it use the class, not the variable.
Images will not be overlyed because coordinates are random.
Excuse me my terrible english.

# Answer
Basically, you'll need some kind of container or collection to hold all entities. Then create some spawn or factory function to actually add them.

When drawing (or updating) your game entities, you'll just iterate through this list and modify them accordingly.

Here's some pseudo-code example:

```
List<Entity> entities;

function spawnEnemy(position pos) {
    entities.push(new Enemy(pos));
}

function updateEntities(time delta) {
    foreach(Entity entity : entities) {
        entity.update(delta);
    }
}

function drawEntities() {
    foreach(Entity entity : entities) {
        screen.draw(entity);
    }
 }

```
> 3 votes

---
Tags: java
---


# Question
Title: How can I allow players to draw decals for their avatar and items?
I want the player to be able to draw a simple symbol, even if it's pixelated black or white, that their character can have on their weapons, armour, forehead or even markers and monuments. How would I go about that, if I want to do it? Better if the suggestion is C#/Unity-specific.

PS: The game would be a turn-based, square grid RPG, maybe somewhat like Dofus, but it should probably be in 3D to allow for more flexibility.

# Answer
> 1 votes
You should probably let player use their own tool and allow them to mod/upload an icon for this purpose into the game. Drawing it in game, is a matter of tracking the mouse position and clicks, designing the drawing tools gui and simply adding and removing pixels at position (x, y). It is not complicated but sounds like a waste of time if you could allow them to upload an existing image that was created with a good tool. This depends on the budget of time / hours you have set for you game and how critical the painting of symbols is to your goals.

To place textures on top of existing ones, I would suggest you add a rectangular mesh to the model where you want the symbol to be and add the icon with a transparent background as a texture for that mesh.This should work well for starters and save you the trouble of writing extra code.

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


# Question
Title: How does one make games playable before they are fully downloaded?
*Diablo 3* and *StarCraft 2* have a nice feature: I can start playing before the full game or update has finished downloading.

I guess *Diablo 3* downloads mandatory files like like UI assets and some meshes and textures that are used across several levels first. However, when starting a game, I can choose any level I want, assuming I have appropriate saves. I never experienced any lag from such when playing—starting is always very smooth.

How does this work? How could I implement a similar feature?

# Answer
> 72 votes
Assets such as sound, video, models, and textures are a majority of the download and for each of these assets there are multiple versions. These multiple versions are to support various graphic options.

By sending the assets needed for a low graphics option first (which also happen to be the smallest ones). You have everything you need to play the game despite having only 15% or so of the total assets needed to support every graphics option.

You can test this by re-installing StarCraft 2. Play it as soon as it will let you then go to the graphical options screen. Many options and setting will be unavailable.

# Answer
> 34 votes
I once implemented this for MMOs. One weekend while attempting to install WOW for my daughter took 48 elapsed hours, (patches, download errors, etc.) so I decided to make my own better solution.

The game usually needs say 10 GB of data before it will run. Not all files are actually needed right away, but games used to wait until all files were locally present. My solution was to have the game run locally as normal, but the EXE was tricked (using a Windows file minifilter) into thinking all files were already present. When a requested file was not local, the file system downloaded it and saved it. The game was slowly copied locally as needed. When there was available bandwidth, the other not yet needed files were trickled in in the background. This worked with ALL games without the need to recompile, because my minifilter driver got files when needed.

The worst drawback was latency. My solution to that was to create a small Markov Chain model to predict which file might be needed next, and prioritizing the background loader. This worked like a charm, and our MMO was able to run almost IMMEDIATELY after just the EXE and a few loading screen files were local (~20 MB). We were able to click a link on a webpage and **run our 10+ GB game in about 30 seconds**. We had a 99% hit rate, meaning when the game needed a new file for the first time it was already there!

I'd be happy to help anyone else implement this.

# Answer
> 3 votes
Also in some games end-game world areas and files are delayed, only the mandatory areas are kept, and can also be installed while still playing the game.

# Answer
> 2 votes
To summarise what several people have said, and maybe add some information:

* initial download is small, just the startup files and download manager for the rest. Would be nice to include account creation, avatar creation, and maybe the start zones in this.
* while that's running, the user is logging in and creating their avatars, start downloading other stuff, low level zones and common files first (like basic sounds and textures, you do reuse those as much as possible all over your game)
* as the user progresses through the levels, start pre-downloading upcoming zones and other content
* if the user selects options that need downloading, download low resolution variants first, then as he's playing download higher resolution versions as needed and replace the low res versions displayed with those on the fly. That way the user sees something, and gradually the full glory of the game is revealed (if he has enough bandwidth and computer power of course)
* repeat until everything is downloaded

It will mean a higher network load while playing, until all content is cached locally, but a smaller initial burst load on your servers as well as a shorter and less frustrating wait for users while they're initially downloading the game.
Of course if the user has a slow network connection he might still get "please wait, loading content" messages (do provide those) when switching zones, or you might want to check the bandwidth when initially starting the game and if too low to download reliably on the fly have him wait there and then for at least the entire first level (and then again when entering zones that haven't been fully downloaded yet).
This to prevent the user lagging out in the middle of actual gameplay because his network connection gets bogged down.

---
Tags: user-experience, deployment, patching
---


# Question
Title: How do I find the shape of Tiled's circles or ellipses in libGDX?
I created a level in the 'Tiled Map Editor' and loaded it into my libGDX game. I can easily transform almost all objects into Box2D objects (although this problem is not Box2D specific), but I have trouble with ellipses.

Tiled seems to only create ellipse objects, without a special case for circles. I'd be happy with just circles if they existed in Tiled.

However, even the EllipseMapObject I load in libGDX only has an `x,y` position. I don't see any information about area or vertices. Did I miss something? How can I create circle or ellipse objects in Tiled and load them into libGDX with right dimensions?

---

Tiled version 0.10.1, libGDX version 1.4.1

# Answer
> 1 votes
The 'Tiled Map Editor' sets the size (width and height) of map objects by default to 0.

For most objects this is not relevant (polylines, rectangles and triangles which are handled as polygon objects) since the vertices are important. But for circles and ellipses I had to set a real value of course.

---
Tags: libgdx, tiled
---


title: Avoiding singletons for puzzle system

text:
# Question
Title: Avoiding singletons for puzzle system
Say for instance I have a puzzle with 3 switches that need to be in some configuration (say all on) in one room, that opens a door in another, with a load screen separating, so I can't link the switches directly to the door. My first thought was to create a singleton that stored the state of each "solution element" which in this case is the switches, but could be a correctly turned knob, ect. then a given "Puzzle Gate" like a locked door would check the required solution elements to decide it's own state, but I'm hesitant to use singletons for all of the commonly given reasons.

What alternatives do I have to singletons that would give me the same or similar control?

# Answer
> 3 votes
I don't think that you should go with static class members (you didn't mention language but I assume some kind of OOP) because that just hides "singleton" in a different place.

Switch things around so your Game holds a bunch (map, set, list, array, whatever) of these across-room global puzzles. Make it so your rooms can ask the game about a puzzle it's interested in using some kind of identifier.

So instead of the linear setup of EXE-\>singletonpuzzles-\>Game-\>Map-\>Rooms you end up with a broader game layer EXE-\>Game-\>\[bunchofpuzzles+Map\]-\>Rooms

Pro: you can have multiple instances of the same puzzle class with different parameters Con: a little extra writing to create each puzzle and way to look them up by identifier

You'll notice that this "bunch of puzzles" could very well be a singleton at global scope instead of buried inside of Game but, like you noted, there are common reasons why this wouldn't be an ideal design.

# Answer
> 0 votes
I think you should keep things simple in this case. The three switch system is a challenge with a solution and this `Puzzle` has two states, currently solved correctly and currently unsolved (or solved and then reverted to unsolved for some reason \[timer?\]). So you have a `Boolean` value and you need to store it somewhere in your game so the door could get it and behave accordingly.

One generic solution would be to make the Door an observer of the Puzzle. So the Door listens to the Puzzle and knows when to open up or close. This could be problematic however since that Door does not exist at all during the puzzle phase. This means the state of the Puzzle resolution needs to be stored somewhere and passed back to the Door somehow.

This is why I would suggest a "delayed Event" system where you store a `Hash` aka Associative array and send a "message" through that Hash, for instance:

```
//In the Puzzle class,
{
    String threeSwitchPuzzle = "The puzzle with three switches";
}

// After completion

delayedEvent(threeSwitchPuzzle, success);

// Which translates to

Hash[threeSwitchPuzzle] = true;

// Construct the Door with the appropriate puzzle String as a member

// Then when the `Door` is created

if (getDelayedEvent(door.puzzle)) // behave accordingly

```

I know this is similar to the obvious solution but if you design it in a way that is legible and maintainable it should work for you and save you the trouble of overthinking this. You simply need the state stored somwhere and retrieved from that place later.

---
Tags: unity, architecture, design-patterns, puzzle
---


# Question
Title: How to deal with extremly big numbers in javascript?
I am making a idle game like http://www.clickerheroes.com/ . I am doing it using createjs html library(doesnt matter). Anyways what i want to know is how i can deal with extremly large numbers that will occur in such games (10x10^100) because javascript doesnt support such big numbers or am i wrong here?

Does anyone have experience with this?

# Answer
You use a library that handles those numbers: https://github.com/MikeMcl/big.js
> 1 votes

---
Tags: javascript, html5
---


title: trasformation matrix for model's bones

text:
# Question
Title: trasformation matrix for model's bones
I was developing an fbx converter for legend of grimrock object model (www.grimrock.net), I just wanted to get the animations cause the rest has been converted by others' tools. I was reading all of their guidelines to convert from their little endian binary file to the format I want (in this case fbx) When I was about to construct the skeleton, I was stuck because of this

```
// A Mat4x3 is a transformation matrix split into 3x3 rotation and 3D rotation parts
struct Mat4x3
{
    Vec3    baseX;
    Vec3    baseY;
    Vec3    baseZ;
    Vec3    translation;
}

```

(btw Vec3 is a three dimensional vector (xyz) you can find complete specifications of their object model here)

what does "A Mat4x3 is a transformation matrix split into 3x3 rotation and 3D rotation parts" mean???? Regarding the creation of bones, I thoughtmatrix should be a transformation matrix not a rotation matrix. So I'm kinda confused. Anyway I should calculate this way? (o = origin)

```
x' = x*x1 + y*y1 + z*z1 + o1;
y' = x*x2 + y*y2 + z*z2 + o2;
z' = x*x3 + y*y3 + z*z3 + o3;

```

# Answer
If you have conflicting comments and code, either one or both of them are incorrect.

In this case, it seems likely that the `3D rotation` in the comment is supposed to be a `3D translation`.

In general, a 4x3 transformation matrix is like a regular 4x4 transformation matrix, but the fourth part with `[0 0 0 1]` is omitted for saving space and work.
> 1 votes

---
Tags: matrix, linear-algebra, fbx
---


title: FBX SDK texture file name

text:
# Question
Title: FBX SDK texture file name
I have built an importer that retrieves necessary vertex data however I wish to be able to read texture file directories. How do I retrieve the texture file name?

# Answer
FBX supports a whole range of texture *properties* per surface material: diffuse, specular, etc.. The *property name*s are stored in static char\* fields in SDK classs *FbxSurfaceMaterial*. You can get a pointer to such a material by iterating across all materials of an *FbxNode* using functions *GetMaterialCount()* and *GetMaterial(index)*.

To load a texture, you first have to retrieve a valid *FbxProperty* from the *FbxSurfaceMaterial* by querying it with *FindProperty(propertyName)*, then iterate over the number of "SrcObjects" using *GetSrcObjectCount()* and *GetSrcObject()* and for each of them retrieve the user data with GetUserDataPtr(). This user data contains the name of the texture. How you map that to your filesystem/packed data/ is up to you.

Keep in mind that most of the properties also have associated factor properties, and they can be queried with their associated names in exactly the same way. The factors are typically used to set material property weights in the lighting shader (such as specular, reflectiveness, ambient, emissive etc.. )
> 2 votes

---
Tags: c++, directx, fbx
---


# Question
Title: Getting the correct texture from an Atlas
I'm writing an OpenGL ES (2.0) app and have a custom Quad class which draws a textured quad for my sprites.

Currently, I put the textures of any sprites *of the same size* into a single file or atlas, then, when drawing, I can simply specify the frame I want. It will the render the correct frame based on how many textures in the atlas and how many total frames etc. Something like so:

```
mySprite.x = 0;
mySprite.y = 0;
mySprite frame = 1;
drawSprite(mySprite);

```

The texture Atlas would look something like this: (Simplified for the purpose of this question, in the real project, there are over 200 textures arranged in neat rows/columns, but the important thing is there is order, every texture is the same size as this is necessary for the calculations).

So, in the example above, I can say, there are 2 columns, 1 row and a total of 2 textures.

So, if I specify 1 as my texture (2nd texture), my sprite class can work out (using the columns, rows, total textures etc..) which texture I want and how to get it. As I said this is simplified, the calculations are a little but more involved when there are multiple rows. But it makes doing animations nice and simple as I can simply increment or decrement the current frame.

However, I keep seeing sprite sheets where there is no order. There are different sized textures seemingly thrown into an atlas like so:

I really would like to go down this route as it means I wouldn't have to separate my sprite sheets by object size, and therefore, vastly reduce the number of separate sheets I have to use.

I can't however work out how one would write a calculation to get the correct texture just by specifying the texture number to render.

So how does this work? Do I need to manually work out the texel coordinates of each and every object (and indeed frame), manually (and maybe store this value in an array and associate it to a frame number?) or am I missing a trick here somewhere?

# Answer
> 2 votes
Your hunch is correct.

There must be external information mapping regions of the image to sprites unless all the information the application needs can be derived from hardcoded knowledge and regularity. Even in your regular grid-based example, you lack some information for the general case.

Common metadata for sprite sheets are:

* *origin*, a location inside the sprite that indicates the logical center of it;
* *collision extents*, the collision hitbox for a sprite is often smaller than the visual, to balance gameplay fairness and how much a sprite can visually penetrate something else without colliding;
* *identifier/name*, for sprite sheets used for visuals for different objects, a way of finding which sprite in the sheet is the one desired is typically done via lookup by name/ID, the metadata would contain a mapping of these.

# Answer
> 2 votes
using a single vec4 uniform you can use arbitrary sized sprites:

```
uniform vec4 spriteLoc;//x and y is the relative offset and z and w is the scaling factor

varrying vec2 texCoord;//0-1 as you would without the atlas

main(){
   gl_fragColor = sampler2D(atlas, texCoord.xy*spriteLoc.zw + spriteLoc.xy);
}

```

---
Tags: textures, opengl-es2, spritesheet, texture-atlas, texel
---


# Question
Title: How do I make a 2D race car turn smoothly?
I'm making a competitive 2-player 2D racing game for a school project. I'm struggling with the movements of my car: I made it a square for testing purposes and it can move left, right, up or down, but it can't make *smooth turns around corners*.

How can I make my car (currently a square) make smooth movements? I've heard vectors might help, but I don't know how to use them.

I'm writing this in C# with Visual Studio.

---

My car control code looks like this right now:

```
private void Form1_KeyDown(object sender, KeyEventArgs key) {
    // player1 controls
    if (key.KeyCode == Keys.Up)     { Player1.Top -= 5; }
    if (key.KeyCode == Keys.Down)   { Player1.Top += 5; }

    if (key.KeyCode == Keys.Left)   { Player1.Left -= 5; }
    if (key.KeyCode == Keys.Right)  { Player1.Left += 5; }

    // player2 controls
    if (key.KeyCode == Keys.W) { Player2.Top -= 5; }
    if (key.KeyCode == Keys.S) { Player2.Top += 5; }

    if (key.KeyCode == Keys.A) { Player2.Left -= 5; }
    if (key.KeyCode == Keys.D) { Player2.Left += 5; }
}

```

# Answer
> 5 votes
Start by adding a variable for the angle that the car is moving at.

```
float angle = Math.Pi / 2;

```

Then add a variable for the current speed.

```
float speed = 0.0;

```

Now create three constants:

public static final float acceleration = 0.1; public static final float maxSpeed = 5.0; public static final float rotationRate = Math.Pi / 50;

For starters, get your controls *somewhat* right:

Do this every frame:

```
private void everyTick()
{
    player.top -= Math.sin(Player1.angle) * Player1.speed;
    player.left += Math.cos(Player1.angle) * Player1.speed;
}

```

Do this on key press:

```
private void Form1_KeyDown(object sender, KeyEventArgs key)
{
    //player1 controls
    if (key.KeyCode == Keys.Up)
    {
        Player1.speed += accelaration;
        Player1.speed = Math.min(Player1.speed,maxSpeed);
    }
    if (key.KeyCode == Keys.Down)
    {
        Player1.speed -= accelaration;
        Player1.speed = Math.max(Player1.speed, -maxSpeed);
    }
    if (key.KeyCode == Keys.Left)
    {
        Player1.angle += rotationRate;
    }
    if (key.KeyCode == Keys.Right)
    {
        Player1.angle -= rotationRate;
    }

}

```

This should get you started.

# Answer
> 1 votes
First use Zehelvion answer to make the car turn correctly, then:

Use the timestamp, you measure how much time it took for your last iteration and use that to modulate the speed at which you are changing things.

```
void RunGame(float deltatime)
{
    if (key.KeyCode == Keys.Up)
    {
        Player1.speed += accelaration * deltatime
        Player1.speed = Math.min(Player1.speed,maxSpeed)
...

```

This will make it much smoother even if the framerate goes up or down (why accelerate twice as fast if the framerate goes from 30 to 60 in some area?).

---
Tags: 2d, rotation, movement, vector, car
---