texts: OpenGL ES Faces appear to be transparent when alpha is 1.0?

texts:
I am working on an object (OBJ File) loader for my app on iOS, currently I have successfully read the vertices and the faces of the object, and I am now just adding colours to the imported models.

I am coming across a major problem now. Out of a cube with six faces, all coloured red apart from two opposite faces which are coloured blue. This cube is set to rotate so I can see all sides, but the colours do not appear correctly as shown in the video below:

http://youtu.be/0L2AIFkd2Qk

The blue faces only shows when the two blue sections overlap, I cannot figure out why - I am used to OpenGL for PC, is there something I am missing which is causing this strange colouring?

The colouring is achieved by sending a large float array of the format RGBA RGBA RGBA etc for each vertex;

// colours is the name of the array of floats
glColorPointer(colorStride, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
glDrawArrays(renderStyle, 0, vertexCount);

Any help you can offer would be great,

[EDIT]

Even if you don't know the problem, but have seen this before and know what it may be that would help as I have no idea where to even start looking as it is!

Many thanks


texts:
I am currently working on a 2d platformer and have the general idea of how to apply 'lighting' to my level, but I am not sure at all how to make it smooth, similar to Terraria, as you can see here.

I apply a tint to my tiles based on how many lights or open tiles there are nearby.  This tint varies from Color.White to a gray to Color.Black.

My question is how to 'smoothen' this out and if there is generally a better method to do this.  I'm not entirely a fan of shaders at the moment, as I am still learning about them.

Thanks!


texts:
I have a Player Class and i have 3 different Animations for it. I can render them perfectly but i don't know how to change from one animation to another. For exmaple i have 3 animations, one for Running, one for Jumping and one for Rolling down. Now i want to to change from running animatioon to Jumping when user presses a button. Inpout is not the problem. I am using the same code at LibGDX wiki to create to sue animation just like in this link: https://github.com/libgdx/libgdx/wiki/2D-Animation

It would be very helpful if you could give an example too but its not necessary though.


texts:
My latest game will take place on a small planetoid. I am looking for good data structure for representing cells on the surface of a sphere.
Triangles, squares, pentagons, hexagons? Which one minimises stretch the most and creates the best tiling?

Spherical mapping is the easiest but the stretch at the poles is unacceptable. Cubemapping is also fairly easy but there would still be considerable stretch near the cube corners.
Subdividing an icosahedron seems the best in terms of stretch but there is the problem of indexing many triangular arrays and finding neighbouring cells at the boundaries would be difficult.

I guess I could use a single linear array of points representing N-gons, each with an array of N neighbour indices, but that seems like a huge waste of space.

The game has RTS elements so I will be storing things like influence maps and performing A* pathfinding and convolution, so the representation has to be efficient.


texts: How can I rotate about an arbitrary point in 3D (instead of the origin)?

texts:
I have some models that I want to rotate using quaternions in the normal manner, except instead of rotation about the origin, I want it to be offset slightly. I know that you don't say, in 3d space, that you rotate about a point; you say you rotate about an axis. So I'm visualizing it as rotating about a vector whose tail is positioned not at the local origin.

All affine transformations in my rendering / physics engine are stored using SQT (scale, quaternion, translation; an idea borrowed from the book Game Engine Architecture.) So I build a matrix each frame from these components and pass it to the vertex shader. In this system, translation is applied, then scale, then rotation.

In one specific case, I need to translate an object in world space, scale it, and rotate it about a vertex not centered at the object's local origin.

Question: Given the constraints of my current system described above, how can I achieve a local rotation centered about a point other than the origin? Automatic upvote to anyone who can describe how to do this using only matrices as well :)


texts: A ball hits the corner slightly, where will it deflect?

texts:
I am currently making an iOS Game but I have a small problem. The game is simply a ball which you can control to avoid obstacles and find the food. When the ball hits, e.g. the top or the bottom of an obstacle, it's easy, the y-speed is just inverted. Same with left and right, where the x-speed is inverted.

But what happens when the mass point of the ball doesn't touch a side of the obstacle, but its surface is? Where will it be deflected? What's the maths behind that?
Here's an image to illustrate the problem:

Thanks in advance for help!


texts:
My mesh looks fine on Blender, but when I export it to my rendering engine (Ogre) the colors seem interpolated, screenshot below.

I am using filtering none in my material, so it shouldn't have any kind of interpolation. The rest of my meshes are fine, without any kind of weird effects.

Does anyone know what would be the cause of this? Thanks.


texts: How to check for collisions in "diagonal" tiles?

texts:
I want to create a tiled map in the following scheme:

The player should be able to walk on the blue line (street). Now, what is the best way to solve collision detection in this case? For example, in the case of tiles C1 and C2: If I make them walkable, then the player could also move in on those black parts of the tiles that should not be walkable.

On the other hand, if I make both C1 and C2 blocked, then the player would not be able to walk on these tiles (and therefore on the street) at all.

Any best practices?
Thanks.


texts:
Currently I'm doing an android 2D game using OpenGLES 2.0 and I noticed that my UVs never change in all of textures when rendering, like this in Java code:

    public static FloatBuffer vertexUv;

    public static void setUpUV()
    {
        float uvs[] = {0.0f, 0.0f,
                       0.0f, 1.0f,
                       1.0f, 1.0f,
                       1.0f, 0.0f
                      };
        ByteBuffer bb = ByteBuffer.allocateDirect(uvs.length*4);
        bb.order(ByteOrder.nativeOrder());
        vertexUv = bb.asFloatBuffer();
        vertexUv.put(uvs);
        vertexUv.position(0);
    }
    ...
    //UV sending in render
    int mTexCoordLoc = glGetAttribLocation(program, "a_texCoord");
    glEnableVertexAttribArray(mTexCoordLoc);
    glVertexAttribPointer(mTexCoordLoc, 2, GL_FLOAT, false, 0, vertexUv);
    ...

The problem is: even the UVs never change, I always sends via Java code to the GPU causing  waste of CPU using VBOs or not(I tested it using OpenGLES tracer). All textures of my game is in 2D mode so I believe that I don't need send it every texture rendering.

What I need to do? I tried to put the UVs in the shader code (I believe that is the way)  but without success... more or less like this: (I tested more alternatives in the shader/fragment shader too... below is only a example of my idea to solve this problem)

    //Vertex shader
    var v_texCoord= var(0.0, 0.0,
                        0.0, 1.0,
                        1.0, 1.0,
                        1.0, 0.0
                        ); //Could I init this in the first vertex processing?
    varying vec2 v_texCoord;
    attribute vec4 vPosition;
    void main()
    {
        gl_Position = vPosition;"
        v_texCoord  = v_texCoord;"   //To fragment shader
    }

Question: is possible put statically UVs in shader?

Performance:
Each blue region represents ONE texture rendering from a FRAME.
Maybe its a minimal and unnecessary optimization...

Thank you!!


texts:
How can I rotate a Transform over a specified time in a single line of code?

I have had a lot of trouble with this in the past.  I wrote a script which rotates a Transform by a specified rotation over n seconds, or rotates a Transform towards a Vector3 over n seconds, in a one liner.  I hope it helps others in the future.  See below.


texts: How should I organize my Unity scene graph?

texts:
In programming, we have coding conventions — self-enforced rules to help maintain order. Does such a convention or consensus exist on how to lay out scenes in Unity?

I've seen two styles of organisation:

By proximity: Like, building X → floor Y → room Z → healing potion Q
By type: A very flat scene graph with nodes like "Walls", "Doors", and "Healing potions".

What other options exist? Is there an overall best style? How do I choose the right one for my needs (e.g. indoor vs outdoor scenes)?


texts: Is there any way to move the sprites inside the sprite editor?

texts: I have imported a .png file of a stickman in which I had placed his head, body, two legs, and two hands a bit far apart from each other so that Unity will automatically convert the picture into sprites. Indeed, Unity did convert those body parts into sprites easily but now I have a problem. I made a bone going through the body and another bone going from the body to the head through the transparent area in between the sprites. Also, I have created one bone for each hand and leg and parented them to the bone in the body. The problem is that when I automatically generate geometry then the mesh rendering works completely fine within the body of the stickman, but it doesn't work anywhere else, be it the hands, or the head, or the legs. I can see the mesh only in the body of the stickman and nowhere else. Does this problem arise because the sprites are not connected, or is there any other reason? I am very new to game development, therefore please try to explain it in simple words. Thank You.


texts: Why can't I see how many installs my game has on its Google Play page?

texts:
I made an Android game, and I uploaded and published it to Google Play. Then, I installed it on my phone.

Why can't I see the install count, on its Google Play page?


texts: How to handle a scrollable map and player coordinates

texts:
I have a large map that a player will navigate over. Currently, it is just a single background image, but I would like to make it tiled map. How do I properly keep track of player coordinates?

Currently what I have working is:

1) I have a 800px wide by 500px high playing area
2) The player is normally positioned in the center of the screen at approximately (400px x 250px)
3) When the arrow keys are pressed instead of the player moving the map moves. I am currently using background-position at the moment to set which area of a background is displayed.

What I am currently trying to wrap my head around:

4) When the map reaches the boundaries it will no longer scroll, but my player is stuck in the center.
5) How to get the player back to the center again when they start to travel away from the corners.

The main problem I am having is knowing what coordinates I should be keeping track of. For example, should I be keeping track on only one of the following, or all three of the following:

Player position in map
Map position on screen
Player position on screen

What is a standard way to handle player movement like this?


texts:
Im currently writing a turn based start game, which will be played in an MMO style (players download clients, central server handling the game logic etc.) and now I need to decide how I charge my players for playing my game, since this will have some implications on how player account handling is going to work.

After looking a bit around, I found two alternative ways of doing this

a)
Classical in-app purchase, for which my clients need to be able to take the payment info, send them to my server which then charges the selected amount (using some API like stripe.com) and provides the selected services

b)
Account administration and payment via website, and then synchronization between website and game server over some database

Most MMO games I know use the website approach (b) although I assume that in-app purchase (a) is faster and easier for my players and will therefore yield higher conversion rates.

So, my question is:
Are there some major problems (security, paperwork) or drawbacks (complicated to implement) with in-app purchase I overlooked?

Im not doing a mobile game (full desktop) and Im from europe, just in case this information might be needed.


texts: Creating Direct2D PathGeometry from XAML format

texts: Is it possible to create a Direct2D PathGeometry object from a XAML string (or from any other vector format) or do I have to create such a parser myself?


texts: Is it better to hard code data or find an algorithm?

texts:
I've been working on a boardgame that has a hex grid as this board:

Since the board will never change and the spaces on the board will always be linked to the same other spaces around it, should I just hard code every space with the values that I need? Or should I use various algorithms to calculate links and traversals?

To be more specific, my board game is a 4 player game where each player has a 5x5x5x5x5x5 hex grid (again, the image above). The object is to get from the bottom of the grid to the top, with various obstacles in the way, and each players being able to attack each other from the edge of their grid onto other players based on a range multiplier.

Since the players grid will never change and the distance of any arbitrary space from the edge of the grid will always be the same, should I just hard code this number into each of the spaces, or should I still use a breadth first search algorithm when players are attacking?

The only con I can think of for hard coding everything is that I'm going to code 9+ 2(5+6+7+8) = 61 individual cells. Is there anything else that I'm missing that I should consider using more complex algorithms?


texts: Turn based Android game using google play games services

texts:
I want to develop a turn-based,multiplayer android game.Its very similar to chess.Is it possible to make entire game just by using google play games services(GPGS) ? ie, creating a game between 2 players,managing player moves,changing game states in database, all this can be done using GPGS?
Also,is google-app-engine anyhow related to this ?


texts: Scale a sprite as it moves down a triangle

texts:
I have a sprite that is inside a triangular like shape. How to make the sprite decrease in size as it moves down the shape?

https://ibb.co/gjc6oS


texts: Is it acceptable to have a global singleton engine class, in an entity component model?

texts:
I am in the process of writing an entity component model game engine, and I wanted to ask about the best way to lay out the code. I have run into an issue that I know will quickly cause me to run into more problems, down the road. In short, I currently have a render component, that I attach to the entity class. The problem is, I need the render component to signal the render engine, and add itself to it.

I thought about creating a singleton for the render system, but I quickly realized that was a bad road, and sooner or later, I would be creating singletons for just about everything (Ex, physics for the physics component). What I am currently thinking of doing is creating the base engine class as my only singleton. The engine class is responsible for initializing all of the systems available, such as the graphics and file systems, storing references to them, calling the game loops update method, and keeping track of all the entities in the game. If I did that, then my components or any other part of the code could easily reference the important systems they need to deal with via a simple Engine.MySystem. In the case of my render component, Engine.Graphics3D.addModel().

I am wondering is if this is an acceptable way of doing things, or not. If not, what would be better? I could, in theory, pass a reference to the GFX system to the render component, but that seems like a really bad idea. I feel like this is a nice middle ground between the two options.


texts: How to check/read multiple elements of the same arrayList at the same time in Java?

texts:
Im making an rpg game and right now I'm working on crafting. I've made a crafting slot class, and an arrayList of that class. I've got 10 of those slots in total, 9 placed in a 3x3 'order' and 1 below (like the minecraft inventory). I want to check if the 9 slots contain some items in a particular way, and if they do to put a item in the 10th slot. I can figure out how to craft stuff, but I don't know how to read all those 9 slots at the same time (btw Im using an enhanced for loop to update and render all of 'em). I figured I would check if the slots contain items in this order

4 4 4
0 3 0
0 3 0

(4 being stone and 3 being the stick item)
Each slot has its own item variable. So how can I access all of them at the same time? Or even if there is a simpler way to do this.
Thank you


texts: Unity ScriptableObject Conversation Dialogue and Reading

texts:
I'm unsure as to how I would reference a scriptable object's variables within a struct from another class. I know I'd have to make a public Conversation, but I'm stuck understanding how I could access it's struct, and how I could access individual variables such as the Position, or line string array.
Is this method even viable or should I look at creating a different way of accomplishing a dialogue conversation scriptable object?
Thanks for any insights and help~
My current code:
[System.Serializable]
[CreateAssetMenu(fileName = "New Conversation", menuName = "Create/Conversation", order = 1)]

public class Conversation : ScriptableObject
{
    [System.Serializable]
    public struct LineData
    {
        public string[] line;
        public string[] option;

        public enum Position
        {
            BottomLeft,
            BottomCentre,
            BottomRight,
            MiddleLeft,
            MiddleCentre,
            MiddleRight,
            TopLeft,
            TopCentre,
            TopRight
        }

        public Position position;

        public enum TextSpeed
        {
            Normal,
            Slow,
            Fast,
            UltraFast
        }

        public TextSpeed textSpeed;

    }
    public LineData[] Line;

}

```


texts:
I'm trying to rotate the camera around the view point of the camera. So when the user looks at a build the camera rotate around that building. But the camera does not need to have the building to rotate around. So therefore I want a camera that can rotate around his own point of view. So that the camera behave everywhere the same in the game.

How can I achieve this in Unity 5.6?


texts: Why was my Facebook game rejected with the note that "your app icon must not overlap with content in your cover image?"

texts:
My FB game just recently got rejected for two reasons. The first I fixed, but I just can't see to figure out what they mean by the second, and I was hoping someone else got the same issue and did know what they meant.

The remaining error is:

  Cover Image

  Your app icon must not overlap with content in your cover image.  Click on 'Web Preview' in the 'App Details' section to check for overlap prior to submitting your app.  See more here.

All I know is that the rejection has something to do with the cover image, not the icons or the screenshots.

The web preview of my game looks like this now:

Please let me know what to do to get approved.


texts:
I made a code for the character to be teleported to the place where the mouse cursor is, if the distance is less than or equal to 350.

Blueprint:

I happen to wish that if the distance were greater, the character teleported to the equivalent point of the line (distance between character and mouse cursor) of 350.

What I would like to know how to do:

I've thought about using the Line Trace by Channel, but I can not think of how to decrease the value of a distance and find the equivalent point in a line (vector value).

EDIT 1 (attempt based in Ocelot comment)

Blueprint:

Result in game:

Now the character teleports to a point that seems to have reference to the center of the level. I tried to add this vector to the character's position, but I did not get the desired result.

PS - The print of the word "Hello" on the screen indicates how many times I clicked on the teleportation key in the last 2 seconds.


texts: Bullet Physics: Applying a force at the point of collision

texts:
Suppose I want to simulate some kind of gripper with two "fingers" (such as pair of pliers, or two-fingered robot hand), picking up an object from the ground. Both the gripper and the object are dynamic rigid bodies.

I want to start with the object roughly in the centre of the gripper, and then move the two fingers towards the object, to determine the point at which they make contact with the object's surface. Then, I want to apply a certain force from the fingers onto the object, before finally lifting the fingers (and hence the object) upwards.

Is there any simple way to achieve this just by treating the two fingers as two individual rigid bodies? I want to just move the fingers towards the object to find the point of collision -- so can I treat them as kinematic objects (with zero mass so they don't fall under gravity, which is what I want), and move them manually by slowly changing the pose of each finger over time? But how will I know at what point the fingers and object collide, so that I should stop moving the fingers and start applying a force?

Thank you!


texts:
We're developing a game, we want to perform actions the moment the user touches the screen, delays make the game impossible to play.

We're testing on samsung S3 mini and samsung a5, we know they are low end devices and lags are to be expected.  But How accurate is Gdx.input.justTouch()? Is it so accurate on high end phones?

If not then how to improve the accuracy?
Is the same problem expected from keyboard or mouse input if we publish a webapp version?


texts: About online game servers and how to handle data

texts:
So my question isn't about what technology to use or how to do this or that, but a more general question.

I'm currently developing a action third person shooter. With elements of RPG - weapon,armor upgrades and items.

Players will be able to create new games or join old ones.
So my question is how to create the game server that players will play in.
I have two ideas on my mind.

The player who made the game is the server. All data passes trough him and he send this data to the server updating the database of the players with their XP points kills/deaths score and other.
Or my host machine is the server, the player who made the game just will open new instance on my host and will be like client. And all players send their input data to the host, the host updates the game and send response back to client for any new changes like where is the enemy and other.

And if i choose option 1 is there a chance the host to change the game content and manipulate the game results? (I think there is but i'm not sure)

And if i choose option 2 isn't that raising the response time and potentially the game lag?

or maybe there is another option?


texts: Trying to find a solution for instant knockback in multiplayer game

texts:
I'm making a server-authoritative fast-paced multiplayer game. I'm trying to implement wack-hammers, they are a melee weapon that knocks close players, in other words, that sets their velocity to inverse of their mass *  to the direction aimed at * the force of the hit. Even if the enemy player is only seen getting knocked after the client input gets processed on the server and after the enemy's position and velocity get sent back, I want to make it seem like your action appeared instantly.
I've tried one thing: when you knock a player, that player gets predicted for a short amount of time instead of being interpolated. That way, players appears to have been knocked out instantly, but there's an issue with that. When should I stop predicting? And how? When you think about it, the prediction is done on your own client time. The positions and velocities of other players are a few millisec old, so when you try to interpolate between your local "futur" predicted player position to the "old" server player position, you essentially move the other players back in time, and it looks real bad.
I'm not quite sure what to try to hide this issue. I can't possibly predict the enemy player's position forward in time, its movement can get too chaotic.
I've already watched the GDC talk from Overwatch's and Rocket League's netcode a million time, I'm not sure if they can help me with my issue.
Edit: I still haven’t found the best solution yet but there’s some useful information over at https://forums.unrealengine.com/development-discussion/c-gameplay-programming/1455487-responsive-knock-back-in-multiplayer-game


texts:
I'm making a simple platformer, and I wanted simple collision handling. So I gave all my objects an AABB hitbox and tried to resolve collisions. However, I can't get it to work.

My main character has a 32x32 hitbox and my walls have a 16x16 hitbox. I've used the separating axes solution to resolve the collision, like so (unoptimized):

Vec2 Box::Collides(Box* a_Other)
{
    Vec2 sum_extents;
    sum_extents.x = (m_Max.x - m_Min.x) + (a_Other->GetMax().x - a_Other->GetMin().x);
    sum_extents.y = (m_Max.y - m_Min.y) + (a_Other->GetMax().y - a_Other->GetMin().y);

    Vec2 double_center_to_center;
    double_center_to_center.x = (a_Other->GetMin().x + a_Other->GetMax().x) - (m_Min.x + m_Max.x);
    double_center_to_center.y = (a_Other->GetMin().y + a_Other->GetMax().y) - (m_Min.y + m_Max.y);

    bool result = (fabsf(double_center_to_center.x) < sum_extents.x) && (fabsf(double_center_to_center.y) < sum_extents.y);

    if (result)
    {
        return (
            Vec2(
                ((sum_extents).x - (double_center_to_center).x) / 2.f,
                ((sum_extents).y - (double_center_to_center).y) / 2.f
            )
        );
    }

    return (Vec2(0.f, 0.f));
}

My character just falls down onto the floor. I check the object I want to check against every other object and just see which one has the smallest intersection area.

Object* Scene::Collides(Object* a_Test, Vec2& a_Difference)
{
    float smallest_area = 10000.f;
    Object* closest = NULL;
    Vec2 final;

    std::vector<Vec2> check;

    for (uint32 i = 0; i < s_ObjectTotal; i++)
    {
        if (a_Test == s_Objects[i]) { continue; }

        Vec2 test = a_Test->GetCollision()->Collides(s_Objects[i]->GetCollision());
        float area = test.x * test.y;
        if (area > 0.f)
        {
            check.push_back(test);

            if (area < smallest_area)
            {
                smallest_area = area;
                final = test;
                closest = s_Objects[i];
            }
        }
    }

    if (closest)
    {
        a_Difference = final;
    }

    return closest;
}

The hitbox for the player is (32, 229.999995)(64, 261.999994) and the hitbox for the floor is (48, 256)(64, 272). So, the resulting movement (to resolve the collision) is (16, 5.9999930). The y is correct, the x is not. As a result, the player character hits the floor, stays above it and slides to the right very fast.

How do I resolve this collision?


texts:
I declared two variables on class level. One is the angle the object is rotated by. The second is a stopwatch.

float yRot = 0.0f;
static CStopWatch rotTimer;

I rotate the cube using the SpecialKeys function.

void SpecialKeys(int key,int x,int y)
{

    if(key == GLUT_KEY_RIGHT)
    {
        yRot = rotTimer.GetElapsedSeconds() * 10.0f;
    }

    if(key == GLUT_KEY_LEFT)
    {
        yRot = rotTimer.GetElapsedSeconds() * -10.0f;
    }

    glutPostRedisplay();
}

Finally the rotation matrix is calculated using the rotation variable, in the RenderScene function.

// Create a rotation matrix based on the current value of yRot
m3dRotationMatrix44(mRotate, m3dDegToRad(yRot), 0.0f, 1.0f, 0.0f);

It actually works. My problem is that when I hold the key the animation looks fine. But if I press it the animation looks a little jumpy, like the angle is bigger then when I hold it. I suppose this hangs together with the stopwatch. How to solve this issue?


texts: Elongated and straight terrain perlin noise

texts:
Why am I getting this kind of results with my perlin noise ? The terrain is wide or elongated or straight at the variations of the noise function.

This is the way I generate terrain:
    public void GenTerrain()
    {
        for (int x = 0; x < this.size.x; x++)
        {
            for (int y = 0; y < this.size.y; y++)
            {
                float xCoord = (float)(x + offsetMirror + origin.x) / this.size.x * scale;
                float yCoord = (float)(y + offsetMirror + origin.y) / this.size.y * scale;
                float noise = Mathf.PerlinNoise(xCoord, yCoord);

                if (noise > 0.6f)
                {
                    this[x, y].terrainType = TerrainType.Grass;
                }
                else if(noise > 0.5f)
                {
                    this[x, y].terrainType = TerrainType.Sand;
                }
            }
        }
    }

This is the way I add chunks of terrain
    void Start()
    {
        maps = new Dictionary<Vector2Int, Map>();

        Res.LoadMaterials();

    }

    void AddNeighbours(Vector2Int position)
    {
        int length = 32;
        for(int x = -length; x <= length; x++)
        {
            for(int y = -length; y <= length; y++)
            {
                Vector2Int addPos = new Vector2Int((x * size) + position.x, (y * size) + position.y);
                CheckAndAddMap(addPos);
            }
        }

    }

    void CheckAndAddMap(Vector2Int addPos)
    {
        if (!maps.ContainsKey(addPos))
        {
            AddMap(addPos);
        }
    }

    void AddMap(Vector2Int origin)
    {
        Map map = new Map(new Vector2Int(size, size), origin);
        maps.Add(origin, map);
        MapMesh mapMesh = new MapMesh(map);

        foreach (KeyValuePair<TerrainType, MeshData> kv in mapMesh.meshes)
        {
            MeshData meshData = kv.Value;
            TerrainType terrainType = kv.Key;

            GameObject go = new GameObject("Mesh");
            go.transform.SetParent(this.transform);
            go.transform.localPosition = new Vector3(mapMesh.map.origin.x, mapMesh.map.origin.y, -(int)kv.Key);
            MeshFilter meshFilter = go.AddComponent<MeshFilter>();
            meshFilter.mesh = meshData.mesh;

            MeshRenderer mr = go.AddComponent<MeshRenderer>();
            mr.material = Res.mats[terrainType.ToString()];
        }
    }

    // Update is called once per frame
    void Update()
    {
        Vector2Int playerPosition = ConvertPlayerPositionToTiles(ShootBehaviour.PlayerInstance.transform.position);
        AddNeighbours(playerPosition * size);
    }

    private Vector2Int ConvertPlayerPositionToTiles(Vector3 position)
    {
        Vector2Int result = new Vector2Int();
        result.x = (int)position.x / size;
        result.y = (int)position.y / size;

        return result;
    }


texts: What is the preferred starting address for a C64 game?

texts:
When writing a C64 game in 6502 Assembler and loading the game using LOAD "Game",8,1, I can choose the address where the game is loaded to. The most popular address I saw is $c000, closely followed by $0810, but I also saw $1000 and $2000 used a lot.

Why would I choose one over the other? I understand $0810 because it's close to $0801 which you have to write the SYS instruction to, but the other addresses all seem arbitrary.

Can someone shed some light into this?


texts:
For example, I created my character drawing on Paint.NET using the Pencil tool and now it's a sprite like asset.

If I want him to move do I need to create many different poses for him and render them according a timer? Or do I need to have each pose side by side in a single image, then render the rectangle I need, thus loading the picture only once?

Thanks.


texts: How do I render everything in software using XNA/C#?

texts:
I'm trying to find how to render everything with software in XNA, but I can't find what option I need to set.

I'd like to know which method/properties I have to call/set to make my app run in software mode as opposed to hardware accelerated mode.


texts: OnTriggerExit() called when game object with collider component gets re-parented

texts:
I have an object Hand, with a rigid body attached to it. In every Update() call, the user's hand controller rotation and position are tracked.

In my scene, there is an object Pin, with a mesh collider attached to it.

In OnTriggerEnter() (inside the Hand class), Pin becomes re-parented to Hand. (Pin's original parent is something else.)

My scene also contains other objects with colliders. However, these other objects do not get re-parented -- only Pin does.

Once this re-parenting takes place, OnTriggerExit() (in the Hand class) is called immediately. This is surprising to me -- I had expected OnTriggerStay() (in the Hand class) to be invoked instead, since Hand is still in contact with Pin.

Is such behaviour by design? Is there an elegant way of working around such behaviour?

UPDATE:

In response to this comment:

  Does the pin object have a parent before it becomes a part of the
  hand?

Yes. As mentioned in my post, Pin's original parent is something else.

  Or is it placed inside another collider? And does the pin leave any of
  these collider areas when the parenting takes place?

As mentioned in my post, Pin itself has a mesh collider component attached to it. Perhaps I am not understanding the question correctly...

  You can prevent the hand's script from getting this OnTriggerExit by
  adding a seperate rigidbody to the pin.

I added a separate rigid body to the pin (setting isKinematic to true), but OnTriggerExit() inside the Hand class is still called immediately after Pin gets re-parented.

MORE INFORMATION:

Pin's original parent (before it gets re-parented to Hand) does not itself have a collider component.
When OnTriggerExit(Collider collider) gets called immediately after the re-parenting takes place, the collider argument passed to the method is the Pin itself.


texts: Update dependent values of Serializable C# classes on Inspector

texts:
I have some data types' properties that depend on the input given into other attributes, but I haven't found in the Unity's API an elegant way to update them automagically on the Inspector.

As an example, let's say I have a struct that has a divider value. Since I want to save division computations, I also have on the class a multiplicative inverse value that depends on the divider's, so I'd rather multiply instead of dividing.

Example Code Snippet:

[Serializable]
public struct SomeNumbers
{
    [SerializeField] private float divider;
    private float multiplicativeInverse;

    /// When the divider is set, the multiplicative inverse is also set.
    public float Divider
    {
        get { return divider; }
        set
        {
            divider = value;
            multiplicativeInverse = (1f / divider);
        }
    }

    public float MultiplicativeInverse
    {
        get { return multiplicativeInverse; }
        private set { multiplicativeInverse = value; }
    }

    /// Constructor.
    public SomeNumbers(float divider) : this()
    {
        Divider = divider;
    }
}

public class ExampleScript : MonoBehaviour
{
    public float value;
    public SomeNumbers numbers;

    void Update()
    {
        float result = (value * numbers.MultiplicativeInverse); /// Instead of (value / numbers.divider)...
        Debug.Log("Result: " + result.ToString());
    }
}

What I'd like, is that each time I change the divider's field, the value under the hood (this case the multiplicative inverse) also gets changed, as if I used the Divider's setter. Since the idea is to have an independent data type, the approach of using OnValidate on a class that contains this struct would not be applicable, since that would be a hard case.

I could also set the Divider's setter on each class at Start/Awake do that for me, but that would be prone to be forgotten. I know about Property Drawers
, but I am not sure if that would be the right approach.

I hope the question was clear enough, if not make me know so I correct it. Thanks in advance.


texts: How do you handle aspect ratio differences with Unity 2D?

texts:
I've gotten a lot of answers to this question, but they are all generic and generally not very useful.  None of the tutorials talk about aspect ratio and dealing with mobile devices and there are a zillion ways to do it, all seem to have gotcha's and flaws.

I really would love to know what successful games have used to handle different aspect ratios on iOS and Android without making a zillion different sized assets.

I am strictly speaking mobile, not desktop, specifically with Unity and I don't care about the UI, I only care about the gameplay canvas.

Issues I have in mind is when there are key things that have to be in certain places and cannot fall off the screen.  Using black bars on top or bottom is unacceptable these days.


texts: Best way to handle abstraction of behaviors(attack,jump, dodge) within Unity?

texts:
I have behaviors for my player such as attack, jump, dodge. I want these to act differently depending on the character the player has selected. I thought about making an abstract class for each of these actions, using an interfaces for each one might be a good way to go, but i'm not sure the best way to go about it within unity.

How do you handle abstracting behaviors like this within your projects? What are the pros and cons of the methods you use.


texts: How do I install SDL.NET in Visual Studio 2010? (Or any other .NET library)

texts:
I'm trying to get SDL.NET to work in Visual Studio 2010, but am really not sure how to go about installing the library (or creating a custom project or something), and any basic instructions would be appreciated. :)

(Im also trying to install the Farseer Physics library and later MOGRE)

Thanks!


texts: I am getting different results when using 'Maximize on play '?

texts:
so i'll be straight to point.
when i move my character without using 'max on play' it works fine just as i wanted it to be.
but when i switch to 'max on play' my character moves very fast.
i am using addForce() to make me character move in Update().
after some googling i found that as i am working with physics i need to use FixedUpdate();
But when i tried with fixed update i felt like it was not registering the keystrokes as it would in Update().
i would really appreciate if someone would help me out here.
Edit - Movement Script Added
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    [SerializeField] float jump_speed;
    [SerializeField] float walk_speed;
    [SerializeField] float max_speed;
    Rigidbody2D rb;
    int jump_counter;
    Animator animator;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        jump_counter = 0;
        animator.SetBool("isIdle", true);
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isWalkingRight", false);
    }
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space)  && jump_counter <=1)
        {
            rb.AddForce(transform.up * jump_speed);
            jump_counter++;
        }
       else if (Input.GetKey(KeyCode.D))
        {
            rb.AddForce(transform.right * walk_speed);
            PlayWalkingRightAnimation();
        }
       else if (Input.GetKey(KeyCode.A))
        {
            rb.AddForce(-transform.right * walk_speed);
            PlayWalkingLeftAnimation();
        }
        else
        {
            if(jump_counter<=0) PlayIdleAnimation();
        }
    }
    void FixedUpdate()
{
     rb.velocity = Vector2.ClampMagnitude(rb.velocity, max_speed);

}
    private void OnCollisionEnter2D(Collision2D collision)
    {
        jump_counter = 0;
    }

    void PlayWalkingLeftAnimation()
    {
        animator.SetBool("isWalkingLeft", true);
        animator.SetBool("isWalkingRight", false);
        animator.SetBool("isIdle", false);
    }
    void PlayWalkingRightAnimation()
    {
        animator.SetBool("isWalkingRight", true);
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isIdle", false);
    }
    void PlayIdleAnimation()
    {
        animator.SetBool("isWalkingLeft", false);
        animator.SetBool("isWalkingRight", false);
        animator.SetBool("isIdle", true);
    }

}

I have added whole script hope this helps understand my problems.


texts: Sprite-sheets vs Sprites/MovieClips in Flash

texts:
We create 3D models in Maya2011 and create PNGs and import the bunch into Adobe Flash CS5 to create a sprite.

I read somewhere that sprite-sheets can save space over making the sprite in Flash. How big of a difference does it make? None of our art team has experience in creating sprite-sheets. Is it worth learning it and adopt that workflow? How difficult is it? How much of a difference in file-size can we achieve?

Keeping size constraints apart, I see a draw back using sprite-sheets: I wont be able to create multiple combinations of loop animations using the same set of images. I can even create multiple sprites within the same SWF with our current workflow.


texts: Where should I store an object? - QuadTree

texts:
I'm designing a QuadTree to scene partitioning, I've read theory and seen some code examples.

When a node has more than 4 objects, it will be splitted into 4 sub-nodes and its objects will be put into them, but if an object is on the edges of any sub-node, it will be placed in the parent node. Why should I do this?

I think it's better put it on every sub-node where it's colliding. Am I wrong?. I've designed a pattern to achieve this ;).


texts:
I'm working on recreating the board game "Hex" as a mobile game. I'm working on implementing zoom and pan features using two fingers. I feel like I managed to get the zoom to work, but the pan moves more than I want it to and I feel like it is because I'm missing something and must be somewhere in the conversion to World Space coordinates. if I could get some help it would be greatly appreciated.
For reference, oldMidpoint is initialized to 0 earlier on.
        Touch touchA = Input.GetTouch(0);
        Touch touchB = Input.GetTouch(1);

        Vector3 midpoint = (touchA.position + touchB.position) / 2;
        if(midpoint != oldMidpoint)
        {
            if(oldMidpoint == Vector3.zero)
                oldMidpoint = midpoint;

            Vector3 moveDistance = oldMidpoint - midpoint;
            moveDistance.y = 0;

            Camera.main.transform.Translate(moveDistance, Space.World);

            oldMidpoint = midpoint;
        }


texts: My position is "changing" when handling animation

texts:
I'm trying to learn Monogames(Old XNA) and how to develop a 2d game.

I'm in the process of animating my sprites. It works but there are somethings that are weird to me.

For some reason when animating my sprites it "changes" the position when being animated WITHOUT changing the origin. Like so

When I have not changed my origin my character "shifts" his body upwards. Something he should not do.

Now if I change the origin to be the width and height of my frame this does not happend. Like so

Ass you can see the rectangle is still changing but my character does NOT shift in its position. I can't really understand why he shifts and DOES NOT shift.

The origin is at the top-left position of the rectangle.

Why does my character position shifts? I think it's something about offset with the different heights of the frames I am unsure. I don't understand how to work with offset.

EDIT.

//I have sheets with more animations (IDLE,WALK etc) This is how I get correct ones
List<CustomTexture2D.Frames> currentsheet = cts.frames.FindAll(x => x.filename.Contains(_currentstate.ToString()));
//Gets the information of the current frame (width, height, position on spritesheet)
var t = currentsheet.Where(x => x.filename.Contains(_currentframe.ToString())).FirstOrDefault();
//Without changing origin
_spriteBatch.Draw(cts.Texture, position, new Rectangle(new Point(t.frame.x, t.frame.y), new Point(t.frame.w, t.frame.h)), Color.White, rotate, new Vector2(0, 0), 1, SpriteEffects.None, 1);
//With changed origin
_spriteBatch.Draw(cts.Texture, position, new Rectangle(t.frame.x, t.frame.y, t.frame.w, t.frame.h), Color.White, rotate, new Vector2(t.frame.w, t.frame.h), 1, SpriteEffects.None, 1);


texts: Move 2D Rotating object in its facing direction

texts:
I have a 2D object that constantly moving forward (in the direction its facing). So initially its facing right, and moving right, but as the rotation z-axis changes, so should its direction. Most of what I'm finding is based on the Asteroids game physics, but what I'm doing is not like that (I think), I'm not adding force to the object when I want its direction to change. Basically what I'm trying to do have it's X & Y velocity change based on its z rotation value. Here is an example of something similar to what I'm attempting to do:
Moving object


texts: How to scroll background image-Android App

texts:
Basically, I have a main menu, and I would like the background image to scroll (parallax I believe is the term?  Like the Angry Bird's title screen background).

However, I'm used to just having a variable iterate (x++) and setting that as the x value so the image scrolls.

So is there any way to confer variables and such between xml and my java files so I can use iteration?  Or can I skirt this completely somehow?


texts: How to add to a MonoBehavior array from an Editor script in Unity

texts:
I've made an editor which makes a list of tags and splits them into two rows of true or false values (selectable by the user). I then compile this list into a dictionary, and each entry is like so:

{"tag", bool, bool}

On my MonoBehavior script, I have two arrays:

string[] depth_tags;
string[] angle_tags;

My goal is to essentially save the dictionary data and be able to recall it/also have it affect the script. To do this, I've been trying to add to these arrays according to the values found in the Editor script's dictionary.

I've done quite a bit of searching and this was the only potential solution I could come up with, but sadly it did not work.

EDIT: Ok, I can now edit the list (added and subtracted from arraySize when doing operations on them), but I have a new problem:

The array reports as being twice as large as it should be. The first half of the arrays are correct and as they should be, but the latter half is made up of empty values. When I try to access beyond the first half, Unity throws an error saying that I exceeded the array's max range.

EDIT 2: FIXED

Answers telling you to increase and decrease arraySize are WRONG/OUTDATED. Clearing, inserting, and deleting from the table does that for you! Quick Tip: Inserting at index 0 in a serialized table takes care of the element bumping for you! No need to cycle through the table and move each array.

void update_tags()
{

    SerializedProperty depth_tags = serializedObject.FindProperty("depth_tags");
    SerializedProperty angle_tags = serializedObject.FindProperty("angle_tags");

    depth_tags.ClearArray();
    angle_tags.ClearArray();

    foreach (string tag in tag_list_values.Keys)
    {

        if (tag_list_values[tag][0] == true)
        {
            depth_tags.InsertArrayElementAtIndex(0);
            depth_tags.GetArrayElementAtIndex(0).stringValue = tag;
        }

        if (tag_list_values[tag][1] == true)
        {
            angle_tags.InsertArrayElementAtIndex(0);
            angle_tags.GetArrayElementAtIndex(0).stringValue = tag;
        }

    }

    serializedObject.ApplyModifiedProperties();

}

}


texts:
I'm making a game with shot powers (user presses and holds and launches an object)

Distance from the cursor was working for testing but obviously a distance of 1 and 2 pixels is double. I scaled this by 4 to make the difference itself less drastic but they're double of each other.

Is there a common way to smooth the strength of a shot so it's not so great per jump?


texts: Process for converting unity asset to scenekit scene/resource

texts:
Has anyone successfully figured out a method for converting a unity3d asset to a 3d SceneKit model/scene? I imagine it would require exporting the asset into some third party file type, and then importing into scene kit. If you have any knowledge that can help me, would you kindly explain the process?

Unity3d has a fantastic asset store, and I want to import some of these things to a project that requires scenekit (unfortunately, "just use unity" is not really an answer to my problem-set).


texts: Is there a size limit when using UICollectionView as tiled map for iOS game?

texts:
I'm working on a turn-based strategy game for iOS, (picture Civilization 2 as an example), and I'm considering using a UICollectionView as my game map. Each cell would be a tile, and I could use the "didSelectCell" method to handle player interaction with each tile.

Here's my question: I know that UICollectionViewCells are dequeued and reused by the OS, so does that mean that the map could support an effectively infinitely-large map, so long as only a few cells are onscreen at a time? However many cells were onscreen would be held in memory, and obviously the data source would take up some memory, but would my offscreen map be limited to a certain size or could it be enormous so long as the number of cells visible at any one time wasn't too much for the device to handle? Basically, is there any memory weight to offscreen cells, or do only visible cells have any impact?


texts: Unity2D: Item selection previous button not working!

texts:
I'm having a problem with my item selection script. As you can see in the video, button 3 (when the previous button is pressed)  goes straight to button 1, instead of going to button 2 and then button 1. Can anyone help me with this issue! Thank you. My script is listed below;

int activeObject = 0;
public GameObject tool01, tool02, tool03, tool04, tool05, tool06;
public int max_number_of_objects;

// in the button press code
public void Right()
{

        // increment the active object, wrapping around to 0
        activeObject++;
        if (activeObject >= max_number_of_objects) {
            activeObject = 0;
        }
        // here's another way to do this that eliminates the conditional logic
        // just pick one of them - don't do them both
        // look up the modulus operator (%)
        activeObject = (activeObject + 1) % max_number_of_objects;
        RightActivateObject (activeObject);
}

public void Left()
{
    activeObject--;
    if (activeObject <= 0) {
        activeObject = max_number_of_objects;
    }
    // here's another way to do this that eliminates the conditional logic
    // just pick one of them - don't do them both
    // look up the modulus operator (%)
    activeObject = (activeObject - 1) % 1;
    LeftActivateObject (activeObject);
}
    // activate the selected object
void RightActivateObject(int activeObject)
{
    switch (activeObject)
    {
    case 0:
        tool01.SetActive(true);
        tool02.SetActive(false);
        tool03.SetActive(false);
        break;
    case 1:
        tool01.SetActive(false);
        tool02.SetActive(true);
        tool03.SetActive(false);
        break;
    case 2:
        tool01.SetActive(false);
        tool02.SetActive(false);
        tool03.SetActive(true);
        break;
    }
}

void LeftActivateObject(int activeObject)
{
    switch (activeObject)
    {
    case 0:
        tool04.SetActive(false);
        tool05.SetActive(true);
        tool06.SetActive(false);
        break;
    case 1:
        tool04.SetActive(false);
        tool05.SetActive(false);
        tool06.SetActive(true);
        break;
    case 2:
        tool04.SetActive(true);
        tool05.SetActive(false);
        tool06.SetActive(false);
        break;
    }
}


texts: How can I express the result of a percentage so that it is easy to understand by the user?

texts:
I'm a professional game developer who has worked on a number of large titles but went indie a few years ago. I'm about to release my 3rd game, a real-time strategy game with a few RPG elements.

My problem is this: what is the best way to express the result of a percentage chance to a player? What I mean is, if the user has a 15% chance of succeeding at something, and the game engine uses a random number generator to generate a percentage, how would the result be shown to the user so that it is easy to understand?

The challenge I have is that if the player has a 15% of achieving something, if the random number generator generates a number between 1-15 (say, 4), then the player succeeds. But expressing this as, say, 4% / 15% just doesn't look right as conversely a lower number means success, where most players are used to "higher numbers = better".

I have thought about inverting the equation and expressing it some way as a chance of failure. So in the above example the player would have an 85% chance to fail, where the 4% would be converted to 96% and the result could be expressed as 96% / 85%, which "looks" more correct. But I just don't like the idea of expressing everything as a chance of failure, rather than a chance of success.

I have also thought of simply expressing the success chance (85%) and not showing the player the result of the random number generator, but I feel that most players would want to see the numerical result rather than simply the victory/failure condition.

I'm at a real loss here and would love to hear the views of players and other game developers alike. Even better if someone can point me to an example of a game which has solved this problem!


texts:
I want to create 2D Terrain randomly. It should look like a connected Cave (Shown below). What is the best method or Algorithm to get similar results?

The important part is the open area(green) and that it is fully surrounded by walls(brown).

4 Examples:


texts: Simple Orbital transfer and intercept equation

texts:
I'm working on a game which has a game board made up of objects orbiting the center of the board.  You can think of it as our solar system, but greatly simplified in terms of physics.  All objects have a mass and gravity of 1.0.  Their orbital speeds are simply a linear function of their radius from the center (Sun).

The player has a base, which in terms of our solar system would be Earth.  The player needs to send a spaceship to another planet in a different orbit.  The spaceship has a constant acceleration (or deceleration), and unlimited fuel.

I need to figure out an equation to get this spaceship going towards one of the planets and intercept it.  I've looked at some orbital mechanics web pages, but this is a little beyond my math skills and I think too complex for what I'm trying to achieve.  Any help would be much appreciated.

NOTE:  If this is better suited for SE.Mathmatica, please feel free to move.


texts: How can I remove the view and projection matrix from ray position to get only the ray model?

texts:
I've got a little problem with my picking module and I need your help.

I have a method to project a ray from the camera to a fixed point when I click somewhere. The computed ray looks good, it go to the asked direction and passes through the pointed box, so I'm thinking everything is OK here.

When I'm trying to pick an object a little further from the origin, there is no intersection found.

I'm sure that the ray is correctly projected and computed to the screen (I draw it) but coordinates are bad during intersection test.

Currently, I compute the ray with this code :

const glm::vec3 position    = glm::vec3( mouse.x, mouse.y, 0.f );
const glm::mat4& view       = camera.getViewMatrix();
const glm::mat4& projection = camera.getProjectionMatrix();
const glm::vec4& viewPort   = camera.getViewport();

ray.origin =  glm::unProject( glm::vec3(mouse.x, mouse.y, 0.f ),
                                        modelView,
                                        projection,
                                        viewPort );

ray.direction =  glm::unProject( glm::vec3( mouse.x, mouse.y, 0.f ),
                                            modelView,
                                            projection,
                                            viewPort );

So, I think the ray origin and direction are computed to world position (with camera matrix: projection and view).

When I test intersection, I use object model (without camera transformation), so I'm thinking error is here.

The question:
How can I remove view and projection matrix from ray position to get the ray model only ?

Thanks a lot!

PS: To test intersection, I create a bounding box from my object's model matrix and I test intersection with the ray computed previously.

EDIT:

Code to compute ray positions in world space :

////////////////////////////////////////////////////////////
bool computeRayPositions( Ray* ray )
{
    glm::vec3 start = ray->getOrigin();
    glm::vec3 end   = ray->getDirection();

    glm::mat4 startMatrix   = glm::translate( glm::mat4(1.f), start);
    glm::mat4 endMatrix = glm::translate( glm::mat4(1.f), end);

    const glm::mat4& viewMatrix       = camera->getViewMatrix();
    const glm::mat4& projectionMatrix = camera->getProjectionMatrix();

    glm::mat4 startWorldMatrix  = startMatrix * glm::inverse(viewMatrix * projectionMatrix) ;
    glm::mat4 endWorldMatrix    = endMatrix * glm::inverse(viewMatrix * projectionMatrix);

    ray->setOrigin( glm::vec3 (startMatrixFinal[3][0], startMatrixFinal[3][1], startMatrixFinal[3][2] ) );
    ray->setDirection( glm::vec3 (endMatrixFinal[3][0], endMatrixFinal[3][1], endMatrixFinal[3][2] ) );

}


texts: Normal transformation and homogeneous coordinates

texts:
I'm very confused about the math behind the model/affine transformation expressed in homogeneous coordinates.
Reading this article, I understood that a generic vector is transformed by multiplying it by the model matrix (M), while a normal must be multiplied by the inverse-transpose of the model matrix (M^-T) in order to preserve the dot product between P and N (this was wrong).

Now I don't fully understand how to use the normal. If I transform the normal I will obtain a vector that does not maintain the relation with its vertex.

Example:
consider P and N in the 3D space, where dot(P,N) = 0. Their homogeneous representation P' and N' will have dot(P',N') = 1 because of the W component.

Now if I transform P' using the model matrix M I will obtain P'' = M*P' which has the W component equals to 1, so going back to the 3D space can be easily done by taking the first 3 coordinates.

If I transform N' I will obtain N'' = M^-T * N' which does not have W = 1. I don't know how to take N back to the 3D space, keeping the dot product with P

Any suggestions?

I need to specify that when I refer to the homogeneous coordinates I'm not talking about the perspective transformation but the affine transformation (in opengl the modelview) that is still a 4D matrix composed by the linear transformation and the translation.

From the Nicol Bolas response I got that the 4th coordinate of a direction vector should be 0, that's because a direction vector does not participate in the translation. In this case the dot(P,N) = dot(P',N') = 0

Integration to Nicol Bolas response:

So basically the claim that the normal must be multiplied by the inverse-transpose of the model matrix in order to preserve the dot product between P and N was wrong (or incomplete). The article referenced is misleading.

If we consider M the model matrix that consists in a linear transformation L and a translation t

we have an inverse-transpose of

which multiplied by N' = [N 0]

This creates a bit of confusion because of the  which is nor 0 or 1 and I couldn't figure out how to get a direction (N') with the w component equals to 0.

The mistake is that we should not consider the translation t of the affine transformation for different reasons (too long to explain here).

So we should only consider the linear transformation L and make sure that dot(P',N') = dot(P,N)

Since L is in the 3D space, no homogeneous space is needed (or if it is used we need to set the t to 0). That's where the article was wrong


texts: How to orthogonalize the "up" vector in a camera based on "eye", "look" and "up" vectors?

texts:
Given a camera position defined as (eye, look, up), where "up" not quite at right angles to eye->look, how would I re-orthogonalize "up"?

I've had a hunt around, but did not find anything, yet if I recall correctly, this being a fairly classic problem for which there is an easy solution.


texts:
I hope this is the right place to ask this. I'm very new to Unity but not to programming. I also have some basic game programming experience.

I'm searching for text based versions of the videos from unity3d.com/learn/tutorials. These tutorials are very good, but I end up forwarding videos a lot to get key screenshots and code snippets.

Is there any text / pdf / html / .doc / .rtf (i'm very open) version or similar resource to learn unity? Again, those tutorials are amazing and I'd hope to find something of similar quality, but I know that if I have to skim through tens of hours of video I'll end up frustrated. I get that the long hard way is probably the most robust one for deeper understanding, but I was hoping to hack a quick project.

EDIT :

If this can make it a relevant question, then I am currently looking at the "Roll a Ball Tutorial". Really, any other text tutorial would be very welcome


texts: Unity Material constructor not applying Shader

texts:
I am proceedurally generating a generic game object and trying to make it transparent using the default diffuse transparency shader.

meshRenderer.materials[0]=new Material(Shader.Find("Transparent/Diffuse"));
meshRenderer.materials[0].color = new Color(0f,1f,0f,0.05f);

Just seems to make it Default-Diffuse, but if I do this

meshRenderer.materials[0]=new Material(Shader.Find("Transparent/Diffuse"));
meshRenderer.materials[0].shader = Shader.Find("Transparent/Diffuse");
meshRenderer.materials[0].color = new Color(0f,1f,0f,0.05f);

It works just fine and I get transparency.  The Material constructor looks like it takes the exact same shader, but it doesnt seem to be applying.  Why?  I am already explicitly inluding the shader in the project settings.


texts:
I know this has been asked before and Ive looked through peoples questions and answers all over the internet and I just cant get it to work.
Im sure its down to my inexperience. Ive got an arrow attached to a sprite, this sprite appears when touched but I want the arrow to point where the sprite will launch.
I have had the arrow moving but it was very erratic and not pointing as it should. Its not moving at the moment but this is what I have.

- (void)update:(ccTime)delta
{
    arrow.rotation = dialRotation;
}

-(void) ccTouchMoved:(UITouch*)touch withEvent:(UIEvent *)event
{
    pt1 = [self convertTouchToNodeSpace:touch];

    CGPoint firstVector = ccpSub(pt, arrow.position);
    CGFloat firstRotateAngle = -ccpToAngle(firstVector);
    CGFloat previousTouch = CC_RADIANS_TO_DEGREES(firstRotateAngle);

    CGPoint vector = ccpSub(pt1, arrow.position);
    CGFloat rotateAngle = -ccpToAngle(vector);
    CGFloat currentTouch = CC_RADIANS_TO_DEGREES(rotateAngle);

    dialRotation += currentTouch - previousTouch;
    }

I have got pt from ccTouchBegan the same way as pt1

Thanks


texts: How would I access a method from another script?

texts:
I have two scripts. I create a reference to my instance of SoulManagement from Soul, but I can not access it's method, and I can not figure out why. Why can't I access my method?

SoulManagement

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

public class SoulManagement : MonoBehaviour
{
    int Souls;

    void SoulPlusMinus(int SoulValue)
    {
        Souls += SoulValue;
    }
}

Soul

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

public class Soul : MonoBehaviour
{
    public SoulManagement soulmanager;
    public int SoulValue;

    void Start()
    {
        soulmanager = FindObjectOfType<SoulManagement> ();
    }
    void OnTriggerStay2D()
    {
        soulmanager.SoulPlusMinus (SoulValue);
    }
}


texts:
I've seen a couple of these, namely Java and C#/XNA...and I've recently been picking up Python. Which kind of made me think.

What (famous) games have been written in Python, with Pygame/Pyglet/Pyopengl?


texts: QuadTree: store only points, or regions?

texts:
I am developing a quadtree to keep track of moving objects for collision detection. Each object has a bounding shape, let's say they are all circles. (It's a 2D top-down game)

I am unsure whether to store only the position of each object, or the whole bounding shape.

If working with points, insertion and subdivision is easy, because objects will never span multiple nodes. On the other hand, a proximity query for an object may miss collisions, because it won't take the objects' dimensions into account. How to calculate the query region when you only have points?

If working with regions, how to handle an object that spans multiple nodes? Should it be inserted in the nearest parent node that completely contains it, even if this exceeds the node's capacity?

Thanks.


texts: Developing Cartography for Simulated Land Navigation or Orienteering

texts: Request to know what the best approach for developing a simulated Large 1:75,000 or 1:50,000 scaled map using GODOT or another game engine. My goal would be to create a 3D world that allows the player to view a 2D map which is similar to real world USGS/NGA style maps using UTM/MGRS for land based navigation. Later I would add tools such as the Cammenga 6605-01-196-6971 Compass and a Maptools style protractor. I have spend hours searching for examples of GODOT developed games using maps similar to approaches used in Arma 3 and Firewatch. I would greatly appreciate any advice on techniques used with GODOT or other game engines to create a mapping system for players. Thank You!


texts: How to give each player in card game the same shuffled deck?

texts:
I'm writing a card game in Swift.  The idea is to make it work on the Apple Game Center framework. I've noticed an issue which I am not sure how to address.

I need the current game data to be the same for all players.
There are 6 players in the game.
There is a deck of 30 cards, they are shuffled.
Each player must have the same deck of cards (post-shuffle).
6 cards are presented to the "table" one at a time (animation).

There are also other activities that a player does that are outside the bounds of this question.

My question is this;

How do I give each player the same shuffled deck of cards?

There are a couple of options I can think of, but perhaps none of these are the best way; hence my question

The start player is the host. The host creates the shuffled deck, and this deck is sent to other players (ie: JSON); in short all activities are facilitated through him.

The problem with this is that the start player could lose internet, abandon the game or all sorts?

So I don't think this is a viable solution

There is a middleman, the server.

There is a "lobby" (waiting area)
There is multiple games.
The game has players.
An AI-bot could be used to fill in abandoned players

But wait, does this then mean the server shuffles the cards and sends the same data to all players and makes the players "thin clients"?

Can Apple's Game Center handle this for me?

I'm not sure about the best solution for this?


texts: Creating a space game. Need help with a solution for creating dynamic spiral graphics

texts:
My friend and I are working on a web based game where we want to have a blackhole-like thing rendered in some form of an engine or 3D program for us to freely manipulate adding more "arms" making it smaller or bigger and playing around with its light.

Here's a picture of our concept of the graphic element:

(smaller black hole:)

(larger black hole:)

We want help to find the best possible solution for this, and possible also some kind on guide to create these elements. So far everything is designed in photoshop but if we want the hole to be dynamic we can't use pictures.


texts:
I have set up a script to set game objects as active/inactive depending on a particular number representing the index of a gameObject array. As you can see the image below. I have two buttons as shown on the page, a backward button and a forward button. I have attached event trigger components to each of the buttons so as to turn pages forward / backward depending on which button I click

The forward button works but this is not the case with the backward button. The function is not even being called. In fact only this sprite which on being clicked does not call the function assigned to it.

More details on the backbutton :

Here is the script for the MonsterRosterManager.cs

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

public class MonsterRosterManager : MonoBehaviour
{
    int MonsterPageNo;
    public GameObject[] MonsterPages;

    void Start()
    {
        MonsterPageNo = 0;
    }

    void Update()
    {
        switch (MonsterPageNo)
        {
            case 0:
                MonsterPages[0].SetActive(true);
                MonsterPages[1].SetActive(false);
                MonsterPages[2].SetActive(false);
                break;
            case 1:
                MonsterPages[0].SetActive(false);
                MonsterPages[1].SetActive(true);
                MonsterPages[2].SetActive(false);
                break;
            case 2:
                MonsterPages[0].SetActive(false);
                MonsterPages[1].SetActive(false);
                MonsterPages[2].SetActive(true);
                break;
        }
    }

    public void PrevMonsterPage()
    {
        Debug.Log ("Monster Page No to decrement: "+MonsterPageNo);
        MonsterPageNo -= 1;
        if (MonsterPageNo == -1)
            MonsterPageNo = 0;
    }

    public void NextMonsterPage()
    {
        Debug.Log ("Monster Page No to increment: "+MonsterPageNo);
        MonsterPageNo += 1;
        if (MonsterPageNo == MonsterPages.Length)
            MonsterPageNo = MonsterPages.Length - 1;
    }
}

Furthermore, the logs below show that the NextMonsterPage() function is called on clicking the forward button, but no calls to the PrevMonsterPage() are being registered.

What am I overlooking here?


texts: Find appropriate camera-projector coordinates to project contours of real objects

texts:
I am developping a game (unity3d + opencv for image processing) where i detect real-life objects from the webcam on every frame, find their edges and then draw them on the real objects. I need to find the real-world coordinates in order to place my camera and projector in a way to get edges that align with their respective objects. I looked into camera calibration which returns the camera's intrinsics, extrinsics, and lens distortion parameters but i don't know how to use them in my case. Is there a possible way to calculate these positions and angles?

Basically my real-world view looks something like this:

And the image that I should project is this:

I think i should also mention that it's a top-down projection and i'm not using any depth sensing camera.

EDIT:
When i put the camera on the same axis as the projector it keeps displaying the projected image infinitely (still didn't figure out the right distance for display)... So where should i place the camera (is there an angle to be mesured?) to be able to detect the objects but not the projection?
I appreciate your help.


texts:
I am working on a MUD engine and I want to do it a little differently then all the MUD games I played. I find a "cycle" system very boring. One of the idea I had is to make every clients socket working in their own Thread. I am aware that it wont end with hundreds of player but I would like to know if there are problems creating "alot" of thread in a single process.

Or, what other strategy I could use if I want to make it (eg. combats) in "real-time".

I hope you guys understand the question.

Thank you.


texts: Highlighting shader but using touch points/mouse

texts:
I have done the following highlighting shader using GLSL.
What I want to do is getting the mouse coordinates and "start" the highlighting from that point. is that possible ? What's the math or the idea behind doing that ?
https://youtu.be/8etJho4agpg


texts: Multiple planar reflections works weird in UE4

texts:
When I add multiple planar reflections for arch-viz, some of them on glasses don't have any result, but ones on mirror works properly.
Sometimes all the planar reflections on glass are invalid. But after restart the engine, the reflections get back to normal.
Any clue to fix it? Or it is the Engine limit.
(No ray tracing.)
Below are my material settings.
Glass material:

Mirror material:


texts: fmod getWaveData() export to WAVE file help (C++)

texts:
I am trying to export the current sound that is being played by the FMOD::System into a WAVE file by calling getWaveData(). I have the header of the wave file correct, and currently trying to write to the wave file each frame like so:

const unsigned int samplesPerSec = 48000;
const unsigned int fps = 60;
const int numSamples = samplesPerSec / fps;
float data[2][numSamples];
short conversion[numSamples*2];

m_fmodsys->getWaveData( &data[0][0], numSamples, 0 ); // left channel
m_fmodsys->getWaveData( &data[1][0], numSamples, 1 ); // right channel

int littleEndian = IsLittleEndian();

for ( int i = 0; i < numSamples; ++i )
{
    // left channel
    float coeff_left = data[0][i];
    short val_left =  (short)(coeff_left * 0x7FFF);

    // right channel
    float coeff_right = data[1][i];
    short val_right =  (short)(coeff_right * 0x7FFF);

    // handle endianness
    if ( !littleEndian )
    {
        val_left = ((val_left & 0xff) << 8) | (val_left >> 8);
        val_right = ((val_right & 0xff) << 8) | (val_right >> 8);
    }

    conversion[i*2+0] = val_left;
    conversion[i*2+1] = val_right;
}

fwrite((void*)&conversion[0], sizeof(conversion[0]), numSamples*2, m_fh);
m_dataLength += sizeof(conversion);

Currently, the timing of the sound is correct, but the sample seems clipped way harshly. More specifically, I am outputting four beats in time. When I playback the wave-file, the beats timing is correct but it just sounds way fuzzy and clipped. Am I doing something wrong with my calculation?

I am exporting in 16-bits, two channels.

Thanks in advance! :)

Reference (WAVE file format): http://www.sonicspot.com/guide/wavefiles.html


texts: Unity get reference of GameObject under another GameObject

texts:
I am trying to get reference of the object underneath my Player.

I don't know if I am aproaching this correctly. Right now, I have a player simply put in the scene, like this:

Then I am trying to get reference of it like this (does not work)

public void CheckTileUnder()
{
    Vector3 halfExtents = new Vector3(0f, -1 / 2.0f, 0f);
    Collider[] colliders = Physics.OverlapBox(transform.position, halfExtents);

    foreach (Collider item in colliders)
    {
        Tile tile = item.GetComponent<Tile>();
        if (tile != null)
        {
            RaycastHit hit;

            if (Physics.Raycast(tile.transform.position, Vector3.down, out hit, 1))
            {
                currentTile = tile;
            }
        }
    }
}

Another aproach that I thought of would be to put the player under the Tile like this: Then I guess I would have to change parents like suggested in one of the answers here?

How should I select the Tile under the Player?


texts: Level Design, Implying a path to the player

texts:
I am looking for articles on level design and particularly for techniques to imply a direction the player to go in, instead of another.

Like which game mechanics can be used, how graphics, sound, etc. can influence the player to go where you want.

For example in Donkey Kong Country bananas were used to show other paths or hidden areas, in Alan Wake, there were orange markers to show weapons caches.

If anyone has ideas, I'd be grateful to hear them too!

Edit:
For anyone that is interested, I found a huge resource with thesis on this question, and others related to Level Design; happy reading!

http://guildhall.smu.edu/Level-Design.226.0.html


texts:
I want to tilt my object left or right depending on which side I'm moving my mouse. I wrote something like that:

    if (Input.GetAxis ("Mouse X") > 1) {
        transform.localRotation = Quaternion.Euler(0, 0, (-35 * Time.deltaTime * speed));
    }
    else if (Input.GetAxis ("Mouse X") < -1) {
        transform.localRotation = Quaternion.Euler(0, 0, (35 * Time.deltaTime * speed));
    }
    else if (Input.GetAxis ("Mouse X") == 0) {
        transform.localRotation = Quaternion.Euler(0, 0, 0);
    }

It's working only when I move mouse very fast and it's not 'smooth'. Would be thankful if anyone would help me :)


texts: How to make (or where to get) a half-sphere mesh that textures properly?

texts:
I'm making a game in Unity that involves lots of spheres.  Said spheres will have lighting applied to them, but will also be viewed from only one camera angle.  Right now, the full spheres look something like this when textured, normal-mapped, and lit:

This is correct.  The spheres in my game will only be seen head-on, thus I only need to render their top halves.

However, if I use the same material on only half a sphere (with a lower resolution, mind you), I get something like this:

(It's not the exact same material, but it's close enough, and shows the same problem.)

This is incorrect.  The weird part is I only encounter this issue in compiled builds of the game; in the editor, the hemisphere is textured exactly as I expect.

At the request of a commentator, here is one of the textures I'm using:

I'm also using it as a normal map.

My question is thus: how can I make (or where can I find) a hemisphere that can be properly textured, and why does my current hemisphere mesh only render properly in the Unity editor?


texts: How are components properly instantiated and used in XNA 4.0?

texts:
I am creating a simple input component to hold on to actions and key states, and a short history of the last ten or so states. The idea is that everything that is interested in input will ask this component for the latest input, and I am wondering where I should create it.

I am also wondering how I should create components that are specific to my game objects - I envision them as variables, but then how do their Update/Draw methods get called?

What I'm trying to ask is, what are the best practices for adding components to the proper collections? Right now I've added my input component in the main Game class that XNA creates when everything is first initialized, saying something along the lines of this.Components.Add(new InputComponent(this)), which looks a little odd to me, and I'd still want to hang onto that reference so I can ask it things.

An answer to my input component's dilemma is great, but also I'm guessing there is a right way to do this in general in XNA.


texts: why contacts length could be 0 when collision2D happens in Unity3D?

texts:
I made a ball with RigidBody2d and CircleCollider2D to collide with other balls with the same component, and I simply use the following snippet to check the contacts of the collision:

public void OnCollisionEnter2D(Collision2D collision)
{
        if(collision.contacts.Length == 0)
        {
            Debug.LogWarning(" collision contacts length is 0 ");
            return;
        }
        // futher more code to deal with situation when contacts exists
}

And I found sometimes the collision could happen without contacts I mean the contacts array could contain 0 points.

Why does that happen?

Cause it's very important for me to find the normal direction of the collision, but without a contact-point, I could find that.


texts: How to create a believable swimming fish animated Sprite in 2d?

texts:
I want to create a fishing game in which fish needs to be swam across in the ocean. I put static fish which just progresses across ocean but it does not look very realistic and interesting to attract users to play.

I have used minimal graphics style to design graphics for the game and want to put some animation, like, moving tails and fins which I can achieve by making multiple images. But I also want to put some big fishes like sharks and only animating fins and tails will not be enough for them. As player will die without touching body due to margin left for tails or fins animation, or consider an eel.

I can use the snake technology for eels but for fishes where only tails move, is there any other way I can use? Or consider the Jumping Fish game by Ketchapp.

Could anyone suggest me proper ways to achieve such animations?


texts:
I'm working on a game where players travel in a city.

This city is defined by streets (names, positions...), points of interest (cinemas, restaurants...) and different zones (high criminality zones, rich zones, poor zones...). I still don't know if this city will be based on a real one (using OpenStreet map data) or made by game designers. In either case, I need to be able to modify the map data (add a cinema here, move a restaurant there...).

I also want to be able to search it for stuff like "Where is the closest restaurant?" or "How long would it take to travel to that street?".

How should I best store such information on disk, to be loaded or modified later?

(I'm working with Unity, but this isn't a Unity-specific question.)


texts: How to shade hair (line segments) correctly in GLSL

texts:
I render my hair geometry in line segments. The problem I have is with the correct shading of the hair.

From what I've read I understood that I need the direction of the line segment and the direction to the light source. Then the dot product of these direction vectors defines how the current vertex is shaded.

My vertex data is in one array buffer and I've decided to pass to GLSL 2 pointers - one for the current vertex and one for the next vertex, so I can calculate the direction of the line segment.

glEnableVertexAttribArray(gpuProgram->attrib("vert"));
glVertexAttribPointer(gpuProgram->attrib("vert"), 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(gpuProgram->attrib("vertNext"));
glVertexAttribPointer(gpuProgram->attrib("vertNext"), 3, GL_FLOAT, GL_FALSE, 0, (void*)sizeof(Vertex));

Where Vertex is a struct with 3 floats.

My vertex shader:

#version 150

uniform mat4 projection;
uniform mat4 view;
uniform mat4 model;
in vec3 vert;
in vec3 vertNext;
in vec3 color;
out vec3 fragVert;
out vec3 fragColor;
out vec3 fragVertNext;

void main(void)
{
    fragColor = color;
    fragVert = vert;
    fragVertNext = vertNext;
    gl_Position = projection * view * model * vec4(vert, 1);
}

My fragment shader:

#version 150

uniform mat4 model;
uniform vec3 lightPosition;
uniform vec4 surfaceColor;
in vec3 fragVertNext;
in vec3 fragVert;
in vec3 fragColor;
out vec4 finalColor;

void main(void)
{
    vec3 lightColor = vec3(1.0, 1.0, 1.0);

    vec3 vertPos1 = vec3(model * vec4(fragVert, 1));
    vec3 vertPos2 = vec3(model * vec4(fragVertNext, 1));

    vec3 segmentDir = normalize(vertPos1-vertPos2);
    vec3 dirToLight = normalize(lightPosition-vertPos1);

    float diffCoef = 1.0 - dot(segmentDir, dirToLight);

    vec3 diffuse = ambient + lightColor * diffCoef * fragColor;

    vec3 result = min(diffuse, vec3(1.0));
    finalColor = vec4(result, 1);
}

This is just the diffuse shading without specular reflection. And the result is wrong.
I have to mention that 1 hair strand is composed of a couple line segments, and also there seems to be bug in the shading of the very last line segment - it appears black.


texts: Transformation matrix that maps a window

texts:
I'm currently learning OpenGL at uni, and they give us questions to help us learn (these are not worth anything), however I'm stuck on this one question and would have to travel over an hour and a half to uni for an answer.

How do I do this question? Please include as many steps as you can, I want to be able to follow exactly how to do this.

Find the transformation that maps a window whose lower left corner is at (1,1)
and upper right corner is at (3,5) onto:

The entire device screen whose dimension is (600, 500)
A viewport that has lower left corner at (100,100) and upper right corner
at (400,400)

Edit: Damn sorry I should have added I am meant to find the matrix, so no code.


texts: Is web browsers, how much latency is there with event listeners?

texts:
I have an event listener in JavaScript looking for keydown events.
document.addEventListener('keydown', e => {
    // Callback code
});

What is the latency between someone pressing a key and my function executing. Is the function immediately added to the event queue or does it wait until the next frame is ready to be drawn? Is the behavior consistent between web browsers?
Just to be extra clear, I'm only interested latency in the context of web browsers, not anything before it.


texts:
I'm trying to change the  speed of the jump. I noticed if I jump twice the fall speed force gets implemented. Otherwise it is unchanged. If I try to change my onGround to be else false it remains false. Any Ideas.?

public class PMRigidBody : MonoBehaviour {
    public Rigidbody rb;
    private ConstantForce cf;
    public float fallSpeed = -10;
    private bool onGround = false;
    private int jumpHeight = 7;

    void Start (){
        // get the components
        rb = GetComponent<Rigidbody>();
        cf = GetComponent<ConstantForce>();
    }

    void Update()
    {
        float dist = 1f;
        Vector3 dir = new  Vector3(0, -1, 0);

        Debug.DrawRay(transform.position, dir * dist, Color.green);

        if (Physics.Raycast(transform.position, dir, dist))
        {
            onGround = true;
        }
        //else
        //{
        //    onGround = false;
        //}

        if (onGround)
        {
            cf.force = Vector3.zero;
            if (Input.GetButtonDown("Jump"))
            {

                onGround = false;
                rb.velocity = new Vector3(0, jumpHeight, 0);
                rb.MovePosition(transform.position + transform.up * Time.deltaTime * 10);

                cf.force = new Vector3(0, fallSpeed, 0);
            }
        }
    }
}


texts: Detecting on which side of the box a collision occurred

texts:
Explanation

I have a rectangle with a trigger on it when it's hit by my player game object from the side it's supposed to activate a certain method. Illustration:

And when it's hit from the bottom or top it's supposed to activate an other method. Illustration:

However the way I'm checking what method to use is not working in all cases.

Problem

There are some cases where the player is hitting the side of the rectangle but the method being called is the one supposed to be called when the rectangle is hit from the bottom or the top. When the player is hitting the top or bottom everything is working just fine.

Code

protected override void OnCollision(Collider2D coll, PlayerMovement player)
{
    float playerMaxY = player.YCord + player.Height / 2;
    float playerMinY = player.YCord - player.Height / 2;

    //YCord is the y coordinate of the rectangle
    float thisMaxY = YCord + Height / 2;
    float thisMinY = YCord - Height / 2;

    base.OnCollision(coll, player);

    //This condition here is where i need an improvement
    if ((playerMinY >= thisMaxY && playerMaxY >= thisMaxY) ||
        (playerMinY >= thisMinY && playerMaxY >= thisMinY))
        BounceHorizontal(coll, player);
    else
        BounceVertical(coll, player);
}


texts: How do I add an image inside a rectangle or a circle in JavaFX?

texts:
Suppose we have a rectangle called r

Rectangle r = new Rectangle(40, 20);

and an image called image

Image image = new Image("...src for image");

How do I fit the image inside the rectangle? Also, how can I make the image move if the rectangle moves too? How do I do the same thing for a circle? Code examples are greatly appreciated.


texts:
When I use this RenderTarget:

renderTarget = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width,
    GraphicsDevice.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.Depth24);

and draw something to it:

graphicsDevice.SetRenderTarget(renderTarget);
// some drawing code here
graphicsDevice.SetRenderTarget(null);

and then when I want to continue with drawing depth buffer seams to be clean. Why? Is possible to save it for future use?


texts: How can I use ImGui to render simple text instead of using stb_truetype directly?

texts:
Since ImGui builds on top of stb_truetype for its font rendering, I thought it could be nicer to use its already built font-processing capabilities (ImGui::GetIO().Fonts), and render with those, instead of using stb_truetype directly.

However, I've been having trouble figuring out how to do this, specifically how to get quad position/texture coordinates for a given string to use with the preloaded texture at ImGui::GetIO().Fonts->TexID.

I'm not looking to draw buttons/text inside ImGui windows, all I want to do is to use ImGui to build vertex data for a given string so that I can render it anywhere.


texts: Efficient way of drawing outlines around sprites

texts:
I'm using XNA to program a game, and have been experimenting with various ways to achieve a 'selected' effect on my sprites. The trouble I am having is that each clickable that is drawn in the spritebatch is drawn using more than a single sprite (each object can be made up of up to 6 sprites).

I'd appreciate it if someone could advise me on how I could achieve adding an outline to my sprites of X pixels (so the outline width can be various numbers of whole pixels).

Thanks in advance,

Greg.


texts: glm::perspective() with wide field of view

texts:
I'm still pretty new to this GL stuff, but I've managed to put together some C and C++ code that allows me to construct simple 3D objects consisting of line segments and display them on my laptop using GLFW and the glm library. I've hooked in enough keyboard callbacks to allow me to navigate the position and orientation of an observer via glm::lookAt(). A couple of the keys allow me to grow or shrink the field of view value that gets passed to glm::perspective(), like so:
float field_of_view; // degrees, not radians

        glm::mat4 proj = glm::perspective(
            glm::radians(field_of_view),    // field of view
            1920.0f / 1080.0f,      // aspect ratio
            0.0f, 100.0f            // near and far clipping planes
        );

From my experience as an amateur photographer, I know that if one takes a photo with a camera with a wide angle lens of a scene that contains straight line near the periphery of the field of view, the physically straight lines will appear bent in the photo. They bow outward so as to create a more circular shape around the center of view.
But when I modify the field of view that gets passed to glm::perspective() such that it is a high value (approaching 180 degrees), with an orientation such that the straight line segments appear near the edges of the field, the rendered line segments never bend like I'd see with a real camera and wide angle lens. Instead, the lines remain straight but appear to get very long.
This creates very unnatural looking images.
Is there some other glm function that I should call instead in order to make the rendered lines curved like I'd expect to see in real life?
Thanks


texts: When scaling the camera with the player, how can I make it more noticeable?

texts:
I am making a game where you play as fish. When you eat food you become larger. I am counting the camera scale as follows:

camera.scale = (player.originalWidth / player.width)

Then I apply it as a transform to the whole world. Now when the fish grows up you don't see any change on your sprite, only on the surrounding world. I want to achieve that you will see the growing a little bit. How should I modify this equation?


texts: How do components and systems relate to each other in an entity component system?

texts:
I'm trying to learn and understand the ECS (Entity Component System) so that I can create a game using this design pattern but I've got a lot of things that I still don't understand.

Lets say I've got a PositionComponent and a MovementSystem or PhysicsSystem. The PhysicsSystem will heavily rely on the PositionComponent since in order to calculate, for example a rigid body motion, it needs the x and y positions (in a 2D game) wich is contained by the PositionComponent.

What is the relationship between Components and Systems? How does the    MovementSystem get the x and y values from the PositionComponent?


texts: How to rotate vertices of 2D shape using a transform matrix?

texts:
I am making a top-down 2D game and am currently working on implementing improved collision using SAT. I programmed a Shape class with a Vector2 center that is its position in world space. On top of this is a list of Vector2's that act as the vertices of the shape and are defined as offsets in local space. The Shape class also has a rotation variable that is used in the Update method with a transformation matrix to rotate it around the Z axis. Since the Shape is parented by a Collider which is then parented by an actor, I have programmed its rotation to lock in with the Collider's parent actor. The problem is when the actor is turning the Shape begins to behave very oddly and spin about the actor at varying speeds. Here is the code:

The Update method inside the Shape class:

    public void Update()
    {
        if (!Circle && Rotation != lastRotation)
        {
            lastRotation = Rotation;

            Matrix rotate = Matrix.CreateRotationZ(Rotation);

            for (int v = 0; v < Vertices.Count; v++)
            {
                Vertices[v] = Vector2.Transform(Vertices[v], rotate);
            }
        }
    }

The Update method inside the Collider class:

    public void Update()
    {
        if (BoundingShape != null)
        {
            BoundingShape.setCenter(position.X, position.Y);
            BoundingShape.Update();
        }
    }

Part of the Update method in the actor class involving the Collider (Test) and Shape:

        Test.Update();
        Test.setPos(position.X, position.Y);
        Test.BoundingShape.Rotation = Rotation;

I looked around quite a bit before asking so I apologize if something similar has already been answered. All help is greatly appreciated!


texts: Good way to establish an inventory system?

texts:
Fairly new to Unity as a whole, and while making a prototype game I came across the issue of setting up an inventory system. So far, I've been stuck on what sort of structure it should have, given:

Each "Mob" (player, enemy, NPC, etc.) has its own inventory
Objects can have children attached, which should be saved (e.g. Gun -> Attachment Manager -> Magazine/Rail/etc.)
Simpler items (ammunition, etc.) are stackable
An inventory has "pouches" which are available only for certain objects (magazines, health items, etc.) and have a certain volume

At first, I simply made a Mob -> Inventory Manager -> Pouch -> Item system where everything was a child of its respective parent, but obviously even with colliders/sprites disabled that's possibly hundreds of transforms per mob being shifted around each update. Right now, I'm just parenting each mob's inventory system to a static "Inventories" object to get past the issue of that many transforms, but is there a better long term solution that takes into account saving/loading and scene transitions?
Right now, I'm considering:

Turning each item with children (guns with attachments) into a prefab and saving it (not ideal)
Using an ID system to instantiate objects on load by loading the root object (gun), then the children (attachments) given certain parameters (but the variables, like the rounds loaded into a magazine, would be tricky to load)
Having different prefabs for items depending on whether or not they're equipped, on the ground, or in an inventory, and switching between them as needed


texts: How to make touch events work in a match three type game

texts:
In "match three" types of games like Crazy Kitchen, when the user touches an image, he can drag his finger over multiple images and create a change in each image he touches in a single gesture. You might drag your finger across 5 images and each image highlights as you drag across it.

I want to create a similar affect in my game but I can only get the first image to change in a single drag or touch event. I have a GridLayout with each cell containing a custom LinearLayout with an OnTouchListener attached. I want to have the user drag across multiple cells and have each view the user drags across change its image to a "highlighted" image.

How do I get more than the first LinearLayout to be affected by the touch event?

Here's my onTouch code:

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        FloorTile singleTile = (FloorTile) view;
        singleTile.getParent().requestDisallowInterceptTouchEvent(true);
        switch(action) {
            case MotionEvent.ACTION_DOWN:
                Log.i(TE, "MotionEvent = DOWN");
                //assign the new Arrow type to the FloorTile
               swapImage(singleTile);
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i(TE, "MotionEvent = MOVE");
                singleTile.swapImage();
                break;
        }
        return true;
    }

public void swapImage(FloorTile mTile) {
        mTile.setBackground(this.getResources().getDrawable(R.drawable.highlight));
//the actual game will pull a Drawable ID from an enum that matches up the original image with an //appropriate highlighted version.
    }