texts: Path following with Asteroids-like movement. Time to complete path

texts:
I'm currently learning about how to do this, but it's best to post the problem beforehand. (posting on Physics and GameDev, as you guys know your math)

It's quite difficult to explain. This specific problem revolves around a problem of creating a guidance system for rocket powered craft.
Think: 'I want the ship from game "Asteroids" to follow a specific path and compute, how much time will the whole trip take beforehand"

A craft has it's own properties like mass, linear and angular acceleration. It is only able to accelerate in its forwards direction. Also, quite a pain in the... it's maximum traverse velocity is limited.

Hopefully the picture clears some things out:

The problem lays in the very first step. The program is initiated while the craft is already moving with random velocity and faces random direction.
In order to move fully toward the target point, first the craft has to turn to face "U" vector. But while doing so, it still moves, so the vector "U" will change.
From the picture you can see that the direction of turn can change, don't worry, it's not a problem.

So, the problem. I tried using only vector math, but with no success as the variable I'm trying to compute relies on equations involving this variable. I'm too dumb to get only the variable I'm interested in on one side of equation.
I think the solution would involve a function of distance from craft to object over time.

[Edit 1]

For your interest. Here is the part where I get stuck.

From the beginning. We have the craft on initial position "A", travelling with velocity "V1" and the target on initial position "B", with velocity "V2" (better include it just in case)

From that we can compute the burn vector "U", that we need to align ourselves to in order to travel towards the target at the speed of "Vmax"

The bigger the angle between craft's heading "Cf" and vector "U", the longer it will take the craft to turn. Which means, the craft will cover more distance while turning (uppermost picture). Which means the angle will change during turning etc. etc.

On second picture, in red box. at the top we compute dot product, at the bottom we multiply magnitudes of vectors. As the Cf vector is of length 1 all the time, we can spare it.

The primary thing I'm looking for is variable "t", currently I'm out of ideas.


texts: About the cameras in the original Metal Gear Solid for PSX

texts:
Since I first played MGS on the PSX I have been wondering about this.
To my understanding, MGS loads the geometry of the 'room' where you are and lets you move through it by using semi-fixed cameras that can follow you to a certain degree until your character gets in the range of another camera, and then seems to transition from the last angle of the previous camera to the initial angle of the current camera.
However, since this game does not seem to have a great deal of reverse engineering done, I wonder if anybody has replicated this scheme on any game (stealth or not) to study it.
As far as I know, the only one I have found with a similar approach is Resident Evil Code: Veronica, which switched from pre-rendered backgrounds to 3D but restricted the cameras available, as in the previous installments, giving the cameras certain degree of freedom in following the player (but less than MGS since RECV is about being afraid, not being stealthy).
I know I am asking a questio too broad and risk to be tagged as such... but it's been a lot of time since MGS got out and I still wonder about if anybody has more concrete answers to my guess about how MGS works.


texts: How to manage drawing loop when changing render targets

texts:
I'm managing my game state by having a base GameScreen class with a Draw method.

I then have (basically) a stack of GameScreens that I render.
I render the bottom one first, as screens above might not completely cover the ones below.

I now have a problem where one GameScreen changes render targets while doing its rendering. Anything the previous screens have drawn to the backbuffer is lost (as XNA emulates what happens on the xbox). I don't want to just set the backbuffer to preserve its contents as I want this to work on the xbox as well as PC.

How should I manage this problem?

A few ideas I've had:

Render every GameScreen to its own render target, then render them all to the backbuffer.
Create some kind of RenderAction queue where a game screen (and anything else I guess) could queue something to be rendered to the back buffer. They'd render whatever they wanted to any render target as normal, but if they wanted to render to the backbuffer they'd stick that in a queue which would get processed once all rendertarget rendering was done.
Abstract away from render targets and backbuffers and have some way of representing the way graphics flows and transforms between render targets and have something manage/work out the correct rendering order (and render targets) given what rendering process needs as input and what it produces as output.

I think each of my ideas have pros and cons and there are probably several other ways of approaching this general problem so I'm interested in finding out what solutions are out there.


texts: Unity Failed to create decoder for ScreenSelector.png

texts:
My game works fine in the editor, but when I build and run the build the view is zoomed in, my tilemap is missing, and the camera follows a gameobject it should not.

How it should look and how it looks

I checked the logs and this is the error I am served:

  Failed to create decoder for 'C:/Users/Hamuel The First/Documents/Jetplatformer/Builds/Builds_Data/ScreenSelector.png': 0x80070002

Further Investigation shows that ScreenSelector.png is absent from the path stated in the error. I cannot find anything that says what ScreenSelector.png is, or does. I am using the post processing stack by unity.

Any help would be much appreciated!


texts:
The picture illustrates

I cannot figure out the math on this. The "arrows" should move at the same speed in both examples.


texts: How to place same canvas on multiple cameras in Unity?

texts: I know how to do It on one, but I don't know how to do it using multiple cameras, 3 of them are important, i want to show the whole UI except for the minimap. I need to change the camera angle on some spots, while keeping the same canvas for displaying the number of coins XP and the current level.


texts:
I've been trying to port Catalinzima's 2D lighting example over to MonoGame to try and get some basic understanding around it and adapt it for use in my engine. I've been trying to convert the two .fx files provided with it to MonoGame compatable .mgfxo files. The first file ran through the converter and compiles successfully. However, the second file ran into issues converting; cmd Dump:

C:\Program Files (x86)\MSBuild\MonoGame\v3.0>2MGFX.exe resolveShadowsEffect.fx /DEBUG
C:\\Program Files (x86)\\MSBuild\\MonoGame\\v3.0\\resolveShadowsEffect.fx(213,8):
error X5608: Compiled shader code uses too many arithmetic instruction slots (85). Max. allowed by the target (ps_2_0) is 64.
(1,1): error X5609: Compiled shader code uses too many instruction slots (99). Max. allowed by the target (ps_2_0) is 96.

Failed to compile the input file 'resolveShadowsEffect.fx'

So i thought fine, ill just change the PixelShader model to ps_3_0. Now this converts fine, but fails to compile in visual studio with the following errors:

A namespace cannot directly contain members such as fields or methods (1, 1)

and..

Unexpected character '' (1, 5)

In the visual studio error message this character shows as '|' but its not the same when i paste it out.

I've tried comparing the first lines of the files, but have not been able to notice any differences.

I'm pretty new to using shaders, so i haven't been able to debug whats going on effectively. Any ideas?

You can find the original shader files and compiled versions here: http://puu.sh/9ZfMe/efe8fbaf9d.zip


texts:
I want to know how I can create a virtual town or city (like skyrim towns or gta4 liberty city)

Should I create something on paper and copy coordinates? (Building1 floor corner coordinates are these, ceiling coordinates are these, 2nd floor coordinates are these etc, and then road1 coordinates are these...) And then apply texture on these things? Start with just 1 building and extend it in time?

But this seems like a ton of work. For simplicity if we assume that there are 5 buildings on a road, this is like 90 vertices. And if I decide to make a house wider, then many things will be affected and I have to find new coordinates for every house corners. How did the developers of GTA 4 do it for example?

I would like to know an appropiate method to create a static virtual map where the player can move into houses and interacts with objects in it. Please note that these buildings are not cosmetic only. I should be able to place objects in houses such as tables and the player should be able to jump on it etc.

Thank you, I will vote when I have the reputation.


texts: Unity sprite renderer uses standard 2D sprite instead of custom loaded one

texts:
I have loaded a 2D sprite from the filesystem and created a sprite from it, which I then attach to a SpriteRenderer. The game object appears in the scene but for some reason it doesn't seem to be using the sprite I loaded, and is instead using the Standard Assets/2D/Materials/SpriteLift sprite. I have attached my sprite creation code and some screenshots:

public static Sprite LoadSprite(string relPath) {
    var fileUrl = "file://D:/Unity Projects/2D-Game/mod/base/textures/" + relPath + ".png";

    // Download texture from file location and resize it
    var www = new WWW (fileUrl);
    var texture = www.texture;
    texture.Resize (textureSize, textureSize);
    texture.name = relPath;
    Debug.Log (texture);

    // Make the sprite
    var sprite = Sprite.Create (texture, spriteRect, spritePivot, textureSize);
    sprite.name = relPath;
    return sprite;
}

The Unity scene with the incorrect sprite:

The desired texture:

The code that creates the game object and attaches the loaded sprite to the SpriteRenderer:

GameObject go = new GameObject ();
go.name = "Tile_ " + tile.location.ToString();
go.transform.position = tile.location.ToVector3 ();
go.transform.SetParent (this.transform, true);
SpriteRenderer sr = go.AddComponent<SpriteRenderer> ();
sr.sprite = tile.Type.sprite;
sr.enabled = true;

Note that the screenshot contains many game objects all with the same sprite, that's why it looks big in the scene.

EDIT: The problem may be due to materials.

EDIT 2: Screenshot of a selected tile:


texts: Unity - Visual Studio 2017 Unity Syntax Highlighting not working anymore

texts:
Everything worked perfectly fine yesterday. But today the syntax hightlighting stopped working:

MonoBehaviour and Sprite should be green, just like Item. What can I try to solve this?

What I tried: Turned computer on and off.

I temporarly solve it by deleting all VS files in my project folder

But If I move a script inside Unity to another folder and then open that script, then Intelli Sense does not work anymore and I have to close Visual Studio, delete all VS files in my project folder again and open the file again in unity. This seems to be a major VS bug.


texts:
Previously, I found an useful article that explained how to convert 3d mesh to SDF easily.

  I want our artists to be able to easily convert from polygonal data to SDFs with little-to-no effort.

  http://colourmath.com/2018/development/signed-distance-fields-in-unity/

this article is what I want but unfortunately there wasn't simple Implemention.

there is algorithm in this article:

foreach (pixel in texture)
    foreach (triangle in mesh)
         get pixel center as mesh bounds position
         get closest point on triangle
         calculate distance from pixel position to triangle
         keep the smallest distance
         perform a raycast along arbitrary vector against triangle
         if(raycast intersects triangle)
            increment an intersection counter
    if(number of intersections is even)
        pixel value is positive // outside mesh
    else
        pixel value is negative // inside mesh

I like to Implement this article but I can't understand above algorithm and I don't know how can I convert 3D mesh to SDF data and then sotre this data to 3D RenderTexture?


texts:
I guess this question pertains more to games like MMO and Diablo-like games.

What are the usual designs for implementing a drop table, where a monster could drop different type of items depending on a percentage? I guess the simplest way there is to have a dictionary of 'percentage weightage' to item types, but this is hard to extend if we wish to introduce new item types (for example, when D2 expansion includes runes and new class items)


texts:
Im making a custom Wavefront .obj loader and the images loads but the texture is flipped. What is the problem? here is code and a image.

std::vector<UINT> vertexIndices, uvIndices, normalIndices;
std::vector<UINT> indices(4119);
std::vector< XMFLOAT3> temp_vertices;
std::vector< XMFLOAT2 > temp_uvs;
std::vector< XMFLOAT3 > temp_normals;
std::vector< XMFLOAT3> out_vertices;
std::vector< XMFLOAT3> out_normals;
std::vector< XMFLOAT2> out_uvs;
std::vector<Vertex::Basic32> vertices( 4119);
const char *path = "C:\\Users\\terry\\Desktop\\untitled.txt";

FILE * file = fopen(path, "r");
if( file == NULL ){
    printf("Impossible to open the file !\n");
    return;
}

while( 1 ){

    char lineHeader[128];
    // read the first word of the line
    int res = fscanf(file, "%s", lineHeader);
    if (res == EOF)
        break; // EOF = End Of File. Quit the loop.

    // else : parse lineHeader

    if ( strcmp( lineHeader, "v" ) == 0 ){
    XMFLOAT3 vertex;
    fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z );
    temp_vertices.push_back(vertex);
    }else if ( strcmp( lineHeader, "vt" ) == 0 ){
    XMFLOAT2 uv;
    fscanf(file, "%f %f\n", &uv.x, &uv.y );
    temp_uvs.push_back(uv);
    }else if ( strcmp( lineHeader, "vn" ) == 0 ){
    XMFLOAT3 normal;
    fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z );
    temp_normals.push_back(normal);
    }else if ( strcmp( lineHeader, "f" ) == 0 ){
    std::string vertex1, vertex2, vertex3;
    unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
    int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2] );
    if (matches != 9){
        printf("File can't be read by our simple parser : ( Try exporting with other options\n");
        return;
    }
    vertexIndices.push_back(vertexIndex[0]);
    vertexIndices.push_back(vertexIndex[1]);
    vertexIndices.push_back(vertexIndex[2]);
    uvIndices    .push_back(uvIndex[0]);
    uvIndices    .push_back(uvIndex[1]);
    uvIndices    .push_back(uvIndex[2]);
    normalIndices.push_back(normalIndex[0]);
    normalIndices.push_back(normalIndex[1]);
    normalIndices.push_back(normalIndex[2]);
    }
}

 for( unsigned int i=0; i<4119; i++ ){
     unsigned int vertexIndex = vertexIndices[i];
     XMFLOAT3 vertex = temp_vertices[ vertexIndex-1 ];
     out_vertices.push_back(vertex);
     unsigned int normalIndex = normalIndices[i];
     XMFLOAT3 normal = temp_normals[ normalIndex-1 ];
     out_normals.push_back(normal);
     unsigned int uvIndex = uvIndices[i];
     XMFLOAT2 uv = temp_uvs[ uvIndex-1 ];
     out_uvs.push_back(uv);

 }

 for( unsigned int i=0; i<4119; i++ ){
     vertices[i].Pos = out_vertices[i];
     vertices[i].Normal = out_normals[i];
     vertices[i].Tex = out_uvs[i];
     vertices[i].Tex.y = vertices[i].Tex.y * -1.0f;
     indices[i] = i;
 }


texts:
I am working on a authoritative client/server game, looking to both Valve and Gaffer to understand the concept.

Currently, the server simulates at 20 ticks a second. The inputs received from the client is buffered and only processed during one of these ticks. However, if a client sends input at a faster rate, say 60 times a second, that client will move about 3x faster than regular clients.

A solution to this would be to have the server combine/unify the inputs in the buffer and process this input once, instead of processing the buffered inputs individually.

Now, given the latter solution, a client with a send rate of 20 could be subject to network jitter, which could cause the server to receive 2 or more inputs at the same time. This would cause the server to combine/unify the inputs, when they should actually be processed individually.

So my question is, how should the server handle inputs to prevent more inputs from being processed than necessary, while not skipping inputs that arrive at the same time?

I hope I make sense, if not just tell me to elaborate :)


texts: Import .fbx animation from Maya 2012 to Unity 2018

texts:
I have a grass made by PaintEffects tool (1) and "animated" by adding turbulence (2) and then baked with Maya 2012.

And in Maya everything looks perfect - animation works. Problem is, when I'm importing that .fbx animation to Unity 2018, nothing happens. I can't either see this animation in Preview, I can see only the "model" itself. I read on the internet that's maybe because I set wrong animation, or rig option in Unity, but I tried every one of them. Is there something I missed, either in Maya, or Unity? Maybe I have too old version of Maya?

Also, I was trying to save that animation into separate files, or with extensions like .ma, .mb... Nothing works either.


texts: collisions: How to handle contact constraints for a rigidbody constrained to a line segment

texts:
I'm trying to come up with a strategy to handle a situation in 2D, where a rigidbody moves along a straight line segment, and can collide with other similar bodies and also static tiles.

A naive approach was to handle collisions by projecting the displacement vectors onto the line segment (worked ok for aabb), and then at the end snap the position of the rigidbody back to the line, which had lots of conflicts.

I'm trying to implement impulse based physics, so far only handling contacts, and unsure how to both constrain the rigidbody to a line segment and handle contacts at the same time. Or is it better to do in two separate phases. It's probably easier to allow some displacement from the line and then gradually move the body back to it. Any suggestions?


texts: MonoGame - scale down a sprite from the middle

texts:
I want to animate a texture's scale. First it's scaled up to 10, and then it gradually goes down to 1. However the texture is drawn at Vector2(0, 0) so it doesn't animate as I had imagined it would - it should scale down from the center of the texture. I'm sure the origin has something to do with it but I just can't figure out the math I need to use. So the texture is 1366x768 pixels, just as the entire screen. So here's what I tried:

private Texture2D texture;
private Vector2 origin;
private float scale = 10.0f;

public void Update(GameTime gameTime)
{
    scale -= 0.05f;
    if (scale <= 1.0f)
    {
        scale = 1.0f;
    }
    origin = new Vector2(texture.Width * scale / 2, texture.Height * scale / 2);
}

public void Draw(SpriteBatch spriteBatch)
{
    spriteBatch.Draw(texture, Vector2.Zero, null, Color.White, 0.0f, origin, scale, SpriteEffects.None, 1.0f);
}

When I debug this, I can't even see the image (the game is fullscreen). Any help is appreciated.


texts:
I am currently making a game in C# using Direct X 9.0. The game remake is Donkey Kong NES. I have nearly everything completed, but I am having problems with the physics of Mario's jump. I have variables declared for the Y and X co-ordinations.

I was wondering if there was a simple method of doing this. I have searched high and low for an answer but the answers I have found are either irrelevant/ or using a different programming language such as XNA.

I currently have a bool variable set to check to see if W has been pressed then that will trigger any code to make him jump. I have been messing around such as.

  if (jump == true)
    {

        Playerypos -=  vel;
        Playerxpos +=  vel;
    }

Which didn't work that well. I have searched high and low for an answer and now I am desperate, if someone could point me in the right direction to a simple solution. That would be great. Much appreciated for any responses.


texts:
So I came up with a distortion pixel shader in hlsl, but it has some issues. First of all, here is how it works:

The shader uses another texture generated by the program as a distortion "map" (if that's the correct term) I called this map a "mask".

The shader uses the red values in the mask for horizontal distortion and the blue values as vertical distortion. The green values are not used.

It subtracts 0.5 from the red and green values so that they have a range from -0.5 to 0.5 instead of 0 to 1. This lets the distortion go in any direction using only two color values.

I let the shader "push" pixels up to 128 pixels.

sampler s0;
texture textu;
sampler tex_sampler = sampler_state{Texture = textu;};
float2 screenSize;

float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0
{
    float4 tex_color = tex2D(tex_sampler, coords);

    if (tex_color.a)
    {
        float distX = (tex_color.r - 0.5f) * (256.0f / screenSize.x) * tex_color.a;
        float distY = (tex_color.b - 0.5f) * (256.0f / screenSize.y) * tex_color.a;

        return tex2D(s0, float2(coords.x + distX, coords.y + distY));
    }
    return tex2D(s0, coords);
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

"textu" being the mask, "tex_color" is the color value from the mask.
It also multiplies the distortion by the alpha value in the mask.

This seemed to work perfectly at first, but I started noticing some issues.
I was using a completely white texture (as the mask) that was blurred around the edges. I set the color of this texture based on its rotation.
Here is the method I used for that:

private Color GetDirectionColor(float rad)
{
    Vector2 v = new Vector2(
        (float)Math.Cos(rad + Math.PI),
        (float)Math.Sin(rad + Math.PI)
        );

    float r = (v.X * 0.5f) + 0.5f;
    float b = (v.Y * 0.5f) + 0.5f;

    return new Color(new Vector3(r, 0, b));
}

This allows the texture to "push" pixels in whatever direction it is facing.
This method seems to work fine.

The problem is, when the texture is rotated more than 135 degrees and less than 315 degrees (as in, the texture is pointing into the upper left half of a circle if you cut it in half at a 45 degree angle) it does something strange. Where the texture is blurred (the alpha values become less than 1) it starts to "push" the pixels in the opposite direction that it should be.

I suspect this has to do with my shader and not something else in the program. Possibly the -0.5f part???

I'm terribly sorry if this is confusing... I could not find a better way to word it.

Thanks a lot for your help!


texts: Creating color texture from greyscale heightmap in shader

texts:
I'm trying to create a shader that takes a grayscale map as input, and returns a colored albedo that I want to use as texture for my PCG planets, I think that the code below should work, but it only produces flatly white objects.

I'm a total shader noob, so I'm terribly sorry if I'm missing something obvious here.

    Shader "Custom/Planet" {
    Properties{
        _height("HeightMap", 2D) = "white" {}
    }
    SubShader{
        Tags { "RenderType" = "Opaque" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
        #pragma surface surf Standard fullforwardshadows

        // Use shader model 3.0 target, to get nicer looking lighting
        #pragma target 3.0

        struct Input {
            float2 _heightMap;
        };

        float minHeight = 0;
        float maxHeight = 1;

        float inverseLerp(float a, float b, float v) {
            return saturate((v - a) / (b - a));
        }

        //UNITY_INSTANCING_CBUFFER_START(Props)
        //UNITY_INSTANCING_CBUFFER_END

        void surf (Input IN, inout SurfaceOutputStandard o) {
            float hv = inverseLerp(minHeight, maxHeight, IN._heightMap);
            o.Albedo = hv;
        }
        ENDCG
    }
    FallBack "Diffuse"
}


texts: How to mouse click an object in scene view to select it from editor

texts: I have several game objects with colliders in my game. I have enabled Always Show Colliders to keep all of them visible in my scene view. Because the objects are a lot, selecting them from the hierarchy window is a bit cumbersome and really slowing down my workflow. How can I select an object by left mouse clicking on it  in the scene view of an editor?


texts: Quad Texture to Pixel Screen Space (DirectX 11)

texts:
I think I must be using the wrong wording for what I want, because I seached and just kept finding pixel shader questions. But this seems like something that anyone making a 2D game would want.

Basically I have my quad, my loaded texture in a ID3D11ShaderResourceView and I can draw it to the screen using coordinates of -1.0 to 1.0.

But what I want to accomplish is drawing based on pixels.

i.e.

I would want to draw a 20x20 pixel image to coordinates 100,100 on a 800x600 screen. But, I want to do this by manipulating the quad to the correct size and position to mimic this (which is, I assume, a common way to do 2D in DirectX11).

As I said, I am able to draw a texture to screen space at the moment but I am lost as to what calculations or methods would be required to convert this to pixel-based drawing.

Thank you :)


texts:
So something came up today when I was going over my Blinn shader. As I've been taught, the half-angle vector is calculated in the fragment shader, and is equal to normalize(lightDir + viewDir). This seems to work fine.

When adding a normal map, this still seems to works, except I use tangent space vectors and dot the half-angle with the normal from the normal map.

But here's what I don't understand: when using normal maps, shouldn't the light & view directions be re-computed for each fragment? Seeing as the interpolation between the vectors is no longer linear, lightDir and viewDir can't possibly be correct anymore?

Somehow I feel like the per-pixel normal should play a part in calculating the view/light directions. Am I missing something?

This came up when working on a fresnel effect which also uses the half-angle vector. Without any changes to the half-angle vector, the fresnel effect can't possibly know anything about the normal map, which seems wrong (and actually looks wrong).

Here's the fresnel calculation:

 // Fresnel (Schlick approximation)
 float base = 1 - dot(viewDir, halfAngle);
 float exp = pow(base, 5);
 float fresnel = exp + fZero * (1.0 - exp);

Given that neither viewDir nor halfAngle incorporate the normals from the normal map, the fresnel effect is computed based on interpolated normals and looks "blocky". Maybe this isn't a problem for the Blinn computation, but I thought it might be too.


texts: Isometric - precise screen coordinates to isometric

texts:
I'm trying to translate mouse coords to precise isometric coords (I can already find the tile the mouse is over, but I want it to be more precise). I've tried several different methods but I seem to keep falling short.

For drawing I use:

batch.draw(
    texture,
    (y * tileWidth / 2) + (x  * tileWidth / 2),
    (x  * tileHeight / 2) - (y * tileHeight / 2))

This is what I currently use for figuring out a tile position:

 float xt = x +  camPosition.x - (ScreenWidth/2) ;
 float yt = (ScreenHeight) - y + camPosition.y - (ScreenHeight/2);

 int tileY = Math.round((((xt) / tileWidth) - ((yt) / tileHeight)));
 int tileX = Math.round((((xt) / tileWidth) + ((yt) / tileHeight))- 1);

I'm just wondering how I could update these to allow for more precise coordinates, instead of tile only.
EDIT:
Following what ccxvii said below, and removing the -1 from tileX, the object follows my mouse just like I had wanted. Just going to re-examine the math and figure out if that change will result in other messes =o


texts:
I'm making a tower-defense game for Windows (not phone) in XNA.

I've seen this video of another tower-defense game for Windows Phone that uses particle effects, which I really like. They change color, glow and density as they move away from the explosion. Really cool stuff!

http://www.youtube.com/watch?v=YhPr4A4LRPQ&hd=1

I would like a similar result (particle-wise) to the stuff in the video, however, I don't know where to start. I suppose I need to do linelist hardware instancing to achieve the result, and then update every particle position on the CPU.

Or is there a better alternative? Post your suggestions. That'd be great, thanks.

Edit It's the explosion particle effect that I want to implement. Not the particle effects that the projectiles leave when they fire.


texts: Anchoring HingeJoint2D to clicked upon spot

texts:
I'm creating a 2D game where the user can click and drag objects around. This is done by connecting a 'Hand' object to the object the user is current clicking on with a HingeJoint2D. Right now it simply connects the HingeJoint2D to the center of the clicked upon object.

I want to anchor the Hingejoint2D to the exact spot on the rigidbody (not the center) that the user is clicking on. This must involve transforming the clicked upon point to coordinates relative to the clicked upon rigidbody, but I've had no success using methods like transform's TransformPoint.

Any help would be appreciated.

This is the code I have attached to the object that the user will be dragging around:

void OnMouseDown() {
     // Create a hinge joint between the hand and this object so object will slowly rotate
     // around the hinge point
     this.gameObject.AddComponent("HingeJoint2D");
     connectingHinge = this.GetComponent<HingeJoint2D>();
     connectingHinge.connectedBody = handRigidbody;

     // Set anchor to offset of current hand position relative to the object.
     //connectingHinge.anchor = new Vector2(offset.x, offset.y);
 }

Image of gameplay:

The gray box is the 'hand', which is the mouse cursor. The gun is an object that the user is dragging about while it is connected to the gray box with a HingeJoint2D.

I want to anchor the HingeJoint2D to the exact spot the user is clicking on, and not just the center of the rigidbody.


texts:
Hi I am using a for loop to check and see if my players character is colliding with a collision object in the game. But for some reason it only checks the last Rectangle of the list.

private void collisionDetection()
{
    for(Rectangle rectangle : colrect) {
        Rectangle rect2 = new Rectangle(posX, posY, 64, 64);
        if (rectangle.overlaps(rect2))
        {
            m.setTileCollision(true);
        }
        else
        {
            m.setTileCollision(false);
        }
    }
}

Why and how is this happening? I gave up on looking for an answer so I'm here. I want to check all of the Rectangles in the list not the last... I even for looped text through Bitmap font to see the positions and set text at all Rectangles and that works properly, but this doesn't.  Another solution perhaps is in order?


texts:
I have created a Third Person Controller.
The camera is behind the player:

I would like to make it so that the player aims at the mouse pointer position.
To do that, I use the following code to rotate the chest towards the position:
        var mousePos = Input.mousePosition;
        mousePos.z = 10; // Make sure to add some "depth" to the screen point
        var aim = Camera.main.ScreenToWorldPoint(mousePos);
        Chest.LookAt(aim);

The hands do not perfectly straightly point forwards, so I need to add an "offset" to the LookAt.
I tried this approach:
var mousePos = Input.mousePosition;
mousePos.z = 10; // Make sure to add some "depth" to the screen point
var aim = Camera.main.ScreenToWorldPoint(mousePos);
aim += new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0);

Chest.LookAt(aim);

Of course I do all rotation patching in LateUpdate(). In Update(), it would simply be erased by the animation itself.
It does work, but when the model is rotated around the Y axis, something goes wrong: The offset is "wrong", it doesn't have the same effect.
This surprises me because all I do is rotate the entire model.
So I think this line is not correct:
aim += new Vector3(ChestAimCenterOffsetForLookatBecauseChestIsNotStraightForward, 0, 0);

Is this not the way to offset the LookAt results?


texts:
I'm using OpenAL Soft 1.16.0.

Everything's running fine, but for some reason my sounds keep getting cut off at either the beginning or the end (hard to tell). It's not really noticable for music and longer sounds, but it's a big problem for anything shorter than a second, e.g. footsteps:

http://youtu.be/xrJVKjFEzYg

The sounds themselves are definitely not the issue, I've grabbed the footstep sounds from another game for testing purposes to be sure and I've tried various different sounds from different sources.

It's not the format either, the same problem occurs regardless of whether I use .mp3, .wav or .ogg files.

What could be causing this problem?


texts:
how to replicate this type of scratch card effect in Unity3D considering its for mobile.

https://youtu.be/6wLWu1BefXs

Two cases
1. Clear part of screen where user touches.
2. How to trigger rewards after certain amount of image get reveal?


texts:
Is there any book or article that describe interaction of RPG elements and human psychology?

For example: what will be more popular and attracting for people - linear function of experience per level or exponential function of experience per level?


texts: Difference between two perspective projection representations

texts:
When researching perspective projections on the web, I've come across two different representations. One is unrelated to OpenGL and the other is strictly associated with it.

What is the relation of these two projections? Both are called the same but the matrices are quite different. The first one seems to project unto the xy plane (z=0), the OpenGL one to the z=near plane.


texts:
I'm working on the server side part of my game (develop your village/farm) and trying to build user identification system. I'd like to have a password-less mechanism: user downloads my app from the store, run it and that's all. He doesn't have to type any login or password. The game connects with the server requesting new player creation so he can start playing as soon as he opens the app.

I assume that this process is connected with GameCenter/GooglePlayGames. A game retrieves player ID from those services and then use it for future requests (saving user progress, game specific data - like village/farm facilities' positions, other information on my server). Is it a valid and safe assumption? If not can ask you to describe how it works/should be done?

I have some doubts regarding security? Single PlayerID seems to be quite weak solution, isn't it?

Edit:

I didn't mention it but I would like to move my progress from one device to another also without creation of any account with login and password.


texts:
I'm working on a MMO game project. I have a question about MMOFPS game architecture. (I have basic network knowladge)

(MMOFPS) I want to send player position to other players(clients) and other players will render the player. Namely this is the base of the game world. I have read some article about positioning and somebody says "use inputs for movement update" and others says "use  position posting". That's the first problem. What is better? input or position based movement posting? What is more suitable for a MMOFPS game? (And how to do it?)

SUMMARY: I need to learn "how real multiplayer games work?" (but basically). In my first project I have used TCP protocol for posting position (not inputs) and I have sent position data 4 times per second. Server delivered them to other clients and other clients handled this data and maked a smooth movement. This is a very basic method to do it but I know that isn't MMO! Can anybody help me about understanding MMO game architecture?


texts: Should an object in a 2D game render itself?

texts:
I'm making a 2D street fighter-like game that is not tile based. Usually people recommend that entities be given to a renderer that render them, not them render themselves, but it seems the inverse is better,

Why is one better over the other?

Thanks


texts: How to use traditional pixel coordinates system in OpenGL? (with C++/SDL2)

texts:
I find the normalized, centralized coordinate system used in OpenGL weird and annoying, is there anything I can do at all to make it work like normal pixel coordinates on everything ever except OpenGL? And yes, of course I Googled it.

EDIT: I'm using OpenGL 2.1


texts: Unity3D) Is there a way not to draw line renderer if vertex pos is zero?

texts:
I make a curved line with line renderer.
and a sphere move along it.
i want to draw a line only behind the sphere.

so i do something like this.

``
lr.positionCount = 256;

    while (delta < time)
    {
        lr.SetPosition(i++, curPos);

        yield return new WaitForFixedUpdate();
    }

``

and the problem is, because of i set the size of Positions 256,
if time is short, there are zero vectors in position.
so line renderer draw meaningless line.

is there a way to set PositionCount dynamically like List?
or any good way to not draw if positions are zero?


texts: Unity UI Button not working on PC build but working on Android mobile build

texts:
I am using Unity to build a game that is going to be used on PC and Android mobile devices. The problem I have is that when I use a UI Button, it works perfectly on mobile, but on PC and in the editor, is not working.

Why could this be happening?


texts: Why are points adjusted using the projection and inverse view matrix during picking?

texts:
I am working on my first 3D game, which contains several vehicles placed on a board. I want to implement mouse picking of the vehicles. I found this great tutorial and used its code. But I don't understand part of the math.

Early in the function (listed below), I convert the input mouse coordinates into the -1 to +1 range:

// Create picking ray from camera position and mouse click
void VehiclePicker::SetPickingRay(LONG mouseX, LONG mouseY) {
    float pointX, pointY;

    /* Conversion to -1 to +1 here: */
    // Move the mouse cursor coordinates into the -1 to +1 range.
    pointX = ((2.0f * static_cast<float>(mouseX)) / static_cast<float>(SCREEN_WIDTH)) - 1.0f;
    pointY = (((2.0f * static_cast<float>(mouseY)) / static_cast<float>(SCREEN_HEIGHT)) - 1.0f) * -1.0f;

    ...

Next, I adjust the points using the projection matrix. Listed below:

    XMFLOAT4X4 prMtrx;
    // Convert projectionMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&prMtrx, _d3d->GetProjectionMatrix());
    pointX = pointX / prMtrx._11;
    pointY = pointY / prMtrx._22;

I don't understand what is exactly done here. I understand that I should somehow transform the points using the inverted projection matrix into world space. But in the tutorial they are using non-inverted projection matrix and using only two elements from it for dividing the points. Why? In tutorial, they say they want "Adjust the points using the projection matrix to account for the aspect ratio of the viewport." Could somebody please explain it?

The same question is for the next part of the code. In tutorial they say "Calculate the direction of the picking ray in view space." Could you please also explain this one?

    // Get the inverse of the view matrix.
    XMFLOAT4X4 invViewMtrx;
    // Convert inverseViewMatrix from XMMATRIX into XMFLOAT4X4 in order to pick its members
    XMStoreFloat4x4(&invViewMtrx, XMMatrixInverse(nullptr, _camera->GetViewMatrix()));
    XMFLOAT3 dir;
    dir.x = (pointX * invViewMtrx._11) + (pointY * invViewMtrx._21) + invViewMtrx._31;
    dir.y = (pointX * invViewMtrx._12) + (pointY * invViewMtrx._22) + invViewMtrx._32;
    dir.z = (pointX * invViewMtrx._13) + (pointY * invViewMtrx._23) + invViewMtrx._33;
    _pickingRayDirection = XMLoadFloat3(&dir);

I understand that the goal is to invert the process of rendering 3D scene into 2D screen. But I don't understand the math used.

Here's the rest of the function, for context:

    // Get the origin of the picking ray which is the position of the camera.
    _pickingRayOrigin = _camera->GetPosition();

    // And finally I must normalize the final vector
    _pickingRayDirection = XMVector3Normalize(_pickingRayDirection);
}


texts: XNA realistic water: How to clip along a mesh instead of a plane

texts:
I hope you can help me with the following problem:

I'm developing a 3d game (in XNA) with an ocean. I want it to look semi-realistic.
So far, I'm rendering 4 things:

The ocean floor (terrain) on the view matrix (refraction)
The terrain above water on the mirrored view matrix (reflection)
The terrain above water on the view matrix (actual terrain)
The water, which is simply a plane, using the refraction and reflection rendertargets, the fresnel term, and a normal map to give the impression of small waves.

Instead of a flat plane, I want to render the water on a mesh, to get some actual waves going. This is where I've been stuck for a while now. It's quite simple to clip the terrain along that plane, but is it possible to clip a mesh along another mesh? Or am I going about this the wrong way?


texts: How can I regulate update and event frequency?

texts:
I'm trying to create a small 2D RPG-type engine using C++, SDL/OpenGL and Tiled. My little demo looks very similar to a Pokemon or Zelda game.

I was curious how to go about regulating FPS and how many times a certain event action is processed. For example, each iteration of my main loop handles events (such as if an arrow key is pressed, move the character up one tile, et cetera), then draws, and then updates then screen.

If I wanted the game to draw 24 frames every second, but only run the keyboard actions 6 times per second, how would I go about doing that? Is this even reasonable? Should I regulate everything to process 6 frames per second? Or would it make sense to create two threads, one for drawing and one for event handling?

This is my main game loop:

    while (!theGame->getQuit()) {
        fps.start();

        handleEvents();

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    theGame->setQuit(true);
                    break;
                case SDL_KEYDOWN:
                    handleKeyDown(event.key.keysym.sym);
                case SDL_KEYUP:
                    handleKeyUp(event.key.keysym.sym);
                    break;
                default:
                    break;
            }
        }
        update();

        render();

        // FRAMES_PER_SECOND = 6 OR 24
        if (fps.get_ticks() < 1000 / FRAMES_PER_SECOND) {
            SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
        }
    }


texts:
The code I'm using is like so:

SDL_Event e;
SDL_PollEvent(&e);
switch (e.type)
{
    case SDL_MOUSEMOTION:
    {
        YCam += e.motion.yrel;
    }
    break;
}

When I run the program, nothing happens, however, once I first move the mouse the SDL_MOUSEMOTION event keeps firing and the mouse keeps moving. This occurs even when I've stopped moving my mouse. Pressing any key including mouse keys stops the movement.


texts: Try-catch or ifs for error handling in C++

texts:
Are exceptions used widely in game engine design or it is more preferable using pure if statements? For example with exceptions:

try {
    m_fpsTextId = m_statistics->createText( "FPS: 0", 16, 20, 20, 1.0f, 1.0f, 1.0f );
    m_cpuTextId = m_statistics->createText( "CPU: 0%", 16, 20, 40, 1.0f, 1.0f, 1.0f );
    m_frameTimeTextId = m_statistics->createText( "Frame time: 0", 20, 20, 60, 1.0f, 1.0f, 1.0f );
    m_mouseCoordTextId = m_statistics->createText( "Mouse: (0, 0)", 20, 20, 80, 1.0f, 1.0f, 1.0f );
    m_cameraPosTextId = m_statistics->createText( "Camera pos: (0, 0, 0)", 40, 20, 100, 1.0f, 1.0f, 1.0f );
    m_cameraRotTextId = m_statistics->createText( "Camera rot: (0, 0, 0)", 40, 20, 120, 1.0f, 1.0f, 1.0f );
} catch ... {
    // some info about error
}

and with ifs:

m_fpsTextId = m_statistics->createText( "FPS: 0", 16, 20, 20, 1.0f, 1.0f, 1.0f );
if( m_fpsTextId == -1 ) {
    // show error
}
m_cpuTextId = m_statistics->createText( "CPU: 0%", 16, 20, 40, 1.0f, 1.0f, 1.0f );
if( m_cpuTextId == -1 ) {
    // show error
}
m_frameTimeTextId = m_statistics->createText( "Frame time: 0", 20, 20, 60, 1.0f, 1.0f, 1.0f );
if( m_frameTimeTextId == -1 ) {
    // show error
}
m_mouseCoordTextId = m_statistics->createText( "Mouse: (0, 0)", 20, 20, 80, 1.0f, 1.0f, 1.0f );
if( m_mouseCoordTextId == -1 ) {
    // show error
}
m_cameraPosTextId = m_statistics->createText( "Camera pos: (0, 0, 0)", 40, 20, 100, 1.0f, 1.0f, 1.0f );
if( m_cameraPosTextId == -1 ) {
    // show error
}
m_cameraRotTextId = m_statistics->createText( "Camera rot: (0, 0, 0)", 40, 20, 120, 1.0f, 1.0f, 1.0f );
if( m_cameraRotTextId == -1 ) {
    // show error
}

I heard that the exceptions are a bit slower than ifs and I shouldn't mix exceptions with if-checking method. However with exceptions I have more readable code than with tons of ifs after every initialize() method or something similar, though they are sometimes too heavy for just one method in my opinion. Are they ok for game development or better to stick with simple ifs?


texts: How to handle a large number of pickups in a MMO game

texts:
How do games like Minecraft, or really any MMO game that has pickups, handle them?

Say terrain spawns 3 pickup drops of "dirt" everytime you dig said terrain.
Say every item has a rotation animation computed every frame.
If the number of pickups in the world goes very high, that would be a useless massive overhead in the frame computation for a client in a given server, as it's likely that a lot of those pickups items are light years away from you.

So what I thought is that you have to "do stuff" only with the pickups close to the local player, but still this would imply that every frame I have to check if any other pickup item is close enough that it has to start animating.

My actual question is: how have other MMOs solved this issue?


texts: Unity: How to fix shadows with several meshes in different objects?

texts:
I'm creating many GameObjects and each one has a single mesh, created in a script. The problem is that I would like to draw them so that they behave like a single mesh. Is it possible? Or I must combine all the meshes togheter?

Thanks for your help!

Edit:
Added the code where I create the mesh and an image to clarify what I did

public void createMesh() {
        List<Vector3> vertices = new List<Vector3>();
        List<int> triangles = new List<int>();

        Vector3 _right = rightBase * radiusBase;

        //BASE
        //POC = Point on circumference
        Vector3 axis = Vector3.Cross(_right, fwdBase); //Axis of rotation of the vector _right for the base
        for(int POC = 0; POC < numberOfSections; POC++) {
            vertices.Add(_right);

            _right = Quaternion.AngleAxis(360 / numberOfSections, axis) * _right;
        }

        //TOP
        _right = rightTop * radiusTop;

        axis = Vector3.Cross(_right, fwdTop);
        for(int POC = 0; POC < numberOfSections; POC++) {
            vertices.Add(direction + _right);

            _right = Quaternion.AngleAxis(360 / numberOfSections, axis) * _right;
        }

        //The 2 points at the center of the base and the top
        vertices.Add(Vector3.zero);
        vertices.Add(direction);

        //Triangles
        for(int face = 0; face < numberOfSections - 1; face++) {
            triangles.Add(face);
            triangles.Add(face + numberOfSections);
            triangles.Add(face + 1);

            triangles.Add(face + 1);
            triangles.Add(face + numberOfSections);
            triangles.Add(face + numberOfSections + 1);
        }
        triangles.Add(numberOfSections - 1);
        triangles.Add(2 * numberOfSections - 1);
        triangles.Add(0);

        triangles.Add(0);
        triangles.Add(2 * numberOfSections - 1);
        triangles.Add(numberOfSections);

        //COVER BASE
        for(int POC = 0; POC < numberOfSections - 1; POC++) {
            triangles.Add(2 * numberOfSections);
            triangles.Add(POC);
            triangles.Add(POC + 1);
        }
        triangles.Add(2 * numberOfSections);
        triangles.Add(numberOfSections - 1);
        triangles.Add(0);

        //COVER TOP
        for(int POC = 0; POC < numberOfSections - 1; POC++) {
            triangles.Add(2 * numberOfSections + 1);
            triangles.Add(numberOfSections + POC + 1);
            triangles.Add(numberOfSections + POC);
        }
        triangles.Add(2 * numberOfSections + 1);
        triangles.Add(numberOfSections);
        triangles.Add(2 * numberOfSections - 1);

        getMesh().Clear();
        getMesh().vertices = vertices.ToArray();
        getMesh().triangles = triangles.ToArray();
        getMesh().RecalculateNormals();
        getMesh().RecalculateBounds();
        obj.GetComponent<MeshCollider>().sharedMesh = getMesh();
    }


texts: I am making a simple shooter game for Android where the player is a human and is being attacked by aliens. How would I make a laser beam, so that when the user touches the screen or presses the trackball the laser just fires in a straight line?


texts: Is using Sprites the most recommended way for doing 2d animations with Directx?

texts: I am working on a game engine of my own and I was using Vertex buffers to create triangles and then draw textures on them. Now I want to extend it so I can do simple 2d animations using "sprite sheets". I'm not sure how to accomplish this by using vertex buffers, since those are "hard coded" and I can't figure out an easy way to draw "portions" of the sprite sheet using them. I've been searching online and most tutorials use DirectX Sprite functions to do it so my question is, is it possible to achieve this by using vertex buffers or should I go and use sprites? The only thing that is stopping me from using sprites is the fact that some graphics stuff I have already relies on vertex buffers.


texts: How do I move a game object instead of the entire scene in Unity?

texts:
I'm trying to move GameObject between scenes but when I do it moves my whole scene instead of just that one game object. How do I move just the game object and not the whole scene?
I have tried SceneManager.MoveGameObjectToScene(UIRootObject, sceneToLoad); and DontDestroy but it keeps moving my whole scene new scene.


texts:
New programmer here.

I am currently trying to create a sample game in Unity (2019.2.11f1) where I push a button using the VR hands of my Oculus Rift (the hands follow my controllers). I can't believe how difficult is to find documentation or tutorials for said task. I've tried to read documentation but I'm at a loss here.

I have tried putting sphere colliders on the Hands, and tried to use raycast, with no success. I use the localAvatar with both grabbers as children, and the avatar is itself child of the OVR Player Controller prefab you get when you download the Oculus asset from the store.

How can I achieve this?


texts: Farseer: How can I calculate the needed velocity in this case?

texts:
I have two platforms and one ball. The ball should fly from the red platform to the blue platform. The ball should land somewhere in the purple rectangle of the blue platform.

How can I know how fast the linear velocity of the ball should be to accomplish the jump of the ball?
Is there a mathematical formula to calculate the linear velocity(x,y) which should be added to the ball so that the ball can jump to the blue platform?
The ball should always land in the purple area.
Distance(width) from the ball to the target: 212 pixel
Distance(height) from the ball to the target: 52 pixel
The distances were measured from the center of the ball to the center of the purple rectangle.
The gravitation of my world is world(0,3).
Upadte
I use the following formula for the impulse:

impulse = Vector2(distance.x / time * mass + gravity.x / 2 * time * mass, distance.y / time * mass + gravity.y / 2 * time * mass);

mass: mass of the ball
It's working with this formula, but only if the value of the time is not too low. time = 2.0f(or higher) is working but if I use time = 1.0f, then the ball is touching the left side of the blue platform.
Why is the formula not working with low time values? I don't understand that.


texts: Is this a good way to handle different game screens?

texts:
While developing my game I am often asking myself if my way of handling different game screens (MainMenu, Game, Ending, Highscore) is a good one.
I am currently using only one activity. The game loop is running in this class.
The currently active screen gets a update and paint method called from this loop like this:

while (running) {
    if (!holder.getSurface().isValid())
        continue;

    float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
    startTime = System.nanoTime();

    if (deltaTime > 0.315) {
        deltaTime = (float) 0.315;
    }

    game.getCurrentScreen().update(deltaTime);
    game.getCurrentScreen().paint(deltaTime);

    Canvas canvas = holder.lockCanvas();
    canvas.getClipBounds(dstRect);
    canvas.drawBitmap(framebuffer, null, dstRect, null);
    holder.unlockCanvasAndPost(canvas);
}

One problem I am often facing is that the screen classes aren't activities, so I am unable to start a DialogFragment, as an example, because it needs a FragmentActivity. Since these classes are just instantiated the FragmentActivity never gets started.

If I need a dialog, I am currently just making an Activity to a custom dialog.

How would you handle a game framework? Are there any good examples out there?


texts: what is the legality behind "openMW" ( an open source implementation of morrowind)

texts:
knowing bethesda those people probably sue hard....yet there is an open source implementation of morrowind which is actually quite good.
but that question remains, what is the legality behind all of this?
is it legal to distribute a free open-source implementation/adaptation of a videogame?


texts: Normalize a rotation around the Z-axis (issue with GLM)

texts:
I'm trying to undo some transformations coming from an external tool*. I'm getting different results depending on subtle differences in the input and wondering how to convert to a rotation about the Z-axis only.
The transformations are expressed as a matrix = translation * rotation * -translation.  I want to decompose the resulting matrix into a single translation and rotation around Z -- I know this is possible given the source material (2D plane).
My problem is coming from GLM decompose.  Given a matrix that looks like this:
[         -0.5 |     0.866025 |            0 |            0 ]
[    -0.866025 |         -0.5 |            0 |            0 ]
[            0 |            0 |            1 |            0 ]
[            0 |            0 |            0 |            1 ]

If I call decompose, then take the eulerAngles of the Rotation I end up with either:

(            0,           -0,      2.09439 ) from quat(          0.5,            0,     0.866025,            0 )
(      3.14159,       1.0472,      3.14159 ) from quat(          0.5,            0,            0,     0.866025 )

The difference depends on how the matrix was generated, whether the rotation was 120degrees or -240degrees. The display must be clipping the floating point, introducing a subtle change.
I'm assuming both these rotations are actually the same.
How do I force/convert the result to be a rotation about the Z axis only.

*The external tool is Inkscape which uses the CSS/SVG function rotate(r, cx, cy) instead of a rotation and transform.  That function results in the matrix: translate(cx,cy,0) * rotate(r, (0,0,1)) * translate(-cx,cy,0)


texts: How can I manually call/fire OnTriggerExit() for colliders a trigger is inside of in Unity?

texts:
In Unity, the OnTriggerExit() method is not called/fired (not sure if it's an event or not) when an object is disabled or destroyed within it's collider. In comparison to it being fired is an active object that was within it's collider no longer being inside the bounds of that collider on the next frame. I want to be able to call OnTriggerExit() on my triggers OnDisable() method as a workaround.

How would I go about calling/firing OnTriggerExit() manually?


texts: Setting up a custom cursor image in LWJGL 3

texts: How can I load a custom cursor image with LWJGL3? It took me a while to figure this out. Here is how it is done for version 3.0.1. Hope this helps.


texts: Looking for architectures to develop massive multiplayer game server

texts: Hello all Where can I find architectures and examples of building massive multiplayer game server Does the does the concept of building it on top of libenevt is right ? or I need to think more on thread per connection ? im targeting to web players playing from flash / html5 clients . Thanks


texts: DirectX11 - Texturing Terrain Mesh with Shared Vertices

texts:
I'm trying to create and texture a terrain mesh in DirectX11. I've managed to create the mesh itself, but I don't know how I should do the texturing. Let me start by explaining what I'm doing so far:

I have a vertex structure that looks like this:

struct Vertex
{
    XMFLOAT3 position;
    XMFLOAT4 color;
};

Then I create all the vertices for the terrain mesh:

for (int z = 0, index = 0; z < terrainHeight; ++z)
{
    for (int x = 0; x < terrainWidth; ++x, ++index)
    {
        vertices[index].position = XMFLOAT3(x, 0.0f, z);
        vertices[index].color = XMFLOAT3(1.0f, 1.0f, 1.0f, 1.0f);
    }
}

Then I create all the triangles for the terrain mesh with indices:

for (int z = 0, index = 0; z < terrainHeight - 1; ++z)
{
    for (int x = 0; x < terrainWidth - 1; ++x)
    {
        indices[index++] = (z    ) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x + 1);

        indices[index++] = (z    ) * terrainWidth + (x    );
        indices[index++] = (z + 1) * terrainWidth + (x + 1);
        indices[index++] = (z    ) * terrainWidth + (x + 1);
    }
}

With 256x256 vertices I get this result (rendering in wireframe):

I'd now like to change the color to a texture, so I change the Vertex structure to this:

struct Vertex
{
    XMFLOAT3 position;
    XMFLOAT2 texture; // Changed the color to a texture coordinate.
};

And this is where I get stuck. Since each vertex now have a texture coordinate (U, V) I'd like to set it up like this:

But each vertex can only hold one texture coordinate. As you can see, the 2 vertices between square A and B needs 2 different texture coordinates each in order to map it correctly. If I'd loop through each pair of triangles, then when I reach square B I'll overwrite the texture coordinates that was correct for square A.

So therefore I have some questions:

Am I doing this in the "right" way? How does modern games do it? Do they texture each square or the entire mesh?
If I'd like to texture each square, how can I solve this problem?


texts: Unity Addressables - do all editor instances need a local copy?

texts:
I'm able to get Unity addressables to load in editor 1 ("project 1"), where it is both generating  the .json/hash/bin and loading the prefab asset into scene. This is then placed on AWS (and the link has been tested to download in browser  https://bucket.amazonaws.com/[BuildTarget]).
However, in editor 2 ("project 2"), after setting up the remote_load to be the link above, the prefab does not load.
Maybe I am misunderstanding how this works - does "project 2" also need a local copy of the prefab, or can that itself load from the server?


texts:
I read this presentation and on 6th slide I found that is not need to use multiple render targets and depth can be taken directly from depth buffer.

From which version of DirectX or OpenGL can be the feature used? How to do that?


texts: How do I efficiently check which object causes the most gravitational force in a list of thousands of objects?

texts:
I'm working on a proof-of-concept space engine, and one of its tasks is to find the object with the greatest sphere of influence towards the player; that is, the mass of the object, divided by the square root of the distance to the player. I don't see much optimization to do, as an octtree or a KDTree only works for points. Even though there might be a planet only a few thousand kilometers away, a black hole many million kilometers away might have a greater gravitational force on the player.

The current check is brute-force. I go through each object, and return the one with the highest gravitational pull on the player. I have around 10,000 objects to perform this check on, but I might increase this number to millions, later. Optimally, I want to perform the check during each frame, which currently lowers the frame rate from 1600 a second to around 100 a second, which is unacceptable.

A few ideas comes to mind, but none of which seems optimal:

Make the system run in its own thread. Great, if the user has a core they don't use for anything, but only gives more overhead if there are no more cores available.
Limiting the check to run only once every few frames, resulting in a better average frame rate. The frames that need to be checked will result in stuttering, so this seems like a bad road to go down.
Limiting the number of objects checked per frame, so no matter what, only 128 objects may be checked per frame. This has the advantages of solution 2, without the disadvantage of stuttering, as each frame is equally heavy. Still, the programmer in me somehow also dislikes this solution. Then again, game programming is quite different from what I have previously worked on.

I'm not asking solely just for the purpose of this specific system, but also to find the best practice for problems like this, where there must be a compromise between running frequently and performance.

Any suggestions specific to this problem, like how to optimize the function through a modified version of a KDTree, is also very much appreciated; but the question is directed more generally towards the best practice for such problem.


texts: How to find out the vertices of the polyhedron formed by the overlapping area of two rotated boxes?

texts:
What is the most efficient way for finding out the vertices of the polyhedron formed by the overlapping area of two rotated 3D boxes?

If it is still confusing what I mean by "polyhedron formed by...", see the picture below:

Of course, in that picture the boxes are still not rotated*.

But imagine I rotate both. I would like to identify the vertices that form the inner area of the overlapping.

What is the less expensive way for doing so? (I'm using C#, but can read C++ well).

*The picture comes from a blog post that teaches how to get the overlapping area of two 3D AABBs: http://blog.meltinglogic.com/2015/04/aabb-overlapping-area/


texts:
I am done with my game's framework and I am trying to implement a
life-management system. My framework so far has:

Systems that hold pointers to the Entities they are interested in.
An Engine class that owns the different systems.
An EntityManager that owns the Entities.

Now every time you add/remove a Component to/from an Entity, the Entity notifies the engine class to run a(n) (un)registration routine that passes the Entity to the Systems which in turn decide whether they want to (un)register the Entity or not.

Say that I have a DestroyerSystem that remembers all Entities with a HealthComponent and is responsible for deleting the ones with no life:

void DestroyerSystem::update(float dt = 0)
{
        for (auto& entity : registered_entities)
        {
                if (entity.getComponent<HealthComponent>().hp == 0)
                {
                        EntityManager.destroy(entity);
                }
        }

}

The problem is that the Systems are supposed to keep valid pointers to the Entities and I am not sure how I can achieve that cleanly.

The only solution that I have so far is to make the Systems have an unregister() function that takes the pointer to the deleted element and erases it from the registered_entities container. The Engine class would also have an unregister() function that would call the unregister() functions of the Systems. This works good for the other systems but creates problems when applied to the DestroyerSystem because it breaks iteration. To tackle this I copy the container and iterate on that one instead:

void DestroyerSystem::update(float dt = 0)
{
        auto entities = registered_entities;
        for (auto& entity : entities)
        {
                if (entity.getComponent<HealthComponent>().hp == 0)
                {
                        entityManager.destroy(entity);
                        engine.unregister(entity);
                }
        }

}

Does anyone have any better proposals for this?


texts: What are the minimum hardware / driver requirements for running a Monogame 3.x game, on each of the various Operating Systems?


texts: Questions to answer and heuristics to use when selecting a new project?

texts:
Say I have a list of (in my case, indie) game ideas, from which I need to select a new project to work on.

What are the questions/heuristics that you would use - and ideally have already used successfully in the past - to narrow down such a list to a single idea to work on?


texts:
I am thinking about a new game idea for the iPhone and presumably all the levels would have to be made programatically. So Im wondering what the best method to approach it?

Say I have a game with a standard typical 2d, top down maze. Thise maze is simply made up of walls, multiple rectangles on screen, making paths.

Do I have to manually work out the position of every rectangle and put it in with an x and y position or is there a better way? I see this taking, forever, there must be certain ways developers approach these situations to get by them efficiently and quickly surely?

Thanks.


texts: Creating a list of buttons dynamically in code

texts:
I have a list of contacts. I need to create a scrollable list of buttons that are created dynamically so I can add each contact name as the button text. How would I do this all in code? My biggest concern is making sure the sizes stay consistent. I haven't had to do that in code before.

EDIT:

And here is the code to add the buttons to this:

for (int i = 0; i < count; i++)
{
    if (i > 0)
        crt.sizeDelta = new Vector2(crt.sizeDelta.x, crt.sizeDelta.y + initHeight);
    GameObject contactButton = Instantiate(Resources.Load("Contact Button")) as GameObject;
    contactButton.transform.parent = contactsList.transform;
    contactButton.GetComponentInChildren<Text>().text = names[i];
}


texts: DirectX11 how to use textures and samplers in slots in shaders

texts:
I have a system to render many objects, but I don’t know how to render more tan one object with same shader, let me explain:

I have a sphere and a cylinder, but both objects can be rendered by different shaders, example:
Shader1: Shader to render object using 1 texture
Shader2: Shader to render object using 2 textures

Both objects need to coexist in space, so if I want to render sphere with shader 1 and I use:
shader1 resources:

context_->PSSetShaderResources(0, 1, &texture);
context_->PSSetSamplers(0, 1, &sampler);
…

shader2 resources:

context_->PSSetShaderResources(1, 1, &texture);
context_->PSSetSamplers(1, 1, &sampler);
context_->PSSetShaderResources(2, 1, &texture);
context_->PSSetSamplers(2, 1, &sampler);
…

in Shader1 the resources are references like this:

Texture2D colorTexture: register(t0);
SamplerState sampler: register(s0);

And in Shader2 the resources are references like this:

Texture2D colorTexture: register(t1);
SamplerState sampler: register(s1);
Texture2D colorTexture: register(t2);
SamplerState sampler: register(s2);

But what if I need to use shader1 resource’s in shader2???? How to manage those resources or do I need to replicate shader2 with shader1 registers?? this is the simplest example, this is part of a very much complex system with many many shaders and many textures, but I don’t know in what slot will be setted the resources, this can be absolutely generic, example, slot 5 will be used for texture 1 of shader2… It is possible to render many objects with minimal change of shaders, but the resources could be updated at any time..
I’m using directX11.


texts: Is my idea of how to use matrices to layer 2D on top of 3D correct?

texts:
I'm new to using matrices, so I'd like some input on whether I've understood the use of them in the context described in the title.

Right now I have a small Direct3D 11-based game engine which renders a stack of scenes, or screens if you will, from bottom to top. I have a static 2D orthographic view-projection matrix that simply maps to screen coordinates from ( 0, 0 ) to ( screen width, screen height ). The position and resulting world matrix of the different entities are set with coordinates relative to this.

However, I'd like to expand on this by enabling different scenes to use different perspectives, so that I would be able to render a 3D scene with perspective, and then a flat 2D GUI on top of it. But since I'm very new to using matrices, I'd like confirmation on whether I have the correct idea of what will happen before I change things, because it takes a fair amount of work to refactor the engine with the way it is set up now.

Let's say I have Scene A as the 3D scene, and Scene B as my 2D overlay.

When entities in Scene A is rendered, the following matrices are passed to the shader:

View = camera position/orientation in the 3D world
Projection = perspective matrix with FoV, aspect ratio and near/far depth
World = the individual entity's position in the 3D world

Then, when I want to render Scene B, I pass these matrices instead:

View = identity matrix since the view is static
Projection = orthographic matrix with screen coordinates
World = the individual entity's position in the screen coordinate system

In both cases the vertex shader multiplies the matrices like so: world * view * projection

Is this correct? Will this draw my 3D scene as expected first, and then correctly draw the 2D elements relative to the screen coordinate system instead? Or have I misunderstood how the matrices work?

EDIT: scratch the question below; I found the answer under related questions...:
Should the modelview and projection matrices be calculated in the shader or on the CPU?

Original question:
And one more thing, would it be more efficient to compute the View-Projection-World matrix on the CPU end before passing it to the shader's constant buffer, or is the GPU better suited at receiving the three matrices and multiplying them on the shader side? I've seen both approaches used, but I haven't found any conclusions on which way is more practical/efficient. I have two constant buffers by the way, one with the View and Projection matrices which is updated once per scene, and one with the World matrix updated for each individual entity, so the memory bandwidth savings would be insignificant if I moved the multiplications to the CPU instead. But would that be faster in theory, and are there any eventual drawbacks to this?


texts: I recently started to create a sidescroller game, for learning purposes. While creating several levels for it, i stumbled upon the question, how to implement these levels into my game. I made (and i think this is the common way, correct me if i am wrong, i appreciate it) a state-based game, with a menu-state, a game-state and so on. So whats the common way to implement various levels in the game-state? Should i create a new state for each level? or should the game-state be the only "playable" state, and "know" (however realized) the current level it is in? How would you realize point-counting or something like that (like a live system, or a simple beat-the-highscore point system)


texts: Need help in making buttons for MenuScreen in Java

texts:
I'm making a Menu for my game and I made the MenuState(class) and made a MouseManager(class, implemented MouseListener and MouseMotionListener) and they are different class in different folder. Here is my problem, usually people make their buttons my drawing rectangles and adds font and makes that their button.
But I didn't do that. I made a button using Photoshop and I put it in my sprite sheet, cropped it and made it my button. now I want to make it that if I click on my 'play' button picture it sends to my GameState and if I click on my 'exit' button picture it closes my window

MyMenuState(class)

 package com.vescorspel.game.MyFirstGame.states;

import java.awt.Color;
import java.awt.Graphics;

import com.vescorspel.game.MyFirstGame.Handler;
import com.vescorspel.game.MyFirstGame.gfx.Assets;

public class MenuState extends State{
// Resizing my button from 64 pixels to 256 pixels
public static final int ButtonWidth = 256;
public static final int ButtonHeight = 256;

// coordinates where my buttons are placed in pixels ;)
public static final int PlayButtonX = 500;
public static final int PlayButtonY = 100;
public static final int ExitButtonX = 500;
public static final int ExitButtonY = 400;

public MenuState(Handler handler){
 super(handler);
}

// My tick method
@Override
public void tick() {
 //This If statement tells my game if I LeftClicked anywhere in the MenuScreen, then it send me to my GameState(GameScreen)
 if(handler.getMouseManager().isLeftPressed())
  State.setState(handler.getGame().gameState);;
}

//My render where i render the button pictures in my MenuScreen
@Override
public void render(Graphics g) {
 //PlayButton from my Assets class(this is an image)
    g.drawImage(Assets.PlayButton, PlayButtonX, PlayButtonY, ButtonWidth, ButtonHeight, null );
    //ExitButton from my Assets class(this is an image)
    g.drawImage(Assets.ExitButton, ExitButtonX, ExitButtonY, ButtonWidth, ButtonHeight, null);
    //these 2 commands tells my game to make a red cube and follow my mouse in the MenuScreen
    g.setColor(Color.RED);
    g.fillRect(handler.getMouseManager().getMouseX(), handler.getMouseManager().getMouseY(), 8, 8);
}
}

MouseManager(class)

package com.vescorspel.game.MyFirstGame.input;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class MouseManager implements MouseListener, MouseMotionListener{
 private boolean leftPressed;
 private int mouseX, mouseY;

 public MouseManager(){
 }

 //Getters

 public boolean isLeftPressed(){
     return leftPressed;
 }

 public int getMouseX(){
     return mouseX;
 }

 public int getMouseY(){
     return mouseY;
 }

 // Implemented methods

 @Override
 public void mousePressed(MouseEvent e) {
  if(e.getButton() == MouseEvent.BUTTON1)
   leftPressed = true;
 }

 @Override
 public void mouseReleased(MouseEvent e) {
     if(e.getButton() == MouseEvent.BUTTON1)
         leftPressed = false;
 }

 @Override
 public void mouseMoved(MouseEvent e) {
     mouseX = e.getX();
     mouseY = e.getY();
 }

 @Override
 public void mouseDragged(MouseEvent e) {
     // TODO Auto-generated method stub

 }

 @Override
 public void mouseClicked(MouseEvent e) {
 }

 @Override
 public void mouseEntered(MouseEvent e) {
     // TODO Auto-generated method stub

 }

 @Override
 public void mouseExited(MouseEvent e) {
     // TODO Auto-generated method stub
 }

}


texts: How to get pixels affected by a light in deferred shading?

texts:
I implemented deferred rendering in my little engine using framebuffers but there is no dynamic lighting for now. The g-buffer contains positions and normals in view space and albedo.

To implement real time lighting, I guess that I need to perform one pass for each light. Given the position and shape of a light, how can find all pixels affected by the light? I want to support point lights, spot lights and directional lights.


texts: Black screen when trying to render multiple textures

texts:
I generate an array for two textures:

int[] textureID = new int[2];
glGenTextures(1, textureID, 0);
glGenTextures(1, textureID, 1);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureID[0]);
glBindTexture(GL_TEXTURE_2D, textureID[1]);

Render:

int Position = glGetAttribLocation(Shader.program_Image, mPosition);
glEnableVertexAttribArray(Position);
glVertexAttribPointer(Position, 3, GL_FLOAT, false, 0, vertexBuffer);
int TexCoordLoc = glGetAttribLocation(Shader.program_Image, atexCoord );
glEnableVertexAttribArray (TexCoordLoc);
glVertexAttribPointer (TexCoordLoc, 2, GL_FLOAT, false, 0, uvBuffer);
int mtrxBackground = glGetUniformLocation(Shader.program_Image, mbackground);
int mtxObj = glGetUniformLocation(Shader.program_Image, mobj);
glUniformMatrix4fv(mtrxBackground, 1, false, m, 0);
glUniformMatrix4fv(mtxObj, 1, false, m, 0);
int mSamplerLoc = glGetUniformLocation (Shader.program_Image, bTexture);
int mSamplerLoc1 = glGetUniformLocation (Shader.program_Image, sTexture);
glUniform1i (mSamplerLoc, 0);
glUniform1i(mSamplerLoc1, 1);
glDrawElements(GL_TRIANGLES, background.getIndices().length, GL_UNSIGNED_SHORT, drawListBuffer);

My fragment shader is like this.

precision mediump float;
varying vec2 v_texCoord;
uniform sampler2D b_texture;
uniform sampler2D s_texture;
void main() {
    gl_FragColor = texture2D(b_texture, v_texCoord );
    gl_FragColor = texture2D(s_texture, v_texCoord );
}

I have no error message, but when I run the application, I only see a black screen.

The app runs correctly with just one texture, but doesn't with more than one. What's wrong in my code?

Do I have to add another set of coordinates and update the vertex shader? Because I have only one “rectangle” constructed from two triangles.


texts: How to use Irrlicht game engine in cygwin?

texts:
How can I develop a game with Irrlicht game engine in a cygwin environment?

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

Thanks, Ehsan.


texts: What is the standard way to render each mesh at their respective locations?

texts:
I have a single mesh, and I give the vertex-shader a matrix which holds the objects position, scale and rotation. It seems to work.

in vec3 position;
uniform mat4 object;
uniform mat4 view;
uniform mat4 proj;

void main() {
   gl_Position = proj * view * object * vec4(position, 1.0);
}

What if I have multiple meshes? What is the standard way to approach this? Feed in a different mat4 for every mesh rendered, or have separate vertex shaders for each mesh?


texts: Why is the "back" key acting like it is pressed twice?

texts:
I want to show toast message when the user presses the back button.
I am handling button using this code, which is in my Update function:

if (Input.GetKeyUp(KeyCode.Escape)) {
  print ("UPUP");
  ToastHelper.ShowToast ("Back", false);
  //Application.Quit();
}

ToastHelper is plugin here.

The issue is that the toast message shows up twice, so it seems like the back key is acting like it was pressed twice. I only want it to execute once.


texts: Create tile map in Cocos2D-X by not using TMX file

texts:
I used to make a tile base game in Windows with my own tile map file, but it is a static tile map. I use an 2D array to store of my tile map. Now I want to make game in smartphone by using Cocos2D-X, and I want to make a random tile map, so I guess using TMX file is not appropriate in this case. I tried to search about making a tile map with Cocos2D-X but there is only a tutorial with TMX file.

Can you give me an idea about this case.

Thanks in advance.


texts: How do I expose a field of an abstract type to the Inspector?

texts:
I have a class hierarchy with an abstract parent class.

I would like to have a field of this type exposed to the inspector but it appears to not display.

This test code:

[Serializable]
public abstract class AbstractClass
{
    public string testField;

    public AbstractClass(string testValue)
    {
        testField = testValue;
    }
}

[Serializable]
public class ConcreteClass : AbstractClass
{
    public ConcreteClass(string testValue) : base(testValue)
    {
    }
}

public class MonoBehaviourClass : MonoBehaviour
{
    public AbstractClass abstractClass = new ConcreteClass("abstract");
    public ConcreteClass concreteClass = new ConcreteClass("concrete");
}

Produces this result:

As you can see the field for the abstract class is missing.

How can I expose a field of an abstract type to the inspector?


texts:
When exporting a model from 3ds Max as FBX to import it into XNA, what metrics should I choose to make 1 unit in 3ds Max equal to 1 unit in XNA?

For example: I have a sphere model with 1m radius exported to XNA. When drawing I use:

Matrix[] transforms = new Matrix[model.Bones.Count];
model.CopyAbsoluteBoneTransformsTo(transforms);
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect be in mesh.Effects)
    {
        be.EnableDefaultLighting();
        be.World = mesh.ParentBone.Transform * Matrix.CreateScale(radius)
                    * TransformMatrix;
        be.View = camera.view;
        be.Projection = camera.projection;
    }
    mesh.Draw();
}

Radius is defined in my class as float.

This will draw a ball smaller than 1.


texts: How can I add a button that opens a pop-up?

texts:
I have developed a game with a libGDX game engine. I want to create a button on the game screen and add a popup to this button. How can I do this?
My current code:
public class GameScreen extends BaseScreen implements ShowDictionaryEvent
{
    private Preview preview;
    public GameController gameController;
    public Dial dial;
    private BoardView boardView;
    public DialAnimationContainer dialAnimationContainer;
    private LevelEndView levelEndView;

    private Rocket rocket;
    private BombDialog bombDialog;
    public AlertDialog bombBlastDialog;

    public ExtraWordsButton extraWordsButton;

    private ImageButton shuffleButton;
    private BoardOverlay boardOverlay;
    private Feedback feedback;

    private DictionaryDialog dictionaryDialog;
    private BonusWordsIncompleteDialog bonusWordsIncompleteDialog;
    private BonusWordsCompleteDialog bonusWordsCompleteDialog;
    public SideComboDisplay sideComboDisplay;

    private Smoke smoke;
    private Ufo ufo;
    public boolean offeredBoosterInThisLevel;
    public int nextBoosterType;
    private Label goldPackBubbleLabel;

    private RemoveAdsDialog removeAdsDialog;
    public Image comboLight;;
    public CameraShaker cameraShaker;

    private DelayAction comboLightDelay;
    private SequenceAction comboLightSequence;
    private RunnableAction comboLightRunnableAction;
    public int tempComboReward;

    public GameScreen(KelimeGame wordConnectGame) {
        super(wordConnectGame);
    }

    @Override
    public void show() {

        super.show();

        setTopPanel();
        topPanel.setY(stage.getHeight());

        topPanel.topComboDisplay.setGameScreen(this);

        dialAnimationContainer = new DialAnimationContainer(KelimeGame.resourceManager);
        dialAnimationContainer.setVisible(false);
        stage.addActor(dialAnimationContainer);

        cameraShaker = new CameraShaker();

        gameController = new GameController();
        gameController.setGameScreen(this);

    }
}


texts: How do I make a sprite blink on an HTML5 canvas?

texts: I'm thinking of the flashing effect many games have when a character gets hit and takes damage. Something like overlaying a lighter color on visible sprite pixels for a second.


texts: How to display all the previous strings except the current strings from the list?

texts:
I would like to create some sort of log to display previous strings for my game, but I still cannot figure out how to properly displaying them. I am using a button to run this method every time player clicks it.

public void AddLog()
{
    foreach (string logEvent in DisplayDialogueList)
    {
        logTextList.text = logText;
        logText += logEvent;
        logText += "\n\n";
    }
}

This method supposed to be displaying all the previous strings that has been displayed before inside DisplayDialogueList but I can't limit the displays only for the previous strings, and it will always display all the strings from the list.

I have tried the .Skip method to detect the current index of the list that are currently being displayed but it does not refresh the list, meaning if I loop to skip the first index from the list, it will always skips the first index even the current index to be displayed is second index and so on.

I also having trouble to skip the last index on the list since C# Unity does not support .SkipLast.

Any help would be appreciated.

EDIT:
Sorry for the confusion, this is how I managed to distinguish which is the current string to be displayed, it runs on button click

public void Display()
{
    //Checks to see which element from the list has the same index number as the current index
    if((index == textIndex) && !(DisplayDialogueList.Count <= index))
    {
        //Displays the string from the list that has passed the argument above
        textList.text = DisplayDialogueList[textIndex];
        index +=1;
        textIndex = index;
    }
}

Everytime the button is clicked, the index number will be increased, so it will matches with the string with the same index from the list and displays it.

UPDATE:
Ok I managed to skip the current displayed index and last index (thanks to the answer below) but this happens apparently

The Hello, my name is Mira text is in the first index of the list. How do I make sure that text won't be displayed again after the back button is clicked, which run the AddLog()?

The updated code is below:

if(!(index > DisplayDialogueList.Count))
    {
        firstIndex = DisplayDialogueList.First();
        lastIndex = DisplayDialogueList.Last();
        foreach (string logEvent in DisplayDialogueList)
        {
            if(logEvent != lastIndex && !(firstIndex == currentIndex))
            {
                logTextList.text = logText;
                logText += logEvent;
                logText += "\n\n";
            }
        }
    }


texts:
I'm trying move animation within screen, here's the code

Animation<TextureRegion> animation_run = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP,
    Gdx.files.internal("run.gif").read());
    float elapsedTime += (Gdx.graphics.getDeltaTime()) * 2;
    float playablePosition = (Gdx.graphics.getWidth()) / 2 - 200;
    float currentPosition = 0;
    for (int i = 0; currentPosition <= playablePosition; i++) {
    currentPosition += i;
    batch.begin();
    batch.draw(animation_run.getKeyFrame(elapsedTime), currentPosition, 0, 200, 300);
batch.end();
}

but I got not exactly what I want

Does anybody know how fix my code to make movement from left edge to the center properly?


texts: Can you use the RangeAttribute to limit the size of an array?

texts:
I recently found out about the RangeAttribute and how you could use it to limit the values of your parameter when entering them in in the inspector window. However, I needed to use an array for randomly selecting Prefabs so they can spawn randomly at any given time. The problem is Unity lets me have an array size of zero, but I also want to limit the number of possible prefabs. I was wondering if there is a way to use RangedAttribute to limit the size of an array, and if not is there a different way to achieve this? I have extensive experience in Java and C# but recently started in Unity, so I don't know if I'm asking the right questions, so any guidance right now would be greatly appreciated. Thanks.

P.S. I would be able to attach the script to give an example if needed.


texts:
I'm having trouble working out a formula using this experience curve to get the total exp after each level. I bet it's easy and I'm just overthinking it.

maxlvl = 10;
increment = 28;
baseexp = 100;
function calc(){
    for (i = 0;i<(maxlvl*increment);i+=increment){
        expperlvl = baseexp + i;
        document.writeln(expperlvl);
    }
}


texts:
I am using WWWForm to do the equivalent of GET and POST from python. To add headers to my unity requests, according to the documentation I could two options:

WWWForm form = new WWWForm ();

form.AddField("user", username); //OPTION 1:
https://docs.unity3d.com/ScriptReference/WWWForm.AddField.html

form.headers["user"] = username; //OPTION 2:
https://docs.unity3d.com/ScriptReference/WWWForm-headers.html

With the risk of asking a very naive question: Can someone explain the difference between the two? Thank you


texts:
Sup?

I've been working on a new environment scene inside 3ds max. It looks something like this -

When I used the cry engine exporter to export my assets onto my level, I've been getting very weird shadow/texture problems. Do any of you know why that's happening? I'm pretty new to all of this, especially cry engine. Here's a screenshot of the same environment inside of cry engine sdk. If you look to the left of the environment, you can see how I'm getting weird results. The area I'm having issues with is highlighted with a faint blue line.


texts: How to map intensity from dot product to float RGB from 0 to 1?

texts:
I'm getting the dot product of the surface normal and light position. The weird thing is the dot product is larger than 1.

Also, I want to map that intensity from 0->1 to Float RGB from 0->1. Here is my code related to the issue:

if (the_object->polys[curr_poly].shading == 1)
{
    // compute the dot product between the light source vector
    // and normal vector to surface
    normal.x = normal.x / Vector_Mag_3D((vector_3d_ptr)&normal);
    normal.y = normal.y / Vector_Mag_3D((vector_3d_ptr)&normal);
    normal.z = normal.z / Vector_Mag_3D((vector_3d_ptr)&normal);

    dp = Dot_Product_3D((vector_3d_ptr)&normal,
        (vector_3d_ptr)&light_source);

    // test if light ray is reflecting off surface

    if (dp > 0)
    {
        // now cos 0 = (u.v)/|u||v| or

        intensity = ambient_light + ( dp / (the_object->polys[curr_poly].normal_length));

        float r = the_object->polys[curr_poly].color.R*intensity;
        float g = the_object->polys[curr_poly].color.G*intensity;
        float b = the_object->polys[curr_poly].color.B*intensity;
        Color color = Color(r, g, b, 1);
        // intensity now varies from 0-1, 0 being black or grazing and 1 being
        // totally illuminated. use the value to index into color table

        the_object->polys[curr_poly].shade = color.ToUInt32();
}

Updated code:

bool bOnce = true;

float normx = normal.x;
float normy = normal.y;
float normz = normal.z;
float mag;
if (bOnce)
{
    bOnce = false;
    mag =Vector_Mag_3D((vector_3d_ptr)&normal);
}

// compute the dot product between the light source vector
// and normal vector to surface
normal.x = normx / mag;
normal.y = normy / mag;
normal.z = normz / mag;

dp = Dot_Product_3D((vector_3d_ptr)&normal, (vector_3d_ptr)&light_source);

updated code version 2 :

if (dp > 0)
                {
                    // now cos 0 = (u.v)/|u||v| or

                    intensity = ambient_light + ( dp / (the_object->polys[curr_poly].normal_length));

                    if (intensity > 1)
                        intensity = 1;
                    if (intensity < 0)
                        intensity = 0;

                    float r = (float)the_object->polys[curr_poly].color.R /intensity;
                    float g = (float)the_object->polys[curr_poly].color.G/intensity;
                    float b = (float)the_object->polys[curr_poly].color.B/intensity;
                    Color color = Color(r, g, b, 1);
                    // intensity now varies from 0-1, 0 being black or grazing and 1 being
                    // totally illuminated. use the value to index into color table

                    the_object->polys[curr_poly].shade =  color.ToUInt32();

calculating normal vector of the polygon

void calculateNormalLenth(Rasterizer *rasterizer, object* the_object, int index)
{
    unsigned int vertex_0, vertex_1, vertex_2;
    vector_3d u, v, normal;           // working vectors
    vertex_0 = the_object->polys[index].vertex_list[0];
    vertex_1 = the_object->polys[index].vertex_list[1];
    vertex_2 = the_object->polys[index].vertex_list[2];

    // the vector u = vo->v1

    rasterizer->Make_Vector_3D((point_3d_ptr)&the_object->vertices_local[vertex_0],
        (point_3d_ptr)&the_object->vertices_local[vertex_1],
        (vector_3d_ptr)&u);

    // the vector v = vo->v2

    rasterizer->Make_Vector_3D((point_3d_ptr)&the_object->vertices_local[vertex_0],
        (point_3d_ptr)&the_object->vertices_local[vertex_2],
        (vector_3d_ptr)&v);

    rasterizer->Cross_Product_3D((vector_3d_ptr)&v,
        (vector_3d_ptr)&u,
        (vector_3d_ptr)&normal);

    // compute magnitude of normal and store in polygon structure

    the_object->polys[index].normal_length = rasterizer->Vector_Mag_3D((vector_3d_ptr)&normal);
}


texts: Why can't cross-platform multiplayer games exist?

texts:
At least, why are they so difficult to make? - assuming that's the reason why not even AAA studios accomplish this feat for their games. Especially with modern cross-platform game engines like Unreal and Unity that can build on Xbox, PS4, and PC, why hasn't this been done yet on a large scale?

For example, Diablo III is a game released on a variety of platforms. Despite it being a product of Blizzard, one of the wealthiest video game companies in the world, it does not allow an Xbox player to play with someone using a PC.


texts:
Is anyone here using MobFox to display their Android app's ads?  I was previously using the AdMob SDK but recently switched to MobFox and while it only took a short time to integrate it, there are a few outstanding issues which I can't work out.

With the AdMob SDK, in my onDestroy method, I would have this line:

adView.destroy();

However, I've looked through MobFox but I can't see an equivalent, am I missing something?!

(there is all the usual pause();, resume methods etc..... just can't find a destroy() method)


texts:
I'm trying to integrate Amazon GameCircle and I have been able to successfully initialize GameCircle in my app, but the problem is when I click on the button that displays achievements, the GameCircle achievement list comes up but it says "You have unlocked 0 of 0 achievements". Same happens with leaderboards i.e there are no leaderboards for this app. I have created a Leaderboard and a few achievements on the online developer portal for Amazon but they don't show for some reason. Can someone help me with this. Any links/resources that help with integrating GameCircle will be appreciated.

Thanks.


texts: Microservice architecture in game client

texts:
We can use microservice architecture for backend in mmo games, like one service for auth, one for chat, etc
But can(or should) we use same architecture for client part in mmo games?
One service for rendering, one for physics, one for chat, one for character creation, service for any game feature, etc
And any service can be written in any language you want and use messaging for communication


texts:
I have a Texture3D. I want to read a part of it from CPU side. (I'm using the SharpDX toolkit (v2.5.1).)

My data is always 0, but the output shows no errors.

This is the source texture:

testTex = Texture3D.New<float>(GraphicsDevice, wx, wy, wz, PixelFormat.R32.Float, texDat, TextureFlags.ShaderResource, sdx11.ResourceUsage.Default);

I'm trying to read part of it here:

tempFloat = new float[1];
TextureDescription stagedTexDesc = new TextureDescription()
{
    Height = 1,
    Width = 1,
    Depth = 1,
    MipLevels = 1,
    ArraySize = 1,
    Format = testTex.Format,
    Usage = sdx11.ResourceUsage.Staging,
    CpuAccessFlags = sdx11.CpuAccessFlags.Read | sdx11.CpuAccessFlags.Write,
};
texNew = Texture3D.New(GraphicsDevice, stagedTexDesc);

deviceContext.CopySubresourceRegion(testTex, 0, new sdx11.ResourceRegion(iHPos.X, iHPos.Y, iHPos.Z, iHPos.X + 1, iHPos.Y + 1, iHPos.Z + 1), texNew, 0);
texNew.GetData(tempFloat);

tempFloat[0] value is always 0.0. The GetData method performs Map and Unmap of the resource automatically

If I try to call GetData on the original texture, it seems to get the data correctly.

Also, is there a better way to read the data?


texts: How to build path to cover for bot if cover moves while player moves?

texts:
I'm changing cover positions depending of player position (to keep obstacle between player and cover point). But when my bot using pathfinding algorithms to build path to that cover, he will spend some time for moving by it. When it reaches the final destination, the real cover point will be moved and bot will not be in cover anymore.
So, how to correctly build path to cover to lead bot to right position when player moves?
And how to detect points from which covered bot can shoot to player? For i.e. bot covered by wall and he can move left or right to see player and shoot him and then return back to cover.


texts: XNA Automatic Collision detection from model?

texts:
This is going to be a rather vague question xD

In XNA is there a way of working out if a point or rectangle is colliding with a 3D .x object? It is a big model, and would take a long time to map out all the rectangles for collision detection so I was wondering if there was a easier way of doing it :)


texts: Is it possible to rent a server for my own game?

texts:
I'm an independent game developer and I don't yet have a lot of money to buy myself a very cool high-speed and low-latency internet connection along with a powerful server machine to place somewhere in the world to host my very own game's server application for my fans to play on.

I know it's possible to rent a server for an existing popular game (for example, Team Fortress 2), but how about renting a server for my own game that I'm developing? Are there services specifically for that, or should I just rent some general purpose something and go from there?

Such a server should be:

Easy to update
With a low-latency for a specific region (I'm planning on renting EU and US servers)