# Question
Title: SDL - Limiting loop with timer? Not polling
I am using SDL/Glew to create an engine for a game I want to make. I am trying to set a constant framerate of like around 60 (once every 17ish ms). I don't know the best way to do this so I do attempted to do it with a timer.

```
//Main Loop
int EngineLoop(int interval, CEngine* engine)
{
    Input->Poll();
}
//---------

void CEngine::Start()
{
    _running = true;

    SDL_AddTimer(17, (SDL_TimerCallback)EngineLoop, this);
}

```

The input poll is this:

```
void CInput::Poll()
{
    SDL_Event evnt;

    while (SDL_PollEvent(&evnt))
    {
        switch (evnt.type)
        {
        case SDL_MOUSEMOTION:
            *(Rect*)(&MousePosition) = Rect(evnt.motion.x, evnt.motion.y);
            *(Rect*)(&MouseDelta)    = Rect(evnt.motion.xrel, evnt.motion.yrel);

            break;

        case SDL_MOUSEBUTTONDOWN:
            _mouseButtons[evnt.button.button - 1] = true;
            break;

        case SDL_MOUSEBUTTONUP:
            _mouseButtons[evnt.button.button - 1] = false;
            break;
        }
    }
}

```

This system works perfectly when I put it in some random class function to pump as much as it'd like. But when I introduced the timer, nothing works, no input is taken and the window freezes up. Is it because I am not Polling the events quick enough or?

I tried using a separate timer function that called the class function to poll the input because maybe having it on a different thread is the reason, that didn't work either.

So why didn't this work?
What other approach should I take if necessary?

# Answer
> 2 votes
SDL\_AddTimer is a problem here. SDL\_AddTimer spawns a new thread, and things won't work like you expect when using multiple threads. When you call SDL\_Init(), you likely do it from the main thread, and that's where your event queue is, so when you call SDL\_PollEvent() from your timer thread, it won't have access to the internal SDL event queue, and thus will not return your events.

As for resolving this issue, you could change your code to keep everything on one single thread (e.g. each loop, check how much time execution took and sleep for whatever time is left). Or take a look at the SDL\_AddTimer documentation, it has some specific recommendations about how to resolve this issue: https://wiki.libsdl.org/SDL\_AddTimer

In any case though, you can only poll for events from the same thread that initialized SDL.

---
Tags: input, multithreading, sdl2, events, timer
---


# Question
Title: Change animation speed through the editor in Unity
How can I change the speed of the animation through the editor if I have the following animation structure?

I would like Adult1@walk to play faster.

# Answer
> 1 votes
Select your Blend Tree.

In the section where you assign animations to the blend tree, there is a column for changing the animation speed. Change the value there from 1 (normal speed) to make the animation on that line play faster or slower.

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


# Question
Title: How do I read color data from UTexture2D in UE4?
Here's my code:

```
// get RenderTarget2D
static ConstructorHelpers::FObjectFinder<UTextureRenderTarget2D> TargetObj(TEXT("/Game/Textures/RenderTexture"));
// generate a UTexture2D
CameraTexture = TargetObj.Object->ConstructTexture2D(Target->GetOuter(), "mytexture", Target->GetFlags(), 255);
//Turn off Gamma-correction
CameraTexture->SRGB = 0;

//Guarantee no garbage collection by adding it as a root reference
CameraTexture->AddToRoot();

//Update the texture with new variable values.
CameraTexture->UpdateResource();

GetColor(CameraTexture);

```

...

```
FLinearColor ANextGenHUD::GetColor(UTexture2D *MyTexture2D)
{
     FColor* FormatedImageData = static_cast<FColor*>(MyTexture2D->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_ONLY));
     for (int32 y = 0; y < MyTexture2D->PlatformData->Mips[0].SizeY; y++)
     {
         for (int32 x = 0; x < MyTexture2D->PlatformData->Mips[0].SizeX; x++)
         {
             int32 curPixelIndex = (y * MyTexture2D->PlatformData->Mips[0].SizeX) + x;
             FColor c = FormatedImageData[curPixelIndex];
             c.A = 255;
             MyTexture2D->PlatformData->Mips[0].BulkData.Unlock();
             return c;
         }
     }
}

```

This code is a bit messy fo testing purposes, but shoiuld theoretically get me the color of the first pixel. Instead it just gives me a random color the constantly changes as well when I draw it on the HUD.

What am I doing wrong?

# Answer
`BulkData` is platform and format specific. It isn't an array of colors, and it may not be valid at all. If you really want to read the bulk data of the texture, you have to determine the file format (via the `PixelFormat` in the `PlatformData` and decode it. You probably don't want to do this.

(You're also unlocking the bulk data inside the loop, but locked it outside the loop, so only the first read is reasonable.)

What you can do instead is (on the render thread), use the RHI to lock the desired mip level of the texture and read that. You'll still have to understand some basic information about the format (such as the number of components per texel), but you won't have to parse the DXT5 compression or whatever other platform specific magic is actually stored in the bulk data:

You can use `RHILockTexture2D` for this purpose, something like:

```
FTexture2DResource* Resource = (FTexture2DResource*)MyTexture2D->Resource;
uint32 Stride = 0; // Assigned by RHILockTexture2D.
void* MipData = RHILockTexture2D(
  Resource->GetTexture2DRHI(),
  MipIndex,
  RLM_ReadOnly,
  Stride,
  false);

```

`MipData` will point to the color data of the texture, in whatever format is appropriate (e.g., you'll want to cast it to a byte if you have 8-bit component textures, whether or not the bytes are RGBA, ARGB, RGB, et cetera, depend on the format, and so on).

Make sure to use `RHIUnlockTexture2D` when you are done.

It's also worth noting that this isn't necessarily particularly *fast*, so it's probably not something you want to be doing every frame if you can avoid it.
> 2 votes

---
Tags: c++, textures, unreal-4
---


# Question
Title: Animating compression wave shader which uses image for displacement map
I've been testing a variety of shockwave or ripple effect shaders, and spent time on this cleaned up and improved version on shadertoy.

I'm not entirely satisfied with that because it produces an ugly "bubbling" effect in the center. I'm trying to add a stronger "compression" effect to the shockwave itself but everything I do results in a stronger bubbling effect in the center.

I've found an example of what I want which uses an image for the displacement map: example

The author of that example only provided a sample of the shader code which I've been able to port. However, I don't understand how to animate this (to expand outward) over time.

Here's my current port into hlsl for Unity:

```
Shader "Hidden/Shockwave2"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _GradientTex ("Texture", 2D) = "white" {}
    }
    SubShader
    {
        // No culling or depth
        Cull Off ZWrite Off ZTest Always

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

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

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 vertex : SV_POSITION;
            };

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                return o;
            }

            sampler2D _MainTex;
            sampler2D _GradientTex;

            fixed4 frag (v2f i) : SV_Target
            {
                fixed2 center = fixed2(.5, .5);

                fixed2 dir = normalize(i.uv - center);

                // Get the pixels off of the maps.
                fixed4 gradC = tex2D(_GradientTex, i.uv);

                // Read the pixel from the displaced position.
                fixed2 pos = i.uv;
                pos.x += (gradC.r * 2.0 - 1.0) * 0.025;
                pos.y -= (gradC.g * 2.0 - 1.0) * 0.025;

                return tex2D(_MainTex, pos * dir);
            }
            ENDCG
        }
    }
}

```

This produces the correct visual, but I need to animate its expansion outward.

# Answer
> 1 votes
You could avoid the displacement map altogether using something like this:

https://www.shadertoy.com/view/ltXBDs

Basically, i create a radius that represents the wave, and make the sample the `uv + direction * (coef/(coef + (signed_difference_from coord to wave))`. You shouldn't have what you call bubbling here and it should in effect compress. You could layer multiple of these on top of one another as well to get multi waves. I also have a factor that is a function of the radius of the wave that reduces the power of it as it goes out.

You can get bubbling back by doing the negative of dir, in order to pull textures from the opposite direction, and you can remove part of the effect on either side by only distorting uv if the radius of the current uv is \< or \> than the wave radius.

If you are really set on the displacment map route, you can accomplish this by *dividing the values used for the sampler over time* then add that value to your current uv position. Something like this:

```
void mainImage( out vec4 fragColor, in vec2 fragCoord ) {
    float slowiTime = iTime/2.0;
    // Sawtooth calc of time
    float offset = (slowiTime - floor(slowiTime)) / slowiTime;
    float time = slowiTime * offset;

    // Find coordinate, flexible to different resolutions
    float maxSize = max(iResolution.x, iResolution.y);
    vec2 uv = fragCoord.xy / maxSize;

    // assuming getting in as vec4, and assuming the values are not signed,
    //we need to offset values to get signed values out, assuming only one
    //value in texture actually used, make sure not to tile the texture, so that all
    // value outside the map itself turn to zero.
    // may need to translate if source of wave not in center of screen
    vec2 displacment_map_value = texture([your_displacement_texture], uv/time).xy;
    displacement_map_value -= halfway_offset;
    // should be zero if not in the bubble, or outside the texture itself
    distorted_uv += displacment_map_value;
    texture_color = texture([your_actual_texture], distorted_uv);

    fragColor = texture_color;
}

```

Note you will probably have to write the entire scene to some frame buffer and use that as a source texture for your actual texture to get this effect to appear on top of everything you want it to.

What this does is at the start, make sure only the center fragments are actually grabbing from the bubble (as uv/time will be large) then as time goes on uv/time will be smaller and all coordinates will be chosen closer and closer to the center of the image (creating the expanding effect). The displacement map should already have the direction encoded into it from the center, if you need it moved use a translation, but regardless all you should have to do is add the displacement value to your uv to get a proper sample. magnitude should be encoded into the xy pair retrieved from the displacement map as well.

---
Tags: shaders, glsl, fragment-shader
---


# Question
Title: Gamemaker studio 2 getting error message
I'm currently using gamemaker studio 2 following a youtube guide on making my first game. I am very new to coding and need some help.

Im getting this error message attached to my code and I'm not sure why.

# Answer
It should be

```
dash_key = keyboard_check_pressed(ord("C"));

```

Note the double quotes ( **"** ) instead of single quotes ( **'** ). If done correctly the `"C"` should be yellow in the editor to signify that a `string` is present.
> 1 votes

---
Tags: game-maker
---


# Question
Title: GameMaker Studio 2: DnD - How do I change Idle animation to Walking Animation
I have an idle animation into an object. I am able to have it moved to one point, left & right but but the problem is transitioning from Idle to Walking Forward. I did tried step but I realized that it's for animation ticks, and I can't really find any tutorials on it yet.

How do make a smooth animation transition from Idle to Walking?

# Answer
sprite\_index changes the sprite and image\_index changes the frame of the sprite

also now setting the speed in the sprite editor for that sprite (default is 15) will set the speed for the transition to the next frame.
> 1 votes

---
Tags: game-maker
---


# Question
Title: Typedef redefinition error when running Unity iOS project in Xcode 9 simulator
I was able to run my Unity 2017.1.0b10 iOS project successfully on my iPhone 6S+ (Using Xcode 9). I changed the `Target SDK` to `Simulator SDK` to try it out on other device simulators then I got the following errors in the `UnityMetalSupport.h` file.

Below are screenshots of my player settings:

# Answer
I got the same error. It looks like simply deleting/commenting out those offending lines works.

```
//typedef NSUInteger MTLPixelFormat;
//enum
//{
//    MTLPixelFormatBGRA8Unorm,
//    MTLPixelFormatBGRA8Unorm_sRGB,
//};

```
> 1 votes

# Answer
Check your build device, change any simulator to "Generic iOS Device". The ENUM produced these errors are already defined in iOS simulators.
> 0 votes

---
Tags: unity, ios
---


# Question
Title: How can I replicate the look of Zelda: BotW in my own shaders?
At the moment I really want to develop a game with a similar shading technique that is used in Zelda BOTW however I do not know how I can achieve that look?

To me it looks like they are using a cel shading technique with rim lighting, however I do not know is how to design textures or use them to achieve similar results. Or even if I’ve got the right basic idea.

I would really like to know how these kind of aesthetics could be replicated and if it would be possible using a tool like Substance Designer (using a PBR workflow) or not.

# Answer
## The Cell Shader

To create a similar effect you will need two or three diffuse textures for the same number of brightness steps.

Use `smoothstep` with a small range to soften the colour band transitions.

As BotW uses different colour hues not just brightness steps for the dark and bright areas of each "colours" you need different diffuse textures. You can't simply make the colours darker/brighter.

This is where most of the style comes from.

This gives a lot of freedom allowing unlit surfaces (eyes), changing details and colours as things get brighter or darker, and other effects.

For example a different hue for the hair when dark and purple/blue dress:

You'll also need a brightness shifting map to add textures to the different surfaces. This simulates ambient occlusion and a bit of subsurface scattering.

The texture is signed (value * 2 - 1) so areas can be made darker ( \< 50% gray) or brighter ( \> 50% gray) compared to normal (50% gray).

You can see the pattern for the sleeves (top left), hair (top right), and dress (bottom right).

And a specular colour map to control the specular amount and its colour:

And the usual normal map (omitted for brevity).

This is the result (without post-effects such as bloom or blue filters for night time that are used extensively throughout the game.)

* Different colours on the sleeves and the hair for the dark/bright/specular shades
* Different brightness thresholds creating hair-strands effect and rougher dress material
* The eyes have only a single brightness level and no specular (it's faked into the texture)

Video of effect: https://www.youtube.com/watch?v=4Vhfmzl31nU

Example GLSL fragment shader code:

```
vec4 diff0 = texture(smp0, uv.xy); // dark "diffuse"
vec4 diff1 = texture(smp1, uv.xy); // bright "diffuse"
vec4 shift = texture(smp2, uv.xy); // brightness shift texture
vec4 specular = texture(smp3, uv.xy); // specular colour

float brightness = length(lights_diffuse_factor.rgb) + (shift.r - 0.5) * 0.3;
float specular_brightness = dot(lights_specular_factor.rgb, lights_specular_factor.rgb);

float band0 = smoothstep(settings.edges.x, settings.edges.y, brightness);

result_color =  mix(diff0, diff1, band0)
                + specular * specular_brightness;

```

## The Environment

The environment uses an ordinary shader. The texture are painted to look more like acrylic paint brush strokes using desaturated colours.

## The Post Effects

You'll need to add at least a bloom post-effect.

This is done by using a copy of the rendered frame buffer as a texture, cutting off everything below a certain threshold and interpolating the remainder back to the range 0.0 to 1.0. This can be accomplished using for example `smoothstep(0.8, 1.0, color)` (remaps the range \[0.8, 1.0\] to \[0.0, 1.0\], cutting off everything below 0.8)

Example (I'm using Gimp here to break down the shader steps):

Then blur the result (use a lower mip map, multiple samples, and/or multiple feedback passes, the choice is up to you, the engine's capabilities, and what the target platform handles best) and apply additively to the frame buffer:

## The Night Effect

Then a de-saturation, colouring, and brightness curve filter can be applied to create the night effect.

De-saturation and colouring can be done with a matrix multiplication or as discrete steps:

```
float gray_scale = dot(colour.rgb, vec3(0.33333, 0.33333, 0.33333));
vec3 desaturated = monochrome_colour.rgb * gray_scale;
colour.rgb = mix(colour.rgb, desaturated, desaturation_factor);

```

The brightness curve filter can be done with a texture lookup, a Bezier curve, a fixed exponent `colour.rgb *= colour.rgb`, or a power function such as `colour.rgb = pow(colour.rgb, exponent_factor_here)`.
> 10 votes

---
Tags: shaders, textures, lighting
---


# Question
Title: Unity - using WWW to download image from web. Not working from my own website, but does from other urls
I have this script attached to a `RawImage` file in my games UI

```
public class DownloadImage : MonoBehaviour {
     string url = "http://megabrogames.rf.gd/pic.jpg";
     //string url = "https://i.imgur.com/xBSyvRx.jpg";

     IEnumerator Start () {
         WWW www = new WWW(url);
         yield return www;
         GetComponent<RawImage>().texture = www.texture;
     }
 }

```

Both jpg files are the same. One I uploaded to Imgur, this works. The other is on my own website. The url to my website works fine, I have checked in on two computers and several browsers.

All I get is the red question mark. But if I uncomment the other one instead it all works perfectly.

My problem is that I have hard-coded the url into the game, and I want to change the image each week. It has to be the same URL for that to work, but i think with Imgur it will auto assign whatever url it feels like.

thanks for any help

# Answer
OK, yes the URL is no good now because I have been fiddling about changing things since posting. But long story short, I tried 3 webhosts and they all blocked hotlinking so my game couldnt get the file. (NOTE: I only tried free hosting options)

Anyway, there was a far easier solution all the time.. i joined GithubPages and hosted a website on that domain which I have full control over. The game pulls the file from that server without issue.
> 0 votes

# Answer
Looks like your URL is no good.
> 1 votes

---
Tags: unity, web
---


# Question
Title: What is the best practice for calculating a succesful action?
Say for example in my game a player is able to kill an NPC, and there is an x% chance of an item dropping.

When calculating if the item actually dropped or not, what is the best way to calculate a success or failure?

Does the context of the action matter? Would you calculate drop chance the same way as a different RNG event? (x% to gain a perk, etc).

# Answer
The simplest way to do random chance events is to generate a random decimal number from 0 to 1, multiplying it by one hundred, and then seeing if that number is less than or equal to the percentage drop chance. Here's some psuedocode:

```
float random = Random.generateDecimal() * 100;
if(random <= dropChance) /*Give the player the item.*/;

```

The problem with this is that there is a possibility that your RNG might generate a string of random numbers that results in a number of failures or successes that *seems* to be disproportionate to the given drop chance even though the outcome was a perfectly possible statistical probability. This will result in either a frustrated player or an unbalanced play session.

I've actually been thinking about this myself for a time, and here is a potential solution:

1. Determine the drop chance.
2. Calculate the number of trials for which it would be expected that exactly one trial would result in success.
3. Randomly generate a list of outcomes that guarantees one success.
4. Cycle through that list each time the action is executed.

Here's some psuedocode for making the array for clarity's sake:

```
float dropChance = 0.25;
int numberOfTrials = 1 / dropChance;

int successfulTrialNumber = (int) (Random.generateDecimal() * numberOfTrials)
boolean[] outcomes = new boolean[numberOfTrials];
for(int i = 0; i < outcomes.length; i++) {
    outcomes[i] = (i == successfulTrialNumber);
}

```

This guarantees that the player won't feel "cheated" while still maintaining enough chance variation to make the outcome seem truly randomly determined. However, the downside to this is that you'll have to keep a separate list of outcomes for each action because different actions have different success rates.

We can fix this by using one array for all of our chance variation events so they don't have to all have the same percent chance of occurring. We'd generate a single master array containing a list of numbers from 1 - 100 (or maybe 1 - 1000 if you wanted some decimal drop chances) and then having all outcomes draw on the next step of this array.

Last bit of pseudocode:

```
int[] outcomes = new int[100] /*You would fill this array with random numbers from one to one hundred with no repeats.*/
int outcomesPointer = 0;
public void generateOutcome(int percentSuccessChance) {
    if(percentSuccessChance <= outcomes[outcomesPointer]) /*Success*/;
    outcomesPointer++;
}

```

This helps to minimize the feeling of "cheapness" while maintaining pseudo randomness.

Sources: Here's where I learned that true randomness in games can lead to bad outcomes: https://www.youtube.com/watch?v=sLXLlJ7FhJU

The pseudocode solutions were made up by me on the spot.
> 4 votes

---
Tags: random
---


# Question
Title: Tilemap Collision w/ different height levels and directions
I've been programming a final fantasy 6 clone in C# using Monogame and Monogame Extended, and have met on a few interesting challenges regarding tilemap collision.

The game seems to have different height levels on tilemaps, such as in the picture below where the bridge is on one height level and the ground on another. I'm using Tiled for my maps and have the bridge on it's own layer, and the ground on another. However, when it comes to collision, you shouldn't be able to for example walk up on the bridge and end up on the ground, which leads to the problem of collision detection. Collision for the ground level should be different than on another height level like the bridge, but I'm not sure what a good solution to handle that could be.

Since I'm using TiledMap from Monogame Extended, I can't really modify the Tile class to hold collision data. My initial idea was to have an extra object or tile layer for each height level to specify collision/solids for each height level, but I found that it wasn't very intuitive and that it was a little messy. Optimally I would only need one tile layer per height level, but I'm at a loss for any ideas on how to handle collision in a scalable and intuitive way, so I was wondering if anyone here had any ideas?

Another interesting problem is regarding tile collisions and directions. For example, when standing in front of the fence in the picture below, you should not be able to walk up and behind the fence. But, if you are standing one tile above the fence, you should be able to walk down and behind it, but once you are behind it you should not be able to walk down again and end up in front of it.

I think the solution to that problem is to define collisions on each edge of the tile, so that the bottom edge of the tile is marked as solid, while the other edges aren't. The main issue with that is that I have no idea how to implement something like that with Tiled. It also presents the problem of rendering, since the tile would need to be rendered below the player if the player stands in front of it, and above the player if the player stands behind it. I think using a Z-index would solve it, but again, I haven't found a way to implement that using Tiled. Soo, I was wondering if anyone has any ideas or pointers on how to use Tiled w/ Monogame + Monogame Extended to implement those things?

# Answer
> 0 votes
I can't comment to any specific feature in monogame that will help you, but I can help you a bit with figuring out what needs to be done in general.

First you need some way of drawing certain tilesets over your character, there is no way around this, if your API doesn't allow z ordering, or different tile layers that can be drawn on top, you *literally cannot do anything you want with out extending the API some how*. Your in luck though since it appears you can orient render order on tilemaps.

You'll then need to have a *separate data structure for collision*, you wouldn't attach it to the tile map anyway. It seems that there are some collision classes included with monogame extended based on the github.

The collision data could be stored in a grid the size of your map with only boolean data of collidable and not collidable. This could be as simple as 2D array of boolean values.

You wouldn't just have one of these though, for each layer you would want one of these, for example top and ground portions of your first image.

To get the guard rail collision working with this system, you could simply make those places not collidable on the second level.

The only thing missing from this system so far is stairs. To get from one place to another you may want to change your collision array into an enum of tile properties for example:

```
enum TileMovement {
    Allowed,
    Blocked,
    StairsDown,
    StairsUp,
    ...
};

```

and check if the tile is stairs, then move to the appropriate level after getting off the tile. You could also add other special tile types that would block from a given direction, but this would make your code more complicated (though could alleviate the need for additional levels on some maps)

`StairsUp` would be stairs that if you step onto you would end up at the next level, `StairsDown` would be stairs that if you step off of you would end up at a lower level.

---
Tags: c#, xna, monogame, tiled, monogame-extended
---


# Question
Title: libpng warning: iCCP: known incorrect sRGB profile
I was working with SDL2 and when I loaded some textures, I got this warning in the console ***libpng warning: iCCP: known incorrect sRGB profile*** Though this doesn't cause any error, everything works fine but I just wanted to know what this warning is about.

This is the picture I'm trying to load, maybe the fault is in the picture?

# Answer
This is a warning that can be safely ignored. If you want to remove it you have to remove the iCCP chunk from the image. You should be able to do this with any image editing program. For example if you're using `ImageMagick` you could do something like `convert your-image-name.png some-other-name.png`. Here's a reddit thread about removing the warning as well.
> 1 votes

---
Tags: c++, textures, sdl2
---


# Question
Title: Difference between Object.Destroy() and GameObject.Destroy() in Unity
What is the difference between using `Object.Destroy()` and `GameObject.Destroy()` in Unity?

I found the following info about that: here and here, but it did not answer my question.

So, could someone explain the matter foolproof, please?

# Answer
> 1 votes
None. `GameObject.Destroy()` is inherited from `Object.Destroy()`. Both statements refer to the same method.

This is *not* explicitly clear in the official API documentation, but most programmers can assume that to be the case based on the fact that both `GameObject` and `Object` contain the method, and `GameObject` inherits from `Object`. It can then be confirmed through IDEs or through the *unofficial decompied source-code by MattRix on GitHub* (`GameObject`'s source code does not contain the `Destroy()` method, meaning it can only come from inheritance).

As such, you will also find the `Destroy()` method on anything else in the inheritance tree of `Object`. For example, `Component` also inherits from `Object`, and so you can add a `Destroy()` statement within any component's code, without explicitly including `Object.` before it.

Note: My answer is independent, but some credits to Hellium for answering correctly first in the OP.

---
Tags: unity, gameobject, objects
---


# Question
Title: What datatype to use for set of needs in a needs system in C#?
I am currently gaining experience in Unity by trying to make a basic Citysim. Since its based on a really small town all my citizen are actual Agents rather than statistical calculations.

I am currently thinking about an Need System but I can't decide on a datatype.

**Requirements for the Need System**

* All needs are regularly iterated over to decrease their Satisfaction level
* Certain events trigger a function specific to each need: `OnSeekNeed()`, `OnSatisfyNeed()`
* Different Actors have different needs: Drug addict has a need "Drugs"
* It should be possible to add new generic needs or remove needs from each actor at runtime: Discovery of Internet `AddGenericNeed(Citizen c, Need n, float satisfaction)`
* It should be able to add new needs to the game without changing other classes
* The need needs to be comparable: A pizza shop satisfies NeedFood but not NeedSleep\`

---

**OLD QUESTION INCLUDING SOLUTION IDEAS - feel free to ignore**

I am currently gaining experience in Unity by trying to make a basic Citysim. Since its based on a really small town all my citizen are actual Agents rather than statistical calculations.

I am currently thinking about an Need System but I can't decide on a datatype. Each Agent should have his own needs and an satisfaction value for each. Not all Agents have the same Needs, a child for example does not need romantic interactions. An addict will have special drug needs.

My first Idea was to make an own class for each need, allowing me to make more Needs for DLCs or

**Parent Need**

```
public abstract class Need
{
    public abstract void OnSeek();
    public abstract void OnFurfill();
    public abstract void OnNotFurfill();
    public abstract bool IsHidden();
    public abstract string GetName();
    //ect...
}

```

Each Character should then get needs assigned and on each update they will be looped through and the value (0-100) would be decreased by 0.25f.

**But how should I arrange the Needs in the Character Class?**

**Option1 - Harcoded Array**

Each Need has an assigned spot in an float Array.

* con: Enabling or disabling Needs requires further overhead instead of just editing the set.
* con: all Citizen need to have the same need-set
* con: no Object orientation allowing to call special events '*OnSeek()*'

**Option2 - Dictinary\<Need,satisfaction\>:**

I tough this would be the solution unfortunately it's impossible to iterate over it and change the value. If there was this with TypeOf Need as Key and an over writable value it would be perfect.

* con: It's impossible to change the satisfaction without replacing the entire node
* con: Apparently its not possible to use Types as Keys

```
private Dictionary<Type, float> n2 = new Dictionary<Type, float>();
private Dictionary<Need, float> n3 = new Dictionary<Need, float>();
//both don't seem to work

```

**Option3 - LinkedList\<Need\>:**

* con: slow to find values when events change a need for all citizen '*needs.findByType(NeedRest)*'
* con: needs can be added twice. Checking for duplicates is expensive
* con: Each need is a new Object for every Citizen containing the statisfaction float

So far I believe the Linked List will be my best bet, most of the time I will be looping through it anyway. I'll need to check for duplicates on insert but maybe somebody can help me get the Dictionary to work or knows a better solution.

Please keep in mind, I am new to C# and maybe I am missing something completely obvious... While trying to write this question I somehow managed to answer a lot of my problems and came up with something that will sort of work. I'll be posting this anyway just in case somebody is stuck on the same problem or has a solution that is way better.

# Answer
Is there anything wrong with simply having a "Need" class and having each person carry around an array of needs(need objects)? That way you could add or remove needs at runtime and each one could be tracked and manipulated per-actor.

I'm talking about having a "Need" class that would have variables for its current level, its type, etc., and then you would create a script for your actors (or add it to an existing one) where you have each actor carrying their own array of type "Need".

Then whenever you go to add a new one, if you're worried about duplicates I would have a function to step through your array on that actor and check to make sure that the one you're about to add doesn't have the same "Need.Type" as any of the ones in their array.

The array doesn't need to be in a specific order, either, you just need to know the maximum number you're ok with them having. So you could set it up to be an array of size 10 and that essentially becomes a bucket for you to store all of an actor's needs.
> 1 votes

# Answer
If you want to use a `Class` as a key in a `List<Need>`, the class must implement the `CompareTo()` operator from `IComparable<T>`.

```
class Need : IComparable<Need>
{
    enum NeedType
    {
        Food, Water, Sleep, Shelter, Drugs, Doctor, Love, Fun, Quiet, Beauty
    }
    public NeedType need;
    public float urgency=0.0f;

    public Need(NeedType n, float urg)
    {
        need=n;
        urgency=urg;
    }

    public Need(NeedType n)
    {
        need=n;
    }

    public int CompareTo(Need other)
    {
        if(other==null) return 1;
        return urgency-other.urgency;
    }
}

```

It's a bit of overkill to make `Need` a class if it doesn't track other attributes other than how much it's needed. In that case, just use the `NeedType` `enum` as the key in a `Dictionary<NeedType,float>`. This will let you quickly update the urgency of each need, check which needs they have, as well as use lambda expressions to sort the Dictionary to find the most urgent need.
> 0 votes

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


title: Terrain not rendering underneath

text:
# Question
Title: Terrain not rendering underneath
I’m having a problem with my terrain, it’s not rendering from underneath, iv’e also noticed this with any other plane I add into unity or model in blender, is this normal or is there a technical fix for this?

# Answer
This is due to Back-Face Culling.

You'll have to create a shader and set "Cull Off" in the SubShader section: See Unity Documentation on shaders.

Be warned that the normals will be inverted on the back side and will cause lighting to be incorrect on two-sided lit materials.

If you need your surface to be lit correctly on both sides you will need to either duplicate the geometry and flip the faces, or apply two materials to the mesh; one regular and one custom shader that both inverts the culling and negate the normals to render the mesh twice (once for front faces and once for the back faces).
> 5 votes

---
Tags: unity, terrain
---


# Question
Title: To implement a game object that expires, should I store the start time and total, or store the remaining time?
Example:
There is a bomb (like in *Counter Strike*) which explodes after 45 seconds. Should I—

* store the 45 seconds in a variable, and decrease it by the delta time at every update, or
* store the time when the bomb was planted, and check at every update if it is less than or equal to the current time minus 45 seconds?

How do I choose which approach to use?

# Answer
> 2 votes
There is no "best" way to do this, both methods are completely viable and personal preference. However I believe that the delta time version is superior because it's inherently less error-prone than checking the time difference.

Imagine this piece of pseudo code:

```
startTime = System.now

function update() {
    now = System.now
    difference = now - startTime

    if (difference >= 45) {
        explode()
    }
}

```

This would work great and would make the bomb explode after 45 seconds. ***However*** think about what happens if we want to pause our game. Pausing your game simply stops movement or perhaps sets delta time to 0 to emulate no time passing by. This would **break this system** since system time keeps ticking on even if you pause your game.

Of course this is quite easily fixed by using your own time system (akin to what Unity does) but, really, why bother if you can just chose the less error-prone way to begin with?

Delta time is more "safe" to use than checking the time difference. If we convert the above pseudo code it would look something like this:

```
countDown = 45

function update(delta) {
    countDown -= delta
    if (countDown <= 0) {
        explode()
    }
}

```

This is immediately more safe than the time difference since if you pause your game using delta manipulation this will also pause the timer on your bomb.

It is also easier to expand on since if you want to change how fast your bomb timer is - say speed it up 2x - you just multiply the `delta` value by your `speed` value. This is more difficult to accomplish using time difference and much less clean code-wise compared to the delta-time method.

# Answer
> 0 votes
Both are completely viable, both are best.

For my tastes, I would go with the Update() and decreasing the float of 45 seconds by Time.DeltaTime - but that is just 100% preference.

---
Tags: timer, timestep
---


# Question
Title: How should I implement hit detection netcode for AI enemies in a co-op first-person-shooter?
I'm working on a FPS/sandbox game that has multiplayer but no PvP. Since the game has no PvP, I'm trying to make the networking code favor the player as much as possible.

For example, I allow the game-clients to decide whether a shot hit/missed an enemy, rather than having the game-server verify. I also allow the game-clients to decide where they are on the map -- with no verification from the server.

This opens the doors for cheaters, but in a PvE game I don't care so much.

However, I don't know how to design the enemy AI. If a player is lagging, the server doesn't know that player's real location, so how could I ensure that the player actually saw himself get attacked by an enemy (for example, a Zombie) before the server registered a hit on the player?

# Answer
When you don't care about cheaters at all (I personally doubt that cooperative games are completely uninteresting to cheaters, but this is the premise of the question), then you could let the clients not just calculate the hits they make but also the hits they receive.

This means all hits on the player get resolved according to the world-state as perceived by the player. So there will be no situation where the player gets damaged by an attack they didn't see connect.

While this favors players, it handicaps the AI. When they make decisions solely based on the server-sided world state which then get resolved according to the client-sided world-state, they will often miss the players. In order to allow the AI to deal with that handicap, you will have to add latency considerations to your enemy AI. So when the AI wants to attack a player who has a latency of 100ms, it would extrapolate the target's current movement vector and attack the location where it will be in 100ms.

As long as the player only pays attention to themselves and their opponents, the hit detection will appear very plausible. The AI might not seem as precise as it could be. But the player will usually expect the AI opponents to not have perfect aim, so this won't be an issue. The drawback is that the game might start to look implausible when they observe opponents attacking their teammates. The player might see attacks which clearly connect from their own point of views, but don't appear to do any damage because from the teammate's point of view they dodged the attack.
> 1 votes

---
Tags: networking, ai
---


# Question
Title: Workflow for tagging a sprites with collision boxes
I have some hundred of sprites and I need to mark collision boxes of them.

What kind of workflow can I use to help this proceed smoothly?

I've thought of using Tiled initially, however one of my requirements would be to not only mark multiple collision boxes per sprite but also to mark each one with a name or type category.

I would love to have final structure equivalent to:

```
<Bodies>
    <Body id="1">
        <CollisionBox>
            <Name>BODY_COLLISION</Name>
            <Vertices>
                <Vertex>12;13</Vertex>
                <Vertex>12;17</Vertex>
                <Vertex>11;17</Vertex>
            </Vertices>
        </CollisionBox>
        <CollisionBox>
            <Name>GROUND_DETECTOR</Name>
            <Vertices>
                <Vertex>12;11</Vertex>
                <Vertex>13;17</Vertex>
                <Vertex>14;17</Vertex>
            </Vertices>
        </CollisionBox>
    </Body>
</Bodies>

```

How can I build this data quickly & intuitively?

# Answer
Turns out that using Tiled editor was good enough. I imported actor sprites as tileset and annotated variuous object in each actor "tile", I gave those objects names and exported to tileset. Then from tileset one can easly get information that is wanted (every object on image is exported with x, y, width, height and name).
> 1 votes

---
Tags: 2d, collision-detection, sprites, tools
---


title: std::map inserts a NULL pointer

text:
# Question
Title: std::map inserts a NULL pointer
I ran into an access violation reading error and when I debugged it, I saw that the insert function of std::map is inserting a NULL pointer into the map.

Though I've fixed the error by first inserting a NULL value into the map and then changing that value to the corresponding object I wanted to insert in the map. But I want to know the reason the error occurs and why it got fixed. My code looks like this:

```
void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));
}

```

In the AddTexture function, I'm first creating a texture object, loading a texture into it and putting that texture into the map. But, this one gives me an access violation reading error.

And doing this doesn't:

```
void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    mTextureList.insert(std::make_pair<int, CTexture*>(ID, NULL));
    mTextureList[ID] = texture;
}

```

So it would be great if someone can tell me why this occurs. Thanks :)

# Answer
According to the standard std::map.insert **will NOT overwrite existing elements**.

> Because element keys in a map are unique, the insertion operation checks whether each inserted element has a key equivalent to the one of an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a value).

So if you already have a `mTextureList[ID]` that is `NULL` in your map `mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));` will do absolutely nothing and leave the `NULL` in place.

Try adding an assert:

```
void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    assert(mTextureList.find(ID) == mTextureList.end()); // Check if ID already in map

    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));
}

```

This will tell you if there's already a NULL in the map.

The easy way to always insert and overwrite is to just use `mTextureList[ID] = texture;` and not use `std::map.insert` but you will possibly leak memory if you don't fist delete the previous `CTexture`.

For basic types there is no significant impact to using the `[]` operator to insert/overwrite into a map. The value in the map's pair gets initialized to zero/NULL then overwritten in the assignment.

In fact the cost of passing `std::make_pair` to `.insert` may be larger but this depends on compilers and compiler settings.

```
void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);

    auto i = mTextureList.find(ID);
    // If you don't have C++11 enabled instead of auto use:
    // std::map<int, CTexture*>::iterator i = mTextureList.find(ID);

    if(i == mTextureList.end()){
        // entry does not exist, insert new one
        mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));
    } else {
      // There's already an entry of this ID
      if(i->second){
          MESSAGE("WOOPS!, THERE'S ALREADY A TEXTURE WITH THIS ID. IS THIS OKAY?\n");
          delete i->second; // delete old texture ??? Is this safe to do?
      } else {
          MESSAGE("It's just a null, we're fine.\n");
          // Someone probably used mTextureList[ID] which created a NULL
      }
      i->second = texture; // overwrite existing entry's value
    }
}

```

Or shorter:

```
void CTextureBank::AddTexture(int ID)
{
    // Create a CTexture object, load texture into it and insert it into the Texture List
    CTexture* texture = new CTexture();
    texture->LoadTextureFromFile(mRenderer, ID);
    auto result = mTextureList.insert(std::make_pair<int, CTexture*>(ID, texture));
    if(!result.second){
       if(result.first->second != NULL){
           MESSAGE("WOOPS!, THERE'S ALREADY A TEXTURE WITH THIS ID. IS THIS OKAY?\n");
           delete result.first->second; // delete old texture
       }
       result.first->second = texture; // save new texture
    }
}

```
> 1 votes

---
Tags: c++
---


title: rotation direction

text:
# Question
Title: rotation direction
I can't understand, which direction (clockwise or anticlockwise) I should rotate my object, after I apply force on it.

So, I have rectangle ABCD (A(1,1);B(-1,1);C(-1,-1);D(1,-1)), and I apply force V(1,1) to vertex D. Of course it should rotate anticlockwise, but what kind of algorithm should I use to define it? Think I already define object speed and direction, rotation speed, but I can't handle with direction.

# Answer
You can determine the direction (and magnitude) of a torque by computing the cross product between the vector from the pivot to the point of application and the vector representing the force.

So, in your example:

```
pivot = (0, 0)
point of application = (1, -1) - pivot = (1, -1)
force = (1, 1)

```

Since all our vectors are in the 2D plane z = 0, we know our torque points along the z axis so we can compute just its z component:

```
torque = point.x * force.y - point.y * force.x
       = 1 * 1 - (-1) * 1
       = 2

```

So we have a positive torque about the z axis, corresponding to a counter-clockwise rotation in the xy plane. If the torque comes out negative, then the resulting rotation will be clockwise instead.
> 1 votes

---
Tags: 2d, physics
---


# Question
Title: GLSL - Overlap shapes generated by the same function with custom size/color
I'm trying to make a ui button shader by overlaping a rounded rectangle on another rounded rectangle but with different size and gradient color. This way I'll have a small outline of a color (e.g. grey) and the body with a grey-ish gradient.

This is how my fragment code looks so far:

```
#ifdef GL_ES
precision mediump float;
#endif

uniform vec2 u_resolution;

const float PI = 3.14159265;

// from http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
float rect( vec2 p, vec2 size, float r ) {
    return length(max(abs(p)-size+r,0.0))-r;
}

void main() {
    vec2 halfRes = 0.5 * u_resolution.xy;
    float aspect = u_resolution.y/u_resolution.x;
    // compute box
    float b = rect(gl_FragCoord.xy - halfRes, halfRes, 30.0);
    b *= rect(gl_FragCoord.xy - halfRes, halfRes * vec2(0.99, 0.96), 30.0);

    // colorize (red / black )
    vec4 c = mix( vec4(0.326,0.603,1.000,1.000), vec4(0.0), smoothstep(0.0, 13.264,b) );

    gl_FragColor = c;
}

```

You can modify it directly here by cp http://editor.thebookofshaders.com/

EDIT: I've managed to get the border, now I'll only need to fill the hollow..

# Answer
now you can control inner and outer color for UI button. if you need more option like gradiant this is useful link: https://thebookofshaders.com/06/

```
 #ifdef GL_ES
    precision mediump float;
    #endif

    uniform vec2 u_resolution;

    vec2 scale = vec2(0.85,0.6);
    vec2 transform = vec2(-50.,-90.);

    vec4 rect( vec2 p, vec2 size, float r ,vec4 InnerColor,vec4 OuterColor) {

        float shape = length(max(abs(p)-size+r,0.0))-r;
        float bigshape = length(max(abs(p)-(size+9.)+r,0.0))-r;
        vec4 border = (1.-bigshape*shape)*floor(OuterColor);
        vec4 fill = (1.-shape)*floor(InnerColor);
        return max(border,fill );
    }

    void main() {
        vec2 halfRes = 0.5 * u_resolution.xy;
        halfRes *= scale;

        float aspect = u_resolution.y/u_resolution.x;
        aspect = aspect;
        // compute box
        vec4 Rectangle = rect(gl_FragCoord.xy+transform - halfRes, halfRes, 80.,vec4(1.,1.,0.,1.),vec4(1.,0.,0.,1.));

        gl_FragColor = vec4(Rectangle);
    }

```
> 0 votes

---
Tags: 2d, glsl
---


# Question
Title: Why did sprites sometimes flicker or disappear in very old games?
I've recently been having a nostalgia run with very old video games such as Battletoads. There is one thing that these very old games seem to have in common: sprite flickering. What i mean by that is that sometimes sprites (or part of sprites) will randomly disappear and re-appear again. Why does this happen?

Here's three images showcasing what I'm talking about:

# Answer
I managed to patch together an answer for the Nintendo Entertainment System (NES) based on some Wikipedia articles and some discussion with a professor of mine.

Before I begin it's important to note that *sprite* in the context of NES means **moveable** textures. This does not apply for static textures (called "background") as far as I can tell.

---

On the NES this happens because the Picture Processing Unit (PPU) in the NES only supports a certain number of sprites. For the PPU this limit is eight per scanline and a maximum of 64 sprites in total. Because of this whenever the system tries to draw another sprite when there's already eight sprites present on the same scanline the PPU simply does not draw that sprite, and instead sets a flag noting that an "overflow" of sprites has happened.

In addition to this the PPU only supports 8x8 or 8x16 sized sprites. Knowing this we can take a look at the pictures in the question body and note that Battletoads use 8x8 sized sprites. *Aproximate image:*

From this image we can see that the sprite is actually cut up into 4 separate 8x8 sprites, and because of "sprite overflow" the bottom right sprite has failed to draw.

Because of how the PPU works it would be very annoying if a projectile completely disappeared because there were too many sprites on screen and it was drawn too late (after 8 other sprites). To combat this the game developers for the NES used the flag mentioned above as an indication that they had to "shuffle" the sprite rendering order. Re-ordering the sprites simply made the sprites on the same scanline draw in a different order than the previous frame, causing a different sprite to be left out than last time.

This is what caused the "flickering" effect of sprites appearing and disappearing randomly since they were sometimes too late in the draw order to be drawn, and sometimes not. While not perfect or aesthetically pleasing it beats out having completely invisible objects.

---

Here's a scan line visualization effect (horizontal lines) courtesy of "ritcharnd moskow" on Wikipedia:
> 3 votes

---
Tags: rendering, sprites, tiles
---


# Question
Title: Unity: RaycastHit2D continually returns point (0,0)
firstly I'm a bit of a Unity noob so sincere apologies if I've done something dumb.

I'm attempting to use a RaycastHit2D to detect when the player is on a platform. If he is, the point it returns should be passed back and used to set the player's rigidbody transform y coordinate so he sits on top of the platform.

The problem appears to be that the RaycastHit2D is continually returning a point of (0,0), so the player keeps getting reset to (x,0) - which causes an amusing bouncing effect, but not the desired effect.

Here's the code:

```
if (onPlatform) {

  RaycastHit2D walkingOnPlat = Physics2D.Raycast(rb.transform.position,Vector2.down,Mathf.Infinity,8);
            platYCollision = walkingOnPlat.point.y;
            rb.transform.position = new Vector3(x, platYCollision,-5f);

        }

```

If I can clarify anything please do let me know, and thanks in advance for your help!

# Answer
> The problem appears to be that the RaycastHit2D is continually returning a point of (0,0)

This happens if the raycast's origin is already within or in contact with an object. In these cases, the raycast's normal will be opposite to the direction it was cast, and it's result will be zero.

Please take a look at the **Physics2D.Raycast documentation**; specially this paragraph:

> Additionally, this will also detect Collider(s) at the start of the ray. In this case the ray is starting inside the Collider and doesn't intersect the Collider surface. This means that the collision normal cannot be calculated in which case the collision normal returned is set to the inverse of the ray vector being tested. This can easily be detected because such results are always at a RaycastHit2D fraction of zero.

---

Secondary notes:

Your raycast's `distance` should definitely ***not*** be set for `infinity`. Raycasts are relatively expensive, and so it's bad practice and ***very*** unrecommended to do it the way you are, currently.

When dealing with raycasts, you should make the parameters (/resulting raycast) *"as little as possible to get the job done"*.

Also, considering you are a self-admitted Unity-noob, and that's a strange way to do things if it's indeed correct, do note that the `int` for the raycast's `Layermask` is a **layermask's bit-wise flags set**, not a layer's index. If the value `8` is not a precalculated bit-mask supposed to represent a set of layers, then it's probably wrong.

Edit: To easily convert from index to layermask, you can simply do the bitwise operation to shift bits left to the correct index position. In this case, that would be `1 << 8`. Where `1` would be the binary/bit-wise `00..01`, and `<< 8` shifts that binary `1` 8 places to the left, resulting in the correct bit-wise mask: `00..0100000000`
> 1 votes

---
Tags: unity, physics, platformer, raycasting
---


# Question
Title: Easy way to project point onto triangle (or plane)
I have a mesh of triangles (navigation mesh), and a point in 3d space. This point should be "over" one of the triangles all the times. I'm trying to determine which triangle is the one the point is "over", but I can't quite figure it out.

I have found a way to tell if the point is in the triangle using one of the techniques described here, but I can't quite figure out how to project the point on the triangle (or the plane the triangle is in, for that matter). I've been looking online but I can't find anything helpful.

Does anyone know how to project a point onto a triangle (or plane)?

Also, if someone knows of a better way to test which triangle is the one the point is over, it would be appreciated.

# Answer
In that case, create an orthogonal projection matrix oriented along that normal, then transform the triangle's vertices and your point through multiplication, and it should becomes a simple 2D check to see if the point lies in the triangle (volume).

Additionally, you would aso have a Z value you could use to discard points too high above the triangle.

LookAtLH is how you could do this in D3D/XNA for example, EyePosition could be the center of your triangle, Focus would be EyePosition + normal, and updirection should be anything perpendicular to that, i.e. any of the vertices of the triangle should work.

I'm sure you can find the source for a similar LookAt transformation matrix with a little googling if you don't want to use a whole library just for one function.
> 0 votes

# Answer
There is an excellent answer to this question on the Math community of Stack Exchange: Determine if projection of 3D point onto plane is within a triangle. Which is, in turn, just a summary of this paper in Journal of Graphics Tools: Wolfgang Heidrich, 2005, Computing the Barycentric Coordinates of a Projected Point, Journal of Graphics Tools, pp 9-12, 10(3).

The transformation of the original query point to barycentric coordinates can be thought of allowing a simple conversion to a point (P’) on the plane of the triangle, or equivalently, of testing whether the query point is within an infinite triangular prism extending perpendicularly from the triangle. Here is some C++ code using the Eigen library, returning a boolean value based on four points: the query point and the vertices of the triangle. (The comments come directly from the math.stackexchange.com page cited above, except that \\$\vec u\\$ is written as \\$u\\$ because of typesetting issues.)

```
bool pointInTriangle(const Eigen::Vector3f& query_point,
                     const Eigen::Vector3f& triangle_vertex_0,
                     const Eigen::Vector3f& triangle_vertex_1,
                     const Eigen::Vector3f& triangle_vertex_2)
{
    // u=P2−P1
    Eigen::Vector3f u = triangle_vertex_1 - triangle_vertex_0;
    // v=P3−P1
    Eigen::Vector3f v = triangle_vertex_2 - triangle_vertex_0;
    // n=u×v
    Eigen::Vector3f n = u.cross(v);
    // w=P−P1
    Eigen::Vector3f w = query_point - triangle_vertex_0;
    // Barycentric coordinates of the projection P′of P onto T:
    // γ=[(u×w)⋅n]/n²
    float gamma = u.cross(w).dot(n) / n.dot(n);
    // β=[(w×v)⋅n]/n²
    float beta = w.cross(v).dot(n) / n.dot(n);
    float alpha = 1 - gamma - beta;
    // The point P′ lies inside T if:
    return ((0 <= alpha) && (alpha <= 1) &&
            (0 <= beta)  && (beta  <= 1) &&
            (0 <= gamma) && (gamma <= 1));
}

```
> 3 votes

---
Tags: geometry, projection, computational-geometry, barycentric-coordinates
---


# Question
Title: How can i make that when pressing F fast many time it will scale the object down/up smooth without waiting?
The first script is for the F pressing and calling the ScaleChange:

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

public class DroidMove : MonoBehaviour
{
    public GameObject droid;
    public ChangeScale changeScale;

    private bool toDisplay = false;

    private void Start()
    {
        droid.transform.localScale = new Vector3(0, 0, 0);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            toDisplay = !toDisplay;
            changeScale.Scale(toDisplay);
        }
    }
}

```

The second script make the scaling:

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

public class ChangeScale : MonoBehaviour
{
    public GameObject objectToScale;

    private float _currentScale = InitScale;
    private const float TargetScale = 0.7f;
    private const float InitScale = 0f;
    private const int FramesCount = 10;
    private const float AnimationTimeSeconds = 0.1f;
    private float _deltaTime = AnimationTimeSeconds / FramesCount;
    private float _dx = (TargetScale - InitScale) / FramesCount;

    private IEnumerator ScaleUp()
    {
        bool upscaling = true;
        while (upscaling)
        {
            _currentScale += _dx;
            if (_currentScale > TargetScale)
            {
                upscaling = false;
                _currentScale = TargetScale;
            }
            objectToScale.transform.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }
    }

    private IEnumerator ScaleDown()
    {
        bool downscaling = true;
        while (downscaling)
        {
            _currentScale -= _dx;
            if (_currentScale < InitScale)
            {
                downscaling = false;
                _currentScale = InitScale;
            }
            objectToScale.transform.localScale = Vector3.one * _currentScale;
            yield return new WaitForSeconds(_deltaTime);
        }
    }

    public void Scale(bool scaleUp)
    {
        if (scaleUp)
        {
            StartCoroutine(ScaleUp());
        }
        else
        {
            StartCoroutine(ScaleDown());
        }
    }
}

```

The problem is if i press on F and it start scaling up and not finished yet the scaling and i press F again instead start scaling down it's like pausing and if i keep pressing F it will keep scaling up each time a bit.

What i want is if i press F and it start scaling to one direction up.down in the middle while it's scaling then change the scaling direction.

The variable TargetScale is like max scale and InitScale is like a min. I want to keep it with the max and min but to make that if in the middle when it's scaling i press F change the scaling direction and not to pause it.

# Answer
If I understand correctly, you want to scale the object to `min` or `max`, when `F` is pressed.

Try this one out:

```
using UnityEngine;

public class TestScaleScript : MonoBehaviour {

    private readonly Vector3 maxScale = Vector3.one * 5f;
    private readonly Vector3 minScale = Vector3.one;
    private Vector3 targetScale;
    private float scaleSpeed = 15f;

    private void Awake(){
        this.targetScale = maxScale;
    }

    private void Update(){
        this.transform.localScale = Vector3.Lerp(this.transform.localScale, targetScale, Time.deltaTime * scaleSpeed);

        if(Input.GetKeyDown(KeyCode.F))
        {
            if(this.targetScale == maxScale) this.targetScale = minScale;
            else if(this.targetScale == minScale) this.targetScale = maxScale;
        }
    }
}

```

Save it as `TestScaleScript.cs` in your scripts and attach it to any `GameObject` you want. Then, press `F` couple times.
> 1 votes

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


# Question
Title: Why will my server not execute a command sent by the client in Unity 5.1?
I'm working on a very simple/basic client-server networking program, the basis of a future game I hope to create. Now the client program/project DOES successfully connect with the 'server program/project' (both completely separate). However when it comes to having the client send a request/command to the server. Well it doesn't send the command to the server, it executes it on the client.

I read about changing the 'Monodevelop' inheritance to 'NetworkBehaviour' so I did and it resulting in an error along the lines of;

Command xxx was sent to the server ...Debug.logerror(object So I seemed to have got half way there, it allegedly sent the command to the server, but the server did nothing with it. I don't know why.

Below are the relatively short programs I've got for my server and client and are pretty much the same, but if anyone can help me out I'd greatly appreciate it, as my University course didn't really go into Network Programming all that much;

**Server Code**

```
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class server : MonoBehaviour
{

    public string IP = "127.0.0.1";
    public int port = 25001;
    public int prevConns = 0;
    private int currConns = 0;

    public virtual void OnServerReady (NetworkConnection conn)
    {
        NetworkServer.SetClientReady (conn);
    }

    void OnGUI ()
    {
        if (Network.peerType == NetworkPeerType.Disconnected) {
            if (GUI.Button (new Rect (100, 100, 100, 25), "Start Client")) {
                Network.Connect (IP, port);
            }
            if (GUI.Button (new Rect (100, 125, 100, 25), "Start Server")) {
                Network.InitializeServer (20, port, false);
            }
        } else {
            //CLIENT - NOT NEEDED
            if (Network.peerType == NetworkPeerType.Client) {
                GUI.Label (new Rect (100, 100, 100, 25), "Client");
                if (GUI.Button (new Rect (100, 125, 100, 25), "Disconnect")) {
                    Network.Disconnect (250);
                }
            }
            if (Network.peerType == NetworkPeerType.Server) {
                currConns = Network.connections.Length;
                GUI.Label (new Rect (100, 100, 100, 25), "Server");
                GUI.Label (new Rect (100, 125, 100, 25), "Connections: " + currConns);

                if (prevConns != currConns) {
                    if (prevConns < currConns) {
                        Debug.Log ("NEW CONNECTION");
                        prevConns++;

                    } else if (prevConns > currConns) {
                        Debug.Log ("Lost CONNECTION");
                        prevConns--;
                    }
                }

                if (GUI.Button (new Rect (100, 15, 100, 25), "Shutdown")) {
                    Network.Disconnect (250);
                }
            }
        }
    }

}

```

**Client Code**

```
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class connection : MonoBehaviour
{

    public string IP = "127.0.0.1";
    public int port = 25001;
    public GameObject player;

    public virtual void OnClientConnect (NetworkConnection conn)
    {
        ClientScene.Ready (conn);
    }

    void OnGUI ()
    {
        if (Network.peerType == NetworkPeerType.Disconnected) {
            if (GUI.Button (new Rect (100, 100, 100, 25), "Start Client")) {
                Network.Connect (IP, port);
            }
        } else {
            if (Network.peerType == NetworkPeerType.Client) {
                GUI.Label (new Rect (100, 100, 100, 25), "Client");
                if (GUI.Button (new Rect (100, 125, 100, 25), "Disconnect")) {
                    Network.Disconnect (250);
                }

                if (GUI.Button (new Rect (100, 150, 100, 25), "Send Cmd")) {
                    CmdSendCommand ();
                }

            }
        }
    }

    [Command]
    void CmdSendCommand ()
    {
        NetworkBehaviour.print ("HELLO");
    }
}

```

# Answer
> 6 votes
As per the documentation, `[Command]` and `[ClientRpc]` should be in a `NetworkBehaviour`, not in a `MonoBehaviour`. `NetworkBehaviour`'s must be spawned using `NetworkServer.Spawn()`. Moreover you should use a `NetworkClient` `Object` to connect to the Server.

Take a look at this

**Note:** As of Unity 5.1 offline documentation is not up to date. Even some aspects of online documentation are misleading. This is the way I have implemented it.

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

public class MatchMaker : MonoBehaviour
{
    public MatchManager matchManager;
    public string ip = "127.0.0.1";
    public int port = 2349;

    NetworkClient client;

    bool showGUI = true;
    bool isServer = false;
    int clientLimit = 1;
    int curretCount = 0;

    private static MatchMaker instance;

    public static MatchMaker Instance { get { return instance; } }

    public List<Player> players;

    const short PLAYER_SYNC_AFTER = 1203;
    const short PLAYER_SYNC_BEFORE = 1205;
    const short GRID_MESSAGE_X = 1240;
    const short GRID_MESSAGE_Y = 1230;
    const short PLAY = 1440;

    public int sizeX;
    public int sizeY;

    public static bool networkSpawn = false;

    void Awake ()
    {
        instance = this;
        players = new List<Player> ();
    }

    void OnGUI ()
    {
        if (isServer && networkSpawn) {
            if (GUILayout.Button ("Play"))
                Play ();
        }

        if (!showGUI)
            return;

        if (GUILayout.Button ("Host Game"))
            HostGame ();
        if (GUILayout.Button ("Join Game"))
            JoinGame ();
    }

    public void Play ()
    {
        matchManager.gm.BeginGame ();
        NetworkServer.SendToAll (PLAY, new EmptyMessage ());
        NetworkServer.ClearHandlers ();
    }

    public void HostGame ()
    {
        NetworkServer.Listen (port);
        NetworkServer.RegisterHandler (MsgType.Connect, OnClientConnected);
        NetworkServer.RegisterHandler (PLAYER_SYNC_AFTER, OnRecievePlayerAfter);
        // HACK Can Changer Server Side Players
        players.Add (new HumanPlayer (Color.green, "Host"));
        showGUI = false;
        isServer = true;
        sizeX = 15;
        sizeY = 10;
    }

    public void JoinGame ()
    {
        client = new NetworkClient ();
        client.RegisterHandler (MsgType.Connect, OnServerConnected);
        client.RegisterHandler (PLAYER_SYNC_AFTER, OnRecievePlayerAfter);
        client.RegisterHandler (PLAYER_SYNC_BEFORE, OnRecievedPlayerBefore);
        client.RegisterHandler (GRID_MESSAGE_X, OnGridSizeX);
        client.RegisterHandler (GRID_MESSAGE_Y, OnGridSizeY);
        client.RegisterHandler (PLAY, (NetworkMessage msg) => {
            matchManager.gm.BeginGame ();
            client.UnregisterHandler (MsgType.Connect);
            client.UnregisterHandler (PLAYER_SYNC_AFTER);
            client.UnregisterHandler (PLAYER_SYNC_BEFORE);
            client.UnregisterHandler (GRID_MESSAGE_X);
            client.UnregisterHandler (GRID_MESSAGE_Y);
            client.UnregisterHandler (PLAY);
        });
        client.Connect (ip, port);

        // TODO Cutomize Client
        players.Add (new HumanPlayer (Color.yellow, "CLient"));
        showGUI = false;
    }

    void OnServerConnected (NetworkMessage msg)
    {
        client.Send (PLAYER_SYNC_AFTER, new PlayerMessage{ color = players [0].color, name = players [0].name });
        Debug.Log ("Server Connected");
    }

    void OnClientConnected (NetworkMessage msg)
    {
        Debug.Log ("Client Connected");
        foreach (var player in players)
            NetworkServer.SendToClient (msg.conn.connectionId, PLAYER_SYNC_BEFORE, new PlayerMessage {
            name = player.name,
            color = player.color
        });

        NetworkServer.SetClientReady (msg.conn);

        curretCount++;
        if (curretCount == clientLimit) {
            NetworkServer.SendToAll (GRID_MESSAGE_X, new IntegerMessage { value = 15});
            NetworkServer.SendToAll (GRID_MESSAGE_Y, new IntegerMessage { value = 10});
            NetworkServer.SpawnObjects ();
            networkSpawn = true;
        }
    }

    void OnRecievePlayerAfter (NetworkMessage msg)
    {
        var playerMessage = msg.ReadMessage<PlayerMessage> ();
        players.Add (new NetworkPlayer (playerMessage.color, playerMessage.name));

        if (!isServer)
            return;

        foreach (var conn in NetworkServer.connections)
            if (conn != null && conn.connectionId != msg.conn.connectionId)
                NetworkServer.SendToClient (conn.connectionId, PLAYER_SYNC_AFTER, new PlayerMessage {
                name = playerMessage.name,
                color = playerMessage.color
            });
    }

    void OnRecievedPlayerBefore (NetworkMessage msg)
    {
        var playerMessage = msg.ReadMessage<PlayerMessage> ();
        players.Insert (players.Count - 1, new NetworkPlayer (playerMessage.color,         playerMessage.name));
    }

    void OnGridSizeX (NetworkMessage msg)
    {
        sizeX = msg.ReadMessage<IntegerMessage> ().value;
    }

    void OnGridSizeY (NetworkMessage msg)
    {
        sizeY = msg.ReadMessage<IntegerMessage> ().value;
    }

    public class PlayerMessage : MessageBase
    {
        public string name;
        public Color color;
    }
}

```

Here is My NetworkBehaviour for `ClientRpc` and `Command`

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

public class MatchManager : NetworkBehaviour
{
    public NetworkGameManager gm;
    public bool canSpawn = false;

    public void UpdateCell (int x, int y, LineDirection lineDirection)
    {
        if (isServer)
            RpcUpdateCell (x, y, lineDirection);
        else {
            CmdUpdateCell (x, y, lineDirection);
        }
    }

    [ClientRpc]
    public void RpcUpdateCell (int x, int y, LineDirection lineDirection)
    {
        gm.UpdateCell (x, y, lineDirection);
    }

    [Command]
    public void CmdUpdateCell (int x, int y, LineDirection lineDirection)
    {
        RpcUpdateCell (x, y, lineDirection);
        gm.UpdateCell (x, y, lineDirection);
    }
}

```

# Answer
> 0 votes
A little addendum to Sri Krishna Paritala's answer:

I've noticed that a `[command]` is **executed only locally**, if it is called from inside of a `MonoBehaviour.Update()` function. To get it executed on the **server**, it was required to call the `[command]` from the context of its `NetworkBehaviour`. In other words, what fixed it was:

1. From inside the `MonoBehaviour.Update()` function, just set a local variable at the `NetworkBehaviour` class containing the `[command]`.
2. Execute the `[command]` from inside `NetworkBehaviour.Update()` if the variable from 1. is set.

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


# Question
Title: Convert gl_TexCoord[0].st to match version #330
I'm currently working on a sfml based library where I'm implementing widgets with shaders. I'm defining an quad with position and texcoord in sfml to make the shader apply to the object like this:

```
quad[0].position = sf::Vector2f(100, 100);
quad[0].texCoords = sf::Vector2f(0, 0);
quad[1].position = sf::Vector2f(410, 100);
quad[1].texCoords = sf::Vector2f(1, 0);
quad[2].position = sf::Vector2f(410, 410);
quad[2].texCoords = sf::Vector2f(1, 1);
quad[3].position = sf::Vector2f(100, 410);
quad[3].texCoords = sf::Vector2f(0, 1);

```

This way I'll make `gl_TexCoord[0].st` ready to use without dividing with resolution to make it in rage `[0, 1]`. But when I'm adding #version 330 I get a deprection error. Since I'm using OpenGL 3.3, I'm looking to stick with the moder shader methods and to avoid deprecated stuffs.

Here's how my shader looks like and works without version definition:

```
void main() {
     vec2 pos = gl_TexCoord[0].st; // deprecated since #120
     gl_FragColor = vec4(pos.y, pos.x, 1.0, 1.0); // also deprecated too
 }

```

# Answer
> 1 votes
Texture coordinates use a different system. First you need a sampler2D:

```
uniform sampler2D sampler;

```

then declare an out for the color:

```
out vec4 out_Color;

```

doesn't have to have that name IIRC. But something like that. Then in the main method:

```
out_Color = texture(sampler, texCoords);

```

where texCoords is a vec2 of the texture coordinates.

Texture coordinates are passed like an attribute in the vertex file:

```
in vec2 a_texCoord0;

```

and in the vertex shader it's just passed to the fragment shader:

```
out texCoords;

void main(){
    ...
    texCoords = a_texCoord0;
}

```

and you have to bind the texture:

```
GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureId);

```

And in 330, `attribute` is `in` and `varying` is `out` in the vertex shader. `varying` in the fragment shader is `in`

---
Tags: 2d, glsl, sfml
---


# Question
Title: How can I change object material color using time and lerp?
I'm using the following code to change the color over time.

The coloring part is working but it's changing the color too fast. Even if I change the duration value to 5 or 10 it's changing the colors less then a second and it should be 5 seconds. I tried in the Inspector to change the duration to 10 but it didn't effect, still too fast.

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

public class ChangeScale : MonoBehaviour
{
    public GameObject objectToScale;
    public float duration = 1f;
    public Vector3 minSize;
    public Vector3 maxSize;

    private bool scaleUp = false;
    private Coroutine scaleCoroutine;

    public Color startColor;
    public Color endColor;
    public float colorDuration = 5; // duration in seconds

    private float t = 0; // lerp control variable

    private void Start()
    {
        startColor = GetComponent<Renderer>().material.color;
        endColor = Color.green;
        objectToScale.transform.localScale = minSize;
    }

    // Use this for initialization
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.F))
        {
            //Flip the scale direction when F key is pressed
            scaleUp = !scaleUp;

            //Stop old coroutine
            if (scaleCoroutine != null)
                StopCoroutine(scaleCoroutine);

            //Scale  up
            if (scaleUp)
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, maxSize, duration));
            }

            //Scale Down
            else
            {
                //Start new coroutine and scale up within 5 seconds and return the coroutine reference
                scaleCoroutine = StartCoroutine(scaleOverTime(objectToScale, minSize, duration));
            }
        }

        if (Input.GetKeyDown(KeyCode.C))
        {
            t = 0;
        }
        GetComponent<Renderer>().material.color = Color.Lerp(startColor, endColor, t);
        if (t < 1)
        { // while t below the end limit...
          // increment it at the desired rate every update:
            t += Time.deltaTime / duration;
        }
    }

    IEnumerator scaleOverTime(GameObject targetObj, Vector3 toScale, float duration)
    {
        float counter = 0;

        //Get the current scale of the object to be scaled
        Vector3 startScaleSize = targetObj.transform.localScale;

        while (counter < duration)
        {
            counter += Time.deltaTime;
            targetObj.transform.localScale = Vector3.Lerp(startScaleSize, toScale, counter / duration);
            yield return null;
        }
    }
}

```

When I press on C it's changing the colors but too fast.

What I want to do is when i press on C to change slowly and smooth the color of the object.

# Answer
You need to accumulate the time as it comes and use the accumulated time for the colorLerp method.

The idea is that the t parameter needs to be framed between a *start* and an *end*. The *end* is easy to get: it's the *start* plus the `colorDuration`. We set the *start* at 0 when our "trigger" occurs, in this case when you hit `C`.

Each frame brings an increment to our duration, which brings us further away from the *start* (which we refer to "time zero" or `t = 0`), and closer to our *end*, which is `colorDuration`. `t` is simply the ratio of that accumulated time over the maximum time we care about. This way, `t` will change from 0 to 1, which is what's expected by the colour lerping method.

```
private float timeAccumulatorForColor = 0; // Value used as the base for lerping the colour.

// [...]

if (Input.GetKeyDown(KeyCode.C))
{
    t = 0;
    timeAcc = 0;
}
if (t < 1)
{
  // accumulate the time
  timeAccumulatorForColor += Time.deltaTime;
  // make sure it's between 0 and the colorDuration (which is our 'end' target)
  timeAccumulatorForColor = Mathf.Clamp(0, colorDuration, timeAcc);
  // convert it to a ratio properly usable for your colour lerping.
  t = timeAccumulatorForColor / colorDuration;
}

```
> 1 votes

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


title: LibGDX - Move camera not working

text:
# Question
Title: LibGDX - Move camera not working
I'm starting with LibGDX and I loving it so far, but I have found some troubles and I'm getting a little frustrated. I've searched a lot for a solution and tried many things, but nothing seems to work. What I want to accomplish is basically a 2d map with a rts-like camera, in other words, a map/world bigger than the viewport where I can move the camera freely. The problem is I can't make the camera move, and I'm not even sure if my world is bigger than my viewport. How can I get these two things done? I'm sure I'm doing something wrong, but I can't figure what it is. Any help would be really appreciated.

These are my classes:

**GameMain**

```
public class GameMain extends Game {

private SpriteBatch batch;

@Override
public void create () {
    batch = new SpriteBatch();
    ScreenManager.getInstance().initialize(this);
    ScreenManager.getInstance().showScreen(ScreenEnum.WORLD);
}

@Override
public void render () {
    super.render();
}

public SpriteBatch getBatch() {
    return this.batch;
}
}

```

**AbstractScreen**

```
public abstract class AbstractScreen extends Stage implements Screen {
protected AbstractScreen() {
    super(new ScreenViewport(new OrthographicCamera()));
}

// Subclasses must load actors in this method
public abstract void buildStage();

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

    // Calling to Stage methods
    super.act(delta);
    super.draw();
}

@Override
public void show() {
    Gdx.input.setInputProcessor(this);
}

@Override
public void resize(int width, int height) {
    getViewport().update(width, height, true);
}

@Override public void hide() {}
@Override public void pause() {}
@Override public void resume() {}
}

```

**ScreenEnum**

```
public enum ScreenEnum {

WORLD {
    public AbstractScreen getScreen(GameMain game, Object... params) {
        return new WorldScreen(game);
    }
};

public abstract AbstractScreen getScreen(GameMain game, Object... params);
}

```

**ScreenManager**

```
public class ScreenManager {

// Singleton: unique instance
private static ScreenManager instance;

// Reference to game
private GameMain game;

// Singleton: private constructor
private ScreenManager() {
    super();
}

// Singleton: retrieve instance
public static ScreenManager getInstance() {
    if (instance == null) {
        instance = new ScreenManager();
    }
    return instance;
}

// Initialization with the game class
public void initialize(GameMain game) {
    this.game = game;
}

// Show in the game the screen which enum type is received
public void showScreen(ScreenEnum screenEnum, Object... params) {

    // Get current screen to dispose it
    Screen currentScreen = game.getScreen();

    // Show new screen
    AbstractScreen newScreen = screenEnum.getScreen(game, params);
    newScreen.buildStage();
    game.setScreen(newScreen);

    // Dispose previous screen
    if (currentScreen != null) {
        currentScreen.dispose();
    }
}
}

```

**WorldScreen**

```
public class WorldScreen extends AbstractScreen {

private GameMain game;
private Texture map;

public WorldScreen(GameMain game) {
    this.game = game;
    map = new Texture("sprites/maps/map.jpg");
}

@Override
public void buildStage() {

}

@Override
public void show() {

}

@Override
public void render(float delta) {
    super.render(delta);

    game.getBatch().begin();
    game.getBatch().draw(map, 0, 0);
    game.getBatch().end();
    this.getCamera().translate(+500, +500, 0);
    this.getCamera().update();
}

@Override
public void resize(int width, int height) {

}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {

}
}

```

I debugged the camera and it's changing its value position, but it's not being reflected in the screen.

Also, is there a way to prevent the map texture from being scaled when resizing?

# Answer
> 1 votes
This is because you are not updating the `projectionMatrix` of the `SpriteBatch`. You have to update the projection matrix otherwise the batch will not know what do display on screen.

To fix this simply add `game.getBatch().setProjectionMatrix(this.getCamera().combined);` before your `batch.begin()` in your `WorldScreen` and anywhere else you use the batch.

Your update should now look like this:

```
@Override
public void render(float delta) {
    super.render(delta);

    // Important line right here
    game.getBatch().setProjectionMatrix(this.getCamera().combined);
    game.getBatch().begin();
    game.getBatch().draw(map, 0, 0);
    game.getBatch().end();
    this.getCamera().translate(+500, +500, 0);
    this.getCamera().update();
}

```

---
Tags: java, libgdx, camera
---


title: Frame independent box2d object movement

text:
# Question
Title: Frame independent box2d object movement
In my game I use box2d objects and, as I understand it, you can move them only in two ways, SetLinearVelocity, and ApplyImpulse. I need to move the object 32 pixels in 1 turn. So I make a constant speed and the next problem appears. If the laptop is connected to the charge and gives 60 frames, the object begins to move faster. How do I make frameindependent movement? Without connection - 30 FPS and the game makes slowly.

I also know that if you want to be frameIndependent you need to use this formula:

**x = x + speedPerSecond * secondsElapsedSinceLastFrame**

But i cant use this formula, because i cant set box2d position. It is make box2d itself. I only can set the Velocity :( Or may me i just dont know.

2 - it is meters per second. 64 pixels.
private void handleInput(float delta) {

```
    if (Gdx.input.isKeyPressed(Input.Keys.W)) {

        b2body.setLinearVelocity(0, 2);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.S)) {

        b2body.setLinearVelocity(0,-2);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.A)) {
        b2body.setLinearVelocity(-2, 0);
    }

    if (Gdx.input.isKeyPressed(Input.Keys.D)) {
        b2body.setLinearVelocity(2, 0);
    }
}

```

How can i move object in another way or how to make movement frameindependent? SetTransform is not a good decision becasuse collisions are ignored. Thank You!

# Answer
Box2D has a step ( on your world object ) to update everything, that's where you should put your timestep in.
> 1 votes

---
Tags: box2d, movement
---


title: Failed LockRect of IDirect3DSurface9

text:
# Question
Title: Failed LockRect of IDirect3DSurface9
I have hooked Present method of the IDirect3DDevice9 interface, and I want to be able to start video capturing.

Taking a screenshoot like this work

```
if (GetAsyncKeyState('O') & 1) {
pDevice->CreateOffscreenPlainSurface((rect.right - rect.left),(rect.bottom - rect.top),D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&back_buffer, NULL);
pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back_buffer);
D3DXSaveSurfaceToFile(L"C:\\screenshot.bmp", D3DXIFF_BMP, back_buffer, 0, NULL );

IDirect3DSurface9_Release(back_buffer);

```

}

I seem to fail to lock the surface with **0x8876086C(D3DERR\_INVALIDCALL)**

```
HRESULT APIENTRY hook_Present(IDirect3DDevice9* pDevice, const RECT* pSourceRect,const RECT* pDestRect, HWND hDestWindowOverride,const RGNDATA* pDirtyRegion) {
IDirect3DSurface9*back_buffer;
D3DDEVICE_CREATION_PARAMETERS cparams;
RECT rect;
pDevice->GetCreationParameters(&cparams);
GetClientRect(cparams.hFocusWindow, &rect);
if (GetAsyncKeyState('R') & 1) {
    if(dx9Capturing == 0) {
        //Create the AVI file
        // etc code
        dx9Capturing = 1
    }
    else if(dx9Capturing == 1) dx9Capturing = 2; // stop capturing
}

if(dx9Capturing == 1) {
    // Capture the current frame
    pDevice->CreateOffscreenPlainSurface((rect.right - rect.left),(rect.bottom - rect.top),D3DFMT_A8R8G8B8,D3DPOOL_SYSTEMMEM,&back_buffer, NULL);
    pDevice->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &back_buffer);
    D3DLOCKED_RECT  lockedRect;
    if(FAILED(back_buffer->LockRect(&lockedRect,&rect,D3DLOCK_READONLY))) {
        MessageBoxA(NULL, "Failed locking the back buffer!", "Error", MB_OK);
        return orig_Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);
    }
    for(int i=0;i<rect.bottom;i++)
        {
            memcpy((BYTE*)pBits+(rect.bottom-i-1)*rect.right*BITSPERPIXEL/8,(BYTE*)lockedRect.pBits+i*lockedRect.Pitch,rect.right*BITSPERPIXEL/8);
        }
    back_buffer->UnlockRect();
    pAviFile->AddNewFrame(rect.right,rect.bottom,pBits);
}

return orig_Present(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion);

```

}

Hooking Reset and I still have the same problem

```
HRESULT APIENTRY hook_Reset (IDirect3DDevice9* pDevice,D3DPRESENT_PARAMETERS* pPresentationParameters) {
HRESULT hr;
if(pFont) {
    pFont->Release();
}

D3DPRESENT_PARAMETERS d3dpp;
D3DDISPLAYMODE d3ddm;
direct->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm );
ZeroMemory( &d3dpp, sizeof(d3dpp));
    d3dpp.Windowed = true;
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    d3dpp.BackBufferFormat = d3ddm.Format;
    d3dpp.Flags =  D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
hr =  orig_Reset(pDevice, &d3dpp);
return hr;

```

}

# Answer
> 1 votes
The device needs to be created with D3DPRESENTFLAG\_LOCKABLE\_BACKBUFFER:

> Set this flag if the application requires the ability to lock the back buffer directly. Note that back buffers are not lockable unless the application specifies D3DPRESENTFLAG\_LOCKABLE\_BACKBUFFER when calling CreateDevice or Reset. Lockable back buffers incur a performance cost on some graphics hardware configurations.

What you should note from this is that you need to add D3DPRESENTFLAG\_LOCKABLE\_BACKBUFFER to your Present Parameters in **two** places:

1. The initial CreateDevice call, and,
2. Any Reset calls that may happen.

It is not sufficient to just add it to CreateDevice because **the original program may make a Reset call which may then overwrite your modified Present Parameters**.

---
Tags: c++, directx, directx9
---


# Question
Title: creating a process to run in c++ // i need to run a process in c++
Hey I don't know why that when I compile this code that the fear.exe process is not running I am using visual studio for my coding ide choice the project is a win32 project // application method, that I am using..

I should say that I added a new item a c++ file called main.c++ and should I use the code file that Defines the entry point for the application. or does it matter.

```
#include "iostream"
#include "Windows.h"
#include "OVR_CAPI_D3D.h"
#include "Win32_DirectXAppUtil.h"
#include "stdio.h"
#include "string.h"
#include "Shlobj.h"
#include "Shlwapi.h"

using namespace std;

int WINAPI WinMain(HINSTANCE hinst, HINSTANCE, LPSTR, int)
{
    STARTUPINFO startinfo = { 0 };

    PROCESS_INFORMATION processinfo = { 0 };

    BOOL bsuccess = CreateProcess(TEXT("E:\SteamLibrary\steamapps\common\FEAR Ultimate Shooter Edition\FEAR.exe"), NULL, NULL, NULL, FALSE, NULL, NULL,
        NULL, &startinfo, &processinfo);

    if (bsuccess)
    {
        cout << "Process Injected" << endl
            << "Process ID:\t" << processinfo.dwProcessId << endl;

    }
    else
    {
            cout << "Error to start the injected process" << GetLastError() << endl;
        }
        cin.get();
        return(0);
    }

```

# Answer
> 1 votes
A single `\` represents character escape sequence so you should replace `"E:\SteamLibrary\steamapps\common\FEAR Ultimate Shooter Edition\FEAR.exe"` with `"E:\\SteamLibrary\\steamapps\\common\\FEAR Ultimate Shooter Edition\\FEAR.exe"`

Also, you are using a hard-coded path, so if the path of `FEAR.exe` changes then `CreateProcess` will fail

---
Tags: c++, winapi
---


# Question
Title: How to handle Japanese on Windows and Linux using SDL_ttf and C++?
In SDL\_ttf, there are a few functions provided that handles non-ASCII string literals, such as:

* `TTF_RenderUNICODE_Solid`
* `TTF_RenderUTF8_Solid`

and etc. I'll be using only the two functions as part of my question.

Currently, I'm fussing over whether to stick to using `TTF_RenderUNICODE_Solid` or `TTF_RenderUTF8_Solid`, mainly because I wanted my program to be able to work flawlessly on both Windows and Linux. (No plans for Mac, because of lack of hardware).

I know for a fact, on Windows, they used UTF-16 for handling wide characters. It's pretty straightforward to use Japanese for SDL, by using `TTF_RenderUNICODE_Solid` and the use the following code, that I'm currently using, to convert from `wchar_t` string literals to `Uint16*` type that the SDL\_ttf uses:

```
static inline Uint16* Convert(wchar_t LString[]) {
    return reinterpret_cast<Uint16*>(&(LString[0]));
}

```

Thus, I can easily do:

```
SDL_Surface* textSurface = TTF_RenderUNICODE_Solid(font, Convert(L"い"), this->color);

```

But, given that any string literals, `L""` is a `wchar_t[]` type, it makes things more complicated for me if I were to port this over to Linux. The only way I know of compiling code for Linux is to use GCC, and GCC clearly defines `wchar_t` to be of 32 bits long.

Of course, I can just straight up use the UTF8 versions:

* `TTF_RenderUTF8_Solid`

And just use string literals, such as `u8"あ"`, or `u8"いいえ"`, and they will all work in most cases. The problem here is, when I store these string literals and then inspect the variables in the debugger, I would not get the values I wanted. The stored data would suffer from integer overflow, like so:

Where at the top, I used `u8"あ"` and for bottom, I used `L"あ"`. You can see how the value is no longer preserved when using UTF8 strings, but the value is preserved when using `wchar_t` type strings.

Thus, I really can't use `TTF_RenderUTF8_Solid` in SDL\_ttf to help me with Japanese encoding.

**May I ask what is the best way to go about this? And how I should correctly handle Japanese on both Windows and Linux platforms?**

Thanks in advance.

# Answer
I'm an idiot.

In C++, the compiler knows what a `u8""` string literal is, and will convert that string literal appropriately to an UTF-8 compatible string.

And since it's UTF-8, it means each character is separated into 8-bits long bytes. With this in mind, you can just point a `char*` at the string literal, and it will work as if it's an ASCII `char*` string.

The Visual Studio's Immediate Window only displays ASCII characters, and will convert some parts of UTF-8 compatible characters into multiple bytes, then display each byte as if they are ASCII characters. This will create an allusion that the values are getting integer overflowed. I was merely tricked by this until now.

Thus, the best way to render text is to use the provided UTF-8 methods:

`SDL_Surface* textSurface = TTF_RenderUTF8_Solid(font, u8"い", this->color);`

And then it should work from there. No need to do any conversion whatsoever.
> 2 votes

---
Tags: c++, windows, sdl2, c, linux
---