texts: OpenGL Arc-Ball Camera Yaw Pitch GLM::Rotate

texts:
I'm currently working on a small Voxel-Editor Project. In the editor, I plan on using an Arc-Ball camera which rotate around the model. My camera is currently working but in an odd way. I can't seem to be able to move around the Z-Axis on my model which cause my camera angle to get smaller as I reach one side. For example, if I go to the left side of my ball, I wont be able to turn around it completly.

Here is my code which update my current View-Matrix into the updated one.

void t_Math::CreateLookAt(glm::mat4& InMatrix, sf::Vector3f pointToFix,   GLfloat InPitch, GLfloat InYaw, GLfloat valueToScale)
{

    glm::mat4 rotationMatrix = glm::mat4(1.0);

    const GLfloat FinalPitchDegree = InPitch / 57.2958;
    const GLfloat FinalYawDegree = InYaw / 57.2958;

    rotationMatrix = glm::rotate(rotationMatrix, FinalPitchDegree,                               glm::vec3(1.0, 0.0, 0.0));
    rotationMatrix = glm::rotate(rotationMatrix, FinalYawDegree, glm::vec3(0.0, 1.0, 0.0));

    const glm::vec4 cameraPosition4 =  rotationMatrix * glm::vec4(1.0);
    const glm::vec3 cameraPositionFinal = valueToScale * glm::vec3(cameraPosition4);

    const glm::vec3 constObjetMiddle = glm::vec3(pointToFix.x, pointToFix.y, pointToFix.z);

    InMatrix = glm::lookAt(cameraPositionFinal, constObjetMiddle,         glm::vec3(0.0, 1.0, 0.0));
}

Here is what I believe my code do.

The function receive a View Matrix, The model Center Coords, The Pitch, The Yaw and finally the Scalar (The zoom). Note: My Pitch and Yaw are simple GLFloat which mean they don't have limits and can go from -R to +R.

Now for the code. -We first create a base Matrix 4 -We Divide the Pitch and Yaw by 57.2958 (a radian) because GLM::rotate works with radian and I want it to be precise so in degree. -We then rotate the base Matrix on their respective Axis using the proper Pitch and Yaw -We then calculate the position of the Camera by using the ROTATED matrix which we transform into a Vec4 -We calculate the final Camera position by multiplying by the Scaling Vector (The Zoom) and we transform this Vector4 into a Vec3 -We create another Vec3 which is the Camera Target by using the value received by the function -We use all we collected to create a new lookAt matrix and we apply it to the view matrix.

I think I might be missing the Z-Axis rotation but how am I suppose to calculate it ? Should I use the Pitch or the Yaw ? Since i'm using (W-A-S-D) to move around here is what my keys does.

W: Increase Pitch S: Decrease Pitch D: Increase Yaw A: Decrease Yaw

Do I need to put the Roll into this and which keys should increase and decrease it ?


texts: Programmatically creating sprite animations in Unity

texts:
Some background: I have a set of animated gifs which I've converted to spritesheets, which are then imported into Unity as multiple sprites. The end result is that each spritesheet in the Unity editor contains a list of sprites named xxxxxxx_yyy_zzz -- for example:

1313000_000_000 to 1313000_000_014, followed by
1313000_001_000 to 1313000_001_008, followed by
1313001_000_000 to 1313001_000_031,
and so on.

Now, I would like to make simple sprite animations out of this spritesheet. In the example above, 1313000.anim should contain all sprites beginning with 1313000 played in numerical order, 1313001.anim should contain all sprites beginning with 1313001, etc. etc.

This isn't hard to do by hand -- highlight desired range of sprites, drag and drop -- but we're talking about a lot of animations. Creating an editor script which lets me right-click a spritesheet and generate a series of .anim files seemed the best solution, but I'm turning up conflicting info on the subject. Getting a sprite array from the spritesheet is simple enough, but programmatically creating an animation is something very few people seem to have discussed.

Essentially, is it possible and practical to create and populate sprite animations from an editor script?


texts: Python - Holding down key to move a sprite works, but only in one direction

texts:
I've been testing out movement for a fighting game that I'm creating in Python.

The problem is that when I try to move the sprite, it moves correctly to the left, but only ever works in that direction.
I think the problem is with my event handling loop, but I don't have much experience so I have no idea how to solve the problem. Googling and spending a while doing trial and error was no help.

My main loop looks like this:

pressedLeft = None
pressedRight = None
pressedUp = None
pressedDown = None

while True:

    #event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                pressedLeft = True
            elif event.key == pygame.K_d:
                PressedRight = True
            elif event.key == pygame.K_w:
                PressedUp = True
            elif event.key == pygame.K_s:
                PressedDown = True
        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                pressedLeft = False
            elif event.key == pygame.K_d:
                PressedRight = False
            elif event.key == pygame.K_w:
                PressedUp = False
            elif event.key == pygame.K_s:
                PressedDown = False

    # movement
    if pressedLeft:
        profx -= 5
    elif pressedRight:
        profx += 5
    elif pressedUp:
        profy -= 5
    elif pressedDown:
        profy += 5
    DisplaySurf.fill(white)
    DisplaySurf.blit(profImg, (profx, profy))
    pygame.display.update()
    fpsClock.tick(FPS)


texts: Is there a way to optimize this 2D lighting effect shader?

texts:
I'm doing a little 2D game in C++ with Direct3D 11.

In the game I want to render a sort of shadow that covers part of the screen:

To do this I am using this pixel shader:

float4 PS_Main( PS_Input frag) : SV_TARGET
{
    float4 color = {0, 0, 0, 1};
    for (int cont=0; cont<lights; cont++)
    {
        int dist = pow(frag.pos[0] - singleLight[cont][0], 2) + pow(frag.pos[1] - singleLight[cont][2], 2);

        if (dist < singleLight[cont][3] * singleLight[cont][4])
        {
            color[3] -= 1 - (dist / (singleLight[cont][5] * singleLight[cont][6]));
        }
    }

    return color;
};

The constant buffer I pass to the shader is:

cbuffer PSbuffer : register( b0 )
{
    int lights;
    float4 singleLight[15];
};

I also pass an array to the shader, each element of which contains the position and radius of a light.

The code works with more than one light, but if I try to use more than ten lights the FPS drops down to 40 or 50. How can I optimize this effect?

Thank to all!!
I try to optimize the pixel shader code but i earn 4-5 fps so i decide to to a "light map" in this way;
I create a second Render Target View i will use to render the lights(sprite i draw).
The light will be alpha-channel inverted in order to have to clear the render target view with color{0,0,0,0}; draw the light on the second target view like this:
and then create a texture with this render target view and render it on the first with a shader that invert the alpha channel (color.a=1-color.a);
but, since i am new in directx i dont now how to do it and i cant find a good tutorial.Can you help me??


texts:
Given the image below, I need to detect the most optimal sequence on the board (the green line). The blue/red lines represent possible, but not the best moves.

Here are the rules:

You can move to any tile that is the same, and is your neighbor (diagonal is valid)
Once you have visited a tile, you can't visit it again.

I have thought about looping through each node, and looking at its neighbors, then recursively going through. Once I find a possible move I can put it into a structure. Once all possible moves are found I just pick the move with the highest count of node. It becomes more difficult when a node has more than one neighbor that matches.

So, is there some algorithm that I can use? I was thinking some sort of flood fill, but that doesn't meet rules #2.

As requested, here is a video of similar gameplay. http://youtube.com/watch?v=eumnCTG0AE8


texts: What exactly are tool pipelines in the game industry?

texts: I've been reading around online and through books and still can't quite figure out what exactly tool pipelines are within the game industry.


texts: How to have operations with character/items in binary with concrete operations?

texts:
I have the next problem.

A item can have a lot of states:

NORMAL  = 0000000
DRY     = 0000001
HOT     = 0000010
BURNING = 0000100
WET     = 0001000
COLD    = 0010000
FROZEN  = 0100000
POISONED= 1000000

A item can have some states at same time but not all of them

  Is impossible to be dry and wet at same time.
  If you COLD a WET item, it turns into FROZEN.
  If you HOT a WET item, it turns into NORMAL
  A item can be BURNING and POISON

Etc.

I have tried to set binary flags to states, and use AND to combine different states, checking before if it is possible or not to do it, or change to another status.

Does there exist a concrete approach to solve this problem efficiently without having an interminable switch that checks every state with every new state?

It is relatively easy to check 2 different states, but if there exists a third state it is not trivial to do.


texts:
I am developing a RTS (real-time strategy) game involving robber and cops. I have designed a simple rule based AI system for the robber.

Goals of the robber AI:

Escape from the cops (robber should not get caught)
Conduct robbery

Current implementation:

The robber AI uses a rule based system to escape from the cops. I have written IF-THEN clauses to build the rule based AI system. The robber AI uses the knowledge of cops’ current positions.

Future requirements:

I am worried about the current architecture of this robber AI system. I read that rule based systems are inefficient and difficult to maintain. For the future,

I want the robber AI to use some power-ups (to escape)
The AI should consider the power-ups used by the cops before making decisions.
For conducting the robbery, the robber has to move to a specific location escaping from the cops.

Questions:

Is the current rule based AI system will flexible enough (and easy to maintain) to meet the future requirements?
What can be better alternatives for the existing rule based system? (Like decision trees or state machines etc.)
I read people suggesting that the rule based systems are difficult to debug. Can anyone explain why?

I would appreciate any thought/suggestions on this topic. Thank you.


texts:
I'm experimenting a strange behaviour of textures inside my shaders.
Basically I need and bind two cubemap textures inside my shader but only one gets actually bound.

I've tried swapping the two textures keeping the samplers untouched and the texture that previouly I could see now I don't see it anymore, so I think the problem is related to the samplers inside my shader.

This is how I bind my two cubemaps to the shader:

int firstTextureLocation = glGetUniformLocation(programID, "ConvolutionSrc");   // returns 5
int secondTextureLocation = glGetUniformLocation(programID, "LastResult");      // returns 9

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, _firstTextureID);
glUniform1i(firstTextureLocation, 0);

glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_CUBE_MAP, _secondTextureID);
glUniform1i(secondTextureLocation, 1);

And this is a portion of my shader (the parts where the cubemaps are used):

uniform samplerCube ConvolutionSrc;
uniform samplerCube LastResult;
...

vec3 Sample(vec3 R)
{
    ...
    vec3 hdrPixel = rescaleHDR(textureLod(ConvolutionSrc, L, lod).rgb);
    ...
}

void main()
{
    ...
    vec3 lastResult = textureLod(LastResult, R, ConvolutionMip).rgb;
    sampledColor.rgb = mix(lastResult.xyz, importanceSampled.xyz, 1.0f / (ConvolutionSamplesOffset));
    ...
}

Basically only the texture at uniform location 5 of my shader gets bound.


texts:
My game uses UDP sockets to stream updates between server and client and I've also made a reliable channel that resends messages if there's no response and makes sure same message isn't processed multiple times.

But TCP is specifically designed to be reliable and the people who made it probably have more experience than me. So would it be good to use TCP to send commands such as "attack", "play animation", etc. instead of my UDP implementation?
(Of course I mean TCP sockets that don't delay sending the data (Nagle algorithm))


texts: Baking details to a low poly model asset - used on enviroment or “world” geometry?

texts:
Usually for the game objects a high poly model is prepared, to then transfer the details onto a low poly model, so that it can be rendered in realtime.

Is this workflow always used, with any object?

I imagine this is used for the polygonal models of the characters in general, but what about the rest?

I'm especially interested in the environment, like a snowy mountain for example. I do not think this high-poly to low poly detail baking workflow is appropriate for this case.


texts: Moving a big set of box2d bodies in an iOS endless side-scroller game (such as Canabalt)

texts:
I am working on an iOS endless-running game (Robot Unicorn, Canabalt, etc). I'm using box2d for the Physics and Collision Checking and cocos2d for graphics.

To achieve the notion of an endless level, I instantiate "boards" which encapsulate a set of box2d bodies (floors, enemies, etc). I place two of these "boards" alongside and I check for their current position every frame. When they leave the visible area of the iPhone screen, I move the board and it's set of bodies to a new position, further ahead.

To do this I use the SetTransform() method of the b2Body class.

I also put all my bodies to sleep before doing this.

My issue is that every time I perform this task, the FPS has a noticeable drop.

I ran the Profiler and it seems the problem is within the SetTransform(). Apparently, box2d is removing and inserting leafs in the dynamic tree.

I am moving around 50 bodies in one frame.

My question to you guys is if anyone knows of a more convenient way to translate bodies without it taking a toll in performance. Perhaps it's cheaper to create new bodies, instead of moving the existing ones? Am I missing some kind of flag I should activate before calling SetTransform()?

Thanks in advance!


texts: Comparing a saved movement with other movement with Kinect

texts:
I need to develop an application where a user (physiotherapist) will perform a movement in front of the Kinect, I'll write the data for the movement in the database and then the patient will try to imitate this motion. The system will calculate the similarity between the movement recorded and executed.

My first idea is to store the position of the recorded points and then compare them in the execution time to the patient's movement. I know that this approach is too simple, however, because I imagine that in people of different sizes the skeleton is recognized differently, so the comparison is not reliable.

My question is about the best way to compare a saved motion with a movement executed (on the fly).


texts: Libgdx--how to store every single point drawn using touchdragged?

texts: Basically i am trying to detect line collision. The problem is when intersection occurs quickly(touch dragged is done quickly like fling), the collision is not detected. It seems as if 'touch dragged' doesn't store all points.


texts: C++ Opengl transforming a glm::vec4 with a glm::mat4

texts:
Its easy enough doing it on the gpu via GLSL, but how would I do this in c++? When I try it gives me an error telling me I cant cast a glm::mat4 to float, Which makes sense, but how should I do it?

EDIT

A little code example of my failed attempt:

glm::vec4 Off = glm::vec4(0, 0, 0, 1);
Off *= Util::createTransform(offset); // Util::createTransform(...) Creates a glm::mat4

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(Off.x, Off.y, Off.z);
}


texts:
I'm wondering how people here on GameDev stack exchange would handle curved meter GUI elements for things such as life bars or energy bars.

My thought on the matter was that you could use a shader with a cutoff value and an image which has one channel dedicated to masking the image (alpha) and one that also has a gradient which I compare to a uniform float to determine whether or not the fragment should be fully transparent.

However, I've been running into some strange behavior when writing this shader. Specifically, the shader's output has a weird artifact where the cutoff begins that looks almost like ripped paper -- the line that indicates the end of the meter has a sloppy contour.

This image has some distortion effect going on with the pixels where the lifebar is supposed to end via the cutoff uniform. There's definitely got to be a better way of doing this same thing in a more tactful way. Shader code is below:

   CGPROGRAM
   #pragma vertex vert
   #pragma fragment frag

        sampler2D _MainTex;
        float4 _Color;
        float _Cutoff;

        struct Vert_IN {
            float4 loc : POSITION;
            float4 texcoords : TEXCOORD0;
        };

        struct Frag_IN
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
        };

        Frag_IN vert( Vert_IN input )
        {
            Frag_IN output;
            output.uv = input.texcoords;
            output.pos = mul( UNITY_MATRIX_MVP, input.loc );
            return output;
        }

        float4 frag( Frag_IN input ) : COLOR
        {
            float4 value = _Color;
            float4 valueFromMask = tex2D( _MainTex, input.uv.xy );

            value.w = valueFromMask.w;
            float desiredTransparency = step( valueFromMask.x, _Cutoff );
            value.w = min( value.w, desiredTransparency );

            return value;
        }

        ENDCG

(Again, the red channel of this image is actually a gradient mask used to determine where the cutoff point should be. Other channels were going to be used for something else (like special scrolling patterns or what not) )

Example of the asset used in the shader:

I'm assuming there's probably something I'm missing when using the step function that could help ease the fade-dropoff in order to make a better looking end result?

What do you think is a good method for making curved meter GUI elements? Is there something wrong with the shader code presented above that causes this strange page tearing artifact?


texts: Using a Viewpoint and a RenderTarget2D in XNA

texts:
I started using a RenderTarget2D in my project so I could use shaders more effectively, but when I went full screen I found that my center viewpoint was no longer centered.  It still resizes correctly, but for widescreen monitors it should center the viewport to the middle of the screen.  And that was working correctly until I started using a RenderTarget2D.  Now, the viewport is being displayed on the left side of the screen instead.

        if (graphics.IsFullScreen)
        {
            // set the viewport to the whole screen
            GraphicsDevice.Viewport = new Viewport
            {
                X = 0,
                Y = 0,
                Width = GraphicsDevice.PresentationParameters.BackBufferWidth,
                Height = GraphicsDevice.PresentationParameters.BackBufferHeight,
                MinDepth = 0,
                MaxDepth = 1
            };

            // clear whole screen to black
            GraphicsDevice.Clear(Color.Black);

            // figure out the largest area that fits in this resolution at the desired aspect ratio
            int width = GraphicsDevice.PresentationParameters.BackBufferWidth;
            int height = (int)(width / targetAspectRatio + .5f);
            if (height > GraphicsDevice.PresentationParameters.BackBufferHeight)
            {
                height = GraphicsDevice.PresentationParameters.BackBufferHeight;
                width = (int)(height * targetAspectRatio + .5f);
            }
            scale = (float)width / (float)Game1.ScreenWidth;
            // set up the new viewport centered in the backbuffer
            GraphicsDevice.Viewport = new Viewport
            {
                X = GraphicsDevice.PresentationParameters.BackBufferWidth / 2 - width / 2,
                Y = GraphicsDevice.PresentationParameters.BackBufferHeight / 2 - height / 2,
                Width = width,
                Height = height,
                MinDepth = 0,
                MaxDepth = 1
            };

            GraphicsDevice.Clear(Color.Black);
        }

        GraphicsDevice.SetRenderTarget(rendertarget);
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

....Draw All of the Game....

        GraphicsDevice.SetRenderTarget(null);
        spriteBatch.End();
        spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend, null, null, null, brightnessShader, Matrix.CreateScale(scale));
        spriteBatch.Draw(rendertarget, Vector2.Zero, Color.White);

Any ideas as to why the viewport is displayed at the left instead of the center?


texts: Animator.Play() only works the first time

texts:
I am creating a game in Unity 3d that is using an animation to move an object. For some reason the animation only works the first time it is accessed and from then on it acts as if it is not being called even though I have debugged and I see that it is being called. Here is the code I use to call the animation:

if (anim == null)
{
    foreach (Transform component in myObject.transform)
    {
        anim = components.GetComponent<Animator>();
    }
}
anim.Play("Flip-Forward");
anim.enabled = true;

As you can see I have an animator connected to myObject that I access in order to plan an animation. "Flip-Forward" is one of the animations I have created.


texts: How can I generate a (relatively) linear dungeon path?

texts:
We developing a concept for an action side-scroller. What we need is a way to generate a (relatively) straight map. By this I mean something like...

It's clear to see that this map follows one simple route, even if it deviates a bit. With that, we're also going to implement straying pathways -- shortcuts, or secret passages. So that, perhaps, to get from the third circled area to the fourth, you'd have the main path, and a secret passageway that's filled with stronger enemies, but is faster and has higher rewards.

Here we've reached an impasse. We're exploring a few options but haven't really made any progress. What approach could we use to generate this kind of path We're not bound by programming languages, as so far we've experimented with Java, C# and C++. Similarly, we don't have any current dependencies on specific game engines.


texts: Why do my update and draw loops throw a concurrent access exception?

texts:
I've taken up the challenge of creating a basic 2D side-scrolling monster truck game for my little brother.  It seems easy enough in theory, but jumping into Java out of XNA feels strange.

My game class has a private class GameLoop extending Runnable.  In the overridden run() method, a while-loop handles time and such.  There's a targetFPS for drawing as well.  The loop looks like this:

public void run()
{
    long fpsTime = 0;

    gameStart = System.currentTimeMillis();
    lastTime = System.currentTimeMillis();

    while(game.isGameRunning())
    {
        currentTime = System.currentTimeMillis();

        long ellapsedTime = currentTime - lastTime;

        if(mouseState.leftIsDown)
        {
            que.add(new Dot(mouseState.getPosition()));
        }

        entities.addAll(que);

        game.updateGame(ellapsedTime);

        fpsTime += ellapsedTime;
        if(fpsTime >= (1000 / targetedFPS))
        {
            game.drawGame(ellapsedTime);
        }

        lastTime = currentTime;
    }

I'm running into a problem when adding entities after a click.  I made a class with a private class extending MouseListener and MouseMotionListener, then on changes I have it set a few booleans to tell me if the mouse is pressed or not which seems to work great. However, when I add the entity, I occasionally get a CME (Concurrent Modification Exception).  All the entities are stored in a LinkedList<Entity>.

I also tried adding a queued LinkedList, where I add the contents of the queue to the normal list later in the update loop.

I think this would work fine if it was just the update method in the game loop, but it's the repaint() method (called from game.drawGame()) that throws the CME.

The only other thing is that I'm currently drawing directly from the overridden paintComponent() method in a custom class extending JPanel.

Is a better way to go about this?  How do I fix the CME?


texts: Unity: Build looks different then gameview: runtime reflection probes not working correctly

texts: Im having a really hard time figuring out how to configure my reflection probes to update in runtime once I build. The game port view looks totally different than the build view. Ive tried turning off baked GI in the lighting > scene panel, and unchecking "auto" under "other settings" but keep getting an error message "baking lighting data asset failed" when I try to build the light maps. Maybe this is not the right way to solve the problem? Has anyone else encountered this and figured it out?


texts: How do I calculate specular contribution in physically-based rendering?

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

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

Right now, I ues this:

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

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

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

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

Here is the full glsl code:

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

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

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

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

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

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

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

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


texts: HLSL Multitexturing with more than 4 textures

texts:
I've come up with an idea that should work in multitexturing a terrain with more than 4 textures, up to a 64 if a supported ShaderModel is used.

I'm trying to use the RGBA color values as both values for blending and identifying which textures should be used.

I'm currently using 16 per textures. Each color has 256 values (R, G, B, A) so by identifying:

Texture 1
Red = 0-16, Blend = (Value / (16 - (16 * 0))
Texture 2
Red = 17-32, Blend = (Value / (16 - (16 * 1))

and by changing from 16 to 32 the blend is better because more rgba values can be included.

...and the closer that value is to 16 the higher blend value it gets with that texture.

All I'm stuck at is this calculation because no matter what I do I can't seem to convert the values correctly or get the values in the right way.

// VS_OUTPUT contains Position, TextureCoordinates and Color

float4 MultiTexturing_Pixel(VS_OUTPUT input) : COLOR
{
    float4 color = float4(0,0,0,0);

    int scale = 16;

    float red = input.Color.r * 256;

    // gets an index between 0~16, add +16 for each color after this
    int redIndex = ceil(red / scale);
    int redValue = 0;

    if ( (red % scale) == 0)
    {
        redValue = 1.0;
    }
    else
    {
        redValue = (color % scale) / scale; // should give a value between 0.0 and 1.0
    }

    // function with alot of ifs that checks the index and returns the Texture Sampler
    color += GetColor(index, value, input.TexCoord);

    // and the same for blue, green, alpa
    // but add blueIndex + 16, greenIndex + 32, alphaIndex + 48

    return color;
}

The math is there, but converting values back and forth is really the problem and since HLSL is basic C it's weird that it doesn't support basic math calculations.

Since I'm not that good at how the calculations should work I hope someone can provide an answer on how to actually perform the calculations below.

I've tried every possible way, all day and I'm totally out of ideas.

UPDATE: Problems with the calculations:

As far as my math knowledge goes, this is how it should go.

A color value is 0~255 (256)
In HLSL this translates to a value of 0.0-1.0, which means 32 = (32 / 256) = 0.125

Step 1 I set the Vertex color to:

new Color(32, 0, 0, 0)

Step 2 In the pixel shader this value would translate to the second texture this way:

float each = 16.0;
float max = 256.0;

float redIndex = (input.Color.r * max) / each;

At this point redIndex should be "2.0" if Color value is (32,0,0,0)
But it's not. Why? This is the flow for me in any other programming language:

float each = 16.0;
float max = 256.0;

float redIndex = 0.125 * 256; // = 32
      redIndex /= 16.0; // = 2.0

int index = redIndex; // = 2
int index = ceil(redIndex); // = 2

If I try to use ceil(redIndex) nothing better happens, it still can't get that "index" value. And this is basic MATH. And ceil (available from SM v1.1) takes the value up to the nearest integer, so if it's 1.9 == 2, 0.1  = 1 and so on. But it cannot do this. Because the values are wrong and the calculation is wrong.

Step 3 To get a value between 0-1 for texture, the closer you are to 16, 32, 48, 64 the more color from texture 1, 2, 3, 4 you get. So: 16 = 1, 8 = 0.5 4 = 0.25

float redValue = 0.0;
float red = input.Color.r * max;

if ( fmod(red, each) == 0.0) // or (16.0 % 16.0), which basically is 0.0
{
    redValue = 1.0;
}
else
{
    redValue = fmod(red, each) / each;
            // or (8.0 % 16.0) / 16.0
            // which is (8 % 16.0) = 8 and 8 / 16 = 0.5
            // which means the texture should be blended 0.5 or 50%.
}

Step 4 And finally by using the function GetColor I collect colors for each texture.

color += GetColor(index, value, input.TexCoord);

// and then do the same for green, blue, alpha values only add + 16
// because colors at (0,16,0,0) would be 16 + 1
// and color (0,0,32,0) would be 32 + 2
// and color (0,0,0,64) would be 48 + 4


texts: Electronic circuit simulator four-way flood-filling issues

texts:
I've made an electronic circuit board simulator which has simply 3 types of tiles: wires, power sources, and inverters. Wires connect to anything they touch, other than the sides of inverters; inverters have one input side and one output side; and finally power tiles connect in a similar manner as wires. In the case of an infinite loop, caused by the output of the inverter feeding into its input, I want inverters to oscillate (quickly turn on/off).

I've attempted to implement a FloodFill algorithm to spread the power throughout the grid, but seem to have gotten something wrong, as only the tiles above the power source get powered (as seen below)

I've attempted to debug the program, but have had no luck thus far. My code concerning the updating of power can be seen here.


texts: How can I check the shader model capabilities of an adapter?

texts:
I'm writing an application that targets Direct3D11 (through SlimDX) and shader model 5.

When I'm running it on a system that doesn't have SM5 capable hardware, I will get a NullReferenceException when trying to access the techniques in the compiled effect instance.

How can I check if the adapter is capable of this before I even attempt to use any of these features?


texts:
Whenever I run my project, this error pops up, I don't know where this came from. I need to fix it cause it kinda annoys me every time I run my project.
Assertion failed on expression: 'm_Memory.renderTextureBytes >= 0'


texts: How reimport a package in UDK with command line?

texts:
sometimes ago, I saw a command to re-import a UDK package content without opening the UDK Editor.
(Especially, it was used for reimporting a Flash package in a scaleform tutorial, but it doesn't matter now )

It's very useful, because every time I change my .swf file, I should open the heavy UDK and just press re-import.

So, can anyone give me that solution again  ?


texts:
I'm building a simple 2.5D Dogfighting game, kinda similar like this one: https://gfycat.com/PleasantDeterminedArcherfish for the moment my movement works like this:

    if (Input.GetKey("left"))
    {
        transform.Rotate(0, 0, rotation);
    }

    if (Input.GetKey("right"))
    {
        transform.Rotate(0, 0, -rotation);
    }

    if (Input.GetKey("up"))
    {
        if (speed <= maxspeed)
            speed += speedIncrease;
        if (gravity > 0)
            gravity -= speedIncrease;
    }

    if (Input.GetKey("down"))
    {
        if (speed > 0f)
            speed -= speedIncrease;

        if (speed <= 0f)
            speed = 0;

        if (gravity < 1.0f)
            gravity += speedIncrease;
    }

    transform.Translate((Vector3.down * gravity), Space.World); //This is for the fake gravity
    transform.Translate(new Vector3(0, 1 * speed, 0)); //This applies the forward speed

I tried to create the gravity by myself, so that I would be able to lower the gravity, at higher speeds, so that I can achieve an "uplift" effect, like in reality. But now I wanted to let my model face the movement direction and all solutions, I found to solve this problem use the rigidbody.velocity, which is zero in my case. Is there another case to solve this problem? Or maybe even a better solution to achieve a similar movement like in the gif than mine? Maybe adding force instead of Translate?


texts:
I want to use NDK to use my existing C++ code for a game. I know there are two ways to use NDK:

I can use Java to create GLSurface and opengl context;
I can use NativeActivity class to entirely write code in C++.

Given that the documentation available about these two approaches is not great, I have trouble making up my mind.

What's the difference between these two approaches?


texts: Simple Android loading screen when using OpenGL

texts:
My game uses openGL ES 2.0 on Android and it's got to the point where the pause (while loading resources) has become noticeable.

All I'm after is to show a static screen (probably via an XML layout if it's the simplest way, but through openGL is OK too).  And then dismiss the view and switch to the game.

I'm loading my resources in the onSurfaceCreated method of my GLSurfaceView class and creating my sprite objects in my onSurfaceChanged method (I need the width and height to scale them, so do it here, plus Google's docs recommend it).  I don't load my resources in onCreate.

I've tried creating a simple XML layout called 'loading' and putting something like this into my glSurfaceView class's constructor (glSurfaceView being an inner class of my Activity class)....

public MyGLSurfaceView(Context context) {
        super(context);
        {
loading_dialog = new Dialog(context,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
loading_dialog.setContentView(R.layout.loading);
loading_dialog.show();
}

This displays my 'loading' screen OK, but I need to call:

loading_dialog.dismiss();

at the end of my onSurfaceChanged method in my GLSurfaceView.Renderer class.  I obviously can't do this as the GLSurfaceView.Renderer class has no knowledge of the loading_dialog object.

I tried to create the object directly in the GLSurfaceView.Renderer class, but I don't have access to the context from here, so I tried to pass it in from the Activity class but then I got different errors at which point, I searched the net and couldn't find a clear answer on how to do this so thought I would post here in the hope that someone could point me in the right direction.


texts: Let one camera frustum intersect another's

texts:
I am currently struggling with the issue of combining two camera's render outputs. One camera renders orthographic 2D objects (e.g. facing the X/Y plane), the other renders 3D objects overlaid on top of the 2D output.

The 3D camera is an orthographic camera rotated 30 degrees to match the 3D objects to the 2D tile's looks. The car is the 3D objects and the background is placed on the X/Y plane.

Now, my troubles arise when moving the cameras up/down. Due to the 30 degree rotation of the 3D camera I can't get their view frustums to overlap perfectly. This results in the 3D content moving a bit faster than the 2D content, resulting in this image (when I move my camera up/down):

GFYCat sample

As you can see, the distance between the car's top and the street is not the same anymore.

My question is, how do I make the 3D camera's frustum match the 2D camera's, but at the same time including the 3d degree rotation.

It'd be awesome if someone could point me in the right direction.

Cheers
Philipp


texts: Game/Level Design Career translations in other fields

texts:
Although I would love to get a job in the gaming industry I can't help but feel I should have a backup plan.  What I wanted to ask is game/level design a marketable skill that translates to other industries?

For example if your a programming in game development, you can be a software engineer in business, health care, finance, scientific etc, industries

If your an artist in game development, you can be an graphic artist, web designer, animator, advertisement, etc.

Do game/level designers have other industries they can get into other than gaming?  If you think so, what are some industries that level design (or game design) would be marketable for?


texts:
I added some screenshots above. When I run the game obstacle are falling rapidly through y axis. So, there's no more obstacle in that ground. If there's ground than those obstacle should stopped. I tried by freezing them. But, when another object hit them they are froze. So, I want ground to stop them. I have another question also. I have player movement. When I will run the program. The Player should be go through z axis. But, The object(player) don't move.
PlayerMovement.cs
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public Rigidbody rb;
    public float forwardForce=2000f;

    void FixedUpdate()
    {
        rb.AddForce(0,0,forwardForce * Time.deltaTime);
        if(Input.GetKey("d")){
            rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }else if(Input.GetKey("a")){
            rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
        }

        if(!Input.touchSupported)
        {
            // Still support PC keys
            if(Input.GetKey(KeyCode.D))
            {
                rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
            else if(Input.GetKey(KeyCode.A))
            {
                rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
            }
        }
        else
        {
            // For touch devices
            if(Input.touchCount == 1)
            {
                var touch = Input.GetTouch(0);
                var touchPos = touch.position;

                var isRight = touchPos.x >= Screen.width / 2f;

                if(isRight)
                {
                    rb.AddForce(30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
                else
                {
                    rb.AddForce(-30 * Time.deltaTime,0,0, ForceMode.VelocityChange);
                }
            }
        }

        if(Physics.Raycast(transform.position,Vector3.down,0.5f)==false){
            // rb.velocity = new Vector3(0, rb.velocity.y, 0);
            rb.constraints = RigidbodyConstraints.FreezePositionZ;
        }else{
            rb.constraints = RigidbodyConstraints.None;
        }

        if(rb.position.y < -1f){
            FindObjectOfType<GameManager>().EndGame();
        }
    }
}

PlayerCollision.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class PlayerCollision : MonoBehaviour
{

    public PlayerMovement movement;

    void OnCollisionEnter(Collision collisionInfo)
    {
        Debug.Log(collisionInfo.collider.name);
        if (collisionInfo.collider.tag == "obstacle")
        {
            movement.enabled = false;
            FindObjectOfType<GameManager>().EndGame();
        }else if(collisionInfo.collider.name == "END"){
            FindObjectOfType<GameManager>().CompleteLevel();
        }
    }
    void Restart(){
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}

If you look at above source code clearly. So, you might see that I have a Debug.Log right there. But, when I run the game. I don't get any message to console.
As a new game developer(learning) I don't know what's happening, what's wrong with this.


texts: How to fold a view from 2 3D cameras in Unity?

texts:
I need to combine view from 2 or more 3D static cameras. Let's say I have 3 humans standing in line side by side.

The first camera is viewing the left person and the left half of the middle person.
The second camera is viewing the person on the right and the right half of the middle person.

Now I need to see the whole middle person.

Any ideas how I can do this?

I don't need to see code or some finished implementation, I just need some ideas, because I can not find anything on this.


texts:
Where is the Try Get Pawn Owner node located in BP? I can't find it anywhere. I'm following the answer here but cannot find this node anywhere. Using version 4.11.2.

Thanks!


texts:
I'm using unity to raycast a line from the center of my camera viewport to a world position (yellow line).

I also want to cast a ray from the center of my character to this same point (blue line).

I have tried two methods to get this to work, however neither has worked.

The two methods are the following:

        if (Input.GetKey (KeyCode.Mouse0)) { //if left click is held down

        Ray crosshairPoint = viewCamera.ViewportPointToRay (new Vector3(0.5f, 0.5f, 0.0f));
        Vector3 crosshairEnd = (crosshairPoint.origin + crosshairPoint.direction * 15);
        Debug.DrawRay (crosshairPoint.origin, crosshairPoint.direction * 20, Color.yellow, Time.deltaTime, false);
        Vector3 intersect = crosshairPoint.GetPoint (20);
        Debug.DrawRay (Vector3.zero, intersect, Color.red, Time.deltaTime, false);

        Debug.DrawRay(_charFace.position, intersect, Color.cyan, Time.deltaTime, false);

    }

The red line being drawn is a line from the origin, which has no problem intersecting my camera ray line. The one from my character just refuses to point at the given point.

The second method is the same as above, but using vector math (origin + direction * distance) to get the same point.

Any ideas why the ray from my character won't point the right way, but one from the origin would? Something to do with world vs. local coordinates?

Thanks]1


texts: How can I tactfully ask users to help support my free game?

texts:
So, I have a game that has a few dedicated users, but very few actual users. It is a free game on the Android marketplace, supported via ads. I've been toying with the idea of periodically popping up a notice to users encouraging them to do stuff like:

Look at the ads presented.
Write positive reviews in the Android Marketplace.
Encourage their friends to play.

Right now, I have it set up in a not released version to do this once every 5 games, once the user has played at least 10 games, unless they are clicking on ads periodically. I am not letting the user know this, I don't want them to click on ads just to get the popups to stop.

Basically, I'm needing a bit more motivation from the users to keep going to the next level, and I'm letting them know what I would like from them.

Is this going to end up helping me out, or am I just going to get myself buried even more? Thanks!


texts:
Maybe I'm asking dumb question, but this problems bothers me...

So I have my networked game in Unity (client), and server written in C# (without Unity). I Use ENet library for networking. Most of networked components are written by myself (lobby, components etc.).

Server doesn't know about Unity entities like players, obstacles etc.
In most cases I send message ("hide object with id 4") to the server, and server pass that message to other clients where they applied message information.

What my problem is, how to assign proper IDs to networked objects, that will be the same across all players?

What I do is that:

On all clients I get all components with specific network component (e.g. NetworkRigidbody)
I sort all of objects using special comparer which compares based on component name with all parents appended to it
ID is just an index in sorted array

Above algorithm works, but I have a feeling that in normal games that problem is handled in other manner.

I searched over Mirror, MLAPI and other libraries source code and I couldn't find how entity id is generated, especially when server is not Unity application.


texts: How to make sure user is running the newest version of mmo client?

texts:
In typical mmorpg game, you have a launcher and a client. You first run the launcher to update the client, then you run the client. In every mmo I tried if you run a client without updating first (if update is available), it automatically closes and (usually) starts launcher.

My question is, how can you check if user has the proper version of client? I though about server asking client about its md5 however it's so easy to cheat. I think that there is no safe way of handling it yet every mmorpg I know uses such a system.

So how do mmorpg games handle this problem? To make sure that the client is at the newest version?


texts: How to approach dual skills in an rpg game

texts:
I am developing an rpg-sort of game.
My question is how a dual-tech system would work (like snes chrono trigger game had).
I already have coded how to use a single skill.

Probably not the best way to do it, but here is how i have it working right now:

I have a Skill class and in my level, I define a Skill currentSkill
When a skill is activated, the level starts rendering everything at half-speed except for the skill caster and the skill target.

Now what i am not really sure how to do is, how to structure my dual-skill class, and how to make this one's animation (which would include animating the 2 skill casters + skill targets) affect the initial skill cast.

The dual skill should be activated after a single skill is activated, eg. Character A casts skill a, which can be combined with character B skill b to produce skill c.

If that was somehow clear to you (think I complicated it) could you please provide some pseudo code / idea / example on how to achieve it?

EDIT:

I realize after reading the comments (and re-reading my question) that i was not clear on what I want to achieve, so I'll try to re-word myself
(non native english speaker, so sorry for the lack of grammar)

Some considerations :

It's not a multiplayer game so I will refer to the characters (or
"players") you can use as units.
Its some kind of rpg battle game ( it's pretty much a clone of the
mobile game battlehearts but with dual-skills added, if you have seen that, you can get a
pretty good idea on what game i'm working on).

basic idea:

Unit A casts skill a.
Unit B checks that he can combine its skill b with skill a.
Unit B casts skill b.
Unit A skill gets canceled
Unit B skill gets canceled
Unit A and B cast skill c.

here's some example:

Unit A is swordman (with a single-target critical-hit skill called
Bash)
Unit B is mage (with a skill called air strike).
bash + air strike = air slash ( skill that pierces and damages all
enemies in a line, for example)

.asd

swordman uses bash
mage "realizes" he can combine it with air strike
on mage, skill air slash gets enabled.
when used, air strike consumes bash's and air stryke's cooldown, but
executes a different skill (im talking about a different animation here, not sync'ing bash and air strike animations)

question is, how would you structure the code to achieve the above behavior? what kind of datastructure would you use
to store information about dual-skills?


texts:
I make fat cube "fbx" with blender and export it to unity. this fat cube not allowed texture to appears ! i make a small cube by unity and texture pop-up !
What is wrong ?


texts: Unity3D (2D) - Make sure Item Dragged Is Top Item Visually

texts: I am using Unity 5 and making a 2D game in which many sprites will be stacked on top of each other and can then be moved by dragging. Sometimes when the users goes to drag from a pile, ones that aren't on the top are dragged instead. Is there any way to make sure that the one that is dragged is the one on top? Thanks


texts: Is it possible to generate and solve a maze in one run?

texts: I'm using recursive backtracker or depth first fearch (correct me if it's not the same) algorithm to generate unique 2d mazes for my game. However for the gameplay I intend to implement the logic also needs to know the solution path from A,B-X,Y (to solve the maze). For that I intend to run a second process, that does that. I wonder if there is any chance to do in one run - generate and solve (to save some processing and load-times).


texts:
i have a gameobject that have a group of plane meshes that created randomly as child every one of this planes have a "2f" offset in x axis between every plane

what i wanna do is i wanna make the parent object arrangement the child objects on rows and columns even if one of this child deleted during the game or added so if i have 8 planes mesh it should look like that 2 rows and 4 columns like that but i don't know how to do that ?

i know how to get child objects and making offset but i do't know how to get the format like that in the image

i wanna to arrangement the planes meshes that i can acces from this for loop

 void Update(){
          Transform[] children = new Transform[transform.childCount];

                 //Debug.Log(transform.childCount);
                     for (int i=0; i<transform.childCount; i++) {
                         children[i]=transform.GetChild(i);

                     }
      }


texts: How to prevent a sprite to move in an angle that will lead to collision

texts:
I have two sprites that can move in any angle. The sprites are rectangular.

I created bounding boxes for both the sprites. These boxes rotate whenever the sprite rotates. They always surround the sprite and only the sprite. (Exact fit).

I have succesfully implemented collision detection for the two bounding boxes. I did this by checking wether box1 contains any of the vertices of the box2, and the opposite. (I know this way is not perfect, since it is possible for two rectangles to intersect without having each other's vertices inside themselves, but for my needs it's good enough).
So now I know when the two sprites collide.

But I have a problem with reacting when the two sprites collide.

When these sprites collide, I want to prevent them from overlapping each other (any more than a few pixels). In other words, upon collision, I want to allow the sprite to move only in a direction where it won't go deeper into the other sprite.

As I said, each sprite can move freely in any angle (the game is for two players, each controls a sprite).

EDIT:
To word it differently - Upon collision of two sprites, I need to find out the range of angles a sprite can move, that will allow it to to move out of the collision - this is so I can prevent the user from moving the sprite in any other angle, upon collision.

How can I do that? Thank you for your help


texts: What's the use of the xyY colorspace in games? I'm not sure what's the advantage of using it in shader programming or elsewhere.


texts:
I am trying to copy data over from a binary file but when trying to instantiate a gameobject, it comes out as "null".

static void LoadBuildings(SaveBuilding[] buildings)
    {
        if (buildings.Length == 0)
            return;
        foreach(SaveBuilding b in buildings)
        {
            if(b.type.ToString() == "Farm")
            {
                Farm build = Instantiate(Resources.Load("Farm")) as Farm;
                Debug.Log("Build: " + build);
                build.position.x = b.positionX;
                build.position.y = b.positionY;
                build.level = b.level;
                build.levelText = build.GetComponentInChildren<Text>();
            }
        }
    }

The debug line shows there is no object and when the next line tries to execute I get an error ArgumentException: The Object you want to instantiate is null.

I initially had it as Farm build = Instantiate(build.prefab) as Farm; as I get an error "Use of unassigned local variable".

I tried adding a prorperty above the if statement "GameObject build", I tried doing Farm build = new Farm() above the if statement also but still get the initial error.

I have a folder titled "Resources" and confirmed a prefab labelled "Farm" is there also.

Could it have anything to do with the "static" prefix for the method?


texts:
So, I intercept the WM_KEYDOWN and other messages.

Thing is, my game can't/shouldn't react to these messages just yet, since my game might be currently drawing to the screen or in the middle of updating my game entities.
So the idea is to keep a keyboardstate and mousestate, which is updated by the part of my code that intercepts the windows messages. These states just keep track of which keys/buttons are currently pressed.
Then, at the start of my game's update function, I access these keyboard and mouse states and my game reacts to the user input.

Now, which is the best way to access these states? I assume that windows messages can be sent whenever, so the keyboard/mouse states are constantly being edited. Accessing say a list of currently pressed keys in the keyboard state the same time another part of the code is editing the list would cause problems.

Should I make a deep copy of a state and act on that?
How would I deal with the garbage generated though, this would take place every frame.


texts: Per pixel collision for scaled textures in Monogame Windows Phone 8

texts:
I have some serious trouble with pixel-collision in my game. I am using the Matrix Scale parameter in Spritebatch.Begin method, to scale the content for each device's resolution correctly.

SpriteBatch.Begin(
  SpriteSortMode.Deferred,
  null,
  null,
  null,
  null,
  null,
  Managers.ResolutionManager.ScaleMatrix );

I am using Per Pixel Collision detection, because I have transparent textures, and I want to make the exact collision between moving textures.
On the resolution, that the game was initially, made for: 800 x 480 the per/pixel collision is working perfectly, but when I am testing on a real device, with resolution 1080 x 1920 (lumia 930) or on any bigger resolutions than the initial one, the per pixel collision doesn't work properly.
I, as a player, can pass through moving textures without colliding, at the good point.

I have made the adjustments for moving texture's rectangles, if the game is playing on bigger resolutions, but still, any difference.

Here is my Per pixel collision function:

public bool CheckCollision(
  Rectangle rect1,
  Rectangle rect2,
  Color[] textureData1,
  Color[] textureData2)
{
  if (rect1.Intersects(rect2))
  {
    int top     = Math.Max(rect1.Top, rect2.Top);
    int bottom  = Math.Min(rect1.Bottom, rect2.Bottom);
    int left    = Math.Max(rect1.Left, rect2.Left);
    int right   = Math.Min(rect1.Right, rect2.Right);

    for (int y = top; y < bottom; y++)
    {
      for (int x = left; x < right; x++)
      {
        Color color1 = textureData1[(x - rect1.Left) + (y - rect1.Top) * rect1.Width];
        Color color2 = textureData2[(x - rect2.Left) + (y - rect2.Top) * rect2.Width];

        if (color1.A != 0 && color2.A != 0)
        {
          return true;
        }
      }
    }
  }
  return false;
}

Here are the rectangles, this player's rectangle

TextureData = new Color[(int)(
  Texture.Width *
  Managers.ResolutionManager.MatrixX *
  Texture.Height *
  Managers.ResolutionManager.MatrixY)];

Texture.GetData<Color>(
  0,
  new Rectangle(0, 0, frameWidth, frameHeight),
  TextureData,
  0,
  TextureData.Length);

Bound = new Rectangle(
  (int)((Position.X - frameWidth / 2) * Managers.ResolutionManager.MatrixX),
  (int)((Position.Y - frameHeight / 2) * Managers.ResolutionManager.MatrixY),
  (int)(frameWidth * scale * Managers.ResolutionManager.MatrixX),
  (int)(frameHeight * scale * Managers.ResolutionManager.MatrixY));

And this is obstacle's:

TextureData = new Color[(int)(
  Texture.Width *
  Managers.ResolutionManager.MatrixX *
  Texture.Height *
  Managers.ResolutionManager.MatrixY)];

Texture.GetData<Color>(TextureData, 0, TextureData.Length);

Bounds = new Rectangle(
  (int)(Position.X * Managers.ResolutionManager.MatrixX),
  (int)(Position.Y * Managers.ResolutionManager.MatrixY),
  (int)(Texture.Width * Managers.ResolutionManager.MatrixX),
  (int)(Texture.Height * Managers.ResolutionManager.MatrixY));

Basically, it is almost the same code.

In my opinion it has to be something in CheckCollision function, because I checked the collision only with rectangles and it worked.

I'm out of ideas; any solution?


texts:
I've been trying to think of ways to approach doing a pipe style game like the one pictured below, but am coming up short.
The pic is from Star Trek Elite Force 2, the hacking minigame part. I've never played the game, but found this particular part via a search.

The player must click on to turn each pipe section and get a path between the blue nodes, while not connecting to any red nodes.
I assumed the way to create the pipe route is to begin from the end node and generate a path towards the starting node, then obscure the path with branches. But on trying this, the path is very obvious (pic added below), so I'm looking for other ideas.
Does anyone have any pointers to set me in the right direction?


texts: SDL2 application occasionally refuses to close

texts:
I've been working on a sliding puzzle/game of fifteen clone in SDL recently. A problem I've had is that when I close the game the app isn't always removed from the dock and I can't force quit it. It shows up in task manager, but doesn't show up in Activity Monitor so I can't quit the game from there and end up having to hard reboot.

I can't find any pattern as to why it happens some times and not others. I thought there might be something wrong with my cleanup of SDL but I can't find any problems, although I'm honestly not sure what to look for. The full source code for this project can be found here. Thank you


texts: Java 2d Gaming, best practice to update random falling objects

texts:
I'm new to game development. I do have basic knowledge in Java and also have moderately good experience in OOP from other languages.

I started developing this simple 2D game as my first project.

The game is simple, I have a character, I can move only right and left with constant speed.

I want to add obstacle objects that fall from the sky (top) that I have to dodge. I created the main class (StartingClass) that contains the game loop. receives input from the user's keyboard and moves the character accordingly.

I created a Character class which describes the character position, and reflect its position with painting its image.

Everything is well. However, I'm now trying to add the falling objects. My delima is how to implement them.

I started by creating a new class (FallingObject). In the instructor I create its width, height, falling speed.. etc (randomly). The issue I'm having is to determine how to update this object's position. I would have created an update method for the object and call it every time in the game loop to update its position. But my problem is I will have multiple objects falling simultaneously, each with different speed. So these are the solutions that came to my mind:

Visible/Active falling objects will be stored in an array list *

1) on every game loop, iterate over the falling objects and update them individually, which doesn't sound that friendly to me.

2) In the falling object instructor, when finished assigning the random values, call a synchronized "startFalling" method on the object, so it keeps falling until it hits the ground.

3) My FallingObject class would implement the runnable interface, and run the function described above through thread. But still... thread for each falling object? I'm not liking that idea.

So I would like to know if I'm somewhat in the right direction in my way of thinking to solve this issue, and which of the above suggestions you think is best, or if there's way better solutions (which I believe is true) that I'm unable to see due to my limited experience in game development design / java.

Thank you very much for your help and support!
Cheers
Shady


texts: Timing of coroutines in Unity is never precise

texts:
I was looking an official example for coroutines in Unity here.

However, when I call WaitAndPrint the time taken is never exactly 5 seconds.

IEnumerator WaitAndPrint()
{
    float timeStart = Time.time;
    yield return new WaitForSeconds(5);
    Debug.Log(string.Format("Time taken = {0}", Time.time - timeStart));
}

if (Input.GetKeyDown(KeyCode.R))
    StartCoroutine(WaitAndPrint());

Instead, it varies around 5.003133.

This is most likely down to the frame rate, which makes me wonder how can I make sure that a coroutine takes the precise amount of time it should take despite the fluctuating frame rate?


texts: Creating force shields: the most efficient way of deforming/reshaping a simpler convex mesh so it envelopes a complex mesh?

texts:
So, the best way I can think of how to explain what I need is the following (images used here are just random images found trough google image search).

What I am trying to create during run-time is pretty much the same as a force shield that envelopes a robot or a space ship in many different futuristic types of games.

However, considering that these robots or ships have a shape that is unknown in advance, I don't want to just use a sphere-mesh around the ship or just assign a shield-shader directly to the ship mesh like in the pictures below:

I want to end up with a shield that is formed by a mesh that loosely represents the shape of the ship. Something like what can be seen in the pictures below:

However, I don't need those shields to be concave like in that pictures. It can be a convex mesh.

So far, what I've tried was to generate a sphere or a cylinder around the complex mesh (robot/ship), loop trough each vertex and try to approximate to the complex mesh. However, that is severely inefficient and gives non-smooth results.

Would you happen to have any idea, code sample, tutorial links, article references or anything on how can I proceed to get what I want in an efficient manner? The shields do not have to very detailed in terms of polygons. In fact, the less the better.

I am currently using C#, but I can handle C++ as well. Thanks in advance.


texts:
I am experiencing difficulties trying to figure out the correct multiplication order for a final transform matrix. I always get either strange movement or distorted geometry. My current model is explained below:

For a single node my multiplication order is:

  L = S * R * T

where

  L = local transformation matrix

  S = local scale matrix

  R = local rotation matrix

  T = local translate matrix

For a node's world transformation:

  W = P.W * L

where

  W = world transformation matrix

  P.W = parent world transformation matrix

  L = the local transformation matrix calculated above

When rendering, for each node I calculate the matrix :

  MV = Inv(C) * N.W

where

  MV = the model view transformation matrix for a particular node

  Inv(C) = the inverse camera transformation matrix

  N.W = the node's world transformation matrix calculated above.

Finally, in the shader I have the fallowing transformation:

  TVP = PRP * MV * VP

where

  TVP = final transformed vertex position

  PRP = perspective matrix

  MV = the node's world transformation matrix calculated above

  VP = untransformed vertex position.

With the current model, child nodes which have local rotation, rotate strangely when transforming the camera. Where did I go wrong with the multiplication order?


texts: How should I adjust starting sample position of audio track to match next buffer fill?

texts:
I've written my own audio mixer. For Linux/Windows, my game uses SDL. On a small handful of Linux machines (including my laptop), SDL has a bug where it allocates a ridiculously large (about 120 milliseconds) audio buffer. While I'm not to the point that I care so much about affected machines, it points out a problem I'd like to solve.

The problem is that when an event occurs that triggers an audio track to be played, I've already written audio for a small portion of "the future." In other words, I can't really play something "now." If I wait until the next audio buffer fill and start playing this track at sample position 0, I will effectively create a small lag period before the track is heard. With the enormous buffer size mentioned above, this is very noticeable.

One approach I've come up with is to estimate how many audio samples the track would play between "now" and the next sample I can give to the audio buffer. However, this would be incorrect if the game were to be paused/resumed or even slowed down, and this introduces some added complexity to the mixing code.

Is there a standard way to solve this problem, and/or do you have any helpful ideas?


texts: What makes aiming in a console first person shooter feel good?

texts:
I think it's pretty much universally agreed that simply mapping the analog stick to rotational speed of the character is not good enough to make console first person shooter feel good.

So what are some input paradigms that make a modern FPS on the console work well?


texts: Can XNA's content pipeline be used to load C# source files?

texts:
I am wondering if its possible to use the XNA Content Pipeline to load C# files?

I'm working on a game and am currently writing a FSM. I would like to be able to load states from the content pipeline, but the states would be written in C# and must use my interface.

Anyone know how to do this?


texts: Problem with the Layer System/Tilemap Layer from Unity

texts:
This is my first time using Unity (and my third time creating a game in general), so I hope I can provide the needed information to solve this problem.

My character overlaps with the upper wall, but doesnt with the lower wall. This is the right behaviour given the layers (seen in the picture). But I want him to be behind the lower wall AND in front of the upper wall.

Side Information:
 - The Wall Tile is one piece, which covers two tiles.
 - Movement is depended on the existents of a ground tile. The reason behind this is, that I wanted the character to always move one tile at a time. And since this is my first time with unity, that was the easiest way of doing it. So there is no actual interaction with the wall. No collsions or anything.
 - There are three Layers (Ground, Creature, Wall) and two tilemap layers (Ground and Wall) (see picture) and the character doesnt interact with the tilemaps at all, he just gets drawn above the ground tilemap layer.

What I see as answers:
 - Split the wall tile into two tiles and let the wall part be on another layer, then the roof part.
 - Split the character into two parts and do the same thing.
Both seem like a good way of solving it, but I dont even know where do start there. I think I can split the walls into two tiles, but I dont know if this is a good way to solve this issue. The other option, to split my character, there I really dont know where to start.

What I tried:
 - Trying around with layers and order in layers.
 - Trying around with the tile atlas (adding the sprite, removing tiles)


texts: Benefit of using Vector2 data type over separate x & y variables

texts:
I'm really curious about why a lot of people and game engines use Vector2 as its coordinate system instead of the traditional x and y value.

Is there any benefit to this?

I feel like it's just slow me down and barely has any benefit other than organizing your code.


texts: Why does my Unity/Android game get a small amount of lag when not being touched for some time?

texts:
I have made a 3d version of space invaders. I made all the assets myself in Blender. I feel that it's a very basic game and my Galaxy Note 3 test device should handle it no problem. (Although it's a few years old now so perhaps some kind of shader issue or something that my phone not updated enough for ?)

There are 55 enemies all with one mesh each. There's the flying saucer model and the player model.

Then there's a plane for a background, and 4 defensive meshes (although I've tested without these and the result is the same).

Basically, it all runs superbly (I have turned down much of the lighting and graphics quality etc, but have left basic shadows in). However I notice that if the player just lets the phone sit there in game without touching it, there is very slight (but noticeable) frame lag.

All the enemies have a very short animation which moves its arms a small amount.

I could post the code but its massively unorganized and really quite an embarrassment (HAHA!). Also I'm not sure what parts are relevant so it would be a huge post.

Is there any known issues that can cause the lag only when not being touched? As I feel like some of my old projects might have had this happening too but they've been deleted now unfortunately so I can't really dabble with it.

It works smooth as silk in the Unity Editor Android 'emulator' and as I say, if I actually play the game on my phone it's smooth too.


texts:
I was talking to a friend the other day and we got onto the discussion about colors in videogames, relating to actual in-game graphics/art. He told me that even though it's easy to see things when everything's brightly colored, sometimes it's better to use dulled or faded colors, especially for things that you might see all the time (like walls or crates or rocks.)

The question I have is, does it matter too much if I have a lot of bright, lively colors for game graphics/art? Or should I tone it down to less lively, dull colors? Does it even matter too much, or can something like this only be evaluated on a game-by-game basis?


texts: Is there a game engine that does not use D3D or OpenGL?

texts: Is there a game engine that does not use a graphics API such as OpenGL or DX? I want a simple 2D game engine for use in my simple game console.


texts: How do i find the circumsphere of a tetrahedron?

texts:
I'm looking for the most minimized equation to find the center coordinates and the radius of a tetrahedron circumsphere given four 3D points.

What I found on the internet mainly deal with the circum sphere of a flat 3D triangle, or some rough mathematical definitions, or some very single case such as regular tetrahedrons. Anyway I managed to find the equation below but I missed something :

    ->  ->      ->
let d1, d2, and d3 three vectors of any face of the triangle :

    | d1x  d1y  d1z |   | x |   | d1^2 |
2 * | d2x  d2y  d2z | * | y | = | d2^2 |
    | d3x  d3y  d3z |   | z |   | d3^2 |

My knowledge in this field has its limits but I think I can handle matrices and vector operations. But is the right part of the equation the square of the norm of each vectors ? (which are into a vector). Is the equation valid ? Is it just the writer who lazely forgot to write |d1|^2 ? Or Is it a common way to define some mathematical property.

PS : It's for a Delaunay Triangulation implementation. The equation (number 9) is in the following link : https://www2.mps.mpg.de/homes/daly/CSDS/t4h/tetra.htm


texts: How to create a split screen display with one frame and canvas

texts:
I am creating a 2D Java game, which looks like this:

My question is what should I do to my display to create two 'separate' displays.
I plan on doubling the height of the program, and have a second display which is able to render completely separately to the top display. I'd like it to look like this:

I would like to not have to click between the two displays to be able for them to recognize input. I think this could be done by just keeping one canvas and just commanding the canvas to draw in certain areas? I also am not planning on using any external libraries.

Game class: (Some irrelevant code removed)

public class Game implements Runnable {

private Display display;
private int width, height;
public String title;

private Thread thread;
private boolean running = false;

private BufferStrategy bs;
private Graphics g;

public State gameState;
public State menuState;

private Handler handler;

public Game(String title, int width, int height) {
    this.width = width;
    this.height = height;
    this.title = title;
}

private void tick() {
    // Ticks the current game state
    if(StateManager.getState() != null) {
        StateManager.getState().tick();
    }
}

private void render() {
    bs = display.getCanvas().getBufferStrategy();
    if(bs == null) {
        display.getCanvas().createBufferStrategy(3);
        return;
    }
    g = bs.getDrawGraphics();

    //Clear screen
    g.clearRect(0, 0, width, height);

    // Gets the current game state and runs its render method
    if(StateManager.getState() != null) {
        StateManager.getState().render(g);
    }

    // End drawing
    bs.show();
    g.dispose();
}

// Initialize the display, assets, and game states
public void init() {
    display = new Display(title, width, height);
    display.getFrame().addKeyListener(keyManager);
    display.getFrame().addMouseListener(mouseManager);
    display.getFrame().addMouseMotionListener(mouseManager);
    display.getCanvas().addMouseListener(mouseManager);
    display.getCanvas().addMouseMotionListener(mouseManager);

    Assets.init();

    handler = new Handler(this);

    gameState = new GameState(handler);
    menuState = new MenuState(handler);

    StateManager.setState(gameState);
}

public void run() {
    init();

    // Some unimportant code is removed for sake of space
    while (running) {
        tick();
        render();
    }

    stop();
}

}

Display class:

public class Display {

private JFrame frame;
private Canvas canvas;

private String title;
private int width, height;

public Display(String title, int width, int height) {
    this.title = title;
    this.width = width;
    this.height = height;

    createDisplay();
}

private void createDisplay() {
    frame = new JFrame(title);
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    canvas = new Canvas();
    canvas.setPreferredSize(new Dimension(width, height));
    canvas.setMaximumSize(new Dimension(width, height));
    canvas.setMinimumSize(new Dimension(width, height));
    canvas.setFocusable(false);

    frame.add(canvas);
    frame.pack();
}

public Canvas getCanvas() {
    return canvas;
}

public JFrame getFrame() {
    return frame;
}

}

Launcher class:

public class Launcher {

private final static String TITLE = "Game";
private final static int WIDTH = 256;
private final static int HEIGHT = 192;

public static void main(String[] args) {
    Game game = new Game(TITLE, WIDTH, HEIGHT);
    game.start();
}

}


texts: Benefits of upgrading from OpenGL ES 1.1 to 2.0 on iOS

texts:
I have an animated 3D iPhone game that I first wrote using OpenGL ES 1.1 in late 2009.

After many updates to the rest of the game, the OpenGL ES 1.1 code still runs fine under iOS 6, but I'm wondering about benefits to 2.0 that I'm missing out on, and whether it is worth converting to. I don't care about backwards compatibility with devices unable to support 1.1.

I've read this post and this post on the sister site, but some information there is no longer applicable, and I would like a perspective specifically from a gaming programmer's point of view about whether it's worth updating, rather than which I should use if I were doing it from scratch.

Thanks for your help.

[Edited to answer comments below]

This is the project. I don't need shaders, textures, or anything ES 1.1 doesn't do in some fasion (at least for a while), but would be tempted to upgrade if for example 2.0 just does it much better, or is much faster, or does something that's just so useful and/or awesome that it would be criminal not to take advantage of it, or 1.1 has some awful bug on a device that I haven't had a chance to test on.


texts: Reduce the number of edges of a graph, keeping it connected

texts:
I'm designing a game with random generated dungeons. I'd like to view this as a connected, undirected graph in which nodes are rooms and edges are doors or corridors. Then I choose a "side" node as the dungeon entrance, I calculate the distance between this entrance and all other nodes, and decide that one of the farthest nodes is the "goal" of the dungeon (the location of the treasure, boss, princess, etc.).

I saw 2 ways to generate the final dungeon topography:

Generate first a random graph, then try to fill the 2d world with rooms at random locations, respecting the edge connections. I figured this would be sometimes difficult because the room generation could be "locked" trying to fit rooms in impossible places.
Generate first rooms, placing them randomly where they fit, then map the result to nodes and edges. I decided to try this.

My idea consists in :

First generate a big room that would contain the whole dungeon.
Put a wall inside the big room, at a random location, dividing the big room into 2 smaller rooms of different area.
Then I continue to divide each room into 2, until they are too small, or the total number of room reach a maximum (or any other condition). Each new room is a node.
Once finished, I check each room and find all adjacent other rooms, marking the 2 nodes as connected by an edge.

That way I ensure that all rooms have a possible location in the 2D world, and are correctly mapped by a connected graph.

My problem is that there are too many doors and corridors connecting the rooms.

So I'd like an algorithm that reduces the number of edges of a connected undirected graph, but keeping it connected (all nodes stay reachable) in the end.


texts: For a custom game engines, what should I do if my core data is malformed or missing?

texts:
I'm writing a custom engine for a game. I started this game well before I understood why I should use middleware, instead, and it's too far along to rewrite.

The vast majority of my data comes from external files, and I don't just refer to assets; I define all of my game objects through .JSON.  But, alas, I am human; occasionally my data files are invalid, or I change the format but forget to update the file, or the loader itself is flat-out buggy.

If, for whatever reason, an attempt to load some form of asset in a custom engine fails, what options do I have?

This is not a duplicate of How should I handle missing resources?, as that question is about user-facing assets like models or textures.  Bad textures can be replaced with a checkerboard, bad sounds with silence, and bad text with "ERROR".  My problem lies with data that's critical to the game even running, such as levels, game object definitions, and GUI layouts.


texts: How do I calculate NDC coordinates in a fragment shader?

texts:
I have some weird problem going on in my openGL shader.

First,, I pass the viewspace position from the vertex shader to the fragment shader like this:

vec4 view_pos = V * M * vec4(world_position.xyz, 1.0);

Then, in the fragment shader, I do this:

vec4 clip_pos = P * view_pos;
vec2 ndc_xy = clip_pos.xy / clip_pos.w
vec2 ndc_fragcoord = 2.0 * gl_FragCoord.xy / viewport_wh - 1.0

I would expect that ndc_xy is the same as ndc_fragcoord; however, when rendering them to textures, they are not nearly the same:

Can someone explain to me the differences? How can I get the same result in ndc_fragcoord by using view space position or vice versa?

This is important information for me for a later stage, when reconstructing the view space position from the depth. I have already been sitting on this the whole day, and am close to despair.


texts: Is there a SDK for 2D games that will deploy to PC, Flash and Android?

texts: Is there such thing as an SDK or toolset that can produce Windows, Flash, and Android executables from the same source? Something like "write once, run in all three platforms?"


texts: How to make planets "stay together" on collision

texts:
I working on a 2D planetary orbit simulator and I've encountered a problem regarding the collision of planets. Currently, here is what I have

if self._dist_between(p1.pos, p2.pos) <= p1.radius + p2.radius:
    pass

I detect the collisions but I don't know how to resolve them. I don't want the planets to bounce or do anything fancy, I simply want them to not pass through one another. I have tried disabling their movement completely on collision but this fails to work when more than 2 planets are active in the simulation, as when 2 planets collide they freeze in time rather than continue to be affected by the other planets.

This is the code that manages the movement

 def update(self):
    for p1 in self.planets:
        for p2 in self.planets:
            if p1 != p2:

                # Calculate and apply force
                temp_force_vector = [
                    self._gravitational_force(p1.mass, p2.mass, self._dist_between(p1.pos, p2.pos)),
                    self._radians_between(p1.pos, p2.pos)
                ]

                if self._dist_between(p1.pos, p2.pos) > p1.radius + p2.radius:
                    p1.apply_force(temp_force_vector)

                p1.update_pos()

Any suggestions?


texts: Allegro: slow drawing lots of images in 2d sandbox

texts:
I want to know if there is any better way to do this. But i want to make a game where its 2d and made of blocks. But a test that draws blocks to the screen and its going so slow that its not even taking keyboard events anymore.

Is there a way to optimize drawing? Or save predawn parts of the map and pan it across the screen when the player moves?

the code is probably unnecessary. But basically im drawing it and p

for (int y = 0; y != Vertical_Block_count; y++)
           {
    for (int x = 0; x != Horizontal_Block_count; x++)
al_draw_bitmap_region(Bitmap, Sprite_Selected * BlockSize, BlockSize * sprites_on_sprite_sheet, BlockSize, BlockSize, x * 16 - 16, y * 16 -16, 0);
            }
    al_flip_display();


texts: Convert Canvas Space point to local space of a rotated rect?

texts:
I got a quite tricky problem:

I have my mouse position and my rectangle position in canvas space(screen space but with adjusted scaling). Now I want my mouse position converted to local space of the rectangle. Problem is, the rectangle can be rotated. Without rotation its quite simple and works nicely.

Heres a graphic for better demonstration:

Edit3: Got it finally working. I messed up with a minus in the calculation instead of using a +. Also the hierarchy of the image in unity was incorrect. Lastly I had to change the rotation from CCW to CW(Thanks unity for using CCW in your UI...). This is my final solution:

Code Unity C#:

    var mapRect = MapContentTransform.rect;

    // Canvas Space Map Center
    var mapPositionCenter = CanvasRectTransform.InverseTransformPoint(MapContentTransform.position);
    mapPositionCenter.x += CanvasRectTransform.rect.width / 2.0f;
    mapPositionCenter.y += CanvasRectTransform.rect.height / 2.0f;
    // Mouse Position in Canvas Space
    Vector2 mousePositionCanvasSpace = CalculateScreenspacePositionCanvasSpace(new Vector2(Input.mousePosition.x, Input.mousePosition.y));

    // Rotation angle of the Map in Radians
    float theta = -(MapContentTransform.eulerAngles.z - 360.0f) * Mathf.Deg2Rad;

    var rotatedX = ((mousePositionCanvasSpace.x - mapPositionCenter.x) * Mathf.Cos(theta) -
                   (mousePositionCanvasSpace.y - mapPositionCenter.y) * Mathf.Sin(theta)) + mapRect.width / 2.0f;

    var rotatedY = ((mousePositionCanvasSpace.y - mapPositionCenter.y) * Mathf.Cos(theta) +
                   (mousePositionCanvasSpace.x - mapPositionCenter.x) * Mathf.Sin(theta)) + mapRect.height / 2.0f;

Thank you Kyy13!


texts: How do I detect image clicks in Dark GDK?

texts:
I am trying to determine if an image has been clicked, using the Dark GDK game engine. I've found no methods in the engine that do this.

I would rather not brute force this with a large nested if/else structure. I was thinking of setting up a container that takes an object which records the mouse position when clicked, as well as a bool value to determine if the image has already been clicked.

I apologize for not adding any example code here; I don't know how I would go about setting something like that up.


texts: How can I recreate the movement of arrow in air?

texts:
Given two Particles A and B which forms the arrow itself, A.P an edge of it and the opposite one B.P. Like so A.P---------B.P.

const float DistArrow = 60;

Where I have structure Particle:

struct Particle
{
    struct Complex P; //Position
    struct Complex F; //Gravitational Force
    struct Complex V; //Velocity
    float m; //Mass
}

At the start each particle, A and B has a starting Velocity of like (40, 70). And I am adding a value of force to A.F(0, -9.21) and B.F(0, -9.81). So that the B.F has much more weight on it, so it drags the A to down kind of.

I want the arrow to move like this:

And I am tried to figure out how to make till I was stuck with this(I am trying to calibrate in a way the arrow to the initial DistArrow:

A = erA->B*(D(AB)-DistArrow)/2+A; where erA->B(unit vector) = (B-A)D(AB);
B = erB->A*(D(AB)-DistArrow)/2+A; where erB->A(unit vector) = (A-B)D(AB);

The problem is that it just rotates 180 degree, dunno why it does, if it will infinitely fall it should be A at the top of B, a line perpendicular with oX.

I am seeking a good solution not involving to much physics, any advice will be highly appreciated.


texts: Is it bad form to use singletons in unity

texts:
I've heard a lot of people say singletons are bad practice and an 'anti-pattern',
like here,
this answer
this article
and here.
However, a lot of the reasons I've read about seem to be to do with dangers in their creation, them not being thread safe, difficult to destroy safely etc. But in unity where there are functions such as awake() and start() which are (as far as I'm aware) guaranteed to only be called once, are they unsafe to use?


texts: Unity detect tap on object or area with Raycast turned off on the object

texts:
I have a large dial which can be rotated by touch. I have a circular crosshairs at the top to show which number is selected. I have had to turnoff the Raycast Target on the crosshairs because it was stopping the dial rotation when the when the finger touch was moving over it.

My problen now is that when the desired number is selected in the crosshairs I want to be able to tap the crosshairs to go to that level. Is it possible to detect the tap on the crosshairs?

Here is the code I have attached to the dial for rotation.The crosshairs is the very next GameObject in the hierarchy.

public void OnDrag(PointerEventData eventData)
{
    //CHECK IF CAN DRAG
    if (!_canDrag)
    {
       return;
    }
    transform.rotation = finalRotation;


texts:
I've been interested in the component based entity system for a while, and read countless articles on it (The Insomiac games, the pretty standard Evolve Your Hierarchy, the T-Machine, Chronoclast ... just to name a few).

They all seem to have a structure on the outside of something like:

Entity e = Entity.Create();
e.AddComponent(RenderComponent, ...);
//do lots of stuff
e.GetComponent<PositionComponent>(...).SetPos(4, 5, 6);

And if you bring in the idea of shared data (this is the best design I've seen so far, in terms of not duplicating data everywhere)

e.GetProperty<string>("Name").Value = "blah";

Yes, this is very efficient. However, it isn't exactly the easiest to read or write; it feels very clunky and working-against-you.

I personally would like to do something like:

e.SetPosition(4, 5, 6);
e.Name = "Blah";

Though of course the only way to get to that kind of design is back in the Entity->NPC->Enemy->FlyingEnemy->FlyingEnemyWithAHatOn kind of hierarchy this design tries to avoid.

Has anyone seen a design for this kind of component system which is still flexible, yet maintains a level of user friendliness? And for that matter, manages to get around the (probably the hardest problem) data storage in a good way?

What designs are there for a component based entity system that are user friendly but still flexible?


texts: Continous collision happening in Unity2d

texts: I am working on Unity2d. I have a game object called gameobject1 on screen. It holds an image (named "state"). When I drag a tree on a gameobject1 collision is happening continuosly in the same layer instead of once. I already added Physics2Ds component Rigidbody2D on to tree object. Is there any solution for this issue?


texts:
I'm new to virtual environments, having worked mostly with Arduino and other physical applications. I'm trying to set up VRPN server on one of the computers in my lab to pass some triggers from a Unity game to a VR environment and there is little to no documentation that a novice can at least hack through to explain how VRPN even works.

Can anyone shed a little light on it and explain how to set up a VRPN server using c#?


texts:
I have a object in my game that when the main character hits it, all I want to do is have the object explode and then notify the character object that a hit has occurred.

Would I use a b2Body and set it as a sensor for this or would I achieve this some other way?

I'm using cocos2d by the way.


texts:
I'm using Unity 2D for my game and I'm facing a weird problem. I have a GameObject (an image) in my scene with a button attached to it. When the player is out of the screen, the image that works as a GameOver panel appears and in case of enough coins, you can resume the game. Everything works fine but when the image appears and I click on button to resume, the image doesn't disappear while the function for decreasing number of coins still works.

Here is my script in which di() is for die and but() for button:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CodeStage.AntiCheat.ObscuredTypes;
using CodeStage.AntiCheat.Detectors;

public class UIManager2 : MonoBehaviour {

    public static ObscuredInt coin_score = 0;

    public Text coin_text;
    public Slider slider;
    public Slider slider1;
    public Slider slider2;
    public GameObject bul;
    public bool reverse;
    public float timer;
    public int delay = 1;
    public float speed=0.5f;
    public GameObject pause;
    public AudioSource[] aud=new AudioSource[3];

    void Start () {
        coin_score = ObscuredPrefs.GetInt ("Score");
        StartCoroutine (elapsed ());
        slider1.minValue = 0;
        slider1.maxValue = 20;
        bul = GameObject.FindGameObjectWithTag ("Player").GetComponent<Plane19> ().bullet;

   }

    void Update () {
        timer += Time.deltaTime;
        if (timer >= delay && reverse == false) {
            timer = 0f;
            slider2.value++;
        }

        if (timer >= delay && reverse == true) {
            timer = 0f;
            slider2.value -= speed;
      }

        coin_text.text = coin_score.ToString ();
        ObscuredPrefs.SetInt ("Score", coin_score);

        if (slider2.value == 10) {
            bul.SetActive (false);
            reverse = true;
        }

     if (slider2.value == 0) {
            bul.SetActive (true);
            reverse = false;
        }

    }

    public void di(){
        pause.SetActive(true);
        GetComponent<AudioSource>().Pause();
        Time.timeScale = 0;
        aud[0].Play();
        aud[1].Pause();
        aud[2].Pause();

}

    public void but(){
        pause.SetActive(false);
        Time.timeScale=1;
        aud[0].Pause();
        aud[1].UnPause();
        aud[2].UnPause();
        GetComponent<AudioSource>().UnPause();
        UIManager2.coin_score-=2;

    }

IEnumerator elapsed () {
        yield return new WaitForSeconds (2f);
        slider.value++;
        StartCoroutine (elapsed ());
    }
}


texts: Shadow map depth error makes all light be covered and hidden

texts:
I've been following the tutorials listed below:

http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series3/Shadow_map.php

http://xbox.create.msdn.com/en-US/education/catalog/sample/shadow_mapping_1

And I made my shadow map creator effect:

float4x4 WorldViewProjection;

float4x4 LightingWorld;
float4x4 LightingViewProjection;

struct VertexToPixel {
    float4 Position : POSITION;
    float Depth : TEXCOORD0;
};

VertexToPixel ShadowMapVertexShader(float4 position : POSITION) {
    VertexToPixel output = (VertexToPixel)0;

    output.Position = mul(position, mul(LightingWorld, LightingViewProjection));
    output.Depth = output.Position.z / output.Position.w;

    return output;
}

float4 ShadowMapPixelShader(VertexToPixel input) : COLOR0 {
    float4 color = input.Depth;
    color.a = 1;

    return color;
}

I use the following flashlight (which has a cone angle: coneAngleHalfRad * 2) View and Projection matrices for the shadow map (and for checking the depths later):

        lightProjection = Matrix.CreatePerspectiveFieldOfView(
            coneAngleHalfRad * 2,
            1,
            1, //0.25f,
            range);

        //Helper.Message(this, "draw shadow maps: " + needsShadows);
        //Helper.Message(this, "rotation up: " + rotation.Up);
        lightView = Matrix.CreateLookAt(position, position + (direction * range), rotation.Up);
        lightViewProjection = lightView * lightProjection;
        DepthMapMakerEffect.Parameters["LightingWorld"].SetValue(Matrix.Identity);
        DepthMapMakerEffect.Parameters["LightingViewProjection"].SetValue(lightViewProjection);
        DepthMapMakerEffect.Techniques[0].Passes[0].Apply();

        device.SetRenderTarget(RenderDirectional);
        device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);

        drawAction(this, DepthMapMakerEffect);

        device.SetRenderTarget(null);
        ShadowMapDirectional = (Texture2D)RenderDirectional;

I set my shadow map to the effect:

TextureManager.DynamicTexturingEffect.Parameters["Flashlight" + numFlashlightsPP + "Map"].SetValue(((Flashlight)lights[lightIndex]).ShadowMapDirectional);

And when I am drawing the light with additive blend state, I use the following code to get the depths from the shadow map and from the camera (is it from the camera? I didn't understand yet):

shared float DepthBias = 0.001f;

//  [...]

shared Texture Flashlight0Map;
shared sampler Flashlight0MapSampler = sampler_state {
    texture = <Flashlight0Map>;
    magfilter = LINEAR;
    minfilter = LINEAR;
    mipfilter = LINEAR;
    AddressU = clamp;
    AddressV = clamp;
};

//  [...]

//  Find the position of this pixel in light space.
float4 lightingPosition = mul(worldPosition, flashlight.LightingViewProjection);

//  Find the position in the shadow map for this pixel.
float2 shadowTexCoord = 0.5 * lightingPosition.xy /
                        lightingPosition.w + float2(0.5, 0.5);
shadowTexCoord.y = 1.0f - shadowTexCoord.y;

//  Get the current depth stored in the shadow map.
float shadowDepth = tex2D(Flashlight0MapSampler, shadowTexCoord).r;

//  Calculate the current pixel depth.
// The bias is used to prevent folating point errors that occur when
// the pixel of the occluder is being drawn.
float ourDepth = (lightingPosition.z / lightingPosition.w) - DepthBias;

//  [...]

float intensity = 0;
if (ourDepth <= shadowDepth) {
    if (atten > 0) {
        intensity = saturate((flashlight.Range - dist) / flashlight.Range) * (dot(vertexNormal, perVertexNormal) * fog) * atten;
    }
}

But what happens is that the result is ALWAYS "ourDepth > shadowDepth", which makes the entire light always hidden so it's always shadowed no matter if there's an object in front of it or not.

What could I possible be doing wrong? I think I used wrong values in the flashlight's View and Projection. But I can't find the error. What might be the problem?

Any suggestion may help!

EDIT: I'm not using the same aspect ratio of the screen and of the camera for the shadow map. Do I need to?