# Question
Title: Unreal Engine 4 - How to avoid blocking game thread when saving file to storage
I'm working on a gearvr app and trying to download an mp4 (aprox 250mb) and save it to the device.

It seems the save operation blocks the game thread, which causes the rendering to freeze for a few seconds, while the gearvr IMU remains active. The result is that the game freezes and you basically end up being able to look around a frozen quad :/

My download and save code is:

```
request->OnProcessRequestComplete().BindLambda([&](FHttpRequestPtr request, FHttpResponsePtr response, bool success) {
        if (!success) {
            return;
        }

        TArray<uint8> data = response->GetContent();
        FString path = FPaths::Combine(FPaths::GamePersistentDownloadDir(), "video.mp4");
        FBufferArchive archive;
        archive << data;

        success = FFileHelper::SaveArrayToFile(archive, *path);

        if (success) {
            UGameplayStatics::OpenLevel(GetWorld(), "Player");
        }
    });

```

Since the downloading operation itself does not seem to be the one blocking the UI, I assume it would be either the insertion operator `archive << data` or `SaveArrayToFile`. So I tried doing both operations on a separate thread, like so:

```
ACard::ACard() {
    PrimaryActorTick.bCanEverTick = true;

    // ...

    request->OnProcessRequestComplete().BindLambda([&](FHttpRequestPtr request, FHttpResponsePtr response, bool success) {
        GEngine->AddOnScreenDebugMessage(-1, 2.f,
            success ? FColor::Green : FColor::Red,
            success ? TEXT("download successful") : TEXT("download failed"));

        if (!success) {
            return;
        }

        task = Task::dispatch([response]() {
            FBufferArchive archive;
            TArray<uint8> data = response->GetContent();
            archive << data;

            FString path = FPaths::Combine(FPaths::GamePersistentDownloadDir(), "video.mp4");
            FFileHelper::SaveArrayToFile(archive, *path);
        });

        SetActorTickEnabled(true);
    });
}

void ACard::BeginPlay() {
    Super::BeginPlay();
    SetActorTickEnabled(false);
}

void ACard::Tick( float DeltaTime ) {
    Super::Tick( DeltaTime );

    if (task && task->complete) {
        SetActorTickEnabled(false);
        UGameplayStatics::OpenLevel(GetWorld(), "Player");
    }
}

```

Where `Task` is defined like so:

```
class  Task : public FRunnable {

private:
    TFunction<void()> task;
    FRunnableThread* thread;

public:
    bool complete{ false };

    static Task* dispatch(TFunction<void()> task) {
        auto newInstance = new Task(task);

        newInstance->thread = FRunnableThread::Create(
            newInstance,
            TEXT(""),
            0,
            TPri_BelowNormal
        );

        return newInstance;
    }

    Task(TFunction<void()> task) : task(task) {}
    bool Init() override { return true; }
    void Stop() override {}

    uint32 Run() override {
        task();
        complete = true;
        return 0;
    }
};

```

But the above seems to make no difference: Saving the file still blocks the UI for about 3secs. So my question is: how should I be saving the file to storage without blocking the game itself?

UPDATE:

This issue is still not resolved. Following the advice in one of the comments below, I added logs to check that the code does indeed execute on separate threads and it does. The logs are consistent with the actions:

1. Dispatch save task from game thread.
2. execute task (save) in background thread.
3. dispatch new task to load the next level from background thread.
4. execute new task (load next level) from game thread.

Yet the UI thread still blocks.

```
01 - 18 19:59 : 10.404 18059 18075 D UE4 : LogTemp:Warning: Dispatch TASK : tID 18075 | is game ? 1
01 - 18 19 : 59 : 10.404 18059 18075 D UE4 : [2017.01.19 - 00.59.10:415][-8608252]LogTemp : Warning : Dispatch TASK : tID 18075 | is game ? 1
01 - 18 19 : 59 : 10.414 18059 18259 D UE4 : LogTemp:Warning: Execute TASK : tID 18259 | is game ? 0
01 - 18 19 : 59 : 10.414 18059 18075 D UE4 : [2017.01.19 - 00.59.10:419][-8608252]LogTemp : Warning : Execute TASK : tID 18259 | is game ? 0
01 - 18 19 : 59 : 10.524 18059 18140 I OVR : PhoneManagerThread - phone running!nfds = 1
01 - 18 19 : 59 : 10.524 18059 18259 D UE4 : LogTemp:Warning: Dispatch TASK : tID 18259 | is game ? 0
01 - 18 19 : 59 : 10.524 18059 18075 D UE4 : [2017.01.19 - 00.59.10:536][-8608252]LogTemp : Warning : Dispatch TASK : tID 18259 | is game ? 0
01 - 18 19 : 59 : 11.064 18059 18075 D UE4 : LogTemp:Warning: Execute TASK : tID 18075 | is game ? 1
01 - 18 19 : 59 : 11.064 18059 18075 D UE4 : [2017.01.19 - 00.59.11:072][-8608252]LogTemp : Warning : Execute TASK : tID 18075 | is game ? 1

```

# Answer
> 1 votes
You do not seem to use the `UGameplayStatics::SaveGameToSlo` that is provided by Unreal Editor 4 to create your save. I also use JSON serialization, in order to have a completely asynchronous and multi-platform save system.

I first followed this example provided by Epic. When it worked well, I decided to put this in a task, by creating a class that inherits from `FRunnable`.

---
Tags: unreal-4
---


# Question
Title: What technique should I use in a shader to give this reflective effect?
I'm working on a top-down 2D strategy game written in Java with LibGDX (though really for the purposes of this question I'll be using GLSL).

I want to give metallic materials in the game a shiny effect - but not a lightsource-based specular highlight or anything similar, I'm after a kind of global shine or shimmer, much like the effect on the word "King" in this logo from King under the Mountain:

While I'm not looking for someone to implement this for me, as a bit of a newbie to shader programming, what kind of techniques or algorithms should I be looking at to give this kind of effect?

# Answer
> 5 votes
Well, a good approach would be to create a bit mask, where the time a specific pixel should be fully lit is indicated by the amount of red it contains. So for example a pixel would be completely black, if you wanted it to light up first, and it had 255 units of red, if you wanted it to light up the last.

Then you need to pass the time and this texture to your fragment shader, sample the fragment of the bitmask, get the difference between the value of the red channel and the remainder of time and 255 (this is so it's loops), and if the difference is less than a specific value, then make that pixel lighter.

You can also store stuff in the green and blue channel, like how bright that pixel should be.

---
Tags: libgdx, shaders, glsl
---


# Question
Title: How to cache resources in my homebrew rendering system
*Background:*

I am designing a simple 3D render system for an entity component system type architecture using C++ and OpenGL. The system consists of a renderer and a scene graph. When I finish the first iteration of the renderer, I might distribute the scene graph into the ECS architecture. For now it is placeholder one way or another. If possible, the following are my goals for the renderer:

1. **Simplicity**. This is for a research project and I want to be able to easily change and expand my systems (hence the ECS approach).
2. **Performance**. My scene might have many small models and also large volumes with a lot of geometry. It is not acceptable to acquire objects from the OGL context and buffer geometry every render frame. I'm aiming for data locality to avoid cache misses.
3. **Flexibility**. It must be able to render sprites, models, and volumes (voxels).
4. **Decoupled**. The scene graph may be refactored into the core ECS architecture after I write my renderer.
5. **Modular**. It would be nice to be able to swap in different renderers without changing my scene graph.
6. **Referential transparency**, meaning that at any point in time I can give it any valid scene and it will always render the same image for that scene. This goal in particular is not necessarily required. I thought it would help simplify scene serialization (I will need to be able to save and load scenes) and give me flexibility to swap in different scenes during runtime for testing/experimentation purposes.

*Problem and ideas:*

I have come up with some different approaches to try but I'm struggling with how to cache the OGL resources (VAO, VBOs, shaders, etc) for each render node. The following are the different caching concepts I've thought up so far:

1. **Centralized cache**. Each scene node has an ID and the renderer has a cache that maps IDs to render nodes. Each render node contains the VAO and VBOs associated with the geometry. A cache miss acquires resources and maps the geometry to a render node in the cache. When the geometry is changed, a dirty flag is set. If the renderer sees a dirty geometry flag while iterating through the scene nodes, it rebuffers the data using the render node. When a scene node is removed, an event is broadcasted and the renderer removes the associated render node from the cache while releasing resources. Alternatively, the node is marked for removal and the renderer is responsible for removing it. I think this approach most closely achieves goal 6 while also considering 4 and 5. 2 suffers from the extra complexity and loss of data locality with map lookups instead of array access. 3 suffers from the homogeneous cache.
2. **Distributed cache**. Similar above except each scene node has a render node. This bypasses the map lookup. To address data locality, the render nodes could be stored in the renderer. Then the scene nodes could instead have pointers to render nodes and the renderer sets the pointer on a cache miss. I think this kind of mimics an entity component approach, so it would be consistent with the rest of the architecture. The problem here is that now scene nodes hold renderer-implementation-specific data. If I change how things are rendered in the renderer (like rendering sprites vs volumes) I now need to change the render node or add more "components" to the scene node (which means changing the scene graph as well). On the plus side, this seems like the simplest way to get my first-iteration renderer up and running.
3. **Distributed metadata**. A renderer cache metadata component is stored in each scene node. This data is not implementation-specific but rather holds an ID, type, and any other relevant data needed by the cache. Then cache look-up can be done directly in an array using the ID, and the type can indicate which type of rendering approach to use (like sprites vs volumes).
4. **Visitor + distributed mapping**. The renderer is a visitor and scene nodes are elements in the visitor pattern. Each scene node holds a cache key (like the metadata but just an ID) that only the renderer manipulates. The ID can be used for array instead of generalized map look-up. The renderer can allow the scene node to dispatch a different rendering function based on the scene node's type, and the ID can be used by any cache. A default or out-of-range ID would indicate a cache miss.

How would you solve this problem? Or do you have any suggestions? Thanks for reading my wall of text!

# Answer
After re-reading your question, I strongly feel you are overcomplicating the problem. Here's why:

1. There are only really two types of rendering system: Forward, and Deferred, none of which are dependant on a scene graph.
2. The only performance issues you should really get with any rendering system, should come from high poly count, and inefficient shader and client code.
3. Cache misses do indeed reduce performance, but they aren't quite the monsters you may think they are. 80% of your performance improvements will be from a more efficient algorithm. Don't make the mistake of pre-optimising your code.

That said:

If you are using a homebrew scenegraph then you should already be using a "Renderer" interface (or base class) to design the rendering part of your scenegraph code. Visitor pattern using double dispatch is a good approach to this, as you may well be using many types of graph nodes such as colour, texture, mesh, transform etc. In this way, during the render cycle, all the renderer has to do is walk the scene tree structure depth-first, passing itself as an argument. In this way the renderer is basically just a collection of shaders and maybe a framebuffer or two. The result of this is that search/removal code is no longer necessary for the rendering system, just the scenegraph itself.

There are certainly other ways to tackle the problems you face, but I don't want to give too long winded an answer. So, my best advice is get something simple working first, then expand on it to find it's weaknesses, then experiment with other approaches and see where their strengths/weakness lie in practice.

Then you will be well placed to make an informed decision.
> 2 votes

---
Tags: architecture, rendering, entity-system, scene-graph
---


# Question
Title: How do i eject bullet shells from a gun? Java/slick2d
So, here is my problem: I am working on a top down 2d shooter in Java and have a character, which can move and rotate/fire to the mouse direction. Shooting guns etc. works fine but now i am trying to implement a shell ejection system, which "ejects" the shells next to the player. The problem is, that i can't just draw the shells next to the player since the player has an x and y position which are rotating. I want the shells to have a random radius in which they will be ejected. But i don't know how to implement something like this. Any suggestions?

**EDIT:** That's my shell-ejection method, which doesn't work(the angle represents the player angle):

```
    public void shellEjection(){
    x=(float) x*((float) (Math.cos(angle)));
    y=(float) y*((float) (Math.sin(angle)));

    double length = Math.sqrt((mouseX - x)*(mouseX - x) + (mouseY - y)*(mouseY - y));

    double xVel = (5 - x) /length * 5*bulletVelocity;
    double yVel = (5 - y) /length * 5*bulletVelocity;

    x+=xVel;
    y+=yVel;
}

```

# Answer
To give you a pseudo code solution:

1. Get X and Y from the gun (gun position).
2. Work out the relative rotation of the gun from the player (purple arrow), so that you can easily offset the shell fall direction later.
3. Work out the direction and distance that the shell should fly, you will probably want a general direction that the shell will fall in since shells in real life don't tend to fall into exactly the same location.
4. spawn the shell and start moving it in the direction that you determined in the last step.
5. stop moving (and manipulating) the shell once it reaches the point you want it to land at.

I made a quick image of what I mean to better illustrate these steps above. That should be the rough steps of what you need to do. Keep in mind that you will want to use an **object pool** to stop yourself wasting resources and if it's available to you stop updating the shell object once it reaches it's final point so that you only render it (not wasting precious CPU cycles).

Hope this helped :)

**EDIT**

From what I understand the problem that you have is that you don't know how to find the XY position of the gun since the gun is at an offset from the middle of the character. I'm guessing that the gun is always in the same position when being fired relative to the center XY (or at least you know about every position or can figure that out another way).

What you can try doing is figuring out what the distance is from the center to the gun, then use Sin and Cos (yay maths) to figure out where the gun is in space based on the rotation. There is a great site that visualises the relationship between sin and cos here.

So to give an example:

Use pythagoras theorem to work out the distance, again check that website i mentioned above to get a better writeup.
> 2 votes

---
Tags: java, lwjgl, slick
---


# Question
Title: How to calculate building cost with production per hour?
I know that it may not detailed thread title but I will give more detail about my question.

I'm working on a strategy game, and can't find a solution about building cost or training cost. I spent 1 week to calculate it but I can't find the formula. I kindly request help from experienced developers.

Here is the example:

Building Name: Quarry Building Time: 15 seconds Production per hour: 25 Stones

I give this building random building cost for Level 1; 20 Stones, 15 Timber, and 10 Iron.

First of all, I thought this: Quarry at Level 1 is producing 25 Stones for p/h, and in 24 hours 600 Stones.

How can I calculate to give building cost for upper levels of Quarry? Is there any formula or we can give random cost for it?

Thanks!

# Answer
> 9 votes
There is no particular formula for this. You have to work it out on your own, based on what you feel is balanced - which relies on all other factors in your game, e.g. you don't mention whether the player can have multiple quarries at the same "location" (say town or city), or how many things you can build at the same time, so we can't possibly have *any idea* whether the player would do better to build say 4x level 1 quarries vs. 1x level 4 quarry... never mind the in-play impacts of the time constraints.

**Why not just keep things simple since it is early days for your game:** double the time cost for each upgrade level, while increasing the production capacity by 25% of the original figure each time? Then if you feel you want to change those figures, do that. Remember, that is a linear function. You can also go for a non-linear function, e.g. `time cost = level squared`.

In essence, as they say to writers who are suffering from writer's block - "just write something! anything!", you need to do the same here, and then improve the function/formula from there.

# Answer
> -1 votes
**You can budget.**

I have defined the exact maximum of any resource anyone can produce for the game lifetime (if they play 24/7 for the server duration).

Any entity you have that produces and/or costs something is given a % of the whole or partial budget.

Then its simple matter of making a curve do distribute the production and cost between the levels of entities you have. If you use stuff like excel and you link in the core figures allowing you to re-iterate the economy within a few key presses.

Also, since people don't play 24/7 any loss of productivity is an opportunity to sell.

Eye balling it like many game designers do is the primary cause of uninspired and broken economies.

You need to have base idea of your pace to wrap mathematics around. Math is just a tool after all. It doesn't serve if there is no purpose.

Learning to budget early on helps you refine your idea of balance while working. Just shoving "whatever" placeholders in without keeping track of the economic concept usually ends up in re-coding things because unforeseen parts of the economy force you to make adjustment to the functionality.

---
Tags: mathematics, game-design, algorithm
---


title: Opengl mutiple texture in a shader

text:
# Question
Title: Opengl mutiple texture in a shader
Im using modern opengl and c++.

How do I draw a number of triangles each one having a different texture in one draw call when I only have 32 texture units on my graphics card and the max texture size is 1024? My video card has 2gb of memory yet it can only hold 32 texture at a time?

Why do graphics cards have this limitation? I'm a c++ programmer and in c++ you don't have restrictions like that. The only restriction that you have is how much RAM you have which is fine.

# Answer
> 2 votes
Modern GPUs have hardware translation tables that bind a 64-bit integer to a texture (called a texture handle). This is the new way to bind textures to a GPU as opposed to only binding a texture to a texture unit which is more limited because textures units are available in a limited number. This is referred to as bindless textures.

Also for the maximum texture size, there are sparse textures (or virtual textures) that expose a way to fit very big textures (even bigger than the VRAM available) by using the virtual memory technique (as used in OSs). It enables just loading the needed parts of a texture when you need it while keeping the rest on disk. It's used in several engines and games that have open worlds.

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


# Question
Title: Using sprites in pygame without classes and objects
**Relevant information**

I'm in a grade 11 computer science class that uses Python & Pygame. We're aloud to use sprites and images though we're never taught it, just drawing graphics like squares and circles. We were taught arrays, lists, functions but not classes and objects. We also relatively do things without using functions like the `init` main one I see a lot on line, we also don't use `self` or `super`.

If it's anything relevant, I'm making a top down (bird's eye view) 2D shooter game similar to a 2D version of dead ops arcade in Call Of Duty: Black Ops.

**What I'm trying to do**

I've been programming with Java & LibGDX before hand. So I want to use sprites in images in Pygame the same way I've been using it in LibGDX. Getting images, obtaining image rectangles for collision, rotating/transforming images, changing the images of the sprite.

Though every tutorial I've seen for sprites and images in Pygame that I can search up uses objects, classes and function calls that I'm not familiar with.

**What I've done**

I've loaded a PNG into my program and drew it to the screen. Simple and straight forward. Though the Pygame documentation doesn't give me a lot of options in terms of manipulating these images other than moving their location.

**What I'm asking for**

A simple run down syntax of how I would use a sprite in Pygame, without objects/classes or any weird function terminology. In terms of functions I can make a function, pass information through parameters and return values. I'm not aware of global variables, `self` or `super`.

The simplest of simple where I can resize an image, change the image of a sprite, transform/rotate it, and get a rectangle that I can use to overlap with another one.

# Answer
> 1 votes
**Use a spritemap/atlas**

You won't need to use global variables (and should be avoided for numerous not listed here), as well `self` and `super` you don't need to fully understand yet until you start extending your program and using inheritance.

You will need your sprite drawn into evenly spaced squares/rectangles on a sprite sheet. I will refer to this as an example. You can think of this png as 6 frames of a walking animation.

Loading that png into your program as you are similarly now, you can then divide it into equal frames (you can also make use of an `array` here by storing each frame `array[0] ... array[5]`). Then in your update loop if the character is walking you simply draw the relevant frame.

Please note my examples are more C# like syntax as I am not familiar with python. The same fundamental principles apply though.

```
// load up other parts, such as animation[] an array of pngs
int frame = 0;
png[] animation;
// begin loop

DrawCharacter(animation[frame]);
frame++;
if (frame == 6) frame = 0; // prevent frame going outside of 0-5.
// back to start of loop.

```

What this will do is draw the first frame of the sprite, then `frame` increments by 1 and when draw is called again it will show the next frame of the sprite. It will happen quickly and give the appearance of the walking animation. Depending on your game engine setup and FPS this may be extremely fast so you may want to only increment `frame` every 15 steps or so.

If you can't figure out splitting the png into frames in code, you could manually save each frame of the png yourself and just load each part in. (Remember arrays are 0 based).

```
animation[0] = "frame1.png"
animation[1] = "frame2.png"
animation[2] = "frame3.png"
animation[3] = "frame4.png"
animation[4] = "frame5.png"
animation[5] = "frame6.png"

```

# Answer
> 0 votes
If a tutorial is using functions or classes you aren't familiar with you should look them up. If a tutorial is using syntax you don't know you should look up a beginner tutorial. If you don't understand a function/class/syntax despite looking it up you could always ask about it specifically.

Considering you want to make a full game (and come from Java which is strictly object-orientated) you'd probably want to learn basics such as creating classes and single-inheritance first. You should especially learn naming scopes (such as global/local variables). You can make a game without making classes, but since pygame use objects like `Surface` you'd probably want some understanding about them.

To answer your question however, the `pygame.transform` module do offer functions to manipulate (resize, flip, rotate and more) images.

* `pygame.transform.rotate(image, angle)` will return the image rotated by the angle.
* `pygame.transform.flip(image, x, y)` will return the image flipped in the horizontal axis (if you set `x=True`) and in the vertical axis (if you set `y=True`).
* `pygame.transform.scale(image, (width, height))` will return the image scaled to the width and height you specify.

Just to name a few.

To get a rectangle the same size of an image it's as simple as `rect = image.get_rect()`. Remember though that a rectangle is an `Rect` object so you need to know how to assign and accessing attributes from it in order to use it effectively.

---
Tags: sprites, python, pygame, image
---


# Question
Title: What are the advantages and disadvantages of using pointers to change data in my physics engine?
I am working on an entity-component system, and I am thinking about this communication protocol:

1. The physics component of a game object sends an `UpdateMyState` message, with its state attached.
2. The physics engine receives this.
3. The physics component sends a pointer to its data, and the physics engine changes the state. Because it is a pointer, no messaging back is required.

The standard way involves the physics engine sending back an `UpdatedState` message, with the new state attached. This will be processed by the physics component. I am not sure if my way is a good exercise. It is not a complete message-based system, but it decreases the amount of required messages, and it simplifies the system.

What are the advantages and disadvantages of using pointers to change data in my physics engine?

# Answer
IMHO Yes, your implementation is a good one.

This allows your physics engine to run on it's own, and be decoupled of your ECS structure.

1. Physics component registers its physics object to the physics engine when it's created
2. Graphics component registers its graphics object to the graphics engine when it's created
3. Main infinite loop has the input processed
4. Main infinite loop calls for physics engine update
5. Physics engine does it's simulation: collision detection and resolution
6. Main infinite loop sends the message to update the transform
7. Main infinite loop sends the message to update the game logic
8. Main infinite loop calls for the graphics engine update

This will de-couple your graphics and physics engines from your ECS and reduce the load of messages sent through that channel.

Of course, this is on paper. You'll have to implement it and try it for yourself. Try a design that seems to work for you first, then finish your project and improve it for your second project.
> 1 votes

# Answer
Your method will reduce encapsulation, meaning that the different systems will be more closely linked, and therefore changes to one of the them might mean large changes to the other. Other advantages of encapsulatio are outlined in the wikipedia aritcle.

Another thing your method will detract from is polymorphism, I'd assume that different types of physics components would need to be processed slightly differently. Therefore you could have an abstract class which each component inherits form, then the engine calls the same abstract method in each component and is therefore much simpler, all the difficult stuff is done by the components rather than having some horrible switch block in the engine. This would mkae it much easier to add different types of physics components.
> 2 votes

---
Tags: c++, architecture, component-based
---


# Question
Title: How do I calculate specular contribution in physically-based rendering?
I'm trying to implement physically-based rendering, in a small game engine built for academic and learning purposes. I cannot understand the right way to calculate specular and diffuse contribution, based on the materials metallic and roughness values.

We don't use any third party libraries or engines for rendering; everything is hand written in OpenGL 3.3.

Right now, I ues this:

```
// Calculate contribution based on metallicity
vec3 diffuseColor  = baseColor - baseColor * metallic;
vec3 specularColor = mix(vec3(0.00), baseColor, metallic);

```

I'm under the impression that the specular has to be dependant on the roughness, somehow. I was thinking to change it to this:

```
vec3 specularColor = mix(vec3(0.00), baseColor, roughness);

```

Again, I'm not sure. What is the right way to do it? Is there even a right way, or should I just use the 'trial and error' method until I get a satisfying result?

---

Here is the full `glsl` code:

```
// Calculates specular intensity according to the Cook - Torrance model
float CalcCookTorSpec(vec3 normal, vec3 lightDir, vec3 viewDir,
    float roughness, float F0)
{
    // Calculate intermediary values
    vec3 halfVector = normalize(lightDir + viewDir);
    float NdotL = max(dot(normal, lightDir), 0.0);
    float NdotH = max(dot(normal, halfVector), 0.0);
    // Note: the following line could also be NdotL, which is the same value
    float NdotV = max(dot(normal, viewDir), 0.0);
    float VdotH = max(dot(viewDir, halfVector), 0.0);

    float specular = 0.0;
    if(NdotL > 0.0)
    {
        float G = GeometricalAttenuation(NdotH, NdotV, VdotH, NdotL);
        float D = BeckmannDistribution(roughness, NdotH);
        float F = Fresnel(F0, VdotH);

        specular = (D * F * G) / (NdotV * NdotL * 4);
    }
    return specular;
}

vec3 CalcLight(vec3 lightColor, vec3 normal, vec3 lightDir, vec3 viewDir,
    Material material, float shadowFactor)
{
    // Helper variables
    vec3  baseColor = material.diffuse;
    vec3  specColor = material.specular;
    vec3  emissive  = material.emissive;
    float roughness = material.roughness;
    float fresnel   = material.fresnel;
    float metallic  = material.metallic;

    // Calculate contribution based on metallicity
    vec3 diffuseColor  = baseColor - baseColor * metallic;
    vec3 specularColor = mix(vec3(0.00), baseColor, metallic);

    // Lambertian reflectance
    float Kd = DiffuseLambert(normal, lightDir);

    // Specular shading (Cook-Torrance model)
    float Ks = CalcCookTorSpec(normal, lightDir, viewDir, roughness, fresnel);

    // Combine results
    vec3 diffuse  = diffuseColor * Kd;
    vec3 specular = specularColor * Ks;
    vec3 result   = lightColor * (emissive + diffuse + specular);
    return result * (1.0 - shadowFactor);
}

```

# Answer
> 1 votes
Specular color for non metallic objects is typically .04 not zero. (That should be your F0) at glancing angles that goes up to 1.

---
Tags: opengl, rendering, pbr
---


# Question
Title: How do I manage monster tables and item databases in my Android game?
To learn more about AI during combat, I made a demo in Unity where a player would fight a creature in an arena. I started here because I plan to implement the system I'm working on in another game. In that game, there are a lot of different creatures a player has to fight.

These creatures have a body part set, a move list, an attribute set and a drop table for that type of creature. Currently I'm managing this by a big static class with drop tables, move tables, monster tables and item tables and so on in them. When a creature gets instantiated it copies monster data from that static class and when it dies items in the referenced drop table are instantiated, copying some data from the item table. Whenever a monster performs a move, the necessary information is looked up in that static class.

I could solve monster data by copying the necessary data into the monsters and then dispose of the class, but that leaves no option for items, which are referenced by ID and need to be looked up frequently. Serializing and deserializing the data wouldn't make sense if I would have to load the entire item table or unit attributes every time every time I access them. Keeping the entire game data loaded all the time doesn't sound like the best way to go about managing my data.

My own system is becoming unmanageable. Because I'm targetting Android, I'm also, to a lesser degree, worried that having such a big static class loaded all the time will become a burden once more features are added to the game. I have read this post but didn't find it of much help.

Which ways are there to improve from the current situation? How could I handle a frequently used item table/database more efficiently. And on the other side, how could I handle a move table and monster table better? How did NetHack do it, for example?

# Answer
> -1 votes
You should remove the static class and start using polymorphism, you should have an abstract superclass (maybe monster). Each monster should inherit from that and it should hold all data for its moves, stats etc. Items should be loaded when the monster is loaded and the monsters should have references to all of the items in their possession.

---
Tags: performance, data-structure
---


# Question
Title: I'm trying to make another object move, besides from the character
I want to create a small build of a TRPG, simaler to the Fire Emblem games. What I want to do is that I want to have the cursor be able to move a 'character' to a certain location. Any help? (I'm doing this in Game Maker)

# Answer
> 1 votes
Are you using GML or DND?

In GML you can do something like

```
x = mouse_x
y = mouse_y

```

in the Step event.

---
Tags: movement, game-maker
---


title: What happens if I delete .meta files?

text:
# Question
Title: What happens if I delete .meta files?
In Unity, what happens if I delete the meta files? Or if I import files, but not their respective .meta files?

What are some issues I could come across? Is there ever a reason I would want to delete meta files?

I was asked this question recently, and I do not know the answer.

# Answer
Some .meta files contain important information.

For example, this is part of a .meta file for a .png file in our project:

```
fileFormatVersion: 2
guid: a652b1795b650454a8270045af8e2a71
timeCreated: 1459880238
licenseType: Pro
TextureImporter:
  fileIDToRecycleName: {}
  serializedVersion: 2
  mipmaps:
    mipMapMode: 0
    enableMipMap: 0
    linearTexture: 0
    correctGamma: 0
    fadeOut: 0
    borderMipMap: 0
    mipMapFadeDistanceStart: 1
    mipMapFadeDistanceEnd: 3
  bumpmap:
    convertToNormalMap: 0
    externalNormalMap: 0
    heightScale: 0.25
    normalMapFilter: 0

```

You can see there are a lot of settings that tell Unity how to use the associated `.png` file.

If you delete this .meta file, it will regenerate it, but you'll lose any import settings you had set. It can cause other issues, but just this example should be enough to convince you to leave them alone. :)
> 9 votes

# Answer
Yes - Unity will reimport all of the assets and the project will rebuild the next time it is launched, if the 'metadata' folder is deleted.

It won't help cut down the file size, because the folder will re-create and grow to about the same size.
> -3 votes

---
Tags: unity
---


# Question
Title: Gradle generated LibGDX project does not work in NetBeans
I have to do rework of Worms (game) and I've chosen LibGDX. So, I've installed Gradle and generated a new project in LibGDX app - as they have in the documentation. But when I'm trying to load it as a project in NetBeans, it does not work. NetBeans sees it as a pure folder, not a project folder. I've also tried to manually create a project and paste there just the `main` that was generated and as expected, I've got errors with the imports (it does not know those imports).

What do I have to do? Thanks for any advices.

# Answer
Try to install a gradle plugin for NetBeans and then reimport the project again by using the plugin.

> A community-contributed plugin is available for Gradle, the Groovy-based build system. The plugin lets you open Gradle projects into the IDE, create new Gradle projects, and invoke Gradle commands in the IDE.

Also, this official Libgdx wiki for NetBeans may be helpful.
> 1 votes

---
Tags: java, libgdx
---


# Question
Title: OpenGL - render to texture - read data to CPU - data are upside down
I am using render to texture and I want to read data back to CPU side of the program. I am using PBO to do this. However, if I save content of texture to the file, data are vertically flipped (upside down). Is this a normal behavior, or I have something incorrect?

PBO init:

```
glGenBuffers(1, pboID);

glBindBuffer(GL_PIXEL_PACK_BUFFER, pboID);
glBufferData(GL_PIXEL_PACK_BUFFER, texture->info.rawDataSize, 0, GL_DYNAMIC_READ);

glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

```

PBO readback:

```
glBindFramebuffer(GL_FRAMEBUFFER, texture->GetRenderTarget()->GetFrameBufferID());

glReadBuffer(texture->GetAttachement());

glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pboID);
glReadPixels(0, 0, texture->info.width, texture->info.height, texture->info.glFormat, GL_UNSIGNED_BYTE, 0);

glBindBuffer(GL_PIXEL_PACK_BUFFER_ARB, pboID);
void * textureData = glMapBuffer(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);

//save tetxure data to file

//unlock PBO and FrameBuffer

```

I know that texture coordinates are "flipped" in comparison to DirectX, so during rendering on the screen, I am flipping the y-coordinate as well (`y = y - 1`). But how to download texture data "non-flipped"?

# Answer
> 3 votes
glReadPixels:

> glReadPixels and glReadnPixels return pixel data from the frame buffer, starting with the pixel whose **lower left corner** is at location (x, y), into client memory starting at location data.

(My emphasis)

So yes, in OpenGL it is perfectly normal and expected behaviour for the bottom-left to be the origin.

Note that when specifying textures, since both glTexImage/glTexStorage and texture coord specification use bottom-left-is-origin, in most use cases they actually cancel each other out and you can use the same texcoords as in Direct3D.

---
Tags: opengl, textures
---


# Question
Title: How to Ignore Raycast for Boxcollider2D by layer or boolean?
How do I ignore raycasts for specific objects? I want a filter, to ignore raycasts for some objects. As an example, when my player selects the ground, I do not want them to accidentally select bullets.

Is it possible to add boolean to the `BoxCollider2D` component, to identify raycast targets? I want to make it similar to the `Image` component.

My problem is that when several objects overlap, I need some of the objects to ignore the raycast.

I can't use Queries Hit Trigger or disable the collider component, because I need them to enter the `OnCollisionEnter` and `OnTriggerEnter` methods.

---

Here is my `Update` method:

```
void Update ()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity,
                1 « LayerMask.NameToLayer("Object"));

        if (hit)
        {
          Debug.Log(hit.collider.gameObject.name);
        }
    }
}

```

# Answer
If you cannot accomplish what you want with Layer Masking, or with the Collision Matrix, then I can suggest an alternative approach to the problem.

You can put a tag on the collider objects you want to avoid raycasting, and then doing something like this:

```
void Update(){
    if (Input.GetMouseButtonDown (0)) {

        Vector2 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        RaycastHit2D[]  hits = Physics2D.RaycastAll (pos, new Vector2 (0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++) {
            if (hits[i].collider.gameObject.tag != "IgnoreRaycast")
            {
                 Debug.Log(hit.collider.gameObject.name);
            }
        }
}

```

However, if you want similar behavior as described above, you may want to consider extending the main MonoBehaviour class into a custom one that you will derive all of your Collidable objects from.

Consider the following class:

```
public class BaseEntity : MonoBehaviour
{
    [SerializeField]
    bool IgnoreRaycast;
}

```

Then, deriving from this class, instead of directly to MonoBehaviour will expose a new property entitled IgnoreRaycast, to all of your GameObjects.

Unfortunately, it doesn't just ignore ray So your update loop would then look like this:

```
void Update(){
    if (Input.GetMouseButtonDown (0)) {

        Vector2 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
        RaycastHit2D[]  hits = Physics2D.RaycastAll (pos, new Vector2 (0, 0), 0.01f);

        for (int i = 0; i < hits.Length; i++) {
            if (!hits[i].collider.gameObject.GetComponent<BaseEntity>().IgnoreRaycast)
            {
                 Debug.Log(hit.collider.gameObject.name);
            }
        }
}

```
> 1 votes

# Answer
Your problem appears to be in your understanding of what your actually trying to do. As such, I can identify two seperate questions. I will answer both, in case it provides more context. Ultimately, you would benefit greatly from using *layers* to selectively ignore raycasts.

---

> **How do I ignore raycasts for specific objects?**

With *layers*. Let's take a look at the API reference:

> # Physics2D.RaycastAll

>
> public static RaycastHit2D\[\] **RaycastAll**(Vector2 **origin**, Vector2 **direction**, float **distance** = Mathf.Infinity, int **layerMask** = DefaultRaycastLayers, float **minDepth** = -Mathf.Infinity, float **maxDepth** = Mathf.Infinity);
>
> ## Parameters

>
> ...
> **layerMask** Filter to detect Colliders only on certain layers.
> **minDepth** Only include objects with a Z coordinate (depth) greater than or equal to this value.
> **maxDepth** Only include objects with a Z coordinate (depth) less than or equal to this value.
> **...**
> The *layerMask* can be used to detect objects selectively only on certain layers (this allows you to apply the detection only to enemy characters, for example).

This very clearly points to *two* ways we can filter game objects, when we raycast; by *layer mask* and by *depth*.

---

### Filtering Raycasts by Layer Mask

*Layer mask* is good when you know *what* your looking for. Put simply, your raycast will only hit objects that use the same layer as `layerMask`. By default, `layerMask = DefaultRaycastLayers`, so your raycast will normally hit all objects that use the default raycast layers. Assuming you were looking for a particular object, you would ensure that object had a unique tag, and specifically use that tag as your `layerMask` parameter.

If you use a *layer mask*, your raycast will *only* hit objects that use the same *layer*. This is case-sensitive, so ensure that you use correct capitalisation.

---

### Filtering Raycasts by Depth

*Depth* is good when you do not necessarily know *what* object your looking for, but know roughly which physical layer it should be in. Filtering by *depth* requires a bit of pre-plan, but it *does* allow a bit more diversity in what you are looking for.

Simply put, you would ensure that you ordered your game objects along the z-Axis in order to categorise them for particular interactions. For example, if your floor is at a z-Axis of -1, and your enemies are at a z-Axis of 1, you could use a depth of `minDepth = -1, maxDepth = -1`. If your enemies were anywhere between 1 and 10, along the z-Axis, you could specifically target them with a depth of `minDepth = 1, maxDepth = 10`.

It is important to remember that the z-Axis is *not* considered, when applying general collision and physics in 2D. As such, you can use the z-Axis to layer your objects, without interrupting normal collision you would expect from them.

---

### Further Consideration

There are going to be times where you will still want to look through the array, returned by `RaycastAll()`, both to provide extended filtering and to ensure that you have actually retrieved the intended game object.

* Consider if there are any other parameters that would naturally filter your intended target. For example, `RaycastAll()` sorts the array of raycasts by *distance* before it is returned. As such, if you know your intended object will be the furthest away, you should always look at the last entry.
* Consider that it is still good form to *validate* your findings. For example, if you know that your returned object should ultimately be an enemy, it can not hurt to ensure the returned object contains relevant enemy components.

---

> Is it possible to add boolean to the BoxCollider2D component, to identify raycast targets?

Not that I am aware of; but it appears your reasoning may be based off an incorrect assumption.

Firstly, `BoxCollider2D` is a *sealed* class. This means that we can not inherit from it, which would be required to add our own elements.

Secondly, the boolean in question does not allow you to ignore raycasts from specific objects. It only allows you to ignore raycasts *completely*. Enabling `RaycastTarget` simply *allows* the image to react to ray-casts. Anything you would want from this behavior can be *replicated* by accessing and disabling/enabling the collider. You have previously stated that this is *not* going to work for you, but regardless, it is a good comparison of behavior.
> 1 votes

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


# Question
Title: What's wrong with this camera implementation?
I'm using WebGL and glMatrix and I implemented a camera. When a move backward, no problem. But when I move to the side and particularly forward, the camera becomes all glitchy. I implemented almost exactly the same camera before in C++ and it worked perfectly. I put the whole code on jsFiddle (with glMatrix because it's not in the list and I didn't find a url, sry).

https://jsfiddle.net/ydx0Lr1v/14/

Click and move the mouse to move around.

Also, the more I decrease the speed of the camera movement, the more it works well. I put a high speed to dramatize the effect. I know I should make the speed of the camera depend on the time between each frame, but I haven't implemented an fps counter yet.

Thanks!

Edit: Hum, that's strange. In jsFiddle the camera seems to work better when moving forward.

# Answer
> 1 votes
I found out what the problem was. It was the lookAt matrix that for some reason was wrong. I don't know if it's a problem with glMatrix or if I did something wrong, but I resolved the problem by making the lookAt matrix myself :

```
var r = this.right,
        u = this.up,
        f = this.front,
        p = this.position;

    var view = [r[0], u[0], -f[0], 0.0,
                r[1], u[1], -f[1], 0.0,
                r[2], u[2], -f[2], 0.0,
                0.0,  0.0,  0.0,  1.0]
    var a = [1.0, 0.0, 0.0, 0.0,
             0.0, 1.0, 0.0, 0.0,
             0.0, 0.0, 1.0, 0.0,
             -p[0], -p[1], -p[2], 1.0];

    mat4.multiply(view, view, a);

```

Now it works.

---
Tags: opengl, webgl
---


title: Why is my sphere jumping?

text:
# Question
Title: Why is my sphere jumping?
I got a sphere that moves with an angular velocity of -2000 in the X axis, I need that sphere moves on 130 platforms, all those platforms have -0.0182175 in the Y axis.

The problem is that when I play, the sphere starts normally but as it advances starts make some jumps, first shorts but then more large, and it is as if the platforms did not have the same value in the Y axis.

Can someone help me, please?

I've put some images.

Very thanks

Hey people!! I've uploaded a video to show you clearly the problem.

Here's the link: Platforms, sphere and sphere script

Sorry for my english by the way.

# Answer
> 1 votes
There is some considerations:
First, why the y is such uncertain value? It's better to set y to a certain value like 0 or 1.
Second, maybe the y of all platforms are equal, but they haven't aligned correctly beside each other.use v key on the keyboard to snap each platform to another one.
Third, maybe platform colliders are not match exactly with sprites. In the collider component, Click on edit to see the shape of colliders.
And finally, check if jumps occur with some specific sprites or it occur randomly. Hopr it helps.

---
Tags: unity
---


# Question
Title: How to know which methods are associated with an event?
In Unity `events` are used as enhanced `delegates`. This is extremely helpful in developing clean concise event management scripts.

However, when debugging said scripts and complex arrangements, is there a way I can see which methods are in an event at any one time?

# Simplified Example:

**Game manager**

```
using UnityEngine;
using System.Collections;

public class EventManager : MonoBehaviour
{
    public delegate void ClickAction();
    public static event ClickAction OnClicked;

    void someMethod()
    {
        if(whatever = true && OnClicked != null)
        {
            //this is the event delegate:
            OnClicked();
        }
    }
}

```

**gameObject script**
*(one of several scripts that can add methods to an `event` )*

```
using UnityEngine;
using System.Collections;

public class TeleportScript : MonoBehaviour
{
    void SomeMethod()
    {
        EventManager.OnClicked += Teleport;
    }

    void SomeOtherMethod(){
        EventManager.OnClicked += Horses;
    }

    void OnDisable()
    {
        EventManager.OnClicked -= Teleport;
        EventManager.OnClicked -= Horses;
    }

    void Teleport()
    {
        Vector3 pos = transform.position;
        pos.y = Random.Range(1.0f, 3.0f);
        transform.position = pos;
    }

    void Horses(){
         instantiate(horses, new Vector3.zero, Quaternion.identity);
    }
}

```

*etc. etc.,*

I have used `Debug.Log(OnClicked.Method);` but this only returns one of multiple methods associated with an event.

So my issue is, that for debugging and general error resolution, how can I find out which method(s) are in the `OnClicked()` event delegate without/before running this delegate?

For example:

```
Debug.Log(OnClicked(listMethods));

```

> //Output to log:
> void Teleport();
> void Horses();

# Answer
You want to get the InvocationList of the event. Here is a brief code example :

```
 public delegate void Test();
 System.Delegate[] invokeList;
 public static event Test OnTest;

  OnTest += TestMethod1;
  OnTest += TestMethod2;
  invokeList = OnTest.GetInvocationList();
  foreach(System.Delegate d in invokeList)
  {
    Debug.Log(d.Method);
  }

```
> 2 votes

---
Tags: unity, events
---


title: Making AI like sims (Unity)

text:
# Question
Title: Making AI like sims (Unity)
I'm not good at Coding or C# and I've been looking around the internet but couldn't find the answer that I was looking for.

I'm using Unity and I want to make an AI somewhat like The Sims, That just walks around aimlessly and maybe interacts with other objects and interacts with the player if the player interacts with the AI. (like the player just talks to the AI)

This is my first time posting and I'm not confident in C# so thanks for the help.

# Answer
> 4 votes
I would suggest as a starting point, that you get some sheets of clean paper and structure what you want to happen. Your phrasing on the question is vague, at best, so you need to clarify things in your plan down to boolean (`true/false`) values for a computer to understand.

You want your AI to "wander around". Does that mean they wander in random directions? What would be a minimal length of a directon (It can look meaningless of the scale of your random walk is gameworld millimetres rather than metres, for example).

Then you want your AI to "interact" with objects. Which objects, what is the criteria for interactions - proximity? time of day? mood?

You need to set a clear process tree and for each subroutine, such as "pick up desk lamp and wave it around for 5 seconds", you need to set what criteria needs to be forfilled by your AI before this event is begun, such as

* "is AI within 5m of a desk lamp?",
* "is AI script state marked as "bored" " ,
* "is AI marked as Awake" (rather than sleepwalking!)

If these criteria are all true, then you can start the "play with desk lamp" subroutine,

Etc. etc.

Overall I would suggest you need to really clarify the behaviours and routines you want to create, and what would cause them and enable them. Then once all these "factors" are set out clearly in your mind and in your plan, you can work on coding each one, one by one, until you have a full behaviour setup.

Good luck.

# Answer
> 2 votes
This is how I would do what you call an "AI like Sims" in a simplistic way:

```
bool canRoam = true;
void Update()
{
if(canRoam&&!isNearInteractable)
    {
    RoamAround();
    }
if(isNearInteractable)
    {
    InteractWithObject(ObjectID);
    }
}
void onPlayerInteraction()
{
    canRoam = false;
}
void onPlayerInteractionEnd()
{
    canRoam = true;
}

```

Of course, those functions have to be custom made and yes you will need to get better at C# if you want to code AI. There's no way around it other than using Unity assets from the store (which would still mean getting better at C#). Try something easier first, make an object move around randomly.

Two "objects" interacting with each other means you have to learn how to send and receive messages or how to raycast. There is no easy way of doing this. (Other than getting ready to use assets in the store of course and that would mean learning to use said assets, which is still not easy.)

---
Tags: unity, ai
---


# Question
Title: How do i get a list of all joysticks connected to my pc in usb using sharpdx with c# ? Getting errors
The code:

```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using SharpDX;
using SharpDX.DirectInput;

namespace Ps4_Controller
{
    public partial class Form1 : Form
    {
        DirectInput input = new DirectInput();
        Joystick stick;

        public Form1()
        {
            InitializeComponent();

            List<Joystick> sticks = new List<Joystick>();

            foreach (DeviceInstance device in input.GetDevices
                (DeviceClass.GameControl,DeviceEnumerationFlags.AttachedOnly))
            {
                stick = new Joystick(input, device.InstanceGuid);
                stick.Acquire();

                  foreach (DeviceObjectInstance deviceObject in stick.GetObjects())
                    {
                        if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)
                        {
                            stick.GetObjectPropertiesById(deviceObject.ObjectType).SetRange(-100, 100);
                        }
                    }
                    sticks.Add(stick);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
}

```

I'm getting error on the line:

```
if ((deviceObject.ObjectType & ObjectDeviceType.Axis) != 0)

```

Severity Code Description Project File Line Suppression State Error CS0103 The name 'ObjectDeviceType' does not exist in the current

And on the line:

```
stick.GetObjectPropertiesById(deviceObject.ObjectType).SetRange(-100, 100);

```

Severity Code Description Project File Line Suppression State Error CS1503 Argument 1: cannot convert from 'System.Guid' to 'SharpDX.DirectInput.DeviceObjectId'

# Answer
> 1 votes
You're getting these errors because the library no longer works the way it did in whatever documentation you are using.

Joystick.GetObjects() supports a parameter that allows you to specify the ObjectDeviceType you are looking for.

Joystick.GetObjectPropertiesById() wants a DeviceObjectId as a parameter, not a Guid.

Relevant code as follows:

```
List<Joystick> sticks = new List<Joystick>();

foreach (DeviceInstance device in input.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
{
    Joystick stick = new Joystick(input, device.InstanceGuid);
    stick.Acquire();

    foreach (DeviceObjectInstance deviceObject in stick.GetObjects(DeviceObjectTypeFlags.Axis))
    {
        stick.GetObjectPropertiesById(deviceObject.ObjectId).Range = new InputRange(-100, 100);
    }
    sticks.Add(stick);
}

```

Please note that I've moved the declaration of the Joystick stick object into the form constructor. There's no reason to declare it outside of that scope.

Also note that some objects can not have their Range property set as it is readonly, so this may fail.

---
Tags: c#, directx, sharpdx, slimdx
---


# Question
Title: how to make a ball move in opposite direction when hitter to ball or paddle
I had set angle but it's not correct and I'm not getting exactly what I needed. The ball should bounce when hit to paddle or border and move in opposite direction. I'm writing the code in c++.

I had presently written this code when the ball and paddle intersects and I couldn't get how the code is working.

```
auto paddleY=paddleSpr->getPositionY();
auto intersectY=ballSpr->getPositionY();

auto paddleheight=65;
auto maxBounceAngle=45;
auto speed =1550;

auto relativeIntersectY=(paddleY+(paddleheight/2))-intersectY;

auto normalizedRelativeIntersectY=(relativeIntersectY/(paddleheight/2));

auto  bounceAngle=normalizedRelativeIntersectY*maxBounceAngle;

float vx = cos(bounceAngle * M_PI / 180) * speed;
float vy = sin(bounceAngle * M_PI / 180) * speed;

pbody11->setVelocity(Vect(vx,vy));

```

# Answer
in my opinion , setting speed to negative should fix the problem ( which negative is opposite with positive ) :

```
auto paddleheight=65;
auto maxBounceAngle=45;
auto speed=-1550;

auto relativeIntersectY=(paddleY+(paddleheight/2))-intersectY;

auto normalizedRelativeIntersectY=(relativeIntersectY/(paddleheight/2));

auto  bounceAngle=normalizedRelativeIntersectY*maxBounceAngle;

float vx = cos(bounceAngle * M_PI / 180) * speed;
float vy = sin(bounceAngle * M_PI / 180) * speed;

pbody11->setVelocity(Vect(vx,vy));

```

***UNTESTED*** , because it is not possible without full project file .
> 1 votes

---
Tags: cocos2d-x
---


# Question
Title: Reversing translational dependency of Sprite on Mouse instantaneously at runtime without causing the sprite to jump
Help me think through a logical way to implement the desired effect.

**Goal**: (I'm using Adobe Animate CC 2017 targeting AIR for Desktop)

* Move a sprite using a controller (mouse on a PC for instance) with a 1:2 ratio.
* Have an event trigger a function that causes this relationship to become a -1:2 ratio (and another one to switch it back to 1:2)

**My First Thought Experiment** (represented in pseudo code)

* `sprite.x = mouse.x * 2 - stageWidth / 2 - sprite.width / 2` (works fine, 1:2 ratio)
* function `reverseRatio():void{ sprite.x = stageWidth - (mouse.x * 2 - stageWidth / 2 - sprite.width / 2) - sprite.width` (also works fine, but with a catch\*)

+ The "catch" is that the sprite, when triggered to reverse ratios, jumps to the reverse side of the display window. What I'd *like* to accomplish is somehow have the motion of the sprite tied to the motion of the mouse, but what I have accomplished is the *position* of the sprite is dependent on the *position* of the mouse. And since when this event is triggered, the mouse does not move, the sprite suddenly does (which I'm guessing would get bad reviews during play testing, although the very saddistic gamer may actual enjoy trying to master this effect!)

So it seems I need to do just that, link the *motion* of the mouse and sprite, instead of the *position*. This also seems to have a "catch" though.

**Here's another thought experiment** using this *motion* dependency method.

1. You move the controller toward the right of the display window with a *motion* dependency to the Sprite of 1:2 (mouse:sprite). \*By motion I mean use the *delta* or change in x position by recording the position in one frame and using the difference in the next frame to determine how much the Sprite translates.\*
2. The Sprite goes to the far right of the window as well (actually getting there before the mouse does because of the imbalanced ratio).
3. The event is triggered that negates the relationship to -1:2 (mouse:sprite).
4. The sprite does **not** jump to the far left side of the window because its motion is dependent on the motion of the controller, which isn't being moved.
5. Now the controller moves further to the right
6. This should have the effect of moving the sprite to the left, which it does, but by the time the sprite moves back to the left half way across the screen, the controller has left the window and thus can no longer influence the sprite (my application pauses when the mouse leaves, because my target framework doesn't support mouse input from outside the display window).

So because these two methods have these "catches" I have to choose between the sprite jumping across the screen or only being able to move the sprite halfway back when this event is triggered. I *think* this means I need to really rethink my whole methodology. Any thoughts on a slick way to achieve this effect? It seems impossible to me without having my PC physically move the location of the mouse cursor (which, if I could do that, would totally work!).

Thoughts? Questions?

in the bottom picture, the event has been triggered, but the sprite can't respond to the movement of the cursor, becasue it is already to the far right. I could manually move the cursor to the far left, at which point things would work fine, but the goal is for this to be instantaneous reversal of the relationship.

**edit**

If I *were* to port this to iOS, I think I could use the accelerometer to control the Sprite which effect could be instantaneously reversed without a cursor running out of real-estate. Right? What about using a finger drag to control the Sprite? Would I run into the same problems as the mouse on a desktop? Just musing here.

**update**

I have an idea (just to give you an idea of the kind of ideas i am open to for suggestions). My idea is give a visual cue as to where the Sprite would "jump" to when the correlation gets reversed. I am imagining a ghost image, or an outline, or a Sprite with raster lines through it to indicate that it is an inactive version. Then when the correlation switches, the feint one becomes solid and vice versa.

# Answer
> 1 votes
It might be easier to take a delta, so record the position of the mouse in the last frame/update, then multiply the distances (change between last position and current position) by the desired amount (2 and -2 if mouse is clicked in your case).

---
Tags: movement, actionscript-3, mouse
---


title: Android native database organization

text:
# Question
Title: Android native database organization
I am developing an Android native game, but I have problems with Data Storage. For a better comprehension think it like as i am developing Clash of Clans, but with Native Andorid.

Now imagine I have to store all datas for Buildings, moneys, troups, ecc in my local phone DB.

I read some guides about SQLite for Android, but i don't really like it. It picks always a `Cursor` object and i have to create an "Helper" class for each table so I can convert the Cursor into the object I picked.

My question is: is there a way to do it in a "easier" way but still complete as SQLite?

I learned SugarORM and it is really simple and intuitive, but it has no possibilities for `ID` and a lot of other limitations.

I want a library or anything else that allows you to do like windows phone c#:

```
SQLiteConnection conn = new SQLiteConnection(DBPath);
return conn.Query<TABLE_NAME>(SQL_QUERY);
//in this way i have a list of TABLE_NAME items without any casting or similar.

```

Is there a way to do it?

# Answer
I tried it all and the best way is the cursor/helper way. Its much simpler than using any framework.

Just create a helper class to manage all db interactions.

Persisting data is as easy as this:

```
ContentValues cv = new ContentValues();
cv.put("column1", "some value");
db.insert("mytable", null, cv);

```

And fetching from db is like this:

```
Cursor c = db.rawQuery("select * from mytable where column1 = ?", new String[]{"some value"});

c.moveToPosition(-1);
while (c.moveToNext()) {
    String userId = c.getString(c.getColumnIndex("userId"));
}
c.close();

```

Thats it, it doesn't get any easier.

You of course can make these queries not in a helper method.

Also make sure to invoke all db writes/fetches not from the UI thread.

You can read more about in my blog posts: http://tocrva.blogspot.com/2015/04/android-sqlite-made-easy-tutorial.html http://tocrva.blogspot.com/2015/08/android-sqlite-best-practices-how-to.html
> 1 votes

---
Tags: java, android, databases, sql
---


title: How can I move my button?

text:
# Question
Title: How can I move my button?
I am new to animations in android. I was wondering, is there a way to keep a button moving around the screen, bouncing off the walls, until it gets clicked? I was thinking to do something like this:

```
    while(!clicked){
    //Run code to move button
        }
  button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
    clicked = true;
        }
    );

```

And to make it random, do something like this:

```
Random r = new Random();
btnCount.animate().xBy(r.nextInt(10)+1).yBy(r.nextInt(10)+1);

```

But that doesn't work, and nothing happens. What is the best way to do this animation?

Thanks,

Ruchir

# Answer
Try this

```
        TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 500);
        anim.setDuration(300l);
        anim.setFillAfter(true);
        button.startAnimation(anim);

```
> -1 votes

---
Tags: java, 2d, android, collision-detection
---


# Question
Title: Best practices for client-server communication in an online Android game
I'm developing an online RPG game for my "Object-Oriented Programming" module laboratory project. The client part must be written in C#, also using Unity 3D as a graphics engine.

The problem is that I don't know how to make the client-server communication rapid. How to achieve that every player sees other players' actions in real time on his device.

I want to get some recommendations on how to implement the client-server communication so that everything happens very quickly, i.e. when some player changes his position in a game, this change is immediately sent to all the other players' devices.

Of course, I also want to save all the players' current states in a database, so that they start where they left off the last time they logged out.

For the server side development, I'd prefer linux environment, but the language in which the server part will be written doesn't really matter to me. I just want it to be very fast.

# Answer
You need to use instant messaging, sockets, etc.

I recommend using PubNub.com, i've been using is a lot.

You actually don't need a back end with this.

So you subscribe to a channel, for example the channel of some location.

Then, when somebody moves, for example to coords 5;10, you publish a message with this coordinates to the channel, and all subscribed devices receive the message almost instantly! Process it and show the player that moved at coords 5;10.

You also can publish the messages from a back end server.

This is how i would do it. Though i haven't used pubnub for game dev.

Its a good way to make prototypes, but as far as i know about game networking, the best speed is achieved by building your own networking architecture/server etc.
> 1 votes

---
Tags: c#, android, rpg, client-server, online
---


# Question
Title: How can I send effects to joystick connected to my PC USB using C# and sharpdx?
I can get a list of the joysticks connected to my PC. But now I want to send effects for example to send a command that will make a button click for example the triangle button or the square button.

But I'm not sure how to continue with the effects and how to send the commands to the buttons.

I'm stuck in the HandleJoystick method.

```
namespace Ps4_Controller
{
    public partial class Form1 : Form
    {
        DirectInput input = new DirectInput();
        Joystick stick;

        public Form1()
        {
            InitializeComponent();

            stick = ListJoysticks()[0];
        }

        private Joystick[] ListJoysticks()
        {
            List<Joystick> sticks = new List<Joystick>();

            foreach (DeviceInstance device in input.GetDevices(DeviceClass.GameControl, DeviceEnumerationFlags.AttachedOnly))
            {
                Joystick stick = new Joystick(input, device.InstanceGuid);
                stick.Acquire();

                foreach (DeviceObjectInstance deviceObject in stick.GetObjects(DeviceObjectTypeFlags.Axis))
                {
                    stick.GetObjectPropertiesById(deviceObject.ObjectId).Range = new InputRange(-100, 100);
                }
                sticks.Add(stick);
            }
            return sticks.ToArray();
        }

        private void HandleJoystick()
        {
            Joystick stick = ListJoysticks()[0];
            int[] axis = new int[0];

            foreach (DeviceObjectInstance doi in stick.GetObjects())
            {
                axis = new int[axis.Length + 1];
                axis[axis.Length - 1] = doi.Offset;
            }

            EffectParameters ep = new EffectParameters();
            DeviceInstance stick1 = new DeviceInstance();

            Effect effect = new Effect(stick.);
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
}

```

# Answer
I'm assuming you are looking to receive input from the controller, and not actually trying to send data to the controller.

First, an Effect in this context is referring to a force-feedback effect (IE. rumble).

If you are looking to query the Joystick object for input, you must first set the object to used buffered data by setting it's BufferSize property.

```
Joystick stick; //Use whatever code you desire for selection of proper Joystick object
stick.Properties.BufferSize = 128;
stick.Acquire();

```

Then you can poll the joystick for input data:

```
while (true)
{
    stick.Poll();
    var datas = stick.GetBufferedData();
    foreach (var state in datas)
    Console.WriteLine(state);
}

```
> 1 votes

---
Tags: c#, directx, sharpdx
---


title: AngelCode's Bmfont about widths

text:
# Question
Title: AngelCode's Bmfont about widths
In AngelCode's Bmfont is there a way to make it so that all of the widths are equal?

# Answer
> 1 votes
No. You can't do that with AngleCode's Bitmap Font Generator. You could take the resulting image and location information and run it through a separate sprite sheet editor to pull the images out. Then resize them to the widest character and put them back.

Though, you're best bet is to find an alternative font generator. This isn't really the place to ask for that however. Though I recommend your search term be something like "fixed width bmp font generator", which had some results for me.

# Answer
> 0 votes
Not using BMFont, no.

If you're willing to pay a subscription fee and are on Mac, Glyph Designer does the best job of any tool out there for building bitmap fonts. Though I'm not sure if they still(?) support grid layout.

If you're desperate for a grid layout i.e. equal widths and heights for each cell, LMNOpc Bitmap Font Builder does this. Unfortunately it's over a decade old and doesn't support unicode the way BMFont does... so you're stuck with Western European. But, it may get the job done for you.

---
Tags: image, fonts, text
---


# Question
Title: Detecting interesting kill in a 2D shooter
In Xonotic for some kills (and maybe even just hits?) the game plays a sound clip saying "Impressive!". I was wondering how does the game recognize that a kill was impressive. In Xonotic it feels like giving larger damage faster (somehow) increases a probability of this announcement.

Does anyone know how are these things implemented? I can imagine it being easy(-ish) for hitscan weapons like a sniper rifle, where I can just take how fast was the target going across my screen and score the hit based on this. But what about rocket launchers where it might take time before shooting and hitting? I can't think of any reasonable rule for this.

In particular I'm trying to fit this idea onto a fast top down shooter with keyboard movement and mouse aiming and with weapons similar to Xonotic or UT99.

What exactly I'm interested in:

* How do existing algorithms for detecting interesting hits / kills work?
* Do these handle non-hitscan weapons?
* How can they be extended to support them non-hitscan if they don't?

# Answer
Well, I didn't, but fortunately for us Xonotic is open source.

A quick grep for the word impressive told me it is an announcement message:

```
MSG_ANNCE_NOTIF(1, ANNCE_ACHIEVEMENT_IMPRESSIVE, CH_INFO, "impressive", VOL_BASEVOICE, ATTEN_NONE)

```

It also shows up in `w_vaporizer.qc` and `w_vortex.qc` which I can only assume are the names of two of the weapons in this game.

A stripped version of `W_Vaporizer_Attack` looks like this:

```
void W_Vaporizer_Attack(void)
{
    damage_goodhits = 0;
    FireRailgunBullet(w_shotorg, w_shotorg + w_shotdir * MAX_SHOT_DISTANCE, 10000, 800, 0, 0, 0, 0, WEP_VAPORIZER);

    if(damage_goodhits && self.vaporizer_lasthit)
    {
        Send_Notification(NOTIF_ONE, self, MSG_ANNCE, ANNCE_ACHIEVEMENT_IMPRESSIVE);
        damage_goodhits = 0; // only every second time
    }

    self.vaporizer_lasthit = damage_goodhits;
}

```

A stripped version of `W_Vortex_Attack` looks incredibly similar:

```
void W_Vortex_Attack(float issecondary)
{
    damage_goodhits = 0;
    FireRailgunBullet(w_shotorg, w_shotorg + w_shotdir * MAX_SHOT_DISTANCE, mydmg, myforce, mymindist, mymaxdist, myhalflife, myforcehalflife, WEP_VORTEX);

    if(damage_goodhits && self.vortex_lasthit)
    {
        Send_Notification(NOTIF_ONE, self, MSG_ANNCE, ANNCE_ACHIEVEMENT_IMPRESSIVE);
        damage_goodhits = 0; // only every second time
    }

    self.vortex_lasthit = damage_goodhits;
}

```

But what is `damage_goodhits`? That can be found in the server source file `g_damage.qc`:

```
if(targ != attacker)
{
    entity victim;
    if((targ.vehicle_flags & VHF_ISVEHICLE) && targ.owner)
        victim = targ.owner;
    else
        victim = targ;

    if(IS_PLAYER(victim) || (victim.turrcaps_flags & TFL_TURRCAPS_ISTURRET) || (victim.flags & FL_MONSTER))
    {
        if(DIFF_TEAM(victim, attacker) && !victim.frozen)
        {
            if(damage > 0)
            {
                damage_goodhits += 1;
                damage_gooddamage += damage;
            }
        }
    }
}

```

So to trigger the "Impressive" achievement in Xonotic you must:

* Be using the Vaporizer or Vortex weapon.
* Be shooting at a player, a vehicle containing a player, a turret, or a monster.
* The target must not be yourself.
* The target must be on a different team.
* The target must not be frozen.
* You must successfully hit the target twice consecutively with the same weapon.

If you want to answer more questions like this, you can acquire Xonotic's source code via their Download page: http://www.xonotic.org/download/
> 11 votes

---
Tags: game-design, shooter
---


# Question
Title: How can I prevent my bullet from influencing other players when colliding with them?
So when my bullet which is a Rigidbody is hitting another player which is also a Rigidbody, the bullet is getting destroyed immediately. But it seems that this isn't enough to prevent the physics to be applied. I guess that's why my player is getting pushed backward all the time when he is getting hit. I don't want this behaviour, so I tried to fix it :

I tried to lower the mass of the bullet which didn't help. I also tried to change the bullet behavior to a trigger, but the collision detection failed very often.

# Answer
I'll do as TobiasW has suggested and turn my comments into an answer format.

First thing to keep in mind when using physics with bullets or short-lived objects is that there can be MANY of them. If your game is anything like Battlefield, you may want to rethink the usage of physics on every single bullet.

For CPUs, doing math is always much cheaper (in terms of performance) than doing physics calculation. So, try not to use physics if you can help it.

Also, try to use stored variables. For example, a gun will shoot a bullet towards a trajectory and calculating that trajectory every time you create a new bullet is costly. Instead, calculate it for the gun and keep that as a stored variable (if you're raycasting, store it in a Raycast variable).

If the number of bullets on screen at any given time is not that high, then it's not a bad idea to use physics, but still, try to avoid using physics calculations as much as you can. For example, if you're never going to have 100 and rarely going to have more than ten rockets on the screen at any given time, then it's not a bad idea to use physics with those. Especially if you're thinking of having "magnetic" traps (like the magnets from Worms games) which attract or deflect the rocket.

If you wish to use physics on an object but not have it push other stuff back, it's a good idea to encase the `rigidbody` inside a `collider`, so if you have a 1cm square (or cube if you're in 3D) rigidbody on a bullet, then make its collider into a 1.1cm square. This will mean that before the physics calculations of the hit can take place, the collider will do the calculations it's supposed to and then get rid of the bullet. Of course, colliders can still do a push-back like effect, but it should be infinitesimal compared to a rigidbody. Besides, you still don't want the physics calculations kicking off for a minigun that's dishing out 6000 bullets per minute.
> 1 votes

---
Tags: unity, physics, rigid-body-dynamics
---


# Question
Title: Remove delay when changing axis input in the Unity Input Manager
I had a problem playing with the Input Manager, where for example:

When Horizontal (+) is pressed, it increase its value but, when Horizontal (-) is pressed, the horizontal value stays positive for a little, but keeps decreasing. This causes the character to continue playing "right" animations and still moving to right for a few seconds, instead of instantly playing 'left" animations and moving to left. The problem also makes the character movie a little after the player releases the key.

I have also used `Input.GetKey()`, but that means the player cannot change the setting from the game launcher, and I don't want to create player setting in-game, for now.

What I am trying to achieve is when Horizontal (+) is pressed, then the player presses Horizontal (-), it should instantly turn left without delay. When the player is not pressing any Horizontal key, it should stop moving horizontally, instantly. This problem also appears along the Vertical axis.

How do I make it so input snaps to -1 or 1, with out slowly moving back and forth?

# Answer
The problem your having is that your directly accessing input; However, the input is set up as an *Axis*, and is intended for "analog" style controls. Consider this; if you use the buttons `a` and `d`, there is logically only a -1 and a +1. If you were to use an *analog controller*, the inputs would *range* between -1 and +1.

As such, there is a level of smoothing that is applied to the input. You could play around with this smoothing for the desired effect, but given you wish to remove the feature *entirely*, there *is* a much easier option; using `Input.GetAxisRaw()` instead of `Input.GetAxis()`.

---

Let's take a look at the API reference:

> # Input.GetAxisRaw

>
> public static float **GetAxisRaw**(string **axisName**);
>
> ## Description

>
> Returns the value of the virtual axis identified by axisName with no smoothing filtering applied.
> The value will be in the range -1...1 for keyboard and joystick input. **Since input is not smoothed, keyboard input will always be either -1, 0 or 1.** This is useful if you want to do all smoothing of keyboard input processing yourself.

---

There you have it. Simply calling `Input.GetAxisRaw("Horizontal")` and `Input.GetAxisRaw("Vertical")` will retrieve the true values (-1, 0 or +1) of the desired input, without any applied smoothing.
> 3 votes

---
Tags: unity, input
---


# Question
Title: Unity equivalent to cocos2D (and Sprite Kit) Actions?
Does Unity have an equivalent to the Actions feature/functionality of cocos2D and Sprite Kit; if so, what is it?

**cocos2D Actions:** http://python.cocos2d.org/doc/programming\_guide/actions.html http://www.cocos2d-x.org/wiki/Actions

**Sprite Kit Actions:** https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit\_PG/AddingActionstoSprites/AddingActionstoSprites.html

# Answer
You might like DOTween, which is a tween engine for Unity and a successor to HOTWeen.
It's said to be a lot faster than iTween, another tween engine for Unity. I also find it easier to use too.
I suggest you check out the documentation page. It has easing like you mentioned, among other many useful features like `Sequence`s and callbacks. It's obvious from looking at the documentation page, but it can tween many objects, including UGUI ones.
I'm using it for my 2D game project for school to animate UGUI objects, so the features that I find particularly useful are the ones listed under "*Unity UI 4.6 shortcuts*" under "*B. The shortcuts way*" on the documentation page.
But again, you can use it to animate things like `Camera`, `Material`, `Rigidbody`, `TrailRenderer` etc etc...
About easing, DOTween's easing options include sine, quadratic, cubic, elastic and many more.
> 0 votes

# Answer
> Does Unity have an equivalent to "Actions"?

That depends *entirely* on your interpretation of what "Actions" do, and of course, your base requirements.

---

Let's take a look at an example of an "Action", as provided by the Cocos2d-x Wiki:

```
// Move sprite to position 50,10 in 2 seconds.
auto moveTo = MoveTo::create(2, Vec2(50, 10));
mySprite1->runAction(moveTo);

// Move sprite 20 points to right in 2 seconds
auto moveBy = MoveBy::create(2, Vec2(20,0));
mySprite2->runAction(moveTo);

```

From what the documentation infers, `MoveTo` is an action that has been built to direct any object to a position. In this case, you appear to be creating a *delegate* function, which your object then stores reference to and runs.

---

Let's take a look at an example of how you would implement this same "Action" in Unity:

```
float speed = 10;
Vector2 targetPosition = new Vector2(50, 10);
Vector2 newPosition = Vector2.MoveTowards(transform.position, targetPosition, speed);
transform.position = newPosition;

```

---

You will immediately note that in Unity, you are writing the "action", yourself. As such, you should have an understanding of either Java or C#. This might seem a little more difficult than the "pre-baked Actions" of Cocos2d-x, but this is often desirable; you should still ideally only have to write the action *once*, and you have access to a lot of powerful functions provided by the `UnityEngine` namespace (alone - there are many other namespaces under the `UnityEngine` namespace). Furthermore, you can make it behave *exactly* how you want it to. For example, you would be able to edit the above script to interpret `speed` as `speed * Time.deltaTime`. This is especially useful, in this context; we need to scale our speed to the delta time of the update functions, to ensure the speed stays the same across a variation of setups and processor speed.

---

> Does Unity implement "Sprite Kit Actions"?

The same rules apply.

You can still manipulate various attributes associated with the sprite, whether that be direct values on the sprite itself to change things such as transition style and speed, or changing values on the *game object* that *holds* the sprite.

These "actions" would simply be methods you have written that manipulate these areas. You can also create variables on the animations, themselves, which can be directly manipulated with built-in functions.

---

Ultimately, it is difficult to say if Unity has "Actions", as it is hard to infer *exactly* what you *want* from the "Actions". That said, if you assume programming capability, you certainly have the ability to set the mechanic up on your own.

Than again, you may not want to. As stated previously, the example appears to show "Actions" being used as *delegates*. Unity typically expects you to call "actions" as standard functions (`MoveTo::create()` versus `Move()`). You might find that with time, you take to using the Unity method; *delegates* are considered more advanced, though you do not appear to be given the same type of control you would expect from advanced technique.

It is important to note that *regardless*, you *are* going to have to do some programming. Unity runs off Unityscript (a variation of Javascript) and C#, where Cocos2d-x runs off C++. You will find *similarities*, but you will not get absolute control by assuming C++ context. Regardless, the Unity website offers excellent tutorials, and provided you put in the effort, it will not be difficult to use code in Unity by comparison.
> 0 votes

---
Tags: unity, cocos2d, spritekit
---


# Question
Title: How do I fix the bug where my Rigidbody gets stuck on the edge of two Colliders?
The boxes are standing right next to each other, but somehow, the player manages to collide with the ghost edge. I use `AddForce` to control the player with a Box Collider, though I also tried using a Mesh Collider, and I tried setting the player's collision to continuous. This also happens in 2D.

I've seen other people's posts about this bug, but I couldn't really understand how to fix it. How do I fix this?

# Answer
I think I had a similar issue in 2D. Try replacing your Box Collider with a reasonably sized sphere or capsule.

In 2D, I ended up using a Circle Collider with a smaller Box Collider. The Circle Collider made it so that my player didn't get hung up on the floor and walls that were composed of discrete boxes (with associated Box Xolliders). I added the smaller Box Collider to the player, because as a 2D platformer, I did not want my player to slide off the edge of obstacles.
> 2 votes

# Answer
Try changing the material of your box colliders. Also, I found a similar thread in Unity forums. That's about 2D, but the problem seems to be the same.
> 0 votes

---
Tags: unity, collision-detection, physics, meshcollider
---


# Question
Title: Access alpha value of opengl texture pixels
I'm trying to get the alpha values of each pixel of an image that I'm loading onto a texture so i can use it to check for per pixel collision. I have a texture class:

```
struct GLTexture {
    std::string filePath = "";
    GLuint id;
    int width;
    int height;
    std::vector<std::vector<int>> alphaPixels;
};

```

When i bind the texture i want to do something like this:

```
//Generate the openGL texture object
glGenTextures(1, &(texture.id));

//Bind the texture object
glBindTexture(GL_TEXTURE_2D, texture.id);
//Upload the pixels to the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(out[0]));

for(int i = 0; i < width; i++)
{
    for(int j =0; j<height; j++)
    {
        alphaPixels[i][j] = getAlpha(GL_TEXTURE_2D); ///<something like this line but i don't know how to access to alpha value
    }
}

```

How can i get the alpha value of each pixel of the image? Is this even a feasible thing to do or is there a better way to do this?

# Answer
> 1 votes
Since you have uploaded the image, you probably still have it in main memory. To access any given pixel, you can get its address by doing the following:

```
uint8* pixelAddress = (uint8*)out + bytesPerRow * row + bytesPerPixel * col;

```

Here I'm assuming that `bytesPerRow` is the number of bytes in a row of pixels in the texture. Furthermore, I'm assuming that `bytesPerPixel` is the number bytes in a pixel. As you can probably guess, `row` and `col` are the row and column for the pixel you wish to access. Note that this will give the address of the first byte of the pixel. If it's an RGBA pixel, you'll need to add 3 to it to get the address of the alpha channel.

The point being that you don't need to create a new alpha-only image, as you already have the alpha information in main memory.

---
Tags: opengl, c++, collision-detection
---


# Question
Title: Mesh generation for procedural city generator
I have a programming problem relating to mesh generation for city grids. I've recently created a city grid generator and I've come as far as being able to reliably generate the road mesh for the grid my system spits out. However, now I am stuck with finding a method to generate the lots and spaces in between the roads. Eventually, I want the city grid to have elevation changes and for that, I need to be able to fill in the spaces between the roads.

Here's an example of what I have:

I've looked into triangulation methods like Delauney Triangulation, but the output is unreliable (maybe due to the way I am using it). Here's another example that shows the problem (the black lines are the road mesh, the magenta ones are the Delauney output):

For the most part, the Delauney output follows the mesh when I present it with only the vertices that make up the intersections. However, sometimes, the Delauney triangles overlap the ones from the road mesh (like with the wide road in the center of the image). I am using a port of as2Delauney for Unity and I simply create a list of all the vertices that make up the intersections and then pass it to the Delauney function and I wonder if there is something I need to consider before passing a bunch of points and letting the function sort it out.

Are there any special considerations I need to be aware of when using Delauney for this type of triangulation, or are there any other methods that I could use to create the fill ins for the road mesh?

I've thought about building a function that tries to follow the intersections in clockwise or counterclockwise order until it loops back to the start, but that would lead to infinite loops as some roads are dead ends.

Right now I am not really sure what to look for as I lack terminology and google has yielded no results as to the methods that I could use to generate the fill ins for the road mesh (there is some good stuff on city generation, however not on the mesh part).

Does anyone have any experience with this?

Edit: This is how my system works:

Basically, I use an open list of lines to grow my network and I check the lines against a bunch of constraints. Then I go through each line and I generate intersections for each start and endpoint. So if the end/start is already in my list, I add the other point as a destination for the current intersection.

I end up with a list of custom objects that hold their own position vector and all the position vectors of the intersections it connects to. With this I then create the mesh points for the intersection by checking the cutting points of the lines that make up the sides of the roads, so I have those points at my disposal and i use them to create the triangles for my mesh.

Now I just need to know how to organize them to create the fill ins that span multiple intersections.

# Answer
There'a a variant of delaunay triangulation: Constrained delaunay triangulation lets you define which edges should never be flipped, e.g. in your use case, the edges belonging to roads.

Unfortunably, out of my head, for libraries which implement constrained delaunay, I can only mention CGAL, which is C++ and released under GPL: http://doc.cgal.org/Manual/3.3/doc\_html/cgal\_manual/Triangulation\_2\_ref/Class\_Constrained\_Delaunay\_triangulation\_2.html

That would allow you to properly triangulate the spaces between roads without damaging the road polygons. You could then use something like the methods described in "Procedural Generation of Parcels in Urban Modeling" by P. Cignoni and T. Ertl (https://www.cs.purdue.edu/cgvlab/papers/aliaga/eg2012.pdf) to divide the resulting city blocks into parcels.

TL;DR: One of the simpler algorithms presented in the paper goes like this:

For each space between roads: generate the oriented bounding box (OBB), divide the polygon along the longest axis, repeat for the resulting smaller OBBs until statisfied. Then place buildings to taste.
> 1 votes

# Answer
**Problem**

You need consistency in your systems / data structures. From your image, it appears that you:

1. Generate the basics on a regular grid / 2D array, where you have `m` vertices across, and `n` vertices down for a `m x n` grid. Then you have `m-1` interstices across and `n-1` interstices down. (This takes into account *only* intersections, not splits of each road into 2 segments. It also does not accommodate expansions / inclusions - see "high street", below.)
2. Split every road segment into 2 rects / 4 tris. I think to assist the curving roads (see next step).
3. Perturb these resultant points or otherwise apply a transformation across the entire space. This gives subtle curvatures to different city sections.
4. Try to overlay the lots (interstices) mesh, over the rest.

Resultant issues:

1. You're not tracking those splits on step 2, in your base array. By adding these splits, you've roughly doubled the number of points, **but the base array does not reflect the new vertices created**. So on step 4 above, you aren't matching vertices exactly.
2. You appear to have a special "high street" running through town, that is not reflected in the original data structure which you are using to generate the lots / interstices mesh.
3. Using a 2D array as your base data, you get crossings where you probably don't want them.

To clarify further, I've superimposed some split lines over the interstices (`[0]`s in solution, below):

**Solution**

You need an intermediate data structure that can hold your special case additions (splitting each road segment into 2 rects / 4 tris, and generation of a high street *after* the overall grid generation). You should use a graph, where every node represents not a road *intersection*, but rather any line down which we can split road *segments*, and where every edge represents a *segment* of road, e.g.

```
[I]--[0]--[I]--[0]--[0]--[0]--[I]->
 |Lot1     |Lot2               |
[0]       [0]                 [0]
 |         |                   |
[I]--[0]--[I]--[0]--[0]--[0]--[I]->
 |         |                   |
 V         V                   V

```

`[0]` = splits in the road, they are basically vertices where you split each road segment into 2 rectangles. `[I]` = intersections. Note that above and below `Lot2`, there are 4 segments of road, not just 2. This is to illustrate how you could add the high street running through, by node replacement:

```
[I]--[0]--[I]--[0]--[I]--[0]--[I]->
 |Lot1     |Lot2     + Lot3    |
[0]       [0]       [0]       [0]
 |         |         +         |
[I]--[0]--[I]--[0]--[I]--[0]--[I]->
 |         |         +         |
 V         V         V         V

```

Or you could *add* it into the existing nodeset rather than *replacing*:

```
[I]--[0]--[I]--[0]--[0]--[I]--[0]--[I]->
 |Lot1     |Lot2          + Lot3    |
[0]       [0]            [0]       [0]
 |         |              +         |
[I]--[0]--[I]--[0]--[0]--[I]--[0]--[I]->
 |         |              +         |
 V         V              V         V

```

Finally, you can have each of these nodes point to special-purpose "lot nodes" in the centre:

```
[I]--[0]--[I]
 | \     / |
[0]-[L1]--[0]
 | /     \ |
[I]--[0]--[I]

```

From the aforementioned graph, generated in full (including high street), you can then generate your meshes. Remember: Update Data/Model first (the above), then Views (mesh information); how you *triangulate* your additions during the latter phase, is totally distinct from the problems you're facing.

Finally, you probably really do want one single mesh to represent everything, lots and roads. Only buildings would likely be kept separate.
> 1 votes

---
Tags: unity, c#, grid, mesh, procedural
---


title: What's the DSA version of glTexImage2D?

text:
# Question
Title: What's the DSA version of glTexImage2D?
I want to set the initial data of a texture in an OpenGL 4.5 program (using OpenTK.Next and .NET), utilizing the new Direct State Access methods.

However, I cannot find a DSA version of `glTexImage2D`. There are methods like `glTextureSubImage2D` which accept a texture object ID, but using those to set the intial data fails with InvalidOperation.

I'm pretty sure there should be such a method... comparing textures to array buffers, array buffers *do* have a DSA version to set their initial data, `glNamedBufferData`.

According to the documentation, the DSA methods are all named `...Texture...` unlike the "old" methods which are named `...Tex...`, but searching through them didn't reveal me something like `glTextureImage2D`.

Anyone knows if there even is a DSA method to set the initial texture data?

# Answer
> 7 votes
GL\_ARB\_direct\_state\_access.

**There is none**.

Issue 5 in the DSA specification reads (in part):

> This extension omits TextureImageND (mutable texture definitions)...

Specifically, glTexImage/glTextureImage is the older "mutable textures" API which DSA omits, requiring you to use the immutable textures API instead. Therefore the non-DSA API is glTexStorage, whereas the DSA API is glTextureStorage.

Note that glTexStorage/glTextureStorage creates the texture object and it's backing storage but does not set the data; you must make a further call to glTexSubImage/glTextureSubImage in order to do that.

There are several advantages to using glTexStorage/glTextureStorage, and I refer you to the GL\_ARB\_texture\_storage specification for a fuller discussion; for the purposes of this answer it's sufficient to quote the first paragraph of the overview:

> The texture image specification commands in OpenGL allow each level to be separately specified with different sizes, formats, types and so on, and only imposes consistency checks at draw time. This adds overhead for implementations.

And issue 24 of the DSA specification confirms the reason why mutable textures were omitted:

> 24) Do we need DSA functions for mutable textures?
>
> RESOLVED: No. Immutable texture is a more robust approach to handle textures

---
Tags: opengl, opentk
---