# Question
Title: Problem with Frustum Culling Right-Handed(LookAtRH GLM)
I am trying to do Frustum Culling based on Goemetric Approach, however don't matter how much i try, the frustrum rotate to opposite side, i tried to find a solution over all internet, but couldn't find any, really need help with this.

FOV is 35.0f (in Radians value) \[fov = glm::radians(35.0f);\] UP is (0.0f, 0.0f, 1.0f) Width : 1280 Height : 720 AspectRatio : 16:9

The API what i am using is DirectX 11, actually it works perfectly, the entire map is being rendered perfectly, if i disable frustum culling, however when i enable the frustum culling it's only rendering a part on the wrong direction.

i am doing this:

Calculate Camera View

```
UP = EVector3(0.0f, 0.0f, 1.0f);
view = glm::lookAtRH(CameraPosition, PlayerPosition, UP);

```

Calculate Frustum

```
EFloat tan = EMath::Tan(fov * 0.5f);
_NearWidth = _Near * tan;
_NearHeight = _NearWidth / _AspectRatio;
_FarWidth = _Far * tan;
_FarHeight = _FarWidth / _AspectRatio;

position = PlayerPosition; // Force frustum at player position for see where it points, if i put camera position when i move the camera the view frustum goes on different way, and it already rotates on opposite direction
direction = EMath::Normalize(PlayerPosition - _CameraPosition);
right = EMath::Normalize(EMath::Cross(direction, UP));
up = EMath::Cross(right, direction);
direction = -direction; // glm::LookAtRH does this inside, if i don't do this the frustum doesn't work, but it still going on opposite direction

EVector3 nearCenter = position + (direction * _Near);
EVector3 farCenter = position + (direction * _Far);

EVector3 upNear = up * _NearHeight;
EVector3 rightNear = right * _NearWidth;
EVector3 upFar = up * _FarHeight;
EVector3 rightFar = right * _FarWidth;

EVector3 nearTL = nearCenter + upNear - rightNear;
EVector3 nearTR = nearCenter + upNear + rightNear;
EVector3 nearBR = nearCenter - upNear + rightNear;
EVector3 nearBL = nearCenter - upNear - rightNear;

EVector3 farTL = farCenter + upFar - rightFar;
EVector3 farTR = farCenter + upFar + rightFar;
EVector3 farBR = farCenter - upFar + rightFar;
EVector3 farBL = farCenter - upFar - rightFar;

EVector3 nearTop =      nearTR  - nearTL;
EVector3 nearLeft =     nearBL  - nearTL;
EVector3 topLeft =      farTL   - nearTL;
EVector3 bottomRight =  nearBR  - farBR;
EVector3 farRight =     farTR   - farBR;
EVector3 farBottom =    farBL   - farBR;

_Planes[WP_NEAR]    = EMathPlane(EMath::Cross(nearTop, nearLeft), nearTL);
_Planes[WP_LEFT]    = EMathPlane(EMath::Cross(nearLeft, topLeft), nearTL);
_Planes[WP_TOP]     = EMathPlane(EMath::Cross(topLeft, nearTop), nearTL);
_Planes[WP_BOTTOM]  = EMathPlane(EMath::Cross(farBottom, bottomRight), farBR);
_Planes[WP_RIGHT]   = EMathPlane(EMath::Cross(bottomRight, farRight), farBR);
_Planes[WP_FAR]     = EMathPlane(EMath::Cross(farRight, farBottom), farBR);

```

EMathPlane:

```
EMathPlane(const EVector3 &normal, const EVector3 &point)
{
    _Normal = EMath::Normalize(normal);
    _Distance = -EMath::Dot(_Normal, point);
    _AbsNormal = EMath::Abs(_Normal);
}

```

all functions of my math library are redirected to GLM, for some reason the frustrum points to different area, i am doing a quadtree frustum culling, and i have static boxes prepared for each test, for example:

```
// First bounding box to check
{0.0f, 0.0f, 0.0f, // min x, y, z
25600.0f, 25600.0f, 1000.0f} // max x, y, z

// Another bounding box
{12800.0f, 12800.0f, 0.0f, // min x, y, z
19200.0f, 19200.0f, 1000.0f} // max x, y, z

```

here is the (IsVisible) function:

```
    EVector3 center = (min + max) * 0.5f;
    EVector3 half = (max - min) * 0.5f;
    EVector3 absHalf = EMath::Abs(half);

    EUInt32 isInside = 0x80000000;

    for (EInt32 index = EMathFrustum::WP_NEAR;index < EMathFrustum::WP_MAX;index++)
    {
        EVector3 &normal = frustum._Planes[index]._Normal;
        EFloat &dist = frustum._Planes[index]._Distance;
        EVector3 tmpHalf = EVector3(EMath::ForceSign(absHalf.x, frustum._SignFlip[index][0]),
                                    EMath::ForceSign(absHalf.y, frustum._SignFlip[index][1]),
                                    EMath::ForceSign(absHalf.z, frustum._SignFlip[index][2]));

        EVector3 corner = center - tmpHalf;
        EFloat dot = EMath::Dot(corner, normal) + dist;

        isInside &= RetrieveSign<EUInt32>(dot);
    }

    return isInside > 0;

```

it is based on Intel Software Culling sample, if the dot value is negative means the object is visible.

Resume of problem: It works(partially), the frustum is working well on the right player position(except when i put camera position, for some reason it goes to another way), however it rotates to wrong direction, if i rotate the camera to right, it rotates to left, i tried to find the problem in the code but i couldn't.

Really thanks everyone for your time, i am with this problem since 2 weeks, and tried everything for sure there is something what i am not doing well, but i don't know what it is, i am getting really stressed about it.

# Answer
Well, at the end it was a mistake in my game data, after update the game data everything worked perfectly, but also did some changes, instead of keep geometric approach algorithm for get all six planes what I did is change to OpenGL Extract Planes from http://gamedevs.org/uploads/fast-extraction-viewing-frustum-planes-from-world-view-projection-matrix.pdf it works like charm.

If someone is stick with same problem as me, related to right-hand, just don't worry, use that pdf, it works for left-handed and right-handed, in my case I just used GLM library, and without transpose anything applied exactly what says that pdf, here is the code in case you need some example:

```
EMatrix4 matrix = MUVideoManager::_CurrentProjection * MUVideoManager::_CurrentView; // Don't transpose or inverse anything, just apply it exactly as you get after do lookAtRH and perspectiveFovRH :)
EVector4 tmp;
tmp = EVector4(matrix[0][3] + matrix[0][0], matrix[1][3] + matrix[1][0], matrix[2][3] + matrix[2][0], matrix[3][3] + matrix[3][0]);
_Planes[WP_LEFT].SetPlane(EVector3(tmp), tmp.w, true);
tmp = EVector4(matrix[0][3] - matrix[0][0], matrix[1][3] - matrix[1][0], matrix[2][3] - matrix[2][0], matrix[3][3] - matrix[3][0]);
_Planes[WP_RIGHT].SetPlane(EVector3(tmp), tmp.w, true);
tmp = EVector4(matrix[0][3] - matrix[0][1], matrix[1][3] - matrix[1][1], matrix[2][3] - matrix[2][1], matrix[3][3] - matrix[3][1]);
_Planes[WP_TOP].SetPlane(EVector3(tmp), tmp.w, true);
tmp = EVector4(matrix[0][3] + matrix[0][1], matrix[1][3] + matrix[1][1], matrix[2][3] + matrix[2][1], matrix[3][3] + matrix[3][1]);
_Planes[WP_BOTTOM].SetPlane(EVector3(tmp), tmp.w, true);
tmp = EVector4(matrix[0][3] + matrix[0][2], matrix[1][3] + matrix[1][2], matrix[2][3] + matrix[2][2], matrix[3][3] + matrix[3][2]);
_Planes[WP_NEAR].SetPlane(EVector3(tmp), tmp.w, true);
tmp = EVector4(matrix[0][3] - matrix[0][2], matrix[1][3] - matrix[1][2], matrix[2][3] - matrix[2][2], matrix[3][3] - matrix[3][2]);
_Planes[WP_FAR].SetPlane(EVector3(tmp), tmp.w, true);

```

Plane function:

```
EINLINE void SetPlane(const EVector3 &normal, const EFloat &distance, EBoolean normalize)
{
    if (normalize)
    {
        EFloat length = EMath::Length(normal);
        _Normal = normal / length;
        _Distance = distance / length;
    }
    else
    {
        _Normal = normal;
        _Distance = distance;
    }

    _AbsNormal = EMath::Abs(_Normal);
}

```

and Intersection Code:

```
EINLINE FrustumCullType Contains(EMathFrustum &frustum, EMathAABB &aabb)
{
    EVector3 &min = aabb._Min;
    EVector3 &max = aabb._Max;
    EVector3 center = (min + max) * 0.5f;
    EVector3 half = (max - min) * 0.5f;
    EVector3 absHalf = EMath::Abs(half);

    FrustumCullType cull = FR_INCLUDED;

    for (EInt32 index = EMathFrustum::WP_BEGIN;index < EMathFrustum::WP_MAX;index++)
    {
        EVector3 &normal = frustum._Planes[index]._Normal;
        EVector3 &absNormal = frustum._Planes[index]._AbsNormal;
        EFloat &dist = frustum._Planes[index]._Distance;

        EInt32 side = frustum.ComputeSide(index, center, half, absHalf);

        if (side == EMathPlane::NEGATIVE_SIDE)
        {
            return FR_EXCLUDED;
        }
        else if (side == EMathPlane::NO_SIDE)
        {
            cull = FR_OVERLAP;
        }
    }

    return cull;
}

EINLINE EFloat ComputeDistance(const EVector3 &v)
{
    return EMath::Dot(_Normal, v) + _Distance;
}

EINLINE EInt32 ComputeSide(const EVector3 &center, const EVector3 &half, const EVector3 &absHalf)
{
    // Calculate the distance between box centre and the plane
    EFloat dist = ComputeDistance(center);

    // Calculate the maximise allows absolute distance for
    // the distance between box centre and plane
    EFloat maxAbsDist = EMath::Dot(_AbsNormal, absHalf);

    if(dist < -maxAbsDist)
    {
        return NEGATIVE_SIDE; // Outside! don't render
    }

    if (dist > +maxAbsDist)
    {
        return POSITIVE_SIDE; // Completely visible!
    }

    return NO_SIDE; // A part of it is visible
}

```

I hope it helps someone, wish you(who is reading) a nice day! :)
> 1 votes

---
Tags: directx, glm, culling, frustum
---


# Question
Title: Constructor in derived class from MonoBehavior
So i've got a Part abstract class which inherit from Monobehavior

```
public abstract class Part:MonoBehaviour

```

And then I've a class frame which inherit from Part class

```
public class Frame: Part
{
    public Frame(string partId) {
    this.partId = partId;
    this.name = "Some Random name";
}

```

 But on the last line which is `this.name = "Some Random name";`, i got this NullReferenceException.

Any suggestions would be appreciated.

# Answer
> 1 votes
Turns out a monobehavior script must be attached to a gameobject inorder to be referenced.

Here's the more detailed explanation.

Well, i just guess that the script (and / or the gameobject it's attached to) has been destroyed, or you created the Wait-instance with "new" which would result in the same behaviour since a MonoBehaviour can't live on it's own.

In C# / .NET / Mono instances actually can't be destroyed since they live in a managed memory environment. Objects are destroyed when all references to the object are gone, no longer valid. After that the garbage collector eventually kicks in and removes the object.

However in Unity, since it's core is written in C++, (native) objects can be destroyed on command (with Destroy to be more precise). The Destroy method actually only destroys the object on the c++ side. The managed representation of the object (your MonoBehaviour script) will still be there since the GC can only collect the object when there are no references anymore. That's why Unity actually "fakes" that the reference is null when the object has lost it's native counterpart.

If you use the "new" keyword to create an instance of a MonoBehaviour derived class the instance doesn't have a native counterpart and will always pretend to be null. If you want to create an instance at runtime it has to be attached to a gameobject. This is done with

Constructor in derived class from MonoBehavior

# Answer
> 1 votes
It's not allowed to have constructor in MonoBehaviour and derived class. Use Awake, Start instead.

In constructor unity fields are not deserialized yet, so it's not reliable to use that data. So unity provides it's methods mentioned earlier which is executed after construction and deserialization phases.

---
Tags: unity
---


# Question
Title: C++/SDL Snake Game: Drawing Tail Crashes Game
I"ve been making a snake game in C++ using SDL (first game and first time using SDL), and I've run into a bug. As the tail of the snake gets longer, the game slows down (snake gets slower), and eventually the game crashes (once the length of the tail reaches 29 pieces/parts). I went and deleted little bits of code until I found what was causing the problem, and I found that the problem is the snake's `draw()` method. It is responsible for drawing the head, and also for looping through each part of the tail and drawing it. Since the tail keeps getting longer, so does the loop, as it has more to draw. When I take out the loop that draws the tail, the game works fine. Is there anything I can do that is more efficient and that will stop the game from slowing down and crashing? Maybe the structure of the program is just bad. Here is some code with all the unnecessary stuff cut out:

# snake.h

```
#pragma once

...

class Snake
{
...

private:
    void drawPart(SDL_Renderer *renderer); // snake is made up of individual parts
    ...

public:
    void draw(SDL_Renderer *renderer); // draws whole snake
    ...

private:
    SDL_Texture *texture = nullptr;
    int x = 0, y = 0; // initialized to something else later, irreverent
    std::vector<Snake> tail; // tail is made up of objects of this class
};

```

# snake.cpp

```
...
void Snake::drawPart(SDL_Renderer *renderer) {
    auto surface = IMG_Load("part.png");
    texture = SDL_CreateTextureFromSurface(renderer, surface);
    SDL_FreeSurface(surface);
    SDL_Rect rect = { x, y, WIDTH, HEIGHT };
    SDL_RenderCopy(renderer, texture, nullptr, &rect);
}

void Snake::draw(SDL_Renderer *renderer) {
    drawPart(renderer);
    // the code below is what slows down the game until it crashes
    for (auto i = 0; i < tail.size(); ++i) {
        tail[i].drawPart(renderer);
    }
}
...

```

If any more code is necessary, please let me know. Thanks!

# Answer
> 1 votes
You are loading `part.png` and creating the surface for each tail part in a loop. That's incredibly slow. Instead you should load it once, at the program initialization and just use it in drawing. You should get rid of these in `drawPart()`:

```
auto surface = IMG_Load("part.png");
texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_FreeSurface(surface);

```

---
Tags: c++, rendering, sdl
---


# Question
Title: How to access triangulates in a 3d model that was imported in Unity?
I have a 3d model of a city. It is in collada format and ina dae file. I imported 3d model to unity but I don't know how can I access the objects of this 3d model with c# script.Because I am new with coding stuff. I am trying to learn bot unity and c# at the same time and I think this is a painful process.I want to access and manipulate the triangles in this 3d model. You can see the model in the attaching picture

# Answer
`Mesh` class contains `triangles` array, as described in the documentation:

> The array is a list of triangles that contains indices into the vertex array
> 0 votes

---
Tags: unity, c#, 3d-modeling
---


# Question
Title: How do I perform interpolation between noise values sampled at a lower resolution?
I'm doing some experimentation with terrain generating using a method similar to that described in this blog post by Markus Persson, where I use 3D simplex noise as a "density" value. Like him, sampling every single position in a chunk was simply too much of a performance drain, so I sample at a lower resolution. This works perfectly fine if I just use the noise values sampled at a lower resolution as densities, but this obviously leads to very "chunky" terrain, like this:

The relevant code used to generate the noise values and the voxels that make up the above terrain looks like this:

```
// Initialize the width, height and depth of the noise values map, and initialize
// the noise value map itself.
int noiseValuesMapWidth = (this.ChunkWidth / this.HorizontalNoiseResolutionDivisor) + 2;
int noiseValuesMapHeight = (this.ChunkHeight / this.VerticalNoiseResolutionDivisor) + 2;
int noiseValuesMapDepth = (this.ChunkDepth / this.HorizontalNoiseResolutionDivisor) + 2;
float[,,] noiseValuesMap = new float[noiseValuesMapWidth, noiseValuesMapHeight, noiseValuesMapDepth];

// Fill the noise values map with noise values.
for(int x = 0; x < noiseValuesMapWidth; x++)
{
    for(int y = 0; y < noiseValuesMapHeight; y++)
    {
        for(int z = 0; z < noiseValuesMapDepth; z++)
        {
            float xSeed = Mathf.Abs((x * this.HorizontalNoiseResolutionDivisor) + this.transform.position.x + seed);
            float ySeed = Mathf.Abs((y * this.VerticalNoiseResolutionDivisor) + this.transform.position.y + seed);
            float zSeed = Mathf.Abs((z * this.HorizontalNoiseResolutionDivisor) + this.transform.position.z + seed);

            noiseValuesMap[x, y, z] = Noise.Generate(
                xSeed * this.NoiseScaleX, ySeed * this.NoiseScaleY, zSeed * this.NoiseScaleZ
            ) - NoiseFalloff(
                this.FalloffACoefficient,
                this.FalloffBCoefficient,
                this.FalloffCCoefficient,
                (float)(y * this.VerticalNoiseResolutionDivisor) / (float)this.ChunkHeight
            );
        }
    }
}

// Generate the chunk's terrain itself by iterating over every voxel position
// and generating simplex noise values at a lower resolution.
for(int x = 0; x < this.ChunkWidth; x++)
{
    for(int y = 0; y < this.ChunkHeight; y++)
    {
        for(int z = 0; z < this.ChunkDepth; z++)
        {
            int noiseValuesMapX = (x / this.HorizontalNoiseResolutionDivisor) + 1;
            int noiseValuesMapY = (y / this.VerticalNoiseResolutionDivisor) + 1;
            int noiseValuesMapZ = (z / this.HorizontalNoiseResolutionDivisor) + 1;

            if(noiseValuesMap[noiseValuesMapX, noiseValuesMapY, noiseValuesMapZ] >= 0.0f)
            {
                this.SetVoxel(new Stone(), x, y, z);
            }
        }
    }
}

```

Obviously, the solution to the "chunky" terrain is to interpolate between each of the sampled noise values, but I have no idea how to perform that interpolation. How is it done?

# Answer
> 2 votes
Linear interpolation is the simplest way to interpolate. Here's the function for it:

```
private double linearInterpolate3d(double xm_ym_zm, double xp_ym_zm, double xm_yp_zm, double xp_yp_zm,
                                    double xm_ym_zp, double xp_ym_zp, double xm_yp_zp, double xp_yp_zp,
                                    double x, double y, double z) {
    return (xm_ym_zm * (1 - x) * (1 - y) * (1 - z)) + (xp_ym_zm * x * (1 - y) * (1 - z)) + (xm_yp_zm * (1 - x) * y * (1 - z)) + (xp_yp_zm * x * y * (1 - z)) +
            (xm_ym_zp * (1 - x) * (1 - y) * z) + (xp_ym_zp * x * (1 - y) * z) + (xm_yp_zp * (1 - x) * y * z) + (xp_yp_zp * x * y * z);
}

```

This code will take the nearest density values to your point and the position of the point within that cube, and return the interpolated value.

Here's how you might implement it in your code (it goes inside your last `for` loop):

```
int x2 = (x / this.HorizontalNoiseResolutionDivisor) + 1;
int y2 = (y / this.VerticalNoiseResolutionDivisor) + 1;
int z2 = (z / this.HorizontalNoiseResolutionDivisor) + 1;

double value = linearInterpolate3d(noiseValuesMap[x2][y2][z2], noiseValuesMap[x2 + 1][y2][z2],
    noiseValuesMap[x2][y2 + 1][z2], noiseValuesMap[x2 + 1][y2 + 1][z2],
    noiseValuesMap[x2][y2][z2 + 1], noiseValuesMap[x2 + 1][y2][z2 + 1],
    noiseValuesMap[x2][y2 + 1][z2 + 1], noiseValuesMap[x2 + 1][y2 + 1][z2 + 1],
    (x % HorizontalNoiseResolutionDivisor) / (double) HorizontalNoiseResolutionDivisor,
    (y % VerticalNoiseResolutionDivisor) / (double) VerticalNoiseResolutionDivisor,
    (z % HorizontalNoiseResolutionDivisor) / (double) HorizontalNoiseResolutionDivisor);

if(value >= 0.0) {
    this.SetVoxel(new Stone(), x, y, z);
}

```

Here's more on how linear interpolation works: https://en.wikipedia.org/wiki/Bilinear\_interpolation#Unit\_Square

---
Tags: procedural-generation, terrain, voxels, procedural, simplex-noise
---


# Question
Title: Animator consecutive set parameter problem
I'm having a little problem with my animations transitions.

I have this diagram: https://i.stack.imgur.com/5ST6x.jpg

My transitions is made by updating the parameter "stateparam".

My code, changing the parameter: https://i.stack.imgur.com/SemfE.jpg

I change stateparam to 2 and right after to 0, then my animation don't restart every frame.

But when I play, the my parameter doesn't change the animation and only change the stateparam to 0. I already debugged and it's passing in the line that change to valid transition value. But i don't know why my animation doesn't changes. If I play and change stateparam manually, it works.

If I take off the SetInteger "0", let only the valid value, the code works, but my animation keep restarting before it can finish itself.

I don't know if the parameter change it's too fast to do the transition or it's any buggy. Any help ?

# Answer
> 0 votes
Take the `anim.SetInteger("stateparam", 0)` from `SetAnimation()` method and put it in the `else` parts of two `if` statements in `Update()`method where you taking input.

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


# Question
Title: Unity 3d - Touchscript Asset: Get object when "touched"
I have a question regarding the exact method for getting the game object that I'm touching. I thought it would be getting the name of the PressGesture once the touch starts...but it returns me a Swipe Controller object name, so that is not the correct. I have read, though not extensively, the TouchScript documentation, but I haven't found a method that gets information from the point you are touching/clicking

This is the code that tries to solve that issue (of course, the wrong way):

```
private void pressedHandler(object sender, EventArgs e)
{
    PressGesture gesture = sender as PressGesture;
    TouchHit hit;
    gesture.GetTargetHitResult (out hit);
    startPos = hit.Point;

    if(gesture.gameObject == this.swipePositions[0])
    {
        Debug.Log ("Pressed on: " + gesture.gameObject.name + " at: " + startPos);
    }
    else
    {
        Debug.Log("Not even from the start...");
        Debug.Log("This name is: " +gesture.gameObject.name);
        Debug.Log("The name should be: " +this.swipePositions[0].name);
    }
}

```

# Answer
> 0 votes
Solved. It works similar to the Raycasting without the TouchScript Asset....there is an GameObject called TouchHit, and it has both RaycastHit and RaycastHit2D properties, I just needed to cast a ray where the hit was touch, and get its transform.gameObject, and that's pretty much it I guess.

Thanks.

---
Tags: unity, touch
---


# Question
Title: How to write an event + eventhandler? C#
Hey guys I want to have an event that would be called "OnMonsterKilled" this should trigger when a monster die so hp = 0. Could you give me some good help? maybe with some explanation I'm not the best atm in those things.

# Answer
Ok, one important thing to know about are delegates. Delegate instances are strongly typed method references.

You define a delegate type like this:

```
public delegate string IntToString(int i);

```

Now, you can declare a delegate variable like this:

```
IntToString myDelegate;

```

And you can assign it a method that has the right signature.

```
string ConvertInt(int i)
{
    return i.ToString();
}

...

IntToString myDelegate;
myDelegate = ConvertInt; // Without the parentheses!
string s = myDelegate(5); // "5"

```

Delegates are mulicast, i.e. they can hold a reference to multiple methods. When the delegate is called, all these methods are then executed in order

Given this other method:

```
string ConvertDecorated(int i)
{
    return "**" + i.ToString() + "**";
}

```

You can add a second delegate:

```
myDelegate += ConvertDecorated;
myDelegate(5); // "**5**"

```

If the delegate has a return type (i.e. is not void), then the result of the last method called will be returned.

You can also remove a method:

```
myDelegate -= ConvertDecorated;
myDelegate(5); // "5" result of first method.

```

---

Ok, now to events. An event is a wrapper around a delegate variable. A little bit like a property is a wrapper around a field. Moreover, an event does not allow you to assign a new method to the event with equal (=) and thus remove all the other method references. You can only use `+=` and `-=`. It also adds a very basic thread safety to the "pure" delegates.

You declare an event by specifying a delegate type:

```
public delegate void MonsterKilledEventHandler(object Source, MonsterInfo mi);
public event MonsterKilledEventHandler MonsterKilled;

```

Now you can rise the event like this, first making sure that it is not null:

```
private void OnMonsterKilled(MonsterInfo mi)
{
    MonsterKilledEventHandler eh = MonsterKilled;
    if(eh != null) {
        eh(this, mi);
    }
}

```

It is important to first assign it to a temp variable if you want to ensure thread safety. This works, because delegates a immutable. I.e. If you add a method with += then a fully new delegate is created with a new method list and assigned to the variable. Event if the delegate was changed by another thread after assigning it to `eh`, eh would preserve its original value.

Starting with C# 6.0 you would simply write

```
private void OnMonsterKilled(MonsterInfo mi)
{
    MonsterKilled?.Invoke(this, mi);
}

```

Now someone wanting to subscribe to the event just writes

```
// monsterManager is an instance of the class defining the event
monsterManager.MonsterKilled += MyMonsterKillledHandler;

...

private void MyMonsterKillledHandler(object Source, MonsterInfo mi)
{
    // Be happy, the world just got better.
}

```

---

Note also that you can easily create a delegate on the fly with lambda expressions:

```
monsterManager.MonsterKilled += (s, mi) => {
    Celebrate("Monster " + mi.Name + " was killed!");
};

```

---

See:
\- Handling and Raising Events (msdn)
\- Delegates and Events (C# in Depth by Jon Skeet)
\- C# Event Implementation Fundamentals, Best Practices and Conventions (on CodeProject by Jeffrey Schaefer)
> 2 votes

---
Tags: c#
---


title: Black screen when launching on phone

text:
# Question
Title: Black screen when launching on phone
I am coding a game in libgdx. While adding the background I used the html module to watch the results fast and easy on my computer. But when I try to see it on my phone I just get a black screen. My project is on GitHub.

**My Gamescreen.java**

```
package com.joelbrun.jetskirider.screens;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.Shape;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.utils.Scaling;
import com.badlogic.gdx.utils.viewport.ScalingViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.joelbrun.jetskirider.buoyancy.Box2DFactory;
import com.joelbrun.jetskirider.buoyancy.BuoyancyController;
import com.joelbrun.jetskirider.utilities.ParallaxBackground;
import com.joelbrun.jetskirider.utilities.ParallaxLayer;

public class Gamescreen extends InputAdapter implements Screen, ContactListener {

    private static final float TIMESTEP = 1.0f / 60.0f;
    private static final int VELOCITY_ITERATIONS = 8;
    private static final int POSITION_ITERATIONS = 3;
    public static final float GAMESCREEN_WIDTH = 20;
    public static final float GAMESCREEN_HEIGHT = 20 * (Gdx.graphics.getHeight() / (float) Gdx.graphics.getWidth());
    public static final int OBSTACLE_TYPES = 5;
    public static final float WATER_HEIGHT = 5; //ToDo: Change to about 5
    public static final float WATER_WIDTH = GAMESCREEN_WIDTH;
    private static final float JETSKI_BOX_X = 1.5f;
    private static final float JETSKI_BOX_Y = 1;

    private World world;
    private Box2DDebugRenderer debugRenderer;
    public Texture jetski;
    public TextureRegion wave;
    public TextureRegion background;
    public SpriteBatch batch;
    public OrthographicCamera camera;
    public Label score;
    Viewport viewport;
    private BuoyancyController buoyancyController;
    private ParallaxBackground bkground;

    @Override
    public void show() {

        world = new World(new Vector2(0, -9.81f), true);
        debugRenderer = new Box2DDebugRenderer();

        //Textures
        Texture[] texture = new Texture[OBSTACLE_TYPES];

        for (int i=0; i<OBSTACLE_TYPES; i++){
            texture[i] = new Texture(Gdx.files.internal("game/obstacles/obstacle" + Integer.toString(i+1)+".png"));
        }
        jetski = new Texture("game/jetski.png");
        wave = new TextureRegion(new Texture("game/water1.png"));
        batch = new SpriteBatch();
        background = new TextureRegion(new Texture(Gdx.files.internal("game/background.png")));

        //Camera & Viewport
        camera = new OrthographicCamera(GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT);

        viewport = new ScalingViewport(Scaling.fillY, GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT, camera);
        viewport.apply();
        camera.position.set(GAMESCREEN_WIDTH / 2, GAMESCREEN_HEIGHT / 2, 0);

        //InputProcessor

        Gdx.input.setInputProcessor(this);

        //Water
        Shape shape = Box2DFactory.createBoxShape(WATER_WIDTH, WATER_HEIGHT / 2, new Vector2(0, 0), 0);
        FixtureDef fixtureDef = Box2DFactory.createFixture(shape, 2f, 0.1f, 0f, true);
        Body water = Box2DFactory.createBody(world, BodyDef.BodyType.StaticBody, fixtureDef, new Vector2(0, 0));

        buoyancyController = new BuoyancyController(world, water.getFixtureList().first());
        world.setContactListener(this);

        //Ground
        Shape groundShape = Box2DFactory.createChainShape(new Vector2[]{
                new Vector2(0, -1.8f),
                new Vector2(20, -1.8f)
        });
        FixtureDef fixtureDefGround = Box2DFactory.createFixture(groundShape, 2, 0, 0.2f, false);
        Box2DFactory.createBody(world, BodyDef.BodyType.StaticBody, fixtureDefGround, new Vector2(0, 2));

        //Jetski
        Shape jetskiShape = Box2DFactory.createBoxShape(JETSKI_BOX_X, JETSKI_BOX_Y /2, new Vector2(0, 0), 0);
        FixtureDef fixtureDef1 = Box2DFactory.createFixture(jetskiShape, 0.9f, 0.5f, 0.5f, false);
        Box2DFactory.createBody(world, BodyDef.BodyType.DynamicBody, fixtureDef1, new Vector2(2, WATER_HEIGHT/2));

        //Background Scrolling
        bkground = new ParallaxBackground(new ParallaxLayer[]{
                new ParallaxLayer(background, new Vector2(1,0), new Vector2(0, 0)),
                new ParallaxLayer(wave, new Vector2(1,0), new Vector2(0, 0))
        }, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new Vector2(150, 0));
    }

    @Override
    public void render(float delta) {
        Gdx.gl.glClearColor(1, 1, 1, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        bkground.render(delta);

        debugRenderer.render(world, camera.combined);

        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.end();
        camera.update();

        world.step(TIMESTEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);

        buoyancyController.step();
    }

    @Override
    public void resize(int width, int height) {
        int SCREEN_WIDTH = width;
        int SCREEN_HEIGHT = height;

        viewport.setWorldSize(GAMESCREEN_WIDTH, GAMESCREEN_HEIGHT);
        viewport.update(SCREEN_WIDTH, SCREEN_HEIGHT,true);
        camera.update();
    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {
        dispose();
    }

    @Override
    public void dispose() {
        batch.dispose();
        jetski.dispose();
        world.dispose();
        debugRenderer.dispose();
    }

    @Override
    public void beginContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();

        if (fixtureA.isSensor()
                && fixtureB.getBody().getType() == BodyDef.BodyType.DynamicBody) {
            buoyancyController.addFixture(fixtureB);
        } else if (fixtureB.isSensor()
                && fixtureA.getBody().getType() == BodyDef.BodyType.DynamicBody) {
            buoyancyController.addFixture(fixtureA);
        }
    }

    @Override
    public void endContact(Contact contact) {
        Fixture fixtureA = contact.getFixtureA();
        Fixture fixtureB = contact.getFixtureB();

        if (fixtureA.isSensor()
                && fixtureB.getBody().getType() == BodyDef.BodyType.DynamicBody) {
            buoyancyController.removeFixture(fixtureB);
        } else if (fixtureB.isSensor()
                && fixtureA.getBody().getType() == BodyDef.BodyType.DynamicBody) {
            if (fixtureA.getBody().getWorldCenter().y > -1) {
                buoyancyController.removeFixture(fixtureA);
            }
        }
    }

    @Override
    public void preSolve(Contact contact, Manifold oldManifold) {

    }

    @Override
    public void postSolve(Contact contact, ContactImpulse impulse) {

    }
}

```

# Answer
Allright I found the solutions. My phone was only capable of processing pictures with a size up to 4096\*4096px and my Sprite was over 5000px...
> 0 votes

# Answer
Here goes some useful information for your problem related to texture resolutions: http://answers.unity3d.com/questions/563094/mobile-max-texture-size.html
> 0 votes

---
Tags: android, libgdx, box2d
---


# Question
Title: Texture coordinates do not map correctly in Direct3D11 game engine
I beg your pardon if this question has been already answered elsewhere or if this is the wrong site, but I have a serious issue with rendering textures with Direct3D 11.

Using Cinema 4D R17, I created a simple cube, triangulated all polygons, and UV mapped a texture, as you can see here:
and it renders correctly.

Next, I exported the file to .x because I created a simpler mesh format and .x is ideal for getting vertices, indices, normals, texture coordinates, etc. This conversion is perfect as all data from the source file is successfully transferred to my file (I checked and double checked it).

However, when I upload the file in my game engine, I get the following result:
The cube is being rendered incorrectly where that strange pattern forms.

This is the original .x file (I included only relevant parts):

```
Mesh CINEMA4D_Mesh {
  8;
  // Cube. These are vertices.
  -0.01;-0.01;-0.01;,
  -0.01;0.01;-0.01;,
  0.01;-0.01;-0.01;,
  0.01;0.01;-0.01;,
  0.01;-0.01;0.01;,
  0.01;0.01;0.01;,
  -0.01;-0.01;0.01;,
  -0.01;0.01;0.01;;

  12;
  // Cube. These are indices.
  3;0,1,3;, // '3;' means that this face contains 3 vertices.
  3;2,3,5;,
  3;4,5,7;,
  3;6,7,1;,
  3;1,7,5;,
  3;6,0,2;,
  3;0,3,2;,
  3;2,5,4;,
  3;4,7,6;,
  3;6,1,0;,
  3;1,5,3;,
  3;6,2,4;;

  MeshNormals {
    8;
    // Cube
    -0.408;-0.408;-0.816;,
    -0.667;0.667;-0.333;,
    0.667;-0.667;-0.333;,
    0.408;0.408;-0.816;,
    0.408;-0.408;0.816;,
    0.667;0.667;0.333;,
    -0.667;-0.667;0.333;,
    -0.408;0.408;0.816;;

    12;
    // Cube
    3;0,1,3;,
    3;2,3,5;,
    3;4,5,7;,
    3;6,7,1;,
    3;1,7,5;,
    3;6,0,2;,
    3;0,3,2;,
    3;2,5,4;,
    3;4,7,6;,
    3;6,1,0;,
    3;1,5,3;,
    3;6,2,4;;

  }
  MeshTextureCoords {
    8;
    // Cube
    1.0;1.0;,
    0.0;1.0;,
    1.0;0.0;,
    1.0;1.0;,
    1.0;1.0;,
    1.0;0.0;,
    0.0;1.0;,
    1.0;0.0;;
  }
  MeshMaterialList {
    2;
    12;
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1,
    1;

    Material C4DMAT_NONE {
      1.0;1.0;1.0;1.0;;
      1.0;
      0.0;0.0;0.0;;
      0.0;0.0;0.0;;
    }
    Material C4DMAT_Mat {
      1.0;1.0;1.0;1.0;;
      1.0;
      0.0;0.0;0.0;;
      0.0;0.0;0.0;;
      TextureFilename {
        "tex.bmp";
      }
    }

    {C4DMAT_Mat}
  }
}

```

I also invert the `v`texture coordinate (`v = 1 -v`). This is the vertex data I extract:

```
8 // Number of vertices.
-0.01 -0.01 -0.01 -0.01 0.01 -0.01 0.01 -0.01 -0.01 0.01 0.01 -0.01 0.01 -0.01 0.01 0.01 0.01 0.01 -0.01 -0.01 0.01 -0.01 0.01 0.01 // Vertices stored in X, Y, Z.
1 0 0 0 1 1 1 0 1 0 1 1 0 0 1 1  // Texture coordinates stored in U, V.
36 // Indices count.
0 1 3 2 3 5 4 5 7 6 7 1 1 7 5 6 0 2 0 3 2 2 5 4 4 7 6 6 1 0 1 5 3 6 2 4 // Indices.
tex.bmp // Texture file name.

```

I read that there might be a conflict between texture coordinates of vertices that are shared among different faces and that resolving this would imply not using index buffers.

**EDIT:** I did what @wondra said (replaced texture coordinates with `0 0 0 1 1 0 1 1 0 1 0 0 1 1 1 0` and it looks better indeed:

I am not sure what is wrong here. Could anybody help me? Thank you.

**UPDATE**: The Cinema 4D .obj is broken. Use Blender or anything else.

# Answer
I you look carefully your cube in Cinema4D, the top most corner show different texture coordinate for the side and the top ( probably the same between front and right side, but the texture can't let me state it for sure ).

And in your final cube indices, you only have a range \[0..7\]. On the GPU, a vertex is a full tuple of values with a single index. It means that your cube is not made of 8 vertex but 24, because each corner has to be split for his own normal and texture coordinate.

Once you split each face properly, you should get the correct visual. A cube is not the best example of index buffer because the vertex reuse rate is quite low, but you still get the idea.
> 1 votes

# Answer
It turns out that the .obj file exported by Cinema 4D was broken.

Using Blender or anything else to create the .obj file seems to solve the issue.
> 0 votes

---
Tags: textures, directx11, uv-mapping, mesh, cinema-4d
---


# Question
Title: How to find an object which is added to a scene only when game starts?
I'm looking for some advice how to find an object which is added to scene only when the game starts? Before start it isn't in Scene hierarchy. It's prefab.

# Answer
> 0 votes
On top of the answer of **Philipp** and **Uri Popov**, You need code something like given below(comments for demonstration):

```
    //make a public  static list for saving all the objects ref you are instantiating during runtime
class InstanceManager : MonoBehaviour {
    public static List<GameObject> runtimeGameObjectList = List<GameObject>();
}

//where you are currently instantiating
GameObject g = Instantiate(myPrefab);
// add this line so that instantiated ref save in the list for later use
InstanceManager.runtimeGameObjectList.add(g);

```

Now you can do whatever you want with this list runtimeGameObjectList.

# Answer
> 1 votes
When you instantiate a prefab with `Instantiate`, you receive a reference to that object which you can then pass to where it is needed.

Alternatively, you can search for an object in the scene by its name with `Find` or by a tag with `FindObjectWithTag`. But keep in mind that these are not very fast (especially on larger scenes), so you should only do it once and save the result in a variable.

# Answer
> 1 votes
you can use on of the following :

```
GameObject.Find("name of object");
GameObject.FindGameObjectWithTag("name of the tag of the object")

```

or alternatively you can just keep the reference to the instantiated game object after you create it.

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


# Question
Title: A way to create a variable that includes a modifier that should be checked every step [Gamemaker]
I can't tell if I am being stupid, but I am looking for a way in Gamemaker to have a variable include a modifier which has the potential to change every step.

This variable is called `mTiredness`, and I would like it to include the `TimeOfDayModifier` which needs to be checked frequently.

However, I obviously can't put

`mTiredness = mTiredness + TimeOfDayModifier`

in a Step event, as this would add the modifier, in my case, 60 times a second, which I do not want!

Instead, I want a **consistent** variable comprised of the base amount and the modifier, while allowing that modifier to change.

Can anybody help me? I cannot think of an easy way to do this.

# Answer
> 1 votes
Make a script. It's a function actually, so you can make it return the sum you desire. That way you don't affect the `mTiredness` value. You will only need to have global access to those variables or either pass them as arguments/parameters.

---
Tags: game-maker
---


title: How do bullets work in video games?

text:
# Question
Title: How do bullets work in video games?
I came across this question when I was designing a video game in C#.

If we consider games such as *Battlefield* or *Call of Duty*, hundreds or even thousands of bullets are flying at the same time. Events are triggered constantly, and from what I know, this sucks a lot of processing power … or does it? I want to know how various game developers manage (2D and 3D) bullets and what the most efficient method for each is.

I read the question How are bullets simulated in video games? but it doesn't touch on how bullets work from a program design perspective.

I had a couple ideas, but each have their drawbacks:

---

Most efficient method I could think of (for 2D games):

Say I was to create a class called Bullet, and for however long the user holds down a button, every 0.01 seconds a Bullet object would be made. This Bullet has:

* **1** Velocity
* **2** Starting position of where it is being shot from
* **3** Sprite texture
* **4** An on-hit effect

Since the bullet would be its own class, it could manage the drawing, moving, and action listeners itself.

Wouldn't it be hard on the processor to process thousands of these objects being instantiated, then destroyed (when on-hit effect is triggered)? RAM space?

---

Efficient method for 3D games - Another thought I had was:

Lets say I create a weapon class. This weapon has various features, some of which:

* **1** Detect where the weapon is aiming, and determine if it's looking at a target
* **2** Trigger an animation of the gun shooting
* **3** Has a doDamage() method that indicates something to subtract health from whatever the gun is pointed at
* **4** Notifies a bullet animation class when button pressed

I could then create a static class, say BulletAnimation, that could get notification from where the gun that triggered it is, where that gun is pointed at (for the bullet destination), and information on an appropriate sprite and velocity to use for the bullet. This class then draws sprites (on a new thread maybe, idk) based on both positions and desired sprite, to simulate a bullet being fired from a gun.

---

The latter seems much harder to code, and wouldn't it take lots of processing power to constantly call the static to do this for thousands of bullets at a time? Getting constant updates on both starting and ending positions would be hard as well.

My question is, what is the most efficient way game creators do it? Does this method change from 2D to 3D games?

# Answer
> 80 votes
I can certainly see why you would think that it would be hard to simulate those, but there are enough constraints on bullets (all projectiles, really) to make them easier.

1. They are generally simulated as a single point, instead of as something with volume. This makes collision detection significantly easier, as now I only need to do collisions against very simple surfaces, such as a line against a circle.
2. We know how they will move, so there isn't much information we need to store or calculate for them. Your list was reasonably accurate, we'll generally have a few more things associated with it, like who shot the bullet, and what its type is.
3. Since all projectiles will be very similar, we can pre-allocate them, to avoid all the overhead of creating them dynamically. I can allocate an array of 1000 projectiles, and now they can be accessed with just an index, and they are all sequential in memory, so processing them will be quick.
4. They have a fixed lifetime/range, so I can expire old bullets and recycle the memory into new bullets very quickly.
5. Once they hit something, I can also expire them, so they have a finite lifetime.
6. Since we know when they were created, if we need new ones and we don't have any free in our pre-allocated list, I can just grab the oldest ones and recycle them, and people won't notice if bullets expire slightly early.
7. They are rendered as sprites (usually) or as low poly models, and take up very little space on screen, so they are fast to render.

Taking all of those things into account, bullets tend to be relatively cheap. If our budget ever got consumed by bullets and rendering them, we'd generally just redesign it to limit the number of shots you can fire at a time (you'll see this in many old arcade games), use beam weapons that move instantly, or slow the fire rate down to make sure we stay within budget.

# Answer
> 45 votes
Probably one of the most efficient ways to implement bullets is using what is known as hitscan. It is rather simple in its implementation - when you fire, you check to see what the gun is aiming at (possibly using a ray to find the closest entity/object/mesh), and then you 'hit' it, doing damage. If you want to make it seem more like an actual, fast moving invisible bullet was fired, you can fake it by adding a slight delay dependent on distance before doing damage.

This approach essentially assumes the fired projectile has infinite velocity, and is typically used for weapons types such as lasers and particle beams/cannons and maybe some forms of sniper rifles.

The next approach would be to model the fired bullet as a projectile, which is modelled as its own entity/object that is subject to collision, and possibly gravity and/or air resistance that alters its direction and velocity. It is more complex than the hitscan approach due to the extra physics equations, and more resource intensive due to there being an actual bullet object, but can provide more realistic bullets.

As for managing collisions between projectile based bullets and other objects in game, collision detection can be greatly simplified by sorting your objects into quad or octrees. Octrees are primarily used in 3d games, while quadtrees can be used in 2d or 3d games. The advantages of using one of these trees is that you can greatly reduce the number of possible collision checks. For example, if you have 20 objects active in the level, without using one of these trees, you'll have to check all 20 for a collision with the bullet. Dividing the 20 objects among the leaves (end nodes) of the tree, and you can reduce the number of checks down to however many entities are present in the same leaf as the bullet.

As for these approaches – hitscan and projectile, both can be used freely in 2d or 3d games. It depends more on what the weapon is, and how the creator has decided that the weapon shall function.

# Answer
> 7 votes
I'm by no means an expert, but to answer your question, yes, you would need many of those things you mention.

For your 2D example, you could have a position and velocity for a bullet. (You might also need a lifetime or maximum distance, depending on how you implement your bullets.) That would usually involve 2 (x,y) values. If they were floats, that's 16 bytes. If you have 100 bullets, that's only 1600bytes or about 1.5k. That's nothing on a machine today.

Next, you mention the sprites. You would only need a single sprite to represent each bullet. Its size would depend on the bit depth you're drawing at and how big it should appear on screen. Even uncompressed at, say, 256x256 in full float 32-bit per channel, that's 1MB for the sprite. (And that would be very big!) You would draw the same sprite at each bullet location, but it doesn't take additional memory for each copy of the sprite. It would be similar for an on-hit effect.

You mention firing every 0.01 seconds. That would be 100 bullets per second from your weapon. Even for a futuristic weapon that's quite a lot! According to this wikipedia article:

> When the trigger is pulled, the rate at which rounds are fired is the cyclic rate. Typical cyclic rates of fire are 600–900 RPM for assault rifles, 1,000-1,100 RPM in some cases, 900-1,200 RPM for submachine guns and machine pistols, and 600-1,200 RPM for machine guns. M134 Miniguns mounted on attack helicopters and other combat vehicles can achieve rates of fire of over 100 rounds per second (6,000 RPM).

So that would the rate of an attack helicopter!

For a large world like you mention in Battlefield/Call of Duty/etc., they may calculate all those bullet positions, but not draw all of them if the action is far away. Or they may not simulate them until you get close. (I have to admit I'm guessing a little on this part as I haven't worked on anything that large.)

# Answer
> 6 votes
> Wouldn't it be hard on the processor to process thousands of these objects being instantiated, then destroyed (when on-hit effect is triggered)? RAM space?

I think you're underestimating just how fast computers are. This *was* sometimes a problem on the systems of the 80s and 90s. It's partly why the original Space Invaders won't let you fire another bullet until the current one has hit. Some games suffered from "slowdown" if there were too many sprites on screen.

Nowadays, though? You have enough processing power for thousands of operations *per pixel* that are required to do texturing and lighting. There is no problem with thousands of moving objects; this lets you do destructible terrain (e.g. Red Faction) where every fragment does collision processing with other fragments and follows a ballistic curve.

You need to be a little careful algorithmically - you can't do the naive approach of checking every object against every other object when you have thousands of objects. Bullets don't generally check for collisions with other bullets.

A little side anecdote: the first version of networked Doom (the 90s original) sent one packet over the network for every bullet fired. When one or more players got the machine gun, this could easily overwhelm the network. The 90s was full of people illicitly playing Doom on university or work networks getting into trouble with their network administrators when the network became unusable.

# Answer
> 1 votes
I'm far from an expert but I've been working on a multiplayer 2D shooter game in my spare time.

## My method

There are varying bullet classes between the client and server (even when playing offline, a server instance is started on a separate process and connected to by the 'main' game).

Every tick (60 per second) the client works out a bearing between the player's mouse pointer and the centre of the screen (where their character is) and it's part of the information sent to the server. If the player is also firing at that moment (assuming the weapon is loaded and ready), a server-side bullet instance is created, with simply some co-ordinates, and a base damage (which derives from the stats of the weapon that shot it). The bullet instance then uses some math functions to work out an X and Y velocity from the bearing we gathered from the client.

For every subsequent tick, the bullet moves itself by those coordinates, and reduces its base damage by a predefined amount. If this value goes below 1, or if it hits a solid object in the world, the bullet instance is deleted, and as testing point collisions is incredibly cheap in 2D, even rapid firing weapons have a negligible impact on performance.

As for the client, the bullet information isn't actually received over the network (it proved wasteful in testing), instead as part of the per-tick update each character has a 'fired' Boolean, which if true the client creates a local bullet object which works almost exactly like server ones, the only difference being it has a sprite.

This means that although the bullet you see isn't an entirely accurate representation of it on the server, any difference would be barely noticeable if at at all to a player, and the network benefits outweigh any inconsistencies.

## Note on different methods

Some games, including my own, move the bullets each tick as if they're physical objects, whereas others just create a vector in the direction of shooting, or compute the bullet's entire path in the tick it is created, for example in Counter-Strike games. There are a few little client-side tricks to disguise it such as an animation of the bullet firing, but for all intents and purposes each bullet is just a laser.

With 3D models which may have complex hitboxes, it's standard to test collisions against a simple bounding box FIRST, and if that succeeds, go on to more 'detailed' collision detection.

# Answer
> 0 votes
It's called collision detection. 8-bit computers did this using player-missile graphics in hardware. Modern day game engines use physics engines and linear algebra. The current direction of a weapon is represented as a 3D vector. That provides an infinite line in the direction of fire. Every moving object has one or more bounding sphere as that's the simplest object to detect a collision with a line. If the two intersect, that's a hit, if not, there's no hit. But the scenery might be in the way, so that has to be checked for as well (using hierarchical bounding volumes). The nearest object that has an intersection is the one that has been hit.

---
Tags: c#, software-engineering, performance
---


# Question
Title: Obscure primitive data types against cheating
im trying to create lightweight value obscurer, against possibility to blatantly change primitive values in memory editor. Such as cheat engine. Here's what i have to far.

```
/// <summary>
/// Obscure for type int.
/// </summary>
public class ObscuredInt{

    public ObscuredInt() {
        this.value = 0;
    }

    public ObscuredInt(int value) {
        this.value = value;
    }

    private int _a;
    private int _b;

    /// <summary>
    /// Current obscure value.
    /// </summary>
    public int value {
        get {
            return _a + _b;
        }
        set {
            _a = Random.Range(int.MinValue, int.MaxValue);
            _b = value - _a;
        }
    }
}

```

usage

```
ObscuredInt health = new ObscuredInt(5);
health.value = 10;

printInConsle(health.value);

```

This works by simply never storing actual value, but rather a combination of two integers, which sum represents the value. That way the value is actually never cached long time in the memory. So finding it in a primitive way using cheat engine is not possible.

**My question**

I've seen other examples of obscuring, which involve conversion to binary or string hashing or other quite heavy operations.

This example is of course much more lightweight, how is this example worse than more advanced hashing or conversions. What flaws do you see with this example? What can you suggest?

Thank you

# Answer
The major flaw is that you are adding random values between `int.MinValue` and `int.MaxValue` leaving no more space for your real value. Okay, the default in C# is to not perform range checks, but this can be changed.

In order to keep the whole `int` value range open for your real values I would suggest to use an XOR operation instead.

```
public int value {
    get {
        return _a ^ _b;
    }
    set {
        _a = Random.Range(int.MinValue, int.MaxValue);
        _b = value ^ _a;
    }
}

```

Applying the same "mask" a second time with XOR restores the original value. The result of XOR is always in the `int`-range and never overflows. XOR is very fast and does not involve range checks.

---

Alternatively you could wrap your code in `unchecked` statements.

```
public int value {
    get {
        unchecked {
            return _a + _b;
        }
    }
    set {
        _a = Random.Range(int.MinValue, int.MaxValue);
        unchecked {
            _b = value - _a;
        }
    }
}

```

See: Checked and Unchecked (C# Reference).

---

Speed: The most expensive operation is the creation of the random number. If speed matters, consider making the random number static and create only one per session.

---

Safety: I think most cheat engines won't be smart enough to get around your trick. But of course, for human hackers that's another story.
> 3 votes

---
Tags: unity, c#, security, anti-cheat, hacks
---


title: Sprite with shadows in both sides

text:
# Question
Title: Sprite with shadows in both sides
I have a gameobject with a SpriteRenderer, and I want it to cast (and receive) shadows like a 3D model. The sprite will turn around depending of his direction, so all faces must cast shadows.

I already activated **Cast Shadows** and **Receive Shadows** in the Sprite Renderer component, and also included a **Transparent Cutout shader** with the `Cull Off` instruction (so all faces are drawn), but only one side of the sprite is being affected by light, while the other is even darker. To ilustrate:

How can I achieve an sprite casting shadows with both faces?

# Answer
> 0 votes
So I finally get it to work using the built-in **"Sprite/Default"** Unity shader with the addition of `Fallback "Legacy Shaders/Transparent/Cutout/VertexLit"` at the end.

# Answer
> 1 votes
Use cast shadows as "Two Sided".

You should use a quad with Standard Shader in Cutout and a duplicated and flipped quad for opposite side. They will have mesh rendered in them and auto shadow cast selected. You can turn off Shadow cast for one. That way you are not bound to sprite. You can take advantage of Standard Shader in that case.

---
Tags: unity, sprites, shadows
---


# Question
Title: How can I duplicate this color/hue shifting effect in C#?
I am looking for a way to duplicate this color shifting effect:

I don't think it matters but the starting frame would be this:

My instinct was that some type of hue shift is occurring in a way that causes it to loop back over. The problem arose when I saw that the source of this effect was taking any image of any color palette and reducing it to this effect, always taking 14 frames to finish the loop.

Input frame:

Result of effect:

I'm not sure how this effect is being performed, I'm hoping someone will be able to help me duplicate it. This is for a game where I'm using C#. If I can get something working in C# I'll probably move it over to a shader. I'm using the MonoGame platform.

# Answer
> 3 votes
The effect you're going for is less of a pure hue shift and looks more like old-school palette shifting effect. On old hardware this was implemented by arranging the color palette used for the image such that there was a run of similar colors (for example, a series of blues increasing in saturation, in the case of your first image) and then shifting and rotating the values in that palette by one (modulo the palette size).

Most modern hardware does not support palette images or rendering.

However, you can simulate the effect fairly easily by creating a 1D texture that contains the range of colors you'd like to cycle through. This will serve as your palette. You'll also want a texture that represents which part of that palette to sample for any given fragment being rendered. This index texture is essentially a grayscale version of your sprite.

Each texel in the index texture/sprite is actually a texture coordinate that looks up a position in the 1D palette texture. In your shader, simply read the index texture and use that result to look up into the color palette texture:

```
// Since the index is grayscale, you only need to deal with one
// component of the resulting color.
float index = texture2d(textureCoordinates, yourIndexTextureSampler).r;
vec4 color = texture1D(index + shiftUniform, yourPaletteTextureSampler);
...

```

The gray values in the index texture should be based on the number of colors in your palette. Let's say you have eight values in your palette and your index texture uses 8 bits per component. You'd use colors like the following in your index image:

```
0, 0, 0        palette entry 0
32, 32, 32     palette entry 1
64, 64, 64     palette entry 2
...

```

All you're doing here is dividing up the color space in the index image into eight discrete buckets so that when you feed that color (which the hardware will turn into value between 0 and 1 for you) back into the dependent texture read for the color texture you'll get the appropriate color (because *that* texture is also broken up into eight discrete chunks, one for each color in the palette).

That will give you a basic approximation of palette-based rendering. To implement shifting, simply add a uniform that represents the shift (which varies over time) and add that to the sampled index value, modulo the range of the palette. In the shader example above, there's no explicit modulo operation because texture address wrapping can take care of it for you.

---
Tags: c#, shaders, monogame, color
---


# Question
Title: What's an optimal procedure to create a connected cyclic grid of nodes and edges for A* pathfinding
like the title says, I'm trying to create a grid of nodes that hold edges or connections to each other so I can perform A\* algorithm to have objects traverse across them as seen in your standard RTS.

I want to know if there is a general structure and algorithm for this node grid data structure as I can't find a good resource online. For instance, I will be moving my objects via position (Vector3) so I will have to calculate my edge weight to be the magnitude between two nodes. Is this a standard practice?

Could anyone perhaps guide me to the rough basics on how this is achieved in a standard RTS? I would greatly appreciate any information!

# Answer
There's not much mention of the nitty gritty because basically this is the hard part, and it depends on your situation. A\* is an easy algorithm to implement but translating from real world maps to actual data nodes is not a pleasant problem.

The approach I use in my game is to use collision detection to fill up a big 2d grid with the unblocked areas. But this would have to be adjusted for 3d.

For other games I have seen people manually place nodes onto the terrain in their game worlds and then have their program pick up and process the nodes into a graph.

For some I have seen something similar to what I did above except in 3d. Using collisions AND gradients to tell if an area is walkable - ie you can walk up a hill but you can't walk up a cliff. Basically you are flood filling outward and accept any location without too much of a gradient as a valid step.
> 1 votes

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


# Question
Title: How to use Irrlicht game engine in cygwin?
How can I develop a game with Irrlicht game engine in a cygwin environment?

I tried google, but honestly I didn't find any useful tutorials about setting that game engine in cygwin.

Thanks, Ehsan.

# Answer
I highly recommend using MSYS2 instead of Cygwin. It is basically a well-maintained fork of Cygwin that includes ① the Mingw-w64 toolchain (basically, GCC for Windows), ② a robust package manager (`pacman` from Arch Linux) and ③ packages for the Irrlicht engine.

Once MSYS2 is installed, you can install GCC and Irrlicht from an MSYS2 shell:

```
pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-irrlicht

```

Here is a simple Irrlicht program that you can try; it just opens a window and clears the screen:

```
#include <irrlicht/irrlicht.h>
using namespace irr;
using namespace core;
using namespace video;

int main() {
    IrrlichtDevice *device = createDevice(video::EDT_SOFTWARE, dimension2d<u32>(640, 480), 16, false, false, false, 0);
    device->setWindowCaption(L"Hello World");
    IVideoDriver* driver = device->getVideoDriver();
    while (device->run()) {
        driver->beginScene(true, true, SColor(255,100,101,140));
        driver->endScene();
    }
    device->drop();
}

```

To compile your project from an MSYS2 shell:

```
/mingw64/bin/g++ example.cpp -lIrrlicht -o example.exe

```

And to launch it:

```
./example.exe

```
> 3 votes

# Answer
I wouldn't waste your time on trying to get it going in cygwin. You would probably actually HAVE to move to mingw to get it to work.

And even if you did get it working there's many issues with cygwin.

If you want to do game development that's definitely not the way to go unfortunately. I have tried before and it was a big headache.

If you just want to run some stuff other people made, it probably still won't work. And if it does it will be with a ton of effort.

Not good news, but that is just the reality.
> 1 votes

---
Tags: c++, irrlicht
---


# Question
Title: How to draw Alpha Masked fragments' depth to depth buffer?
I feel like an absolute idiot for asking this. But how exactly do safely draw the depth of a fragment featuring a Masked ( Alpha 1) texture on it's surface?

So far I've literally been doing a depth test on truly opaque geometry.

Here's a logarithic Z-bufer from GTA. And yes... it's strange that I know that and how to do it... but not a alpha mask depth.

EDIT: From this, it looks like it's actually possible to write solid texture data to the depth buffer, and ignore the binary transparency.

Here's an image that's an example of the problem I would like to solve.

# Answer
> 1 votes
In the case of a masked texture, only fully opaque pixels should update the depth buffer. Any pixel that is partially or completely transparent should *not* update the depth buffer. Updating the depth buffer will prevent pixels of greater depth from being drawn/calculated, and pixels with alpha need to blend with pixels in the background. If no blending occurs, then you update the depth buffer, otherwise skip it.

---
Tags: opengl, directx, graphics
---


# Question
Title: Specular Light not working (Phong Lighting)
There seems to be a problem with my current Phong Shading implementation. I have been using the per fragment approach. The specular highlight aspect of the technique is not rendering as it should, as a matter of fact it is not rendering at all. My shininess is at 100, but nothing seems to appear. What could be the problem?

```
glUniform1f(Shin_location, 100.0f);

```

Vertex Shader:

```
  #version 400

  layout (location = 0) in vec3 VertexPosition;
  layout (location = 2) in vec3 VertexNormal;

  out vec3 fragPosition;
  out vec3 fragNormal;

  uniform mat4 rotation_matrix;
  uniform mat4 ModelViewMatrix;
  uniform mat3 NormalMatrix;
  uniform mat4 PVM;

  void main()
   {

       fragNormal   = normalize(NormalMatrix * VertexNormal);

       fragPosition = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0));

       gl_Position = PVM * rotation_matrix * vec4(VertexPosition, 1.0);
    }

```

Fragment Shader:

```
                                     #version 400

 in vec3 fragPosition;
 in vec3 fragNormal;

 uniform vec4 LightPosition;
 uniform vec3 LightIntensity;
 uniform vec3 Kd;
 uniform vec3 Ka;
 uniform vec3 Ks;
 uniform float Shininess;

layout (location = 0) out vec4 FragColor;

vec3 ads()
  {
    vec3 n = normalize(fragNormal);
    vec3 s = normalize(vec3(LightPosition) - fragPosition);
    vec3 v = normalize(vec3(-fragPosition));

    vec3 r = reflect(-s, n);

    return LightIntensity * (Ka + Kd * max(dot(s, n), 0.0) + Ks *  pow(max(dot(r, v), 0.0), Shininess));
   }

  void main()
   {
      FragColor = vec4(ads(), 1.0);
   }

```

Main:

```
    // Vertex Position
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(VERTEX_POS, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
    glEnableVertexAttribArray(VERTEX_POS);

    // Color
    glBindBuffer(GL_ARRAY_BUFFER, VBO[1]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(color), color, GL_STATIC_DRAW);
    glVertexAttribPointer(COLOR, 3, GL_FLOAT, GL_FALSE,  0, nullptr);
    glEnableVertexAttribArray(COLOR);

    // Normal Vertex
    glBindBuffer(GL_ARRAY_BUFFER, VBO[2]);
    glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
    glVertexAttribPointer(NORMALS_POS, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
    glEnableVertexAttribArray(NORMALS_POS);

    GLint rot_location  = shader.getUniformRotLocation();
    GLint proj_Location = shader.getUniformProjLocation();
    GLint PVM_Location  = shader.getUniformPVMLocation();

    GLint LightPos_location        = shader.getUniformLightPositionLocation();
    GLint LightIntensity_location  = shader.getUniformLightIntensityLocation();
    GLint KD_location              = shader.getUniformKDLocation();
    GLint KA_location              = shader.getUniformKALocation();
    GLint KS_location              = shader.getUniformKSLocation();
    GLint Shin_location            = shader.getUniformShininessLocation();
    GLint MV_location              = shader.getUniformModelViewMatrixLocation();
    GLint NM_location              = shader.getUniformNormalMatrixLocation();

    glm::vec4 lightpos = glm::vec4(5.2f, 3.1f, 2.0f, 1.0f);

    glm::mat4 model_matrix(1.0f);
    glm::mat4 view_matrix = glm::lookAt(glm::vec3(0.0f, 3.0f, 5.0f), glm::vec3(0.0f, 0.75f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f));

    glm::mat4 ModelViewMatrix =  view_matrix * model_matrix;

    glm::mat3 NormalMatrix    =  glm::mat3(1.0f);

    glm::mat4x4 rot_matrix(1.0f);
    glm::mat4x4 proj_matrix = glm::perspective(45.0f, 4.0f/ 3.0f, 0.1f, 100.0f);

    glm::mat4x4 PVM = proj_matrix * view_matrix * model_matrix;

    float angle = 0.957283f;
    const float angle_in_degrees = 0.01f;
    float Rotate = 0.0f;

bool stop = false;

glEnable(GL_DEPTH_TEST);

```

while loop:

```
    glm::mat4x4 PVM = proj_matrix * view_matrix * model_matrix;

    glUniformMatrix4fv(rot_location,  1, GL_FALSE, glm::value_ptr(rot_matrix));
    glUniformMatrix4fv(PVM_Location, 1, GL_FALSE, glm::value_ptr(PVM));
    glUniformMatrix4fv(MV_location, 1, GL_FALSE, glm::value_ptr(ModelViewMatrix));
    glUniformMatrix3fv(NM_location, 1, GL_FALSE, glm::value_ptr(glm::mat3(glm::vec3(ModelViewMatrix[0]), glm::vec3(ModelViewMatrix[1]), glm::vec3(ModelViewMatrix[2]))));

    glm::vec4 worldLight = view_matrix * lightpos;

    glm::vec4 vec = glm::vec4(10.0f * cos(angle), 3.0f, 10.0f * sin(angle), 1.0f);

    glUniform4f(LightPos_location, vec.x, vec.y,vec.z, vec.w);

    glUniform3f(KD_location, 0.9f, 0.5f, 0.3f);
    glUniform3f(KS_location, 0.95f, 0.9f, 0.9f);
    glUniform3f(KA_location, 0.1f, 0.1f, 0.1f);
    glUniform1f(Shin_location, 100.0f);

    //Clear the framebuffer with dark green
    static const GLfloat dark_green[] = {0.0f, 0.25f, 0.0f, 1.0f};
    static const GLfloat one = 1.0f;
    glClearBufferfv(GL_COLOR, 0, dark_green);
    glClearBufferfv(GL_DEPTH, 0, &one);

```

# Answer
> 0 votes
```
vec3 viewDir = normalize(viewPos - FragPos);
float spec = pow(max(dot(viewDir, reflectDir), 0.0), shininess);
vec3 specular = specularStrength * spec * lightColor;

```

You need viewDir and reflectionDir.

Your reflectionDirection looks ok.

Your viewDirection looks messed up though.

You also have them backwards from the norm but it shouldn't matter.

If that is not the problem then make sure your Kd/specularStrength is not zero.

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


# Question
Title: Unity / How do I change the color of an object based on its depth?
The objective here is to **change the color of the nearest object**. (the nearer the object, the more "colorful" the object gets rendered; and the farther away, the more "grey" the object gets rendered), so far away objects are completely grey and close objects are in full color.

How I'm thinking about this so far:

You know, every frame, there is this certain float value, which determines if a pixel should be drawn or not. (aka z-buffer)

Can anyone tell me the variable - name of it? Or how can I access it? Can I even access it?

Edit:

> The GPU is comparing two values: the depth of the new fragment you're drawing (a) and the depth value of whatever's already been drawn in that spot of the depth buffer (b).
>
> Typically if b \<= a it skips drawing the fragment because it's behind whatever's already been rendered previously.

I think I need both (a) and (b) variables - since I always need the nearer one.

Im not sure though... I think its also fine if I could only access the (b) and check every frame if the previous b was smaller.

# Answer
The lowest-effort way to get what you describe:

> far away objects are completely grey and close objects are in full color

...is to **use fog**, either directly through the Lighting settings for your scene (see the Fog entries at this link, no custom shaders required) or by using the legacy shader paths.

Here's an example of what it looks like with linear fog on a series of four identical red cubes at increasing distance:

This is also straightforward to incorporate into a **Surface shader**:

To do this, we add a fog colour parameter in the shader `Properties` block:

```
_FogColor ("Fog Color", Color) = (0.5, 0.5, 0.5, 1)

```

and define a corresponding variable in our `CGProgram`: `fixed4 _FogColor;`

Then modify our `Input` struct to include the `screenPos` parameter, which signals to Unity that it should pass the screenspace position of the fragment to us:

```
struct Input {
    float2 uv_MainTex;
    float4 screenPos; // This we add.
};

```

Now we use the z value of this screenspace coordinate to blend between our texture colour and the fog colour, z being the depth or distance of the fragment from the camera:

```
void surf (Input IN, inout SurfaceOutputStandard o) {
    // Albedo comes from a texture tinted by color
    fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
    c = lerp(c, _FogColor, saturate(IN.screenPos.z * 0.05f));
...

```

Here the `* 0.05f` is just a magic number to get the fog to fall off over the example depth range I was using. In practice you might want to expose extra variables to control the fog density or falloff distance.

Note that applying it this way only affects the object's albedo. Lighting and shadow will be applied on top of this colour. To apply the fog at the end, we can do this in a `finalcolor` method instead:

```
#pragma surface surf Standard fullforwardshadows finalcolor:mycolor
...
void mycolor(Input IN, SurfaceOutputStandard o, inout fixed4 color)
{
    color = lerp(color, _FogColor, saturate(IN.screenPos.z * 0.05f - 0.5f));
}

```

...also note that the snippets above were written for a DirectX system, where screenspace z increases with distance. To make it work on DirectX and OpenGL you might need to add a bit like this:

```
#if (defined(SHADER_API_GLES) || defined(SHADER_API_GLES3)) && defined(SHADER_API_MOBILE)
    // multiply z by -1 before using it to compute fog amount.
#endif

```

Lastly we can do this in a **vertex/fragment shader pair** like so (using an unlit shader in this example for simplicity):

```
Shader "Unlit/UnlitManualFog"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _FogColor ("Fog Color", Color) = (0.5, 0.5, 0.5, 1.0)
    }
    SubShader
    {
        Tags { "RenderType"="Opaque" }
        LOD 100

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                // Add a variable to carry depth information
                float depth : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed4 _FogColor;

            v2f vert (appdata v)
            {
                v2f o;
                // Transform vertex into view space
                o.vertex = mul(UNITY_MATRIX_MV, v.vertex);
                // Copy the viewspace z coordinate and call it depth
                o.depth = o.vertex.z;
                // Finish transforming the vetex by applying the projection matrix
                o.vertex = mul(UNITY_MATRIX_P, o.vertex);

                o.uv = TRANSFORM_TEX(v.uv, _MainTex);
                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                fixed4 col = tex2D(_MainTex, i.uv);
                // Blend colour using depth parameter we calculated earlier
                return lerp(col, _FogColor, saturate(-0.05f * i.depth));
            }
            ENDCG
        }
    }
}

```

To answer your **"bonus question"** about reading from the depth buffer to change behaviour based on what's already rendered, I'd recommend checking out the Unity presentation "Special Effects with Depth." It's a five years old now, but the core techniques hold up, and it gives a solid primer on how this works in Unity, what you can use it to achieve, and what costs it comes with.
> 4 votes

---
Tags: unity, shaders, fog, shaderlab
---


# Question
Title: How can I model AI Interactions across the entire game world without computing them individually?
I'm making a 2D top-down tile-based game in C++ using SDL2. The game uses a very large world map (think Dwarf Fortress).

My world terrain is generated using a noise function, another function is then used to build towns, model NPCs, etc. which are then saved to a local SQLite database (I'm using a database because NPC states, for example, are quite complicated - the database models their relationships with other NPCs, changing personalities, goals etc., and can be affected by player interactions with them as well).

At any point in time during play, the player is in some 'sector' of the world map. Currently, only interactions in the player's current sector are modeled (e.g. NPCs talking to each other, NPCs fighting each other etc.).

How can I model interactions across the entire world map, without the obvious computational problems of modelling every single interaction that occurs?

Is there some pattern which can generalise interactions?

The game uses time heavily (where a minute of game-time is a second in real-time, and thus in-game minutes, hours, days, months and years can be used). Could I somehow compute large-scale estimations of changes overtime? Some of these changes could be computed on player entry into the sector, based on how long it has been since the player has been in that sector (e.g. NPC getting older, dying of age etc.), but some changes should occur as they actually 'happen' (e.g. cross-sector things like an army or a trader travelling across the map).

# Answer
You must to divide your whole world into parts, and check is each of them is close/further from your position. It gives you priorities how frequently you should update your map part. Because there are some algorithms which allow to optimise such updates.
> -1 votes

---
Tags: ai, tilemap, maps, events, perlin-noise
---


title: Best way of making scenes persistent?

text:
# Question
Title: Best way of making scenes persistent?
I am using Unity 2D for the past 2 weeks and when it came for changing rooms i got disappointed. Its not like ex. Gamemaker where you press a button and the room becomes persistent. I have though a way of making the scenes persistent and thats:

\*Save all the variables that make the scene as it is(positions, etc.)

\*Change scene.

\*Move back to the same scene.

\*Apply the saved data.

So, will this work? If it doesnt work or if its not good, what is the easiest way of doing that?

Thanks in advance

# Answer
> 1 votes
you can use `DontDestroyOnLoad` on any gameObject to make it persistent between scene changes. Then simply have some logic that either enables or disables the object based on the level name. Another approach is to have everything in the same scene but on different layers and switch between cameras to render the desired object. Your way is also viable but its a pain in the ass to implement.

Edit: Like it was suggested in the comments instead of using the different layers approach all the room objects could be parented to a single empty gameObject and then you can enable disable that object. This might very well be the simplest thing to do.

---
Tags: 2d, unity, scenemanager
---


# Question
Title: Unity - Exporting and Importing Terrains
To provide modding support via Unity editor, I need to export terrains in editor and load the exported terrain in runtime.

Is this possible by any manner?

# Answer
Right Click on the terrain and click "Export Package", open the package in an archiving program then open the "archtemp.tar" from within that package.

Copy The "Asset" File and give it the file extension ".asset".
> 1 votes

---
Tags: unity, terrain, modding
---


title: Why are my screen images flashing?

text:
# Question
Title: Why are my screen images flashing?
I'm currently working on a 2D Java Game. When I start the game everything works fine with a constant framerate. When I'm using normal graphics methods to draw shapes nothing happens. But as soon as I draw images (`BufferedImage`s) they start to randomly flashing white.

I've already removed every single line of my code that might have cause any performance issues. All that I'm currently using is:

Launcher (main) class:

```
public class Launcher
{
    public static void main(String[] args)
    {
        new Engine().run();
    }
}

```

Engine class:

```
public class Engine implements Runnable
{
    private static final String TITLE = "My Game";
    private static final int WIDTH = 1280;
    private static final int HEIGHT = WIDTH / 16 * 9;

    private static final int MAX_BUFFER_STRATEGY = 3;

    private static Engine instance;

    private static boolean isRunning;
    private Thread thread;

    private BufferedImage image1 = Utils.Images.load("/symbol1.png");
    private BufferedImage image2 = Utils.Images.load("/symbol2.png");

    public Engine()
    {
        instance = this;

        new Display(TITLE, WIDTH, HEIGHT);

        run();
    }

    private void tick()
    {

    }

    private void draw()
    {
        BufferStrategy strategy = Display.get().getCanvas().getBufferStrategy();

        if(strategy == null)
        {
            Display.get().getCanvas().createBufferStrategy(MAX_BUFFER_STRATEGY);
            return;
        }

        Graphics graphics = strategy.getDrawGraphics();

        graphics.clearRect(0, 0, Display.get().getWidth(), Display.get().getHeight());

//      graphics.drawImage(image1, 100, 100, 200, 200, null);
//      graphics.drawImage(image2, 200, 200, 200, 200, null);

        strategy.show();

        graphics.dispose();
    }

    @Override
    public void run()
    {
        start();

        while(isRunning)
        {
            Time.calculate();

            try
            {
                Thread.sleep(20);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            while(Time.tick())
            {
                tick();
            }

            while(Time.draw())
            {
                draw();
            }
        }
    }

    public synchronized void start()
    {
        if(!isRunning)
        {
            isRunning = true;

            thread = new Thread(this);
            thread.start();
        }
    }

    public synchronized void stop()
    {
        if(isRunning)
        {
            isRunning = false;

            try
            {
                thread.join();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void destroy()
    {
        instance.stop();

        try
        {
            Thread.sleep(250);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        System.exit(-1);
    }
}

```

Display class:

```
public class Display extends Canvas
{
    private static final long serialVersionUID = 1L;

    private static Display instance;

    private JFrame jFrame;

    public Display(String title, int w, int h)
    {
        defaults(title, new Dimension(w, h));

        instance = this;
    }

    private void defaults(String title, Dimension dimension)
    {
        setPreferredSize(dimension);
        setMinimumSize(dimension);
        setMaximumSize(dimension);

        jFrame = new JFrame();

        jFrame.setTitle(title);
        jFrame.setSize(dimension);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jFrame.setResizable(false);
        jFrame.setLocationRelativeTo(null);
        jFrame.setIgnoreRepaint(true);

        jFrame.setVisible(true);

        jFrame.add(this);
        jFrame.pack();
    }

    public Canvas getCanvas()
    {
        return this;
    }

    public JFrame getJFrame()
    {
        return jFrame;
    }

    public static Display get()
    {
        return instance;
    }
}

```

Time class:

```
public class Time
{
    private static final int TIME_COUNTS = 2;

    private static final int FPS = 60;
    private static final double TIME_PER_TICK = 1000000000 / FPS;

    private static double[] lastTime = new double[TIME_COUNTS];
    private static double[] deltaTime = new double[TIME_COUNTS];
    private static double[] time = new double[TIME_COUNTS];

    public static void init()
    {
        lastTime[0] = System.nanoTime();
        lastTime[1] = System.nanoTime();
    }

    public static void calculate()
    {
        for(int i = 0; i < TIME_COUNTS; i++)
        {
            time[i] = System.nanoTime();
            deltaTime[i] += (time[i] - lastTime[i]) / TIME_PER_TICK;
            lastTime[i] = time[i];
        }
    }

    public static boolean tick()
    {
        if(deltaTime[0] >= 1)
        {
            deltaTime[0]--;
            return true;
        }
        return false;
    }

    public static boolean draw()
    {
        if(deltaTime[1] >= 1)
        {
            deltaTime[1]--;
            return true;
        }
        return false;
    }
}

```

Utils class:

```
public class Utils
{
    public static class Images
    {
        public static BufferedImage load(String path)
        {
            try
            {
                return ImageIO.read(Images.class.getResource(path));
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return null;
        }
    }
}

```

I hope someone knows what I'm doing wrong and may have a clue how to help.

# Answer
In your Main you create an Engine object an Call `run()` on it. But in the constructor you also Call run.

Could it be that you have two Threads where you want only one ?
> 0 votes

# Answer
Try changing the value of MAX\_BUFFER\_STRATEGY to 2, it sounds to be like there isn't a doubble buffer on the code, if nto comment below the rest of the code, and i will have a mess around with it later on, or might be able to see something else.
> 0 votes

---
Tags: java, graphics
---


# Question
Title: How do I calculate collision response between a sphere and a plane?
I'm trying to create a simple 3D game and need to constrain the player within the limits of the game world. When the player hits the sides of the world I want the player's ship to bounce off slightly.

In effect I'm trying to trap the player within a box, and stop them from escaping through the sides...

I've managed to define the limits of the gameworld as a collection of planes, with normals and distances from the origin. The player has a spherical bounding sphere and from following this website http://www.gamasutra.com/view/feature/3383/simple\_intersection\_tests\_for\_games.php I have managed to detect collisions.

I now can't quite work out what to do when a collision is detected. The best I can manage is the player getting stuck in the plane, going straight through it, or bouncing repeatedly off it at a really fast rate.

Common sense tells me I need to calculate the reflected angle off the plane, using its normal and apply that to the player's velocity, however I think I need to first see if the player has gone through the plane which is the bit I can't work out.

# Answer
> 4 votes
You'll have to apply an impulse to your object, which is an immediate change in it's velocity. In the real world, a powerful force would be applied to the object over a very short timestep, reversing its acceleration and causing its velocity to change. However, since we're working in a discrete world, we have to cheat a bit to simulate this abrupt change in direction. For a sphere and a plane, it's pretty straightforward. The most basic collision response is to reflect the sphere's velocity around the plane's normal, and then the result is the sphere's new velocity. Pseudo-code would look something like this:

```
reflected = 2 * plane.normal * (plane.normal * sphere.velocity)
sphere.velocity -= reflected

```

From there, you can add some damping (multiply by some coefficient, like 0.9) to account for energy lost to heat or friction. If you want to get angular velocity involved (perhaps your sphere is rotating), then the equations get a little more complicated.

For more info, I'll refer you to Chris Hecker's articles on Rigid Body Dynamics. If you haven't heard of Chris Hecker before, he's well known for game physics as well as his work on the procedural character generation and animation in Spore.

# Answer
> 1 votes
F = ma, or a = F/m. Calculate the collision point between the sphere and plane. This is usually Sphere centre - normal\* radius. If you want more accuracy, calculate how far the sphere has penetrated the plane, and adjust your calculation. This is largely optional of course, unless you want really accurate physics. Now calculate the relative velocity along the normal. For a static plane this is: Vball Dot N. Then Multiply VballDotN by -1, and multiply by mass. In physics at this stage you would also multiply this by the coefficient of restitution (bounce factor). Multiply this scalar by N and you have your force.

When adjusting Vball, divide the force by mass again and you have the final acceleration, so just add this to the velocity and you have your final post collision velocity.

```
vec3 Vrel = Ball.getVelocity();
float vDotN = Vrel.Dot(CollisionNormal);
vec3 F = -(1.0f+Ball.getRestitution())*vDotN;
F*=Ball.getMass();
Ball.accelerate(F/Ball.getMass());

```

This method is accurate to the formulae of collision response. If you want even more accuracy, you will want to take friction into account, which will cause the ball to spin, but I don't know if you want that in your game. In case you do, this is how you calculate the tangential force:

```
vec3 Ft = -(Ball.getvelocity()+(vDotN*CollisionNormal));
Ft*=Ball.getKineticFriction()+Wall.getKineticFriction(); //you could fudge these numbers
Ft*=Ball.getMass();
vec3 vec2Centre = Ball.getPosition()-ContactPoint;
vec3 Torque = cross(vec2Centre,Ft);
Ball.AngularAccelerate(Torque/Ball.getMomentofInertia(glm::normalize(Torque)));

```

Make sure to calculate Ft before applying any linear effects, or the friction won't be accurate.

# Answer
> 0 votes
I would suggest calculating you distance from plane first; and then when the distance \<= to the radius carry out the collision reaction.

You can then alter this to calculate distance and if the distance is less that radius( which mean the object is overlapping) shift the balls position and then carry out the collision reaction.

---
Tags: c++, 3d, collision-detection, vector
---


# Question
Title: Synchronize objects' movements moved by coroutine function
I'm using Unity version 5.3.5.

I'm having problems to synchronize the movement of three different objects from point A to point B and vice versa. To move the objects I use the following code:

```
public float time;
public Vector3 endPos;
private Vector3 startPos;

 void Start()
 {
     startPos = transform.position;
 }

 void FixedUpdate()
 {
     if(transform.position == startPos)
     {
         StartCoroutine(Move(gameObject.transform, startPos, endPos, time));
     }
     if(transform.position == endPos)
     {
         StartCoroutine(Move(gameObject.transform, endPos, startPos, time));
     }
  }

 public IEnumerator Move(Transform thisTransform, Vector3 startPosition, Vector3 endPosition, float time)
 {
     float i = 0f;
     float rate = 1/(time);
     while(i < 1)
     {
         i += Time.deltaTime * rate;
         thisTransform.position = Vector3.Lerp(startPosition, endPosition, i);
         yield return null;
     }
 }

```

As long as all of the objects have the same "time" value, their movements is correctly synchronized regardless the distance that they have to cover. The problems arises when they all have different "time" value. For example, if they have to move backwards and forwards from startPos(0,0,0) and endPos(5,0,0) with the following "time" value:

* Object A time = 1 second
* Object B time = 2 second
* Object C time = 4 second

After 4 second, they should all be again at the same start position. However, what happen is that the fastest object (Object A) has a delay over the other two and this delay increase over time.

How can i fix this problem?

# Answer
I would say the reason is there is small numeric error in position computation. Because you `i +=` the error starts accumulating resulting in out-of-sync after some time. In order to overcome this, I would suggest a different implementation. Try calculating the position from total time on move:

```
public float startTime;
public float time;
public bool move = true;

void Start()
{
   //you probably want to re-set the start time if you resume moving later
   startTime = Time.time;
}

void FixedUpdate()
{
   if(!move) return;
   float delta = Time.time - startTime; //note: not Time.deltaTime
   //get remainder for round trip
   float tripTime = Mathf.Repeat(delta, time * 2.0f/*time back and forth*/);
   if(tripTime < time) //from start to end
   {
      thisTransform.position = Vector3.Lerp(startPosition, endPosition, (tripTime / time));
   }
   else //from end to start, tripTime is between (1.0, 2.0)
   {
      //subtract 1 to get into (0.0, 1.0) range, and 1 to reverse movement
      thisTransform.position = Vector3.Lerp(startPosition, endPosition, 2.0f - (tripTime / time));
   }
}

```

note: code not tested, but I hope you get the idea
> 0 votes

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


title: Using brand names in game?

text:
# Question
Title: Using brand names in game?
Playing Game Dev Tycoon I noticed they rename all the console and company brands ever so slightly. Is something like this done in parody or to avoid copyright?

For example Nintendo is Ninvento and has the consoles name TES (Super TES, TES 64 etc.)

In many pokemon games (I know they are licensed by nintendo though) they make direct references to consoles.

My question is, can you make a game and directly reference Sony Playstation or SNES etc?

# Answer
> 2 votes
Names are not covered by copyright (although logos would be). Names are subject to *trademark*.

Generally, yes, using the name "Ninvento" instead of "Nintendo" is an attempt to avoid trademark infringement. Generally one does this when creating a parody, as positioning oneself as such allows one to attempt to employ a "fair use" defense if or when one is served with legal action concerning the name.

Simply changing a name slightly is *not sufficient* to grant immunity to trademark or other intellectual property action. It's not a get-out-of-jail-free card; even if you can successfully argue "fair use" due to parody (or whatever) you generally need to go to court to do so.

If you are thinking about using marks that are similar to existing trademarks, you should consult a lawyer about the best course of action for your project. If you are thinking about using *actual* trademarks (that is, "directly referencing" Sony's products or the Super Nintendo, et cetera), you should *definitely* consult a lawyer, as you will need to obtain permission from the IP holder.

---
Tags: trademark
---


# Question
Title: android - How Do I Replace A Scene in Cocos2D
I am using Cocos2D for Android: I have two scenes `MainScene` and `LogoScene`. I want to show a Splash screen on `LogoScene` then, I want to go to `MainScene`.

I am wondering how I can go from `LogoScene` to `MainScene` using:

```
CCDirector.sharedDirector().replaceScene(MainScene.scene());

```

What is an example of Scene Transition from a splash screen to the main scene?

# Answer
The splash screen can just be another scene and you can transition between them using scene transition effects. Just change the code to match this

```
Director::getInstance()->replaceScene(TransitionFade::create(0.5, mainMenuScreen, Color3B(0,255,255)));

```

This creates a fade effect between your screens. Hope it gives you the desired effect.
> 0 votes

---
Tags: android, cocos2d, ccsprite
---


# Question
Title: Why does this whirlpool simulation not work?
I am trying to create a simple whirlpool simulation, where particles are constantly compelled to move towards a point in a whirlpool like fashion.

To do this I do the following (in sudo code)

```
variable speed = 1.0 //This can vary to speed things up
Rotate by (70 * speed) degrees
Move Forward (4 * speed) Steps
Point Towards center

```

And this works quite nicely, however as the particles get nearer to the center it breaks down causing there to be an area where they just circle around never getting closer to the center. The larger the speed variable is the larger the radius is that they begin to not move closer to the center.

If one decreases the rotate by to a value of like 50 degrees the anomaly is much smaller, however the points rotate around the center many less times.

Why is this happening? How can I fix this?

I am open to completely changing the method I use even if it means physics, however polar coordinates will not work because of the way the center moves among other simulation reasons.

# Answer
Your mathematics simply fail at some point.

Consider this case: The particle is 0.00000000000001 units from the center. Apparently it should rotate 1000000000 times around the center, given the speed it has, and given your iteration time for this re-calculation.

Move it a little bit out, to 0.0000001 units from center. Now it should only rotate 10000 times around center during T.

Move it further out, to 0.001. Maybe it should now rotate 10 times?

Even if it needs to rotate only once, it fails. Your maths work only if it shall rotate 1/10 of a full circle, or maybe the limit is 1/20, ie. and arc of 18 degrees?

A re-aim of 70 degrees * speed-model fails at distance D, whatever D may be. It simply aims erratically and will not get closer to the center. Apparently it finds a balance, or then goes to hell, as you say :-).

Just re-calculate a new, smaller radius first (somehow), then see how much distance it consumes along it's path this time (or how much it shall travel, where it ends), and re-position by a polar coordinate or similar.
> 1 votes

---
Tags: physics, mathematics, trigonometry
---