texts: Monodevelop does not show the contents of the UnityEngine namespace in the autocomplete popup, but the scripts are still working properly. Why?

texts:
This is not the first time when I use Monodevelop for script editing it shows all UnityEngine related stuff in the autocomplete popup and than it randomly decides not to do so.

Reopening it didn't help.

What should I do?


texts: How is the "continues road" from 80's games called and done?

texts:
i like to test the "continues road" effect from 80's racing games . i call it like this i have no idea how it really called
the effect that a car is in front of you , and the road is Approaching to you ,
some thing that can seen in games like :
http://www.myabandonware.com/game/turbo-1ti
http://www.myabandonware.com/game/angel-nieto-pole-500-sp-2le

where i can find example of implementing such alurithem ? c++ is prefered but dosn't have to be c++ .
Thanks !


texts: Is an in-app purchase required to unlock game in order to bypass pirating acceptable?

texts:
I'm considering writing a mobile game and looking at distribution.  The game will have a server requirement, which means I will have to pay for bandwidth, hosting, processor time, etc.  Because of that I'll need to make at least a little money off this thing.  According to the press piracy is rampant in the android community.  To get around this, I'm thinking of implementing a simple model where the game is free, perhaps allowing play for X number of turns or something, and then requiring an in-app purchase to continue to play.  I would clearly explain this in the app description, and the in-app purchase would be managed per account so it would be linked to your google play account so you wouldn't have to re-purchase every time you get a new device.

Would gamers accept this model or see it as unreasonable?


texts: Multithreading vs Asynchronous game loop for multiplayer online game?

texts:
I'm trying to create a turn based multiplayer online game where players can be grouped in a room/lobby and play (similar to Ludo but number of players can be more than 4). There can be multiple such rooms at a time.
Here is brief overview of the game: The game is not resource heavy. Each player gets his turn to perform some actions for some time (~90 seconds) and meanwhile other players just communicates with server to get the actions performed by the player. There can be multiple game rounds and a winner is declared at the end.
The game state of each room would be different at a given time. Therefore, to manage the game states for all the rooms, I could think of two approaches:

Multithreading approach: Spawn a new thread for each room and run/manage the game loop and corresponding game states in room specific threads. But if there are too many rooms, the number of threads would be very large and this approach is not feasible as per this answer's comment. However this approach is preferable for mass multiplayer games online games (MMO) as per this answer. I also think this should work for considerable number of rooms because most of the time, threads are waiting for player's actions.
Asynchronous approach: Here, the game states of all the rooms would be stored in server's memory and whenever any requests is received from any player, the game state object will be retrieved using player's room ID and based on the state, the server will command players in that room. The state will then be updated. There will be only one main thread here.

So my question is what would be the better approach for this type of games, considering the future scaling requirements? Also suggest any better alternatives which I couldn't think of.


texts: SDL zooming/upscaling without images becoming blurry?

texts: I'm working on a game with 32px tiles and I have one question regarding this and scaling. When I try to see my game fullscreen my image just becomes blurry. I remember playing NES games and when the image was scaled you just saw pixels as big blocks but they were still as crisp as when they were small, so I'm wondering how I can do this in SDL.


texts: Choosing a correct collisionshape for a voxel engine

texts:
I am building a voxel engine on Ogre with bullet as a physics engine.

I separated my blocks into chunks to help batch together render calls.

At the moment, each chunk's physics is handled by a btBvhTriangleMeshShape that is constructed through the vertices and indices.

Each time the user breaks a voxel, I modify the vertex and index array and construct a new btBvhTriangleMeshShape.

Unfortunately, because btBvhTriangleMeshShape has to recreate an optimizedBVH each time it is created, this becomes quite slow, taking several seconds each time the user breaks a block.

I've alternatively tried using a btConvexTriangleMeshShape, but the broadphase collision detection now becomes very low performance dropping the fps to single digits if the player is near the blocks.

What is the proper collisionshape to choose?


texts: Unity - Easier way to resize group of buttons to the same size

texts:
I have a canvas with buttons, with a script attached to each button. This script creates an array for buttons and resizes every button to the same size as the longest one in that array (the button with the longest line of text in it). Everything works, but I was wondering: is there is an easier, more automatic way for this instead of having to drag every button in every array in the Inspector tab?

Any ideas would be greatly appreciated

UnityPackage: https://transfer.sh/6BCDG/buttonwidth.unitypackage

public Image[] otherbutton;

void Start () {

    for(int i = 0; i < otherbutton.Length; i++)
    {

        if (otherbutton[i].rectTransform.sizeDelta.x > gameObject.GetComponent<Image>().rectTransform.sizeDelta.x)
        {
            gameObject.GetComponent<ContentSizeFitter> ().enabled = false;

            gameObject.GetComponent<Image>().rectTransform.sizeDelta = new Vector2( otherbutton[i].rectTransform.sizeDelta.x, otherbutton[i].rectTransform.sizeDelta.y);

        }
    }
}


texts: Selecting components (only in editor) created in construction script

texts:
Question is about Unreal Engine 4
Is it possible to catch click (or other mouse) event on dynamically added component in editor?
For example:
I create 5 instances of StaticMeshComponent on OnConstruction function (5 would be BlueprintEditable property).
Then I would like to be able to click on one (or multiple) of them and change some values (same as if they were added using Components section).
Sample code of what I tried:
// ALayoutBaseActor inherits from AActor
void ALayoutBaseActor::OnConstruction(const FTransform & Transform)
{
    Super::OnConstruction(Transform);

    for (size_t i = 0; i < 5; i++)
    {
        auto name = this->GetName();
        name += FString("-staticMesh_mesh_" + i);

        auto staticMesh = NewObject<UStaticMeshComponent>(this, *name);
        staticMesh->SetStaticMesh(staticMeshSegmentMesh);
        staticMesh->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
        staticMesh->RegisterComponent();
        staticMesh->SetRelativeTransform(FTransform(FVector(i * 250.f, 0, 0)));

        // this works, but function is called for each component, also it does not highlight selected mesh
        staticMesh->SelectionOverrideDelegate.BindLambda([](auto &&x) {
            UE_LOG(LogTemp, Warning, TEXT("ALayoutBaseActor (%s) click"), *x->GetName());
            return false;
        });

    }
}

I think similar functionality works for Spline and InstancedMeshComponent, but I cannot find list of functions that needs to be overriden.
Thanks
To clarfiy: I need this functionality only in editor, not during gameplay.


texts: All GameObjects and Models are Transparent

texts:
Whenever I create a new game object its completely transparent, with the Mesh Renderer selected.

This is really frustrating as I am new to Unity and Google offers no solutions.


texts: Sea is higher than land when importing large real world terrain

texts:
I am trying to import some real world terrain into Unity with the help of Global Mapper. The data I am using is download from CGIAR SRTM(http://srtm.csi.cgiar.org/,http://srtm.csi.cgiar.org/srtmdata/). The land part works well but I am having trouble with the sea part.

This is a larger view of that weird thing in the first image. This strange is actually the sea. This is happening because I am using the gradient shader. Lokks like:

The sea is represented with white, but when Unity reading the .raw file, the white means the highest part. Does anyone know how to deal with problems like this? Thanks very march.


texts: Which opcodes are faster at the CPU level?

texts:
In every programming language there are sets of opcodes that are recommended over others. I've tried to list them here, in order of speed.

Bitwise
Integer Addition / Subtraction
Integer Multiplication / Division
Comparison
Control flow
Float Addition / Subtraction
Float Multiplication / Division

Where you need high-performance code, C++ can be hand optimized in assembly, to use SIMD instructions or more efficient control flow, data types, etc. So I'm trying to understand if the data type (int32 / float32 / float64) or the operation used (*, +, &) affects performance at the CPU level.

Is a single multiply slower on the CPU than an addition?
In MCU theory you learn that speed of opcodes is determined by the number of CPU cycles it takes to execute. So does it mean that multiply takes 4 cycles and add takes 2?
Exactly what are the speed characteristics of the basic math and control flow opcodes?
If two opcodes take the same number of cycles to execute, then both can be used interchangeably without any performance gain / loss?
Any other technical details you can share regarding x86 CPU performance is appreciated


texts: What is happening during queue_free() process?

texts:
From time to time, I encounter a hard-to-reproduce bug with a similar line of code:
## File: Level.gd

func _on_player_invisible() -> void:
    player.queue_free()

which sometimes crashes with: Attempt to call queue_free in base null instance on a null instance

I have added this null check condition, but the crash can still be observed:
## File: Level.gd

func _on_player_invisible() -> void:
    if player: player.queue_free()


texts: HTML5 - multiple animations, different fps

texts:
I want to create an html5 game which contains multiple sprites.

For different elements I want to create an fixed fps.

For example:

Walk - 10 fps, so 10 sprites will be shown within 1 second

Run - 15 fps

Attack - 3 fps

How can I create this with requestAnimationFrame and not using set timeout or setinterval.


texts: Unity Inspector | Displaying min and max variables on a single line

texts:
In a C# Unity script, how can I add fields that will be displayed in the Unity Inspector with min and max values on a single line? (like it is done for the Particle System, where you can choose Between Two Constants)

WHAT I HAVE | Separate lines for min and max:

public class MyTest : MonoBehaviour {
    [SerializeField] float projectileRateMin = 1f;
    [SerializeField] float projectileRateMax = 3f;
}

WHAT I WOULD LIKE: Single line with both min and max:

Another example is Vector2, which also gets displayed in the Inspector on one line. I did look at the Vector2 code and tried to copy and rename the relevant parts of the Vector2 struct to my own version, but it didn't show up in the Inspector at all.


texts: Behaviour of containers in Phaser 3 framework

texts:
I don't understand the behaviour of containers in this example:

Phaser example

The part I don't unerstand is line 41. Why is lastContainer assigned to newContainer? In line 40, newContainer is added as a child of lastContainer; my intuition would be that the effect of line 40 is so that the rotations can be performed on lastContainer (or, rather, on containerTails, which seems to contain four nested container structures, one for each arm), and propagated to its children.

It makes no sense to me that the variable containing the parent container should be assigned to its own child; how does that not overwrite the nested structure of containers, effectively removing the parent container from the picture?


texts: How to use LuaJIT the same that Lua in a C++ program?

texts:
I'm using Lua in my C++ program, as an library. But I read that LuaJIT is a better implementation.

Is it posible to replace with LuaJIT with little change? How?


texts:
Rather than computing potential fields in a grid and performing a lookup for them, I've decided to query the potential fields at a given point in 3D space by simply querying all the objects in a sphere of a given size- after this, I decide that their contribution to the final target is minimal and not worth computing.

However, after this, my efforts seem to be falling a bit short. Everything that I've tried results in either absolutely no effect whatsoever, or the units endlessly jerk around in circles.

I have the target position given by A*, and the direction I need to be facing in to face that target.

Right now, I'm running with this:

float total_distance = 0;
auto units = Units.collision(Physics::Sphere(unit->GetPosition(), range));
std::for_each(units.begin(), units.end(), [&](Unit* u) {
if (u == unit)
    return;
if (Math::Length(u->GetPosition() - unit->GetPosition()) > range)
    return;
total_distance += Math::Length(unit->GetPosition() - u->GetPosition());
});
std::for_each(units.begin(), units.end(), [&](Unit* u) {
    if (u == unit)
        return;
    if (Math::Length(u->GetPosition() - unit->GetPosition()) > range)
        return;
    auto relative_vector = unit->GetPosition() - u->GetPosition();
    auto heading = Math::Normalize(relative_vector);
    auto scaled_heading = heading * ((total_distance - Math::Length(relative_vector)) / total_distance);
    target_heading += scaled_heading;
    if (target.x != target.x)
        __debugbreak();
});
target_heading = Math::Normalize(target_heading);

If anybody can suggest a superior algorithm, I'd be interested in hearing about it.


texts: Disable automatic expansion of folder/parent when dragging objects into?

texts: I'm organizing a large scene.  I have a few subfolders like Trees, Flowers, etc.  When I drag a tree into the Trees folder, it expands the folder and scrolls to the bottom (where it added them).  Is there any way to disable this behavior?  I immediately have to scroll back up and collapse it so I can see the structure again.


texts: Path finding in grid for objects that occupy more than one tile

texts: In a grid-based game I am working on, I want to add objects that occupy more than one tile of the grid. Are there any algorithms or techniques to find paths for this kind of objects?


texts: XNA 4.0 - container with content, that can slide (C#)

texts:
I got an idea, but I got no idea on how to make it.
Okay, so here is the deal.

I want a container which can contain certain objects (These objects will draw the sprites/graphics).
But because of different screen sizes, I want to be able to scale the containers width and height. But I do not want the objects in the container, that go outside of the container, because of the scaling to be visible.

Because I want the objects all to be positioned horizontaly to eachother and I want a horizontal sliderbar, so I can slide from left to right within the container.

I wonder if anyone could point me in the right direction.

Thanks in Advance,
Mark


texts: Textures not working on glTF Embedded Models. Picture Explains The Issue. (GODOT ENGINE)

texts: I wanted the tree to look a bit more stylized, or have a bit more to it than just flat planes. Yet when I tried to put this texture on it, it just looks completely wrong. Is this a model issue or a mapping issue?


texts: GLFW shift key not behvaing like other keys

texts:
I am using GLFW 3.2.1

Currently I am implementing a camera. For the vertical controls I am using space to go up and shift to go down.

For all other keys, pressing the key results in the section of the code associated with the key always executing.

But for shift, it only gets exectuted when pressing and releasing but not while keeping the key pressed.

The key callbak is:

#define CAM_SPEED 0.2f
void static key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GLFW_TRUE);

    if(key == GLFW_KEY_W)
    {
        c.translateForward(CAM_SPEED);
    }
    if(key == GLFW_KEY_S)
    {
        c.translateForward(-CAM_SPEED);
    }
    if(key == GLFW_KEY_A)
    {
        c.translateSideways(-CAM_SPEED);
    }
    if(key == GLFW_KEY_D)
    {
        c.translateSideways(CAM_SPEED);
    }
    if(key == GLFW_KEY_SPACE)
    {
        c.translate(vec3(0,1,0)*CAM_SPEED);
    }
    if(key == GLFW_KEY_LEFT_SHIFT || mods==GLFW_MOD_SHIFT)
    {
        c.translate(vec3(0,-1,0)*CAM_SPEED);
    }
}


texts: For drawing many layered 2D tiles, should one use the painter's algorithm, or Z-buffering?

texts:
Sorry if this question doesn't make sense, I'm still very new to WebGL / OpenGL.
Basically, I'm trying to draw a tilemap similar to the one in Stardew Valley. Here's a screenshot from that game: https://i.imgur.com/eEgWu6b.png
So, there are several tile layers that are drawn after one another to simulate depth. And I believe that when two objects are on the same layer, their draw order is based on their Y coordinate. For example, in this screenshot notice how if you are above the scarecrow, you'll be drawn behind it, and otherwise, in front of it.
I'm trying to figure out how to efficiently do this, and there seem to be two main ways:

Use z-buffering in OpenGL. That is, the map is drawn "3d" like in the following image: https://i.imgur.com/Bi8C8z2.jpg where quad has a z value. Then, assuming the camera only translates and never rotates and just always looks top-down, then it should still look like a proper top-down 2D game with depth.

Use the painter's algorithm. That is, first draw everything on the first layer, then everything on the second layer, then everything on the third layer, etc. Your main application code should sort all objects on the same layer based on their Y coordinate so that everything is drawn with the proper depth.

So, I actually really like the idea of the first one. Because I heard that texture swapping was really expensive in OpenGL, and some of my maps are very large so they use 3-5 sprite sheets to draw everything. So with this method, I believe I should be able to just first draw every sprite that uses my first spritesheet, swap to the next texture, draw all sprites that use that texture, etc. Since they have z values, everything can be drawn out-of-order and still be layered properly, right? Also, if I space out the z coordinate for my layers enough, I think I should be able to incorporate the sprite's y coordinate into their z coordinate. That is, as an example, for a 2x2 map, the first layer would have z values 10000, 10001, 10002, 10003, then the next layer will have z values 20000, 20001, 20002, 20003, etc. My only concern is that I heard depth testing and occluding and whatnot can be expensive. And also apparently something called z-fighting can occur?
I think the painter's algorithm is the more traditional way of doing this? My only concern with this one is that it seems like it could be expensive to use software sorting on all the sprites each frame. Also, I don't know how to handle this with texture swapping. If one layer happens to include monsters that are all from different sprite sheets, won't that include a lot of texture swapping when rendering them all out, if we have to do them in order from top left to bottom right?
I'm just not sure which of these I should do. Using the z index sounds like it could make everything a lot easier, but I'm not sure if the price of depth testing is cheaper than software sorting and texture swapping. Also, I'm concerned about possible z fighting. How do people normally do this?


texts: Unity 5 - Manually zooming/scaling in and out of an image with a text layer while still retaining text sharpness when zoomed?

texts:
I have a section in my scene where I have an image on a layer, as a child of this layer I have a load of text objects.
I need the ability to zoom in and out of the image (it's a technical drawing, so necessary to zoom in and out), so I have set up a simple Scale of the image itself (via Playmaker) and applied the zoom in to a button and the zoom out to another button.
When zoomed out, the image Scale is set to the default 1 and when zoomed in it goes to Scale 3.
It works perfectly.
I have also added a 'Scroll Rect' to the parent canvas, this enables me to click and scroll around the image when it is zoomed in - this also works perfectly.

However the main problem I have is that while the image looks fine zoomed in (the original image is a large size, so looks fine even when scaled up to Scale 3) - the text does not look good when scaled.
It is essentially just 'zooming' in on the text and therefore the bigger it gets, the worse it looks.

Text is set to 'Best Fit' - it has to be this way due to the fact I have dynamic translations on the text, so the text needs to stay within its specified area and shrink if necessary.

Ideally I would like the text size to scale in line with the image scale  - ie. if the text is size 10 when zoomed out, then it should be size 30 when zoomed x3 (as opposed to a scaled size 10) - is this possible?
The text must stay in the exact same position relative to the image, as text is placed at specific points on the drawing.
The text also needs to be able to be scrolled in exact line with the image (hence why I have it as a child of it, so it follows nicely).

Canvas is set to 'Screen Space - Overlay' with 'Scale with Screen Size' and 'height' at 1 (works perfectly across the game like this).

Screenshots attached...

Canvas

Text

Any help would be appreciated.

Thanks in advance

Unity 5.3.5
PC/Mac Standalone only


texts: How to destroy bullet on collision but only after it makes the collided object to bounce?

texts:
I made a scenario that shooting a bullets on crates make them both bounce nicely (both the bullet and crates are RigidBody2D & Colliders).
When I use OnCollisionEnter2D to destroy the bullet when it hits the crate then the bullet destroyed before it pass the force to the crate and thus the crate stay still and not move physically...

How to make the crate move because of the bullet hit and also make the bullet to destroyed?
There is more elegant way from just destroy the bullet a frame after the hit?


texts: How to handle player slowness while moving up and down in a Top Down game with angled ortho camera and angled sprite due to stretching of ground?

texts:
So i'm making a 2D top down game setup in 3D using tilted Sprites and angled orthographic camera.
My camera setup is as shown.
In my game I have the floor flat on the X/Z plane with walls/characters rotated +45 degrees about the X axis. The orthographic camera is pointing down also at 45 degrees about the x axis, parallel with my walls/characters.
As a result, I dont see any distortion for players/characters since they face the camera directly on, while the ground however sees a distortion of sqrt(2) shorter. This makes sense considering how an orthographic camera works. To fix this, I've made my Tilemap set up with X:1 Y:1 Z:Sqrt(2) so that each tile is stretched on the Z axis by Sqrt(2) to compensate for this distortion.
All looks well with only one problem now... foreshortening with regards to movement: Forward and backwards movements of objects/characters along the z axis are perceived to be slower than movements left/right on the x axis. This makes sense because while each tile is perceived to be a square in the camera view thanks to scaling Z on the tilemap by sqrt(2), the real world tile is, well, sqrt(2) times taller than its width, so obviously it takes longer to travel forwards / backwards.
How do i correct this?


texts: Unity, interior poly always missing in clothing

texts: I've modeled interior polygons but for some reason they do not show up in Unity. I've tried changing import settings for normals to both calculate and import... How do you have a tshirt's interior poly show up?


texts: How can I implement (almost) infinitely large maps in Unreal Engine 4?

texts:
I'm making a game where a helicopter travels around.

I'd like that the environment around be as realistic as possible. For instance, since the helicopter can travel at speeds up to 200 km/h, I want the player to see very far away, in a realistic fashion.

I'm talking about a map where let's say there is a "real" mountain 50km away and you could "walk" there, as well as the mountain looking like a mountain in game from the any distance (no matter the quality).

How could I manage my map in UE4 that would allow me to implement such a "real" world?


texts:
I'm working with the C# wrapper for SDL and am stumped at how to handle this issue. Right now I have a simple Actor that spawns N number of bullets from himself and fires them circularly outward. The problem is that the last bullet renders on top of everything and looks awful.

Below is a picture with the last bullet painted blue with the shooting actor in the center (also blue).

I was hoping to try and figure out how to get it above the 2nd to last bullet while the bottom half is under the first. The closest thing I could find on this subject was this CSS article. The problem though is that it is solving the issue with 3D and I am working in pure 2D. Here's a picture from the article of what I am trying to achieve.

I can't tell if this is something easy or really hard to achieve, but it appears I definitely don't know what to search for because even that one article I found, I just happened to stumble upon it by looking at Google Images.

So I guess my question is, what is the proper term for this and what are the tricks to trying to solve this in a 2D space?


texts: Problems implementing a screen space shadow ray tracing shader

texts:
Here I previously asked for the possibility of ray tracing shadows in screen space in a deferred shader. Several problems were pointed out. One of the most important problem is that only visible objects can cast shadows and objects between the camera and the shadow caster can interfere. Still I thought it'd be a fun experiment.

The idea is to calculate the view coordinates of pixels and cast a ray to the light. The ray is then traced pixel by pixel to the light and its depth is compared with the depth at the pixel. If a pixel is in front of the ray, a shadow is casted at the original pixel.

At first I thought that I could use the DDA algorithm in 2D to calculate the distance 't' (in p = o + t d, where o origin, d direction) to the next pixel and use it in the 3D ray equation to find the ray's z coordinate at that pixel's position.
For the 2D ray, I would use the projected and biased 3D ray direction and origin. The idea was that 't' would be the same in both 2D and 3D equations. Unfortunately, this is not the case since the projection matrix is 4D. Thus, some tweak needs to be done to make this work this way.

I would like to ask if someone knows of a way to do what I described above, i.e. from a 2D ray in texture coordinate space to get the 3D ray in screen space.

I did implement a simple version of the idea which you can see in the following video: video here

Shadows may seem a bit pixelated, but that's mostly because of the size of the step in 't' I chose.

And here is the shader:

#version 330 core

uniform sampler2D DepthMap;

uniform vec2 projAB;
uniform mat4 projectionMatrix;

const vec3 light_p = vec3(-30.0, 30.0, -10.0);

noperspective in vec2 pass_TexCoord;
smooth in vec3 viewRay;

layout(location = 0) out float out_AO;

vec3 CalcPosition(void){
    float depth = texture(DepthMap, pass_TexCoord).r;
    float linearDepth = projAB.y / (depth - projAB.x);
    vec3 ray = normalize(viewRay);
    ray = ray / ray.z;
    return linearDepth * ray;
}

void main(void){
    vec3 origin = CalcPosition();
    if(origin.z &lt -60) discard;
    vec2 pixOrigin = pass_TexCoord; //tex coords
    vec3 dir = normalize(light_p - origin);

    vec2 texel_size = vec2(1.0 / 600.0);

    float t = 0.1;
    ivec2 pixIndex = ivec2(pixOrigin / texel_size);
    out_AO = 1.0;
    while(true){
        vec3 ray = origin + t * dir;
        vec4 temp = projectionMatrix * vec4(ray, 1.0);
        vec2 texCoord = (temp.xy / temp.w) * 0.5 + 0.5;
        ivec2 newIndex = ivec2(texCoord / texel_size);
        if(newIndex != pixIndex){
            float depth = texture(DepthMap, texCoord).r;
            float linearDepth = projAB.y / (depth - projAB.x);
            if(linearDepth &gt ray.z + 0.1){
                out_AO = 0.2;
                break;
            }
            pixIndex = newIndex;
        }
        t += 0.5;
        if(texCoord.x &lt 0 || texCoord.x &gt 1.0 || texCoord.y &lt 0 || texCoord.y &gt 1.0) break;
    }
}

As you can see, here I just increment 't' by some arbitrary factor, calculate the 3D ray and project it to get the pixel coordinates, which is not really optimal. Hopefully, I would like to optimize the code as much as possible and compare it with shadow mapping and how it scales with the number of lights.

PS: Keep in mind that I reconstruct position from depth by interpolating rays through a full screen quad.


texts: What data structure do I use to store Archetypes in ECS?

texts:
I am implementing an ECS with "archetypes" similar to how they are defined in Unity:

A unique combination of component types is called an Archetype. For example, a 3D object might have a component for its world transform, one for its linear movement, one for rotation, and one for its visual representation. Each instance of one of these 3D objects corresponds to a single entity, but because they share the same set of components, they can be classified as a single archetype:

In this diagram, entities A and B share archetype M, while entity C has archetype N.
You can fluidly change the archetype of an entity by adding or removing components at runtime. For example, if you remove the Renderer component from entity B, then B moves to archetype N.

I know that an archetype is a group of entities with a specific set of components. However, I am confused as to how to actually store the different archetypes. The tutorials I've found online are all quite vague or opaque. I'm using JS.
My first instinct was to use a hash table using a bit array denoting the set of components as the key and the archetype data structure as the value. However, this doesn't seem to work well in JS because TypedArrays use reference equality.
Another approach I tried was using the bit array as an array of integers which index nested hash tables, but this approach is convoluted and introduces several unnecessary layers of indirection.
A third approach I tried was indexing a hash table using the string representation of the bit array but I'm not sure about the performance implications of this approach. (Strings are slow)
What is the ideal data structure (eg array, hash table, set, etc.) to store archetypes or references to archetypes?
To be clearer, I'm looking for a way to determine which archetype an entity belongs to upon addition/removal of components. I'm also looking for a data structure in which to store that component data such that it is friendly to iteration.
An example is Unity, however, other approaches that work are fine as well.
I'm not looking for specific implementations or code, but if they help explain then that's ok, but rather general ideas or guidelines.


texts: Unity: Can objects override shader/material properties?

texts:
I have a situation in unity where I have a custom shader with some properties where every object that uses this shader will want different values for those properties.

As far as I can tell, that means that I need to make a unique material for each object, which is a lot of materials and a tedious pain to set up.

Is there a way to make it so that I don't need to create and use a unique material for each object that uses this shader?

Also, if there is, are there downsides to doing so?


texts: ASSIMP transformation hierarchy and animations

texts:
I don't fully understand the transformation hierarchy used by ASSIMP.

According to the docs (http://assimp.sourceforge.net/lib_html/structai_node.html) an aiNode's transformation is relative to its parent. Does this mean I need to concatenate its parents (and their parents) matrices with the nodes matrix to get the LOCAL matrix for the model? Or is the nodes transform already per-multiplied with all the parents, meaning transforming the nodes vertices by the nodes transform directly puts the vertices in the models LOCAL space (and not just the 'NODE' space)?
Kinda same as 1) but does transforming the vertices with the aiNodes transform put it in the "bind pose"?
What is the point of even having a transform per aiNode? Why not just pretransform all the vertices? From what I understand the counter-argument has something to do with animations... but each animation step already has its own position/scale/rotation!

Any help is much appreciated, I don't fully grasp the transform hierarchy which makes it hard to formulate good questions.


texts:
At the top of script:

public Quaternion _lookRotation;

In Update:

void Update()
{
 transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation,
 Time.deltaTime * RotationSpeed);
}

I want to know when the transform rotation ended and is at _lookRotation
Maybe using some flag ?

This is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;

public class FadeScript : MonoBehaviour
{
    public UnityStandardAssets.ImageEffects.Blur blur;
    public UnityStandardAssets.ImageEffects.BlurOptimized blurOptimized;
    public FirstPersonController fpc;
    public float fadeDuration = 5;
    public float startAcceleration = 0.6f;
    public float endAcceleration = 0.6f;
    public float maxSpeed = 1.0f;
    public float rotationSpeed = 0.6f;

    private Material material;
    private float targetAlpha = 0;
    private float lerpParam;
    private float startAlpha = 1;
    private bool rotated = false;
    private Quaternion clampedTargetRotation;

    void Start()
    {
        material = GetComponent<Renderer>().material;
        SetMaterialAlpha(1);

        fpc.enabled = false;
    }

    void Update()
    {
        lerpParam += Time.deltaTime;

        float alpha = Mathf.Lerp(startAlpha, targetAlpha, lerpParam / fadeDuration);
        SetMaterialAlpha(alpha);

        if (alpha == 0)
        {
            fpc.enabled = true;

            if (rotated == false)
            {
                fpc.GetComponent<FirstPersonController>().enabled = false;
                rotationSpeed += Mathf.Clamp(rotationSpeed + startAcceleration * Time.deltaTime, 0, maxSpeed);
            }

            if (fpc.transform.localRotation == Quaternion.Euler(0,0,0))
            {
                fpc.GetComponent<FirstPersonController>().enabled = true;
                rotationSpeed = Mathf.Clamp(rotationSpeed - endAcceleration * Time.deltaTime, 0, maxSpeed);
                blur.enabled = false;
                blurOptimized.enabled = false;

                rotated = true;
            }

            clampedTargetRotation = Quaternion.RotateTowards(fpc.transform.localRotation, Quaternion.Euler(0, 0, 0), rotationSpeed * Time.deltaTime);
            fpc.transform.localRotation = clampedTargetRotation;
        }
    }

    public void FadeTo(float alpha, float duration)
    {
        startAlpha = material.color.a;
        targetAlpha = alpha;
        fadeDuration = duration;
        lerpParam = 0;
    }

    private void SetMaterialAlpha(float alpha)
    {
        Color color = material.color;
        color.a = alpha;
        material.color = color;
    }
}

What i want in the rotation part is to start the rotation slowly and then accelerate a bit and then in the end when it's getting "close enough"  to 0,0,0 so start accelerate down until complete stop. Complete stop not must be at 0,0,0 but close to it. Th way i'm doing it now is wrong i'm not using the t 0/1 solution and not courtine.

The rotation now in my script is almost working as i want. It start slowly and accelerate but in the end it stop at once without smoothly accelerate down.


texts: Where can I Find Free TOS or Privacy Policy Templates?

texts:
I've come to the point in development where I think I should take care of some of the "cover my butt" things.  In particular, I'm looking for free samples or templates for "terms of service/use" and "privacy policy" statements.

I actually do have my law degree and know something about IP, contracts, etc.  However, it's always better not to reinvent the wheel with these type of industry-wide boilerplate documents.

I couldn't find this answer anywhere on this or other StackExchange sites. Of any legit looking sites, I only found paid templates.

Does anyone know of a good website that offers these templates for free?  I can edit a general one if needed, but it would be best to have some already geared towards an online game.

UPDATE

Some promising resources I found out there:

TRUSTe Privacy policy generator:

http://www.truste.com/technology/#labs

I think you are supposed to pay to use the TRUSTe seal or something, but that doesn't stop you from using this as a starting point.  I guess it might help to read their TOS first (LoL).

Legal River TOS / Privacy Policy Generator:

http://terms-of-service-generator.legalriver.com/

http://privacy-policy-generator.legalriver.com/

For now I'll start with these and rework them for my needs.  Would still love to hear if anyone knows of a better one geared towards online games.


texts: Make my Random.range not repeat same position

texts:
So I want to make my array Gameobject transform to transform array points position but it will be randomized position when start only without repeating a position
so make some script like this:

    public GameObject[] collectibleAyatGO;
    public Transform[] transformPoint;
    public List<int> TakeList = new List<int>();
    private int randomNumber;

public void RandomTransformPosition()
    {
        TakeList = new List<int>(new int[transformPoint.Length]);

        for (int i = 0; i < transformPoint.Length; i++)
        {
            randomNumber = Random.Range(0, transformPoint.Length);
            while (TakeList.Contains(randomNumber))
            {
                randomNumber = Random.Range(0, transformPoint.Length);
            }

            TakeList[i] = randomNumber;
            collectibleAyatGO[i].transform.position = transformPoint[TakeList[i] - 1].position;
        }
    }

it seem not working or make my unity notresponding maybe due to while loop, Am I doing right here ?


texts: Is non-indexed, non-instanced rendering useful anymore?

texts:
I'm adding batched rendering to my game engine and I'm wondering: Should I support non-indexed, non-instanced batches or just indexed and/or instanced?

It's my understanding that the concept of indexed rendering was invented after pure "vertex only" drawing. That said, is supporting vertex-only rendering useful anymore? Is there a modern use-case for it?


texts: Make object follow another object while keeping the same distance from it

texts:
I want an object to follow another object just like the way it follows it when it's parented to it, but smoothly and only in the x and z axis.

Here's my code so far:

distanceX = player.position.x - transform.position.x;
distanceZ = player.position.z - transform.position.z;
transform.position = Vector3.Lerp(new Vector3(transform.position.x, transform.position.y, transform.position.z), new Vector3(transform.position.x + distanceX, transform.position.y, transform.position.z + distanceZ), Time.deltaTime);

Now the problem is that it goes way too close to the player and ignores the current distance.

If you got any questions please don't hesitate to ask.

Thank you for your time!

Edit:

I'm not looking to make the object go to the target's position, just to follow it and keep the distance, just like it does when it's parented to that object, but smoother movements.

Edit 2:

Looks like I have made a mistake when I said that I wanted to keep the same distance between the two objects. What I actually meant was that I want the offset to be the same. I apologize to anyone who I confused or wasted their time! P.S. I'm still looking forward to finding a fix for my issue.


texts: Playing Sounds and removing instances once they have played -- Android

texts:
I am playing sounds in my application I have the following code

sounds = new HashMap<String, MediaPlayer>();

Then when guys are created on screen they are given a sound.

sounds.put("sounds"+Integer.toString(ncount), MediaPlayer.create(this, R.raw.hit));

I want to remove the MediaPlayer from the hashmap like I do the enemies when they die

sounds.get("sounds"+Integer.toString(ncount)).setOnCompletionListener( new MediaPlayer.OnCompletionListener() {

    public void onCompletion(MediaPlayer mp) {

        sounds.remove("sounds"+Integer.toString(ncount));
    }

});

This errors out... how would I reference the sounds hashmap to remove the associated MediaPlayer when sound is complete?

Thanks!


texts: Difference between texture.Load and texture.Sample(PointSampler,..) in HLSL/Dx

texts: Conceptually, I understand the difference between load and sample but I want to know if essentially point sampling and load do the same thing when it comes to selecting a texture value (ignoring an out of bound situation).


texts:
I am trying to simulate throw of javelin using projectile motion. The basic physics of projectile motion of a point was used to position the javelin. For the rotation part, I just assumed that the javelin must be tanget to the projectile path as shown below.

But, if the launch angle was extremely huge, we can see that the projectile range will be extremely small. Now, lets assume, the height of projectile was big, the projectile motion will look as shown below.

The animation looks unnatural because the stick rotates really fast because the curve is extremely steep.

So, I am sure the javelin is not always tangent to the path(of Centre of Gravity of the javelin).

So I thought maybe I need to calculate torque on the javelin. I've also tried this approach but the javelin is extremely shaky. My steps were:

$$torque = r \times \vec{F}$$
$$\vec{F} = mg + ma$$
$$ a = \frac{dv}{dt} $$ v is the
velocity of the centre of javelin at any point of time of projectile motion. We integrate the equation to find the change in torque.
$$d\vec{Torque} = r \times d\vec{force}$$
$$d\vec{Torque} = Id\vec{\omega}$$
Now, we obtain the change in angular velocity, which is then integrated to obtain the orientation of javelin.

I must have messed up somewhere because the integration is not working. Its extremely shaky and it works in some cases where launch angle is small, but fails when launch angle is huge.

So can anybody give me some pointers?


texts: Combining two independent rotations relative to the world frame

texts:
I am implementing a mouse rotation which works by accumulating the X-Y delta between frames to yaw and pitch rotation angles. The problem is that I wish rotations to be independent of each other. But as you can see from the picture:

I wish it behaved like this instead:

In the second picture, instead of dragging, I am releasing the mouse button and performing a second drag movement. So the local Y-axis is not rotated as in the first picture.

This is the code I am using:

Vector2 delta = current - lastPointerPosition;
totalYaw += delta.X;
totalPitch += delta.Y;
var r = Quaternion.RotationAxis(Vector3.UnitY, totalYaw / 100f);
var s = Quaternion.RotationAxis(Vector3.UnitX, totalPitch / 100f);
var qOrientation = s*r*qStart;

Please ignore for the moment the crude division by 100, I wanted to get the rotation right before optimising that part. That code causes the behaviour in the first picture.

I tried to rotate the UnitX axis used in the second quaternion by doing var q = r*new Quaternion(Vector3.UnitX, 0)*Quaternion.Invert(r); and then using q.Axis in place of UnitX in s.

I have looked all over the web but so far none of the solutions seemed to work for me. What am I doing wrong?

EDIT every time the mouse moves, I am updating lastPointerPosition with the current one (after updating the rotation matrix); when the mouse pointer is released, totalYaw/totalPitch are restored to 0.


texts: odd line artefacts on my screen? (C++ DirectX11)

texts:
I'm getting some odd lines on my screen in my program:

They seem to be in a static location on the screen and occur at regular intervals. They are also on the horizontal too but are harder to see in the image.

So far I have tried:

turning anti-aliasing off,
turning multi-sampling off,
rendering my images at full size (no scaling) and
using texture sizes of a power of 2.

And none of that seems to work. Right now I am working on adding fonts in, but this issue means that lines of the fonts can disappear (the bottom of an 'o' the middle of a 'B' (so it looks like a 'D'), etc).


texts:
How can i set a fixed 720p resolution on any devices using unity3d android?

  unity3d version: 2018.4.5f1


texts: How could I do simple per-fragment lighting on BSP geometries?

texts:
I am programming a graphics engine for an old game. The game uses a BSP geometry which I have rendering perfectly. For it's lights however, it simply has light instances with the standard x, y, z, rgba, brightness, type. Now I know that OpenGL has an 8 light limit. How should I go about handling multiple lights.

I am learning per fragment light just to have the concepts under my belt. I know per pixel lighting is the standard and I will eventually move there, just want to learn how to get this concept put in play as well.

I assume I will just calculate which lights are the closest and render those 8. Does anyone have any other ideas?


texts: How do I implement features in an entity system?

texts:
After asking two questions about entity systems (1, 2), and reading some articles on them, I think that I understand them much better than before. I still have some uncertainties, mainly about building a particle emitter, an input system, and a camera. I obviously still have some problems understanding entity systems, and they might apply to a whole other range of objects, but I chose these three because they are very different concepts, should cover a pretty broad ground, and help me understand entity systems and how to handle problems like these, myself, as they come along.

I am building an engine in JavaScript, and I've implemented most of the core features, which include: input handling, flexible animation system, particle emitter, math classes and functions, scene handling, a camera and a render, and a whole bunch of other things that engines usually support. I read Byte56's answer, that got me interested into making the engine into an entity system. It would still remain a HTML5 game engine, with the basic scene philosophy, but it should support dynamic creation of entities from components.

The problem I have, now, is fitting my old engine concept into this new programming paradigm. These are some of the definitions from the previous questions, updated:

An Entity is an identifier. It doesn't have any data, it's not an object, it's a simple id that represents an index in the scenes list of all entities (which I actually plan to implement as a component matrix).
A Component is a data holder, but with methods that can operate on that data. The best example is a Vector2D, or a "Position" component. It has data: x and y, but also some methods that make operating on the data a bit easier: add(), normalize(), and so on.
A System is something that can operate on a set of entities that meet the certain requirements; usually the entities need to have a specified set of components, to be operated upon. The system is the "logic" part, the "algorithm" part, all the functionality supplied by components is purely for easier data management.

Camera

The camera has a Vector2D position property, a rotation property and some methods for centering it around a point. Each frame, it is fed to a renderer, along with a scene, and all the objects are translated according to its position. The scene is then rendered.

How could I represent this kind of an object in an entity system? Would the camera be an entity, a component, or combination (as per my answer)?

Particle Emitter

The problem I have with my particle emitter is, again, what should be what. I'm pretty sure that particles themselves shouldn't be entities, as I want to support over 10,000 of them, and I believe that creating that much entities would be a heavy blow on my performance.

How could I represent this kind of an object in an entity system?

Input Manager

The last one I want to talk about is how input should be handled. In my current version of the engine, there is a class called Input. It is a handler that subscribes to the browsers events, such as key presses and mouse position changes, and also maintains an internal state. Then, the player class has a react() method, which accepts an input object as an argument. The advantage of this is that the input object could be serialized into .JSON, and then shared over the network, allowing for smooth multiplayer simulations.

How does this translate into an entity system?


texts: How do I ensure my skybox is always in the background, with OpenGL?

texts:
I created a skybox in OpenGL (through LWJGL), but the only way I found to render it behind all objects was to make it very big. This leads to ugly edges between the 6 skybox planes.

Optimally, I would draw a small skybox and disable DepthTesting on all other objects, but since I want those to display in the right depth order, that isn't possible.

How can I do this?


texts: Unity, how do I pause the Audio in the Level?

texts:
I wanna pause the Audio if I press the Pause Button also, I need help..

Pause Script:

#pragma strict

var pausemenu: GameObject;

public function pause()
{
    pausemenu.SetActive(true);
    Time.timeScale = 0;

}

public function Resume ()
{
    pausemenu.SetActive(false);
    Time.timeScale = 1;
}

public function Restart ()
{
    Application.LoadLevel("IntroScene");
    Time.timeScale = 1;
}

public function MainMenu ()
{
    Application.LoadLevel("string");
}

public function Quit ()
{
    Application.Quit();
}


texts:
once again i need your help! with help from here i managed to make a function that sends a formated json text to a subscription service.the format is this
{
    "profiles":
    [
        {
            "email":"example@example.com"
        }
    ]
}

that works fine and great from my pc but once i upload the game it gets blocked by cors. Now i have cors enabled so i contacted klaviyo which handles the data and they told me their api does not accept data from the front end and i could use ajax to make it happer, an example of which is this:
var settings
=
{

"async"
: true,

"crossDomain"
: true,

"url"
:
"https://manage.kmail-lists.com/ajax/subscriptions/subscribe"
,

"method"
:
"POST"
,

"headers"
: {

"content-type"
:
"application/x-www-form-urlencoded"
,

"cache-control"
:
"no-cache"

},

"data"
: {

"g"
:
"LIST_ID"
,

"email"
: "email@address.com",

/
/
pass
in
additional fields (optional)

"$fields"
:
"$source, $first_name, $last_name"
,

"$source"
:
"Account Creation"
,

"$first_name"
: firstname,

"$last_name"
: lastname

}

};

$.ajax(settings).done(function(response) {

console.log(response);

})

now my code which is working from my pc is this :
public class testing : MonoBehaviour
{
    public InputField field;
    private string URL = "https://a.klaviyo.com/api/v2/list/YeXzKp/members?api_key=pk_ec448e1bdab7504c143466ca5eeabc5e95&profiles=[]";

    public void SaveData()
    {
        string data = JsonUtility.ToJson(
      new EmailApiData()
      {
          profiles = new EmailApiProfileData[]
          {
             new EmailApiProfileData() { email = field.text }
          }});
        StartCoroutine(SaveIntoJson(URL , data));
    }
    IEnumerator SaveIntoJson(string url, string data)
    {
        var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("Access-Control-Allow-Origin","*");
        request.SetRequestHeader("Access-Control-Allow-Credentials", "true");
        var jsonBytes = Encoding.UTF8.GetBytes(data);
        request.uploadHandler = new UploadHandlerRaw(jsonBytes);
        request.downloadHandler = new DownloadHandlerBuffer();
        yield return request.SendWebRequest();
        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log(request.error);
            Debug.Log(request.downloadHandler.text);
        }
        else
        {
            Debug.Log("Form upload complete!");
        }
        Debug.Log(data);
    }
}
[Serializable]
public class EmailApiProfileData
{
    public string email;
}
[Serializable]
public class EmailApiData
{
    public EmailApiProfileData[] profiles;
}

how can i put those two together?? i know im way out of my waters here but i want to learn it!Thank you once more!


texts: Instantiate creates a clone in wrong position

texts:
I have this prefab with this transform:

And then using this code to create a clone (the prefab is assigned to a public property of a script, which I assign using the editor, which is the e.Weapon):

Instantiate(e.Weapon, new Vector3(0f, 0f, 0f), Quaternion.identity, rightHand.transform);

I am parenting it to my character's right hand. But whenever the clone gets created, it has different position than the one I have in my code. It appears like this:

Any idea why this is happening?


texts: How can I encourage population balance between two factions?

texts:
I'm making a game in which players must choose between two factions after reaching a certain level.

PvP and PvE are not influenced by this choice as it's mostly for role play and the sense of belonging to a community (and perhaps seasonal events).

The two factions can communicate. Preferably, guild members must be in the same faction and it should be impossible or not easy to change factions.

I fear that if a faction starts to have the majority of players, new players will want to join it to play with their friends or have more guild choices.

How could I mitigate or prevent that? Are there alternatives?


texts: How camera works in 2d platformer in level transitions

texts:
I want to know how Camera works in game of Celeste.

Currently what I have is, camera follows the player using interpolation:
cameraPosition = cameraPosition + (playerPosition - cameraPosition) * 0.1;

and I clamp the camera position to the edge of the world size:
cameraPosition = mu.clamp(cameraPosition - [160, 90], 0, worldSize);

I subtract [160, 90] to center the camera.
This works OK. But is that all there is to it.
Specifically, how does the camera work between room transitions.
I might drop room transitions, and just do a black screen transition between levels, but I've heard there is camera triggers that offset the camera relative to player position, and what other tricks are used?


texts: What to do when a function to return something is null?

texts:
I have a generic Items class that keeps track of all items, and when Items are created they are added to this list. The problem is that I have a function that returns the item by its ID, but what do I return in items[id] doesn't exist? It won't let me return null...

Should I just use a for loop that iterates through every item and checks if items[i].id equals the input ID?

Here's my code

public static class Items
{
    public static List<Item> items = new List<Item>();

    public static Item getItemById(Items instance, int id)
    {
        if (items[id] != null)
        {
            return items[id];
        }
        else
        {
            return null;
        }
    }
}


texts:
I'm considering building a multiplayer game having a central server handling the game and keep clients updated. I was checking various examples of ".io" games styles of implementation and seems pretty straight forward that the logic is on server and clients are mostly dummy.

Now the question that I have is .. how dummy should be the client? Where do you draw the line?

To give more context, I was thinking of building a platformer with 2 players on it, a few obstacles on the way etc.

What is clear for me is:

any input the characters receive needs to be sent to the server and updated the other client.
any map event logic will stay on the server and update clients when happening

What is not clear for me is:

where do you place basic physics? like keeping the character on the map
how about a simple movement like Jumping? should it be like a state sent to the server?
what about the whole map? should the server know the entire map?
what if I want to destroy one tile of the map?

I would appreciate your point of view or if you know some examples / links where I can find more info about these things.

Cheers!


texts: Unity2D 5 - Flickering sprites on Android

texts:
So the game had been working fine for a few days on Android phone without any issues. Today, after adding some scripts and tweaking the game a little bit (tweaks which have nothing to do with the sprites and the issue itself), the game assets/sprites started on flicker. On PC, they looked fine, but once ported to Android as a developer build, they started to flicker constantly, even after restart.

I decided to go in Player Settings and played with some check marks but nothing seemed to help.

Following are my current Player Settings :

Any help would be appreciated.

Oh also, I have GUI in my game, can it be the problem?


texts: In a browser, is it best to use one huge spritesheet or many (10000) different PNG's?

texts:
I'm creating a game in jQuery, where I use about 10000 32x32 tiles. Until now, I have been using them all separately (no sprite sheet). An average map uses about 2000 tiles (sometimes re-used PNG's but all separate divs) and the performance ranges from stable (Chrome) to a bit laggy (Firefox). Each of these divs are positioned absolutely using CSS. They do not need to be updated every tick, just when a new map is loaded.

Would it be better for performance to use spritesheet methods for the divs using CSS background-positioning, like gameQuery does?

Thank you in advance!


texts:
I have read a lot about movement in multiplayer games, but not so much on preventing cheating.

Let's say a client sends moves packets whenever the player press a movement button, then the server checks if that move is valid (that is, if the player is not colliding with anything).

At the same time, there must be some speed check, like dropping packets if the client is sending too many in a short period of time. But the server has no guarantees whether the packets received were sent at the same time or just received at the same time. Client could include a timestamp, but there are 0 guarantees it was crafted by a malicious client.

In short, how can i validate movement speed?


texts: How can I randomly generate objects inside of a Complex Area?

texts: In my game, I want to generate randomize enemies inside of this green area that I made with a custom editor tool.


texts: Can a generic class inherit from MonoBehaviour?

texts:
Expanding upon a previous tutorial, I am adapting a follow script to support multiple variations of a Bezier spline. Each spline variation uses a custom interface called IBezierInterface, and the follow script accesses the method GetPointOnCurve() to determine the correct position. In theory, this all seems very simple. However, I appear to be running in to some trouble. While I intend to pursue the general issues a bit more, myself, I realise that I may be shooting myself in the foot with the generic implementation.

While I can find a lot of good examples demonstrating the correct use of generic types, I can not find anything that gives an example of a generic class that inherits from another class. For example, Microsoft documentation includes examples of inheritance as a restriction on the actual type, and an example of inheriting from a generic class; but there are no examples of a generic class that inherits from a standard class. Unity documentation has even less examples, but none pertaining to my query. I am not getting errors; but that is no guarantee against error. I can not conceive a good prototype model to test my theory, either, given the fact that I am fairly new to the concept of generic types.

Given that I am specifically needing my class to be a MonoBehaviour; can I make a custom generic class that inherits from MonoBehaviour, such as in my example?

public class SplineWalker<T> : MonoBehaviour where T : IBezierInterface
{
    // ...
}


texts: Conversion of a number from Single precision floating point representation to a Half precision floating point

texts:
Hope it is relevant here.

I have a code where I have to work on Half precision floating point representation
numbers. To achieve that I have created my own C++ class fp16 with all operators(arithmetic logical, relational) related to this type overloaded with my custom functions, while using a Single precision floating point number with a Half precision floating point number.

Half precision floating point = 1 Sign bit , 5 exponent bits , 10 significand bits = 16 bit

Single precision floating point = 1 Sign bit, 8 exponent bits, 23 significand bits = 32 bits

So what I do to convert from a Single precision floating point number to a Half precision floating point number:-

For significand bits - I use truncation i.e. loose 13 bits from the 32 bits to get 10 bits significand for half precision float.

What should I do to handle the exponent bits. How do I go from 8 exponent bits to 5 exponent bits?

Any good reading material would help.


texts: How to create guides to off-screen objects?

texts:
I've played Metroid Blast on Wii U, and would like to build one of its features in a three.js game.

The feature is: if an opponent is out of view, a guide is displayed showing the direction of the opponent.

An example of it is here:

(Image source)

Notice the small circles with arrows in the left side.

How could I have a similar feature in my game?


texts: How to position a sprite in a 2D animation skeleton?

texts:
Given two joints that define a bone, I would like to know how to decide where, between those two joints, I should draw the sprite. This should be a fairly simple thing to solve, but there is one thing that I am not sure about.

After I've determined the rotation of the sprite (which is the absolute angle the joints form with the x-axis), I also need to determine the origin point from where I need to start drawing the transformed image.

So how should I position the sprite between the two joints? Should I make the center of the image be the midpoint between the two joints, or should I make one the of the joints be the origin? Do these things matter that much (could the wrong positioning make the sprite move oddly during the animation)?


texts:
I want to create a pause menu where everything in the background gets darker. I've looked up a bunch of possible solutions (even the second page on google) but it doesn't seem to work. I do already have something in my code that makes a single texture darker when hovered over, by calling: GL11.glColor3f(alpha, alpha, alpha); before drawing vertices. What I want to achieve is everything getting darker, so when hovering over a texture it should be even darker than before so it is still darker than the rest in the background when that has been made darker because of a pause menu that pops up.

Another thing I noticed is that glColorMask(true, false, false, true); does not get overridden and blends colours everywhere, so I was wondering if there is a version of this method that puts a transparent black overlay so everything becomes darker. I have enabled blending.

-Edit-

One solution I came up with (not just now) is multiplying alpha in every glColor3f function with a variable that is smaller than 1 so everthing gets relatively smaller, but I worry about this being uneffective and badly mantainable


texts: Using DirectX(SharpDX) what is the best way to create a single large image from smaller images?

texts: I'm looking for the best way to combine several images (1060 x 1060)each into on large image. I'm looking to create one texture to apply to a single Quad. I was thinking multiple quads and then just use a Shader in 3D. However, I cannot seem to figure out how to get this to work correctly. I have 16 quads in a 4 x 4 arrangement. However, I can only see 4 of 16. I'm trying to get the 16 to fit like a single quad would without a camera.


texts:
I have two spheres that are bounded by spheres for collision detection. I do not want them to intersect. My intersection works. But it gets stuck. Once the function returns true, I cannot get it out. I tried

collideBool = ObjectOne.Intersect(ObjectTwo);

if(collide == true)
{
    leftright = leftright;
    updown = updown;
}
else
{
if(GetAsyncKeyState(VK_RIGHT))
leftright -= dt;
if(GetAsyncKeyState(VK_LEFT))
leftright += dt;
if(GetAsyncKeyState(VK_DOWN))
updown += dt;
if(GetAsyncKeyState(VK_UP))
updown -= dt;
}

collide = false;

My sphere gets stuck. What is a way around this?


texts: Can you write the current frame number to a text file?

texts:
I am running an experiment in Unity 5 to see the effect increasing the particles of a particle effect has on FPS over time. (this is background work for a much larger piece of work). Currently I write the FPS count from the profiler to a log file and this shows the framenumber and its FPS at that frame. To a seperate log file I write the number of particles on screen and the time.

I have no way of linking these two files to draw up results.

So my question is, how do I write the current framenumber to a file? Can I do this?

UPDATE

I would like the same framenumber that the unity Profiler gives me in its log.


texts: How to determine if character has fallen into the gap in an infinite runner/jumper?

texts: I'm building a 2D infinite runner. In the game, character jumps from pillar to pillar and pillars are randomly generated. I have this working. But how to determine if the character failed to jump on to a pillar and has fallen into the gap between pillars? A pillar is ordinary rectangular in shape.


texts: How to know when Android OpenGL Context has been preserved?

texts:
I am implementing a pause menu for my game in Android.

If the activity pauses and then resumes, it loses the OpenGL context.
However, if you use setPreserveEGLContextOnPause(true) it MAY preserve the context if the device supports it.

How can I check if the context has been preserved or not?


texts:
Recently been trying to implement volumetric lighting. The alphaness texture comes out perfectly on Renderdoc, however a strange glitch occurs whenever I either try to directly render the texture through a quad to the screen, or through multiplying the alphaness component with my regular texture. A strange static pattern (as shown in the image below) appears on the texture. The texture also periodically turns completely black, and in some frames the image comes out perfectly.

The volumetric lighting texture is rendered to a framebuffer with the settings below:

' Configure God Rays Buffer
' -------------------------
godRaysFramebuffer = GL.GenFramebuffer()

' Create color buffers
GL.BindFramebuffer(FramebufferTarget.Framebuffer, godRaysFramebuffer)
currentFrameTex = GL.GenTexture()
GL.ActiveTexture(TextureUnit.Texture0)
GL.BindTexture(TextureTarget.Texture2D, currentFrameTex)
GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, All.MirroredRepeat)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, All.MirroredRepeat)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, All.Nearest)
GL.TexParameterI(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, All.Nearest)
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.R16f, resolutionWidth,
              resolutionHeight, 0, PixelFormat.Red, PixelType.Float, IntPtr.Zero)
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
                        TextureTarget.Texture2D, currentFrameTex, 0)

Dim attachments() As Integer = {FramebufferAttachment.ColorAttachment0}
GL.DrawBuffers(attachments.Length, attachments)

The alphaness texture, from Renderdoc, is shown below:

The fragment shader which samples from the god rays texture (my HDR shader) is shown below. When I comment out the * texture(godRaysTex, TexCoords).r it renders perfectly, however without the god rays.

#version 440 core

out vec4 out_color;

in vec2 TexCoords;
in vec3 vPos;

uniform sampler2D hdrBuffer;
uniform sampler2D godRaysTex;

uniform float exposure;

void main() {
    const float gamma = 1.8;
    vec3 hdrColor = texture(hdrBuffer, TexCoords).rgb * texture(godRaysTex, TexCoords).r;

    // Exposure tone mapping
    vec3 mapped = vec3(1.0) - exp(-hdrColor * exposure);
    // Gamma correction
    mapped = pow(mapped, vec3(1.0 / gamma));

    out_color = vec4(mapped, 1.0);
}

Here is my volumetric lighting shader:

#version 440 core

uniform vec2 lightPositionOnScreen;
uniform sampler2D occlusionTex;

const int NUM_SAMPLES = 100;

const float exposure = 0.45;
const float decay = 0.98;
const float density = 0.9;
const float weight = 0.07;

in vec2 TexCoords;
in vec3 vPos;

layout (location = 0) out vec4 FragColor;

void main() {
    vec2 textureCoords = TexCoords;
    vec2 deltaTexCoords = vec2(textureCoords.xy - lightPositionOnScreen.xy);
    deltaTexCoords *= 1.0 /  float(NUM_SAMPLES) * density;
    float illuminationDecay = 1.0;

    // Evaluate summation from Equation 3 ( see https://developer.nvidia.com/gpugems/GPUGems3/gpugems3_ch13.html) NUM_SAMPLES iterations.
    for(int i = 0; i < NUM_SAMPLES; ++i) {
            textureCoords.x = clamp(textureCoords.x, 0.0, 1.0);
            textureCoords.y = clamp(textureCoords.y, 0.0, 1.0);

            textureCoords -= deltaTexCoords;
            vec4 occlusionSample = texture(occlusionTex, textureCoords);
            float alpha = occlusionSample.r;
            occlusionSample.r = 0.0;
            occlusionSample.a = alpha;

            occlusionSample *= illuminationDecay * weight;

            FragColor += occlusionSample;

            illuminationDecay *= decay;
    }

    FragColor *= exposure;
    float alpha = clamp(1.0 - FragColor.a, 0.0, 1.0);
    FragColor.a = 0.0;
    FragColor.r = alpha;
}


texts: Can I set the origin of the texture to its center in OpenGL?

texts:
I want "texture2D(texture, vec2(0,0))" to fetch the pixel at the center of the texture and "texture2D(texture, vec2(-1,-1))" to fetch a pixel from the corner of the texture. I don't want to calculate from (-1,+1) to (0,+1) like s*.5+.5
I don't want that.

Is there some command that I can use to configure the hardware that way?


texts: Tiling perlin noise seamlessly, but without repeating to generate an infinite 3D world

texts:
I have been working on a 3D game in java using LWJGL for a while now. I am trying to make procedurally generated infinite 3D terrain that is generated around the player.

So far I have:

3D terrain chunks that are loaded and unloaded when the player moves. These chunks are made up of triangles not quads, and are 128x128 vertices.
A Perlin noise class that can successfully generate Perlin noise. (I think it is actually something called value noise, but it works)
A world class that handles loading and unloading of chunks, and applying the height maps to the chunks.

All of this works as it is coded to do, but not how I want it to. I don't know how to tile the noise seamlessly.

How would I make the noise tile, and furthermore, how would I generate large structures such as mountains that occupy probably up to hundreds of chunks.

Here is what is currently happening with the chunks and noise not tiling:

Here is my Perlin noise code:

private float[][] perlinNoise(int width, int height, int octave, float[][] whiteNoise)
{
    float[][] result = new float[width][height];

    int samplePeriod = 1 << octave;
    float sampleFrequency = 1.0f / samplePeriod;

    for (int i = 0; i < width; i++)
    {
        int x1 = (i / samplePeriod) * samplePeriod;
        int x2 = (x1 + samplePeriod) % width;
        float xBlend = (i - x1) * sampleFrequency;

        for (int j = 0; j < height; j++)
        {
            int y1 = (j / samplePeriod) * samplePeriod;
            int y2 = (y1 + samplePeriod) % height;
            float yBlend = (j - y1) * sampleFrequency;

            float top = (float) MathHelper.interpolateLinear(whiteNoise[x1][y1], whiteNoise[x2][y1], xBlend);

            float bottom = (float) MathHelper.interpolateLinear(whiteNoise[x1][y2], whiteNoise[x2][y2], xBlend);

            result[i][j] = (float) MathHelper.interpolateLinear(top, bottom, yBlend);
        }
    }
    return result;
}

public float[][] generatePerlinNoise(int width, int height, Random random, int octaveCount)
{
    float[][] whiteNoise = new float[width][height];
    float[][][] totalNoise = new float[octaveCount][][];
    float[][] perlinNoise = new float[width][height];
    float amplitude = 1.0f;
    float totalAmplitude = 0.0f;
    float persistance = 0.5f;

    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            whiteNoise[i][j] = random.nextFloat() % 1;
        }
    }
    for (int i = 0; i < octaveCount; i++)
    {
        totalNoise[i] = perlinNoise(width, height, i, whiteNoise);
    }
    for (int o = octaveCount - 1; o >= 0; o--)
    {
        amplitude *= persistance;
        totalAmplitude += amplitude;

        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                perlinNoise[i][j] += totalNoise[o][i][j] * amplitude;
            }
        }
    }
    for (int i = 0; i < width; i++)
    {
        for (int j = 0; j < height; j++)
        {
            perlinNoise[i][j] /= totalAmplitude;
        }
    }
    return perlinNoise;
}

I think it would also be worth mentioning that I have asked about this on StackOverflow as well.


texts: How should I prepare for pitching a game to potential sponsors?

texts:
We have developed a mobile game, and are preparing ourselves for demo day. We will be presenting our game to potential sponsors, and we are having trouble deciding how to make a quality presentation.

Specifically, what are the unique challenges and opportunities in pitching a game, in contrast with product demos generally?

Being developers, we are worried we might wrongly focus on elements important to developers, but not to investors. How can we go about identifying them?

For demoing game play, in what situation should we consider switching to a separate app, embedding the game in a slide show, showing canned game footage, or something else?


texts: Detect Collisions While Dragging 3D Game Object

texts:
Hello i am making a game in which i have to drag a sphere on x axis and z axis on a plane with my mouse and i have created walls from cubes so that my sphere not go anywhere else in the game but while dragging my sphere is not detecting collisions with the wall i also added rigidbody but nothing is working ths is my code thanks

using UnityEngine;
using System.Collections;

public class Ball : MonoBehaviour
{
    Rigidbody r;
    private void Start()
    {

        r = GetComponent<Rigidbody>();

    }

    void OnMouseDrag()
    {

        float distance_to_screen =
Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
        Vector3 pos_move = Camera.main.ScreenToWorldPoint(new
Vector3(Input.mousePosition.x, Input.mousePosition.y,  distance_to_screen));
        transform.position = new Vector3(pos_move.x, transform.position.y,
pos_move.z);

    }

  }


texts: Ive seen a lot of people make sprite sheets magenta instead of transparent and then they make the magenta transparent using code. What is best (Performance) to use transparent images or use a color (example : magenta) instead of transparency?


texts: How to store 3d transformation in a game?

texts:
I am curious what is the best strategy to save 3d transformation of a model.

Here are the few choices I think about:

4x4 matrix
4x3 matrix(skip the bottom row of a 4*4 matrix)
Dual quaternions with a 3d scaling vector
3x3 matrix with a 3d translation vector


texts: After setting fixedDeltaTime to timeScale * 0.02f physics is behaving weirdly

texts: I'm just facing a problem that when I slow time and set fixedDeltaTime to timeScale * 0.02f the physics starts behaving really weirdly. I have a chain of hinge joints and it makes kinda wave when I slow the time down. I tried slowing the time without changing fixedDeltaTime and it worked normally (it was only laggy, which is normal), but when I change it, it makes the physics weird. Here is video showing my problem: https://youtu.be/wEakZ03bWso Notice the wave on the chain in the first test.


texts: SDL_RenderDrawLines isn't drawing complete geometry

texts:
So I am trying to draw hexagons with [SDL_RenderDrawLines][]. It looks to be working fairly well, however, it fails to draw some of the lines.

So each of the hexagons in the screenshot is a hex object. They each have a center x/y , and an array of SDL_Points for the six corners of the hex.

Here is the hex object draw call:

SDL_RenderDrawLines(
    TheGame::Instance()->getRenderer(),
    corners,
    HEX_NUMBER_OF_CORNERS);

There is some reoccurring condition that causes a vertical line to not be rendered, and I can't seem to figure out why.

The two obvious things that stand out don't explain why there is no line:

The draw order of the objects shouldn't matter since all of the borders for each hex are being drawn.
The horizontal distance between adjacent hexes' centers can be +-1 because of rounding would lead to a double thick border and not a missing border.

If anyone has any insight, I welcome the input.

EDIT:

I have been over suggestions you have mentioned prior to this question, increasing the array of points to 7 is correct, I tested it on a triangle before I tried with hexagons. When you don't close of the shape, you typically get drawn lines that shoot off the edge of the screen.

The part on three lines is also something else I discovered while messing around. I included some of my code to show the two ways that I preformed the very thing you mentioned:

// render the hexagon to on screen
void Hex::draw()
{/*
 draw order of points
 rotate ccw 90 degrees for actual postion
  [2] ____ [3]
     /    \
[1] /      \
    \      / [4]
     \____/
  [0]    [5]
 */

    // draw the hex with a fill color
    // 0XAABBGGRR is the bit order for the color param
    filledPolygonColor(
        TheGame::Instance()->getRenderer(),
        vx, vy,
        HEX_NUMBER_OF_CORNERS, r_order(CLEAR));

    // set outline color to black
    SDL_SetRenderDrawColor(
        TheGame::Instance()->getRenderer(),
        0, 0, 0, 255);

    // draw the hex outline

    //SDL_RenderDrawLines(
    //  TheGame::Instance()->getRenderer(),
    //  corners + 2,
    //  HEX_NUMBER_OF_CORNERS - 2);

    // or
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[2].x, corners[2].y,
        corners[3].x, corners[3].y);
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[3].x, corners[3].y,
        corners[4].x, corners[4].y);
    SDL_RenderDrawLine(
        TheGame::Instance()->getRenderer(),
        corners[4].x, corners[4].y,
        corners[5].x, corners[5].y);
}

Just for clarity, it still occurs in spots where there should be a drawn line. This is a shot with the above code:


texts: Most Efficient way to read a Settings Configuration File

texts:
I have been working on a game for quite a while, and I am using Ogre3D for the rendering engine. It is getting to the point I need to move adjustable settings to a configuration file such as video settings/options, player keybindings, etc.

I am using RapidXML for parsing and loading my scenes, but I am not sure this is the best way to go about doing configurations. As a long time fan of Valve games, I know there's are just a long list of settings, basically no grouping, just a list. Where as UT games do something like

[VideoOptions]
...
...

[GameSettings]
...
...

Anyways, I am just wondering what the best way to go about this is.


texts: Instead of the specified Texture, black circles on a green background are getting rendered. Why?

texts:
I'm trying to render a Texture via OpenGL. But instead of the texture black circles on a green background are rendered. (They scale, depending what the rotation of the texture is)

Example:

The texture I'm trying to render is the following:

This is the code I use to render the texture, it's located in my Sprite-class.

    public void Render()
    {
        Matrix4 matrix = Matrix4.CreateTranslation(-OriginX, -OriginY, 0) *
                        Matrix4.CreateRotationZ(Rotation) *
                        Matrix4.CreateTranslation(X, Y, 0);

        Vector2[] corners =
        {
            new Vector2(0,0), //top left
            new Vector2(Width ,0),//top right
            new Vector2(Width,Height),//bottom rigth
            new Vector2(0,Height)//bottom left
        };

        //copy the corners to the uv coordinates
        Vector2[] uv = corners.ToArray<Vector2>();

//transform the coordinates
        for (int i = 0; i < 4; i++) corners[i] = new Vector2(Vector3.Transform(new Vector3(corners[i]), matrix));
        //GL.Color3(TintColor);
        GL.BindTexture(TextureTarget.Texture2D, _ID);
        GL.Begin(BeginMode.Quads);
        {
            for (int i = 0; i < 4; i++)
            {
                GL.TexCoord2(uv[i]);
                GL.Vertex3(corners[i].X, corners[i].Y, _layerDepth);
            }
        }
        GL.End();

        if (EnableDebugDraw)
        {
            GL.Color3(Color.Violet);
            GL.PointSize(3);
            GL.Begin(BeginMode.Points);
            {
                for (int i = 0; i < 4; i++) GL.Vertex2(corners[i]);
            }
            GL.End();

            GL.Color3(Color.Green);
            GL.Begin(BeginMode.Points);
            GL.Vertex2(X, Y);
            GL.End();
        }

    }

This is how I setup OpenGL.

    public static void SetupGL()
    {
        GL.Enable(EnableCap.AlphaTest);
        GL.AlphaFunc(AlphaFunction.Greater, 0.1f);

        GL.Enable(EnableCap.Texture2D);
        GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);

    }

With this function I load the texture:

public static uint LoadTexture(string path)
    {
        uint id;
        GL.GenTextures(1, out id);
        GL.BindTexture(TextureTarget.Texture2D, id);

        Bitmap bitmap = new Bitmap(path);

        BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

        GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
            OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);

        bitmap.UnlockBits(data);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
        GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
        return id;
    }

And here I call Sprite.Render()

protected override void OnRenderFrame(FrameEventArgs e)
    {
        GL.ClearColor(Color.MidnightBlue);
        GL.Clear(ClearBufferMask.ColorBufferBit);
        _sprite.Render();
        SwapBuffers();
        base.OnRenderFrame(e);
    }

As I stole this code from the Textures-Example from OpenTK, I don't understand why this doesn't work.


texts: How to get surrounding tiles in a tile array

texts:
I've created a tiled map that holds two layers, one for the tile type, and the other for whether it is solid or not. I plan on creating very big maps, and checking every tile seems like it would slow down my game immensely.

So lets say I had an array of integers. "0" representing solid, and "1" representing not solid. How would I check only the 8 surrounding integers instead of the whole array each update.

0 0 0

0 1 0

0 0 0


texts: How do I make a pointer point to the current running level if each level is its own class?

texts: I'm hard-coding my levels and coding each level in its own class...The problem is that I need to have a pointer that points to the class of the current level.  I don't know how I would go about doing this.  I ideally want to have a vector that stores the levels, and I'm working on a level managing class to load, update, draw, and unload the levels in.


texts: Python/java framework for developing artificial intelligence for board games like Diplomacy/Risk

texts:
I am trying to pick a python/java framework for developing artificial intelligence for board games like Diplomacy/Risk for research purpose. I am specifically looking for multiplayer, multiple-round games without any dominant strategies that require players to cooperate as well as non-cooperate at certain times.

The idea of the research is to not build the game itself or the AI bot, but to discover novel methods for game theory, specifically to deceive other players- bots or humans.

This research is specifically based on Deceptive Artificial Intelligence. Please share any frameworks(game code with stubs for decision making) that you may know about. It would be a lot of help for my work.

If you have any ideas about some other game that I can pick, please mention that as well.

I have tried a few frameworks but the lack of documentation is extremely annoying and I haven't been able to move forward in the process.

Thanks and Regards!


texts:
I need a book that's beneficial for me and not something that contains what i have already read.

I have a strong maths,physics background and I have good c++ programming skills

and i  want to start game programming in 2d because after a lot of research on net people recommend not to jump in 3d directly.

Also I don't want to study from online tutorials like those in SFML because there is lot of knowledge scattered on the net but what i want to study from a good book because in the book all knowledge is in one place

I have also done research that books like Beginning 2d game programming by Charles Kelly,Game Engine Architechture,Game Coding Complete,Advanced 2d game development by Jonathan Harbour are all good But I can Only Buy one at the moment and i already know c++,physics and maths pretty well (dont know graphics though) so which one is the right one for me.
So please guide me
Thank You


texts: Dynamic pathing algorithm for tower defense game

texts:
I'm making a Tower Defense and I need a good pathing algorithm for it.

I have thought about Dijkstra but I need one that can be dynamic; it must be able to update itself when one edge is removed or added without a full recalculation.

I'm coding in C# if it helps.


texts:
I have an object moving around, let's say it's a cycle. In cycle dynamics, when the object takes a turn, it often leans into the direction of the turn. I would like to simulate this.

I'm using the equation: atan(v^2 / r * g), where v is the current velocity, r is the radius of the turning circle and g is the gravitational force. I get r with v^2 / a, where a is the current acceleration.

However it doesn't seem to work right. In some cases it leans to the right direction, in others, it leans to the opposite, meanwhile the leaning should always be inwards.

I've determined the direction where the acceleration force pulls the object with sign(velocity.y * acceleration.x - acceleration.y - velocity.x) and multiplied the leaning with the result, but it has no effect.

What am I missing?


texts: Loop through multidimensional array in C#(Unity)

texts:
I have this data

As you can see there's a 2nd board there.

Now what i want is something like this

PSEUDO CODE

If the first boards table[1,1] is not `NULL` then I will need to find out
now if table[0,1] and table[0,0] has the same length as table[1,1] and
table[1,0]

then display in the 2nd board a blue circle if it is the same in length if
not red circle

But if the table[1,1] is `NULL` then I need to know compare 1st column and
2nd column if they have the same length

then display in the 2nd board a blue circle if it is the same in length if
not red circle

END PSEUDO CODE

I tried doing the following

//COLUMN
    for(int col = 0; col < table.GetLength(0); col++)
    {
        int sum = 0;
        //ROW
        for (int row = 0; row < table.GetLength(1); row++)
        {
            if (table[col, row] != null)
            {
                Debug.Log("Column 1 has this value : " + table[col, row]);
            }
        }
        //Debug.Log("table column: " + col + " has " + sum + " data");
    }

For now I can only get the whole Row and Column but I don't know how to do that pseudo code.


texts: Leapfrog integration vs Euler integrator

texts:
I am looking at various integration methods for my n-body simulation and I'm slightly confused about actual implementation of leapfrog integration.

According to the wikipedia page leapfrog method is defined like this:

When I imagine how to code it, i come up with something like this:

while true:
    dt = time since last frame

    for every object:
        object.position += object.velocity * dt

    for every object:
        acceleration = object.calculate_acceleration()
        object.velocity += acceleration * dt

    render()

But this is Euler integration, right?

So moving the initial velocity back by one half step makes a first order method into a second order method?
But for me a small change of initial velocity is not important, it will be set as a random value anyway...

Why I won't just use velocity verlet: This is for a game where tens of thousands particles fly around affected by forces roughly resembling gravity.
I'd like to keep amount of data stored in every partile as low as possible to improve cache locality, which is why I don't want to use a method that requires storing acceleration (and recalculating it would be too slow).


texts: Please help with bounding box/sprite collision in darkBASIC pro

texts:
So I just recently learned BASIC and figured I would try making a clone of pong on my own in darkBASIC pro, and I made everything else work just fine except for the part that makes the ball bounce off the paddle. And yes I'm aware that the game is not yet finished. The error is on lines 39-51
EVERYTHING IS 2D.
The problem i am having is that when the ball hits the paddle it gets like stuck(itll move away like 3 pixels and the back onto the paddle), and will move up or down until it
finally gets to the edge of the paddle, or it gets sucked into the inside of the paddle, or it does the same thing where it gets stuck on the paddle, but it does it from behind.

  ///////////////////////////////////////////////////////////
  //
  //     Project: Pong
  //     Created: Friday, August 31, 2012
  //     Code: Brandon Spaulding
  //     Art: Brandon Spaulding
  //     Made in CIS lab at CPAVTS
  //     Pong art and code © Brandon Spaulding 2012-2013
  //
  //////////////////////////////////////////////////////////
y=150
x=0
ay=150
ax=612
ballx=300
bally=200
ballx_DIR=1
bally_DIR=1
hide mouse
set global collision on
//objectnumber=10
//make object box objectnumber,5,150,0
do
load image "media\paddle1.png",1
load image "media\paddle2.png",2
load image "media\ball.png",3
sprite 1,x,y,1
     sprite 2,ax,ay,2
     sprite 3,ballx,bally,3
     if upkey()=1 then y = y - 4
     if downkey()=1 then y = y + 4

    //num_1 = sprite collision(1,0)
    //num_2 = sprite collision(2,0)
      num_3 = sprite collision(3,0)

for t=1 to 2

//ball&paddle collision
if num_3 > 0
    if bally_DIR=1
        bally_DIR=0
    else
        bally_DIR=1
    endif
    if ballx_DIR=0
        ballx_DIR=1
    else
        ballx_DIR=0
    endif
endif

//if bally > 1 and bally < 500 then bally=bally + 2.5
if bally_DIR=1
    bally=bally-2.5
        if bally<-2.5
            bally_DIR=0
        endif
else
    bally=bally+2.5
        if bally>452.5
            bally_DIR=1
        endif

endif
if ballx_DIR=1
    ballx=ballx-2.5
        if ballx<-2.5
            ballx_DIR=0
        endif
else
    ballx=ballx+2.5
        if ballx>612
            ballx_DIR=1
        endif

endif
//bally = bally + t
//if bally < 600 or bally > 1 then bally = bally - 2.5
//if ballx < 400 or ballx > 1 then ballx = ballx + 2.5
//move sprite 3,1

   next t
   if escapekey()=1 then exit
   loop
   end

Thank you in advance for the help.


texts: How can I write a trigger to detect when a terran building burns to its death? (Starcraft 2)

texts:
I'm working with Starcraft 2 Map Editor, and am having a little bit of a trigger problem.

It's quite easy to detect when a specific unit kills a structure (simply check if triggering unit == whatever) but I'm not quite sure how to tell when a building dies to to either fire (terran buildings) or bleeding out (zerg buildings when off creep).

What condition should I be looking for in my "a unit dies" trigger to see if one of those two situations occured?

PS: Sorry for lack of available tags!


texts:
I'm currently working in an Angry Bird-esque game, where the user flings a bomb at buildings and the bomb explodes.

How do I create explosions in Corona? Essentially some sort of area of effect explosion should occur on collision, which pushes all the elements within the area out of the way (this could probably be done with applyForce)

I've tried the following, but left me with lackluster results:

function setExplosion(self, event)
    event.other:applyForce(300, 300, circle.x + (circle.width/2), circle.y + (circle.height/2))
end

Note that the circle is the explosion radius.

Anybody have any tips on creating explosions?

EDIT:

function setExplosion(self, event)
    event.other:applyForce(500, 500, circle.x + (circle.width/2), circle.y + (circle.height/2))
end

function drawExplosion(eventX, eventY)
    return function()
        circle = display.newCircle( eventX +20, eventY +20, 150 )
            circle.myName = "circle"
            game:insert(circle)
       circle:setFillColor(100,100,100, 100)
     physics.addBody( circle, "static", {isSensor = true} )
        circle.collision = setExplosion
        circle:addEventListener( "collision", circle )
end
end


texts: Giving one controler button two functions

texts:
I'm currently working on a game that allows the player to do some different actions.

Dodge (X button)
Attack (A button)
Use Item (Y Button)
Block (BButton)

I would like to be able to use the "Y" button to both use items and pick items up. This dual functionality would be determined by how long the player held the button and if the player was standing next to an item. I'm sure there have been studies on this and how long the player expects for a delay to use the second functionality but I'm worried that I have become biased in my testing and I can't find anything online.

My question is: Is there some sort of standard for this type of a time delay for the button? If so where can I learn more about it?


texts: Rendering part of an equirectangular video on a plane

texts:
For a Unity project I have a 360 camera which produces an equirectangular video.
I need to realize preview of this video for putting it on a plane.

In most cases the part of the video to be drawn on the plane is the central part of the video, which is not so stretched and so it can be drawn as is. In some cases, instead, the camera has to be put above the scene, upside down, in order to capture the scene below, as shown in the following image.

In this kind of situation I need to produce a preview from the upper part of the video; in other words I need to project a portion of the upper part of the video on a plane.

I imagined two ways, the first one is easy but not so effective, the second one is tricky but surely better.

I project the video on a sphere and capture, with a virtual camera, the interesting part, which is taken and rendered on a plane.
I write an appropriate shader which, given the equirectangular video, crops the portion of it and draws it correctly on a plane.

May you give me a hand on writing the shader?


texts: Gradually rotate vector towards another vector

texts:
For a game I'm making there is an AI bot in it. I want it to rotate so that it is facing it's opponent. The direction it is facing is determined by a vector (it will face the direction that the vector represents.) I can rotate it to face it's opponent like so:

 glm::vec3 opponentRefPos = opponentPos - position;      //for comparing AI's opponent's position to AI's position

glm::vec3 directionTarget = glm::normalize(opponentRefPos);
direction = directionTarget;

Where direction is the direction that the AI bot is facing (and it is a vec3) I want to gradually rotate it to face directionTarget. So let's say that I have a constant variable called SPEED (and deltaTime, which is the time between frames that SPEED will be multiplied by to keep the speed that it rotates at constant), which is the speed that I want the AI bot to rotate at. How can I rotate it towards this vector at that speed?