texts:
The Logic

The player which is a cube (32 by 32 pixels) checks if their is a cell next to it that has the name Wall. (This is done using a tileset).

To do this collision check I made four checks in this order:

Is their a wall under the player.
Is their a wall to the left of the player.
Is their a wall to the right of the player.
Is their a wall above the player.

If the player for example touches the wall to the left of him The x coordinates of the player are set to the tile right of the wall(cell) that was collided with.

The Problem

If for example I move the player left, the loop will first check for a collision under the player however this makes the player move up if their is a wall to the left of the player which he is touching. (Note: it doesn't always do this only if the player moved enough pixels to the left). The player should have just stopped moving to the left. Moving up was not desired.

Experiments

I tried adding the left and right check for collision first. This way the bottom check should not see the cell. This made the player teleport to the left and right of the cell the player was currently on because gravity has time now to drag the player down enough pixels. (The player is always affected by gravity and I rather not change this for it wouldn't make sense for an entity like the player to not be affected by it).

Making the movement speed of the player smaller. This did have an affect which was more desired but the players movement speed should not be effected at all as a fix.

The Code

Collision detection code

    // Floor collision
    if (map.isWall(xCoordinates, yCoordinates - 1) || map.isWall(xCoordinates + 31, yCoordinates - 1))
        yCoordinates = ((int)(yCoordinates / 32) * 32) + 32;

    // Left collision
    if (map.isWall(xCoordinates - 1, yCoordinates) || map.isWall(xCoordinates - 1, yCoordinates + 32)) {
        xCoordinates = ((int)((xCoordinates - 1) / 32) * 32) + 32;
        canMoveLeft = false;
    } else
        canMoveLeft = true;

    // Right collision
    if (map.isWall(xCoordinates + 32, yCoordinates) || map.isWall(xCoordinates + 32, yCoordinates + 32)) {
        xCoordinates = ((int)(xCoordinates / 32) * 32);
        canMoveRight = false;
    } else
        canMoveRight = true;

    // Roof collision
    if (map.isWall(xCoordinates, yCoordinates + 32) || map.isWall(xCoordinates + 31, yCoordinates + 32)) {
        canGoUp = false;
    }

The isWall function

public Cell getCellByPixel(float cellPositionX, float cellPositionY) {

    if (cellPositionX >= 0 && cellPositionY >= 0)
        if (tileid.getCell((int)cellPositionX / 32, (int)cellPositionY / 32) != null)
            return tileid.getCell((int)cellPositionX / 32, (int)cellPositionY / 32 );

    return null;
}

private TiledMapTile getTileByPixel(float cellPositionX, float cellPositionY) {
    if (getCellByPixel(cellPositionX, cellPositionY) != null)
        if (getCellByPixel(cellPositionX, cellPositionY).getTile() != null)
            return getCellByPixel(cellPositionX, cellPositionY).getTile();

    return null;
}

// Check if the cell has a tile with the property of Wall. We can see this in the tsx file.
public boolean isWall(float cellPositionX, float cellPositionY) {
    if (getTileByPixel(cellPositionX, cellPositionY) != null)
        if (getTileByPixel(cellPositionX, cellPositionY).getProperties().get("Wall") != null)
            return true;

    return false;
}

Player movement

private void Movement() {
    if (canMoveLeft)
        if (Gdx.input.isKeyPressed(Keys.A) || Gdx.input.isKeyPressed(Keys.LEFT))
            xCoordinates -= (playerMovementSpeed * Gdx.graphics.getDeltaTime());

    if (canMoveRight)
        if (Gdx.input.isKeyPressed(Keys.D) || Gdx.input.isKeyPressed(Keys.RIGHT))
            xCoordinates += (playerMovementSpeed * Gdx.graphics.getDeltaTime());
}


texts: how to do sprinkle effect of water in opengl in android?

texts:
I want to achieve sprinkling effect of water in android using opengl.
so,
do i need to achieve it with graphics?
is there any other way to do it using opengl?

or how can i start working on this,any links?


texts: Shader effect similar to Metro 2033 gasmask

texts:
I was thinking about effects in games the other day and I was reminded of the Gasmask effect from Metro 2033. Once you put the gasmask on it blurred a bit in the corners and could ice up and even get cracked.

I assume that something like that is done using a shader. I have been experimenting a bit with game development, so far mostly playing with existing rendering engines and adding physics support etc.

I would like to learn more about this sort of effect. Can someone give me a simple example of a shader that would alter the entire scene like this. Or if not a shader then an idea on how it would be done. Thanks.

Edit : Include screenshot of the metro 2033 gasmask effect.


texts: What's the most efficient way to create underground layers of procedural terrain?

texts:
Background information

I am in the process of making a game engine so I have complete, explicit control over everything, anything is an option. I desire to make procedurally generated 3D terrain. It's mostly coming along quite well actually.

I am however, having a difficult time finding any good information on how exactly destructible terrain can be done optimally. I think the mesh deformations could be done at run-time and written to disk but the issue I encounter there is the desire to have ore and similar resources under the ground. I've had the idea to layer additional maps for each unit length of depth but that just seems like it'd have a heavier impact on performance than I'd like.

I know it's of course possible to do that but how to do it efficiently is what I'm interested in here. Perhaps I'm just using bad keywords when I search for information but I'm not turning up much of anything of use on this topic.

I've gone beyond just Perlin Noise for the generation as well using various other algorithms for layers such as vegetation, ground cover like small rocks, etc. By generating the texture maps using the techniques I'm sure we're all familiar with.

A lot of the ideas I've been coming up with would work I suppose but I don't like the obvious impact of performance my ideas have been so far.

Eventually of course I'd have a layer of solid indestructible bedrock but I can't figure out a way better than having a texture map for each layer down per unit length. So if I had a depth of 60 units before hitting the layer of solid bedrock that would mean 60 texture maps. I don't like that at all. Surely there is a better way. I've seen a lot of games not render or even generate the underground at all during initial creation of the game world and do that at run-time but I can't figure out how ore and similar resources could be generated in varying depth layers effectively on initial creation of the world. If the map is color coding by resource it wouldn't exactly work to also color code the height as you would with a height map. It must be one or the other.

Question

The problem I'm having now is underground. What would be the best way to implement underground layers in a performance friendly way that doesn't involve an excessive number of textures used?


texts: How to manage in-game factions, alliances, federations, etc

texts:
So this question is code or engine agnostic but, I’m looking for ideas on how a game can keep track of a pre-determined number of factions or alliances. For example, say I made a space game that has 2 major and 3 minor federations of planets. A planet may join or leave a federation, but the federation itself may have an alliance or be at war with another (actually, to keep it simpler, I think all these changes will solely be reliant on the player’s actions).
However, I would also like to keep track of such diplomatic endeavours on the ‘individual’ level as well. Say the player has joined one federation that is at war with another. If the player should encounter another ship of the opposing federation, that ship becomes hostile. On the other side, two ships have an alliance, they might help one another.
What is the best way to keep track of all this?
One way I was thinking was creating a manager that holds all the Federation classes (which hold the status it holds with all other federations — say less than 0 and the federations are at war; more than x-amount, there’s an alliance). Meanwhile, each player/ship holds similar data in its class, along with its current alliance to whatever federation. Is my thinking logical in this or are there better ways of managing such things? Many thanks.


texts: How do I smooth janky movement over ground as rope length is reduced?

texts:
Here is a video showing the type of movement I am talking about:
video

I have a configurable joint attached to the player which reduces in length every frame the player touches the ground. I do this so that the player has an easier time getting off the ground and it adds a bit extra velocity. The problem is that when the rope shortens it causes the player to bounce across the ground (because the player is pulled toward the anchor then gravity pulls the player back down) which can make the movement seem a bit unpolished. I see two possible ways to solve this, both of which I am unsure on how to do:

stop the bouncy movement
smooth the camera so the bounce isn't noticed by the player

Here is the code that shortens the rope:

if (_playerGameobject.isGrounded())
        {

            SoftJointLimit softJointLimit = new SoftJointLimit();
            ropeLength -= .1f;
            softJointLimit.limit = ropeLength;
            _playerGameobject.playerJoint.linearLimit = softJointLimit;
        }

Can someone give me some tips or ideas for this problem?


texts: How can I use pan gestures to zoom a camera in and out

texts:
I have the following scene tree for my player:

They have a Camera2D as a child, which has a script attached to it. How can I make the camera zoom in and out as I pan on e.g. a MacBook trackpad?


texts: What's the proper practice to organize relationship between components in an ECS pattern?

texts:
I'm new to ECS concept and trying to refactor my app with an ECS manner.
After reading some articles, I still don't get a sense about how to organize hierarchy for such pattern. My questions are

Is a component allowed to have another component inside? For example I saw a RenderComponent that contains a Mesh inside. Is the mesh also a component or the raw data of it, which should be stored inside the RenderComponent?
What happens when an instance of component needs to be shared by two entities?
If an entity should be just an integer, how do you organize the relationship between entities? Should it have a parent/child/linked entity or should all these relationship be managed by the system?

Thanks!


texts: Resources for designing (not programming) 2D platformer mechanics

texts:
I've been making a 2D platformer in Unity and it's been going great. I have the fundamentals down (and as an experienced programmer, I know how to get the results I want; this is not a programming question.)

I've been floundering, though, because I realize that I lack vision in terms of a game direction. I originally wanted to make a Metroidvania-style game, but decided to scale back as I thought that would be too ambitious (and take too long) for my first game. As such, I've decided to create a platformer/run-and-gun type game.

I've played enough platformers to know and intrinsically understand basic mechanics, but I also realize that the best games have a core mechanic that defines the game. Megaman's core mechanic, for instance, is obtaining and using boss weapons and abilities; boss battles and levels are built around this. Metal Slug revolves around weapon pickups and its tank gameplay.

I guess I'm at the point where I have a code demo....but it's not a game; it has no soul. I've basically just proven to myself that I can write a platformer game in Unity.

I want to know of any good resources on aspects of video game mechanic design not centered around programming - book recommendations would be amazing, but online resources or other types of resources would be great as well. (Worth noting that I'm not looking for guides on designing levels, but lower-level mechanics, like jump height, hp limits, core mechanics to define a game, etc.)


texts: Repairing back-facing triangles without user input

texts:
My 3D application works with user-imported 3D models.
Frequently, those models have a few vertices facing into the wrong direction. (For example, there is a 3D roof and a few triangles of that roof are facing inside the building). I want to repair those automatically.

We can make several assumptions about these 3D models: they are completely closed without holes, and the camera is always on the outside.

My idea: Shoot 500 rays from every triangle outwards into all directions. From the back side of the triangle, all rays will hit another part of the model. From the front side, at least one ray will hit nothing.

Is there a better algorithm?
Are there any papers about something like this?


texts:
I am working on a 2D Plattformer with melee attacks. The player is using a Kinematic Rigid Body and a Capsule Collider. Movement (even in slopes), jumping and and collission are working fine.
My problem is that when swinging the axe I am animating a Box Collider 2D with IsTrigger set to true. But it is still not ignored and are pushing the player.

For movement and collissions I use the following code:

void Movement(Vector2 move, bool yMovement)
{
    float distance = move.magnitude;
    if(distance > minMoveDistance)
    {

        foreach (var item in hitBuffer)
        {
            if (item.distance > 0)
                Debug.DrawRay(item.centroid, item.normal, Color.red, 0.5f);
        }

        int count = rb.Cast(move, contactFilter, hitBuffer, distance + shellRadious);
        hitBufferList.Clear();

        for (int i = 0; i < count; i++)
        {
            hitBufferList.Add(hitBuffer[i]);
        }

        foreach (var item in hitBufferList)
        {
            Vector2 currentNormal = item.normal;
            if (currentNormal.y > minGroundNormalY)
            {
                grounded = true;
                if (yMovement)
                {
                    groundNormal = currentNormal;
                    currentNormal.x = 0;
                }
            }

            float projection = Vector2.Dot(velocity, currentNormal);
            if (projection < 0)
            {
                velocity = velocity - projection * currentNormal;
            }

            float modifiedDistance = item.distance - shellRadious;
            distance = modifiedDistance < distance ? modifiedDistance : distance;
        }
    }

    rb.position = rb.position + move.normalized * distance;
}

I suspect it might have some thing to do with the raycast being cast also from the animated box but I do not know if this is the case and how I could test it. I have setup a filter that I pass in to the rb.Cast but even with useTriggers set to false it does not make any difference.

Any feedback that could point me to in the right direction would be very helpful!


texts: I'm trying to do a navmesh. Everything seems to work fine exept that my character in almost completely under the ground. The ground is a plane with a mesh collider. I have baked it and checked my heigth mesh. My character has a rigidbody and a collider. What could be the problem ?


texts: Significance of Bresenhams Line of Sight algorithm

texts:
What is the significance of Bresenhams Line of Sight algorithm in chasing and evading in games?

As far as i know and implemented this algorithm calulates the straight line between two given points. However while implementing it in game development i stored the points calculated using this algorithm in an array.Then im traversing this array for chasing and evading purpose. This looks to be working good with some angles only.In an pixel based environment/tile based.

What if there are some obstacles added in the paths of the two points? then this algorithm will not work right?

How well can we use the Bresenhams Line algorithm in game development?


texts: How to render a grid of dots being exactly 1x1 pixel wide using a shader?

texts:
I would like to render a grid with many dots, all equally spaced and being exactly 1 pixel wide.
What I was able to achieve so far is this :

What I would like is (simulated using image editing program):

Here is the shader I wrote (which give result of 1st image).
This is rendered as a giant quad.
Shader "Custom/Grid"
{
    SubShader
    {
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct vertInput {
                float4 pos : POSITION;
                float4 uv : TEXCOORD1;
            };

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

            vertOutput vert (vertInput input)
            {
                vertOutput o;
                o.pos = mul(UNITY_MATRIX_MVP, input.pos);
                o.uv = input.uv;
                return o;
            }

            fixed4 frag (vertOutput output) : SV_Target
            {
                float4 uv = output.uv;
                float x = step((uv.x * 100.0 + 0.025) % 1.0, 0.05);
                float y = step((uv.y * 100.0 + 0.025) % 1.0, 0.05);
                float c = min(x, y);
                return float4(c, c, c, 1.0);
            }
            ENDCG
        }
    }
}

Is it possible to achieve what I want using a shader ?
What is needed from first draft is to control the size of each dot.
I have tried to use partial derivatives (ddx and ddy) but was not able to make it work.


texts:
I am using the following algorithm to test if my camera frustum contains an axis-aligned bounding box:
float plane_dot(XMVECTOR plane, XMVECTOR point)
{
    return XMVectorGetX(XMVector3Dot(plane, point)) + XMVectorGetW(plane);
}

bool is_box_visible(XMVECTOR planes[6], XMVECTOR center, XMVECTOR extents)
{
    for (size_t i = 0; i < 6; i++)
    {
        XMVECTOR plane = planes[i];
        float aabb_radius = fabs(XMVectorGetX(plane) * XMVectorGetX(extents))
                          + fabs(XMVectorGetY(plane) * XMVectorGetY(extents))
                          + fabs(XMVectorGetZ(plane) * XMVectorGetZ(extents));
        to_center = plane_dot(plane, center);
        if (to_center <= -aabb_radius)
            return false;
    }
    return true;
}

Usage code:
    XMMATRIX to_view = XMLoadFloat4x4(&debug_cam->m_view);
    XMVECTOR center = XMVectorSet(0.5f, 0.5f, 0.5f, 0.f);
    XMVECTOR extents = XMVectorSet(0.5f, 0.5f, 0.5f, 0.f);

    center = XMVector4Transform(center, to_view);
    extents = XMVector4Transform(extents, to_view);

    XMVECTOR vs_far_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_far_plane), to_view);
    XMVECTOR vs_near_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_near_plane), to_view);
    XMVECTOR vs_top_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_top_plane), to_view);
    XMVECTOR vs_bottom_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_bottom_plane), to_view);
    XMVECTOR vs_left_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_left_plane), to_view);
    XMVECTOR vs_right_plane = XMVector4Transform(XMLoadFloat4(&debug_cam->m_right_plane), to_view);

    XMVECTOR planes[6] = {vs_left_plane, vs_right_plane, vs_bottom_plane, vs_top_plane, vs_far_plane, vs_near_plane};

    extents = XMVectorAbs(extents);
    center = XMVectorAbs(center);

    is_visible = is_box_visible(planes, center, extents);

It works correctly in most situations, as can be seen here (notice the is_visible checkbox is correctly checked):

But when looking from certain angles the function returns incorrect results:

Is this a limitation of this particular algorithm or is there a bug in my code?


texts:
Let's say I have a right handed column major 4x4 transformation matrix. Can I safely assume (even though there exist non uniform scale) that first column is X axis vector, second column is Y axis vector and third column is Z axis vector?

$$
\begin{bmatrix}
Xx & Yx & Zx & 0 \\
Xy & Yy & Zy & 0 \\
Xz & Yz & Zz & 0 \\
0  &  0 &  0 & 1
\end{bmatrix}
$$

Iis the above layout correct? By the way I am using glm and I don't know if there is a function to extract these axis.


texts: Best way to store items with statistics in an mysql database?

texts:
Im currently working on an multiplayer game. Therefore using MySql for my game to store different data ( For example players, resources and so on ).

Lately i implemented items, players receive them by gathering resources for example, later they should also be able to craft them or even equip them if its a sword or an armor piece.

My problem is that due to my small experience with MySql, i have no clue how to add different statistics ( Equipable, Damage, Different Effects and so on ) to the items. Not every item should have them ( For example "Wood" shouldnt have statistics ).
How should i modify my tables ? Any help would be appreciated ! Thanks !

My current table structure looks like this :

ItemCategories ( ID, Name )
ItemTypes ( ID, Name, ItemCategories_ID )

For more information, how i actually manage/spawn those items in... here two more important tables.

This table contains resources ( For Example "Basic Tree" ) and the item it drops when gathered.

Resources( ID, Name, ItemTypes_ID, gatheringTime, gatherAmount, spawnWeight)

This table contains the items in the players inventory.

PlayerInventory( ItemTypes_ID, Player_ID, amount)


texts: What are the legal considerations about making a game with a dynamic age restricted content?

texts:
What I mean by this is - is it legal to make a game which asks (or proves) your age during install or on initial load, and then dynamically sets the content to the players age.
For example if the players is under-age then all swear word assets are replaced with there PG13 equivalents.
Or the same with blood and gore.

Does this make sense?
Also what are the communities opinions or feelings about this?
(note for locality I am referring to UK law but laws and opinions for any other country is encouraged!)

(ps i can't create tags)


texts: How can I handle the subject of an action disconnecting before the action executes?

texts:
Let's assume I have a CEntity class that describes every entity within the game.

Each entity class has it's own std::vector of CActions. Each CAction is just an action that the entities can perform, for example CActionFight would have the logic for fighting.

To command my player (or any other entity) to fight all I do is:

CActionFight *pActionFight = new CActionFight();
pActionFight->SetTarget(pTargetEntity);
pPlayer->AddAction(pActionFight);

Before this action is started, all other actions queued earlier have to be finished. Imagine player starting to execute the CActionFight over pTargetEntity and suddenly, pTargetEntity disconnects. pTargetEntity is invalid and here's my question.

How do you normally handle that in actions?

If a disconnection event of an entity is received on the server side, do you iterate through the actions of all entity in the map and remove these which are related to an entity that has just dropped connection?

EDIT
Liked Josh's approach and implemented the solution, sounds very sensible and worked like a charm.

// Example of an action, checking wether Entity is still valid.
void CActionFight::Execute()
{
    m_iCycles--;

    if(m_iCycles>0)
    {
        if(m_pTarget->IsValid() == false)
        {
            m_pTarget = NULL;
            m_bValid = false;
        }
        else
        {
            printf("Attacking.%s\n", m_pTarget->GetName().data());
        }
    }
    else m_bValid = false;
}


texts: animating humanoid r in unity. root transform position (XY) makes the model wiggels left and right in almost all animations

texts:
The animation works well with generic rig but in humanoid it starts wiggling when I fix all the axis and position...
I have many models; how can I fix this problem keeping the humanoid rig?

I got the animation and model from mixamo!


texts:
I'm reimplementing an old 4X space-rts game which has diplomacy options. The original was based on a relation scoring system (0..100) and a set of negotiation options (improve relations, alliance, declare war, etc.) The AI player usually had 3 options: yes, maybe and no; each adding or removing some amount to the relation score.

How should the AI chose between the options?
How does the diplomacy work in other games and how are they imlemented?
Any good books/articles on the subject?

(Googling the term diplomacy yields the game Diplomacy, which is unhelpful.)


texts: Spatial Partitioning - Objects larger than cell?

texts:
I'm developing a top down 2D tile based game. Recently I started working on collision detection and have gone down the route of simply using spatial partitioning.
Each object belongs in a cell and checks the neighbouring cells for collisions like this.

However, I realise I'm absolutely going to need to have some collision boxes that are bigger than a single cell.
Are there better algorithms for what I need or is there a simple work around I'm not seeing?
EDIT: multiple objects can be in a single cell at the same time.


texts: Having to check collisions twice per game tic

texts:
I have vertically moving elevators (3 solid tiles wide) and static solid tiles.  Each are separate entities and therefore have their own respective collision routines (to check for, and resolve, collisions with the main character)

I check my vertical collisions after characters vertical movements and then horizontal collisions after horizontal movements.

The problem is that I want my platform to kill the player if it squashes him from the top, and also if he's on a moving platform (that is moving up) that squashes him into a solid block.

Correct behaviour, player on solid blocks being squashed from above by decending elevator

Here is what happens.  Gravity pushes character into solid block, solid block collision routine corrects characters position and sits him on the solid block which pushes him into the moving elevator, elevator routine then checks for collision and kills player.

This assumes I am checking solid blocks first, then elevator collisions.

However, if it's the other way around, this happens....

Incorrect behaviour, player on accending elevator gets pushed into solid blocks above

Player is on an elevator moving up, gravity pushes him into the elevator, solid block CD routine detects no collision, no action taken.  Elevator CD routine detects character has been pushed into elevator by gravity, corrects this by moving character up and sitting him on the elevator and pushes him into the solid blocks above, however the solid block vertical routine has now already run for this tic, so the game continues and the next solid block collision that is encountered is the horizontal routine.  This detects a collision and moves the character out of the collision to the left or right of the block which looks odd to say the least (character should get killed here).

The only way I've managed to get this working correctly is by running the solid block CD, then the elevator CD, then the solid block CD again straight after.  This is clearly wasteful but I can't figure out how else to do this.

Any help would be appreciated.


texts: Creating an illusion of stress and danger

texts:
I'm currently experimenting with an adventure game setting where at some point the game is quite calm and the player has to solve puzzles and at some point there are enemies or environmental traps.

I don't want to have any surprising danger events coming out of nowhere that would scare the player, so I would like to build up the players' tension before a section of the game starts which will contain multiple "player-killing" obstacles (may they be enemies, or the ground falling apart..).

My sound artist made some really good music and sound effects to slowly build up the tension, but game elements during this phase are missing. It's like the player is running from a puzzle-zone to danger-zone through a boring plain section.

Beside sound, what are some generic ways to build up the players' tension? Can i aid with special Visuals, or do i have to improve the story or possibly invent some pre-danger-zone easy obstacles?


texts: Porting Ruby/NCruses Rogue-Like to .NET and FlatRedBall

texts:
I created an awesome rogue-like game in Ruby. For the GUI, I used NCurses. Since I'm using FlatRedBall as my engine of choice for Silverlight game development, I want to port this game over.

What is the best way to efficiently doing this, and what are the pitfalls I should expect?

For example, Ruby is object-oriented, like C#, and I should be able to just convert (rewrite) classes one by one. However, I will run into issues like:

NCurses API. I need to possibly create my own notions of a "Window", or else rewrite GUI code. It's one class, but it's BIG.
Mix-Ins. These are essentially aspect-oriented development. There are a couple of solutions in .NET, like dynamic classes.

What else? Also, I should mention that I want to create a FlatSilverBall (C#) application out of this. That is to say, I will be using the FlatRedBall 2D engine as my foundation. I am not interested in Curses, or any other variation that will allow me to make a console-type game.

As much as possible, I'll dump reusable and helper code, algorithms, etc. into separate projects and generate reusable DLLs.


texts: Can I use xna tutorials to learn monogame? I can't find any good monogame tutorials but there are tons of xna tutorials available and from what I have seen they are pretty much the same thing.


texts: Is state change command less reliable than sending the entire state?

texts:
I'm asking for a game that I develop right now.
The game is using TCP communication, there's server and multiple clients.
While players in a room are playing the game, I send state update commands in a custom binary protocol every 33 ms. (30 FPS)
Problem is those states are huge - there are players moving, objects spawning and also destructible blocks.

If I were to send all this data a single state update to every player will be huge, resulting in huge bandwidth.

So I'm thinking different approach:

Initially send the huge state with all moving and stationary objects, when the room starts
Do the state update commands every 33 ms, but include just the moving objects, and not include the state and location of the stationary objects.
For stationary objects, issue separate commands to tell they are destroyed or spawned and expect clients to update their copy of the state.

My concern is that it may somehow happen that due to not including the stationary objects in every state update, clients may somehow miss the separate commands that update on those and not reflect that change in their copy of the state.

Here is a visual representation of what I imagine:

Less bandwidth (is it less reliable?):

game started -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 1 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
state update 2 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
state update 3 -> obj1 {id,location}, obj2{id,location} #assumes obj3 is there
object removed -> obj3 #removing the object locally
state update 4 -> obj1 {id,location}, obj2{id,location} #obj3 not present at this point

More bandwidth - include all objects in every state update and assume if something is not present, it has been removed (is it more reliable?):

game started -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 1 -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 2 -> obj1 {id,location}, obj2{id,location}, obj3{id,location}
state update 3 -> obj1 {id,location}, obj2{id,location} #obj3 is not here, so removing it locally
state update 4 -> obj1 {id,location}, obj2{id,location} #obj3 not present at this point


texts: Why does Unity launch Visual Studio but opens files in Notepad?

texts:
In Unity 5.2.0f3, when I double-click a C# script, it effectively launches Visual Studio Community 2015 but then opens the source code file in Notepad instead of inside the Visual Studio IDE.

How can I make sure that source code is opened inside Visual Studio (the one Unity started)

Investigation Notes:

It happens both from double-clicking an attached script the inspector or the script icon in the project/assets panel.
Although the specific file is not open, the "Class View" in the VS IDE loads that I'm in MyGame.CSharp and MyGame.CSharp.Editor, so some kind of interaction must happen.
It happened to me that initially Visual Studio claimed it was in "expired trial mode", then I created a MS account and bound it to the the VS. Don't know if this had any effect on that.
I can't tell if it was working previously, as I come from a Unity version
that used to use MonoDevelop.


texts: How to make party members appear and move to begin a conversation scene?

texts:
A common conversation starting trope in JRPGs, when the party is represented as a single character, is for the characters to come out of the player's position and begin talking with each other and the original character.   Essentially they appear in the player's position and then move to a nearby square either one at a time or simultaneously.  Then they start talking in classic JRPG fashion with one message box after another from one or another character.

What's the easiest way to do this in RPG Maker MV?

Is there a way to do it so the characters appear at the same time and move to their conversation positions simultaneously? Or is that not worth the trouble?

I can't find or create a tag for rpg-maker mv


texts:
This is what I am trying to achieve: A given image would occupy say 3/4th height of the screen. The remaining 1/4th area would be a reflection of it with some waves (water effect) on it.

I'm not sure how to do this. But here's my approach:

render the given texture to another texture called mirror texture (maybe FBOs can help me?)
invert mirror texture (scale it by -1 along Y)
render mirror texture at height = 3/4 of the screen
add some sense of noise to it OR using pixel shader and time, put pixel.z = sin(time) to make it wavy

(Tech: C++/OpenGL/glsl)

Is my approach correct ? Is there a better way to do this ? Also, can someone please recommend me if using FrameBuffer Objects would be the right thing here ?

Thanks


texts: libGDX - How to rotate with a specific duration

texts:
I want to rotate my player to 90° for a specific duration. I know scene2d provides this, but I don't want to use it for my players.

With how much to rotate every frame, so after x seconds the rotation is finished? The game can run on different FPS also.


texts: Any recommended books/resources on component-based design?

texts:
I come from a background with heavy use of the classical object-oriented paradigm for software development.

The company I am a part of switched to Unity not too long ago, and we're all very excited to get started using it  However, one aspect that have sparked my interested, and which I think will become a very important part of our future development, is Unity's approach to component-based design with scripting; with less focus on typical hierarchical aspect.

Question

I was wondering if anyone could recommend any good books on this subject? I have had trouble finding any books or books with reliable reviews, and was wondering if anyone more experienced here had something to say on the issue?

Any other kind of resource would be excellent too, I'm just interested in getting to learn everything I can about it.

This is not meant as a discussion about best books or resources on the topic, but simply a question regarding any resources that any of you find useful.

Thank you all for your time!


texts: Ways to make my game world bigger without slowing users CPU

texts:
I've been developing my first game for a little while now, but I've found that I want to make the game world MUCH bigger. It's currently about 300*300 tiles, but has creatures and bad guys running around the whole thing, so I've got to keep track of all the enemies movement and hostile-finding algorithms.
I'm wondering how I can scale something like this up? It seems (from code profiling) that enemies are the limiting factor, and it's mainly that for each enemy, I need to scan through all the player-units and creatures to see if they're close enough for the enemies to see/attack.
Edit: W,S,A,D,B,Q, if anyone's interested in controls :)
Edit 2: Please tell me if there's any way I could improve the question!


texts:
I am wondering whether I should look into implementing an octree of some kind.

I have a very simple game which consists of a 3d plane for the floor. There are multiple objects scattered around on the ground, each one has an aabb in world space.

Currently I just do a loop through the list of all these objects and check if its bounding box intersects with the frustum, it works great but I am wondering if if it would be a good investment in an octree. I only have max 512 of these objects on the map and they all contain bounding boxes. I am not sure if an octree would make it faster since I have so little objects in the scene.


texts: How do I implement a field of vision for AI entities?

texts:
I am considering how to implement a field of vision system for my AI entities, but am not sure on the order of steps to take. The thought process that I had was to use a combination of radial distance and dot product.

Keeping in mind that this is a 3D environment (meaning that all vectors have 3 components), and I will be using quaternions for the orientation of all entities.

What order should I do these in? and is my logic accurate?

Dot product: Taking the position of the playerObject, and the position of the AIEntity create a vector, and then take the orientation quaternion, and convert that to a vector of fixed length, and perform the dot product between them (testing for a specific range of values) to see if it is within a given arc.

Radius test: Simple 3D radius to determine distance.

I know for sure that a dot product test should be quite simple (3 subtractions, 3 multiplications, 2 additions, and however many operation to turn a quaternion into a vector), but arriving at the orientation vector I have no direct idea (if this process could be explained it would be of great help, I know I would have to multiply by the needed magnitude after normalizing), and radius test is also simple (3 subtractions, 3 additions, and 4 multiplications) both of these would still include a boolean tests, but which order would reduce faster?

My first guess would be to be the dot product, and then the radius test; As the dot product would be outside of bounds if the player is outside of the arc or to far away, and the radius test would only fail if the object is to far away. I understand that both tests can give false positives, but for some reason I feel that the dot product test would give fewer.


texts: Displaying an image when ScrollPane item is highlighted

texts:
I would like to have images displayed when an item in the list is highlighted as a form of a "preview" of the map that is selected. I'm not sure how i would implement this with clickListeners or things of that sort as I am new to libgdx and would like some assistance in making this happen. For example the transition between the images following:

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;

public class LevelSelect implements Screen {

private Stage stage;
private Table table;
private Label heading;
private BitmapFont white, black;
private TextureAtlas atlas;
private Skin skin;
private List<String> list;
private ScrollPane scrollPane;
private TextButton play, back;
private String[] items = new String[] { "UNDECIDED", "\"East Side!!! West Side!!!\"" };

@Override
public void show() {

    stage = new Stage();

    Gdx.input.setInputProcessor(stage);

    atlas = new TextureAtlas("ui/atlas.pack");
    skin = new Skin(Gdx.files.internal("ui/menuSkin.json"), atlas);

    table = new Table(skin);
    table.setBounds(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

    list = new List<String>(skin);
    list.setItems(items);

    white = new BitmapFont(Gdx.files.internal("font/fd.fnt"), false);
    black = new BitmapFont(Gdx.files.internal("font/fd2.fnt"), false);
    LabelStyle headingStyle = new LabelStyle(black, Color.WHITE);
    heading = new Label("Level Select", headingStyle);
    heading.setFontScale(3);

    scrollPane = new ScrollPane(list, skin);

    play = new TextButton("PLAY", skin);
    back = new TextButton("BACK", skin);
    back.addListener(new ClickListener() {
        @Override
        public void clicked(InputEvent event, float x, float y)
        {
            ((Game) Gdx.app.getApplicationListener()).setScreen(new MainMenu());
        }
    });

    //TEXTURES FOR MAP PREVIEW
    Texture kingdoms_0 = new Texture(Gdx.files.internal("image/mapPreview/kingdoms_0"));
    Image kingdoms_0_pic = new Image(kingdoms_0);
    Texture kingdoms_1 = new Texture(Gdx.files.internal("image/mapPreview/kingdoms_1"));
    Image kingdoms_1_pic = new Image(kingdoms_1);

    table.add(heading).center().colspan(3).row();
    table.add(scrollPane).expandY().left();
    table.add(kingdoms_0_pic).row();
    table.add(play);
    table.add(back);

    stage.addActor(table);
}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    stage.act(delta);
    stage.draw();

}

@Override
public void resize(int width, int height) {
    stage.getViewport().update(width, height, false);
    table.setFillParent(true);
}

@Override
public void pause() {

}

@Override
public void resume() {

}

@Override
public void hide() {

}

@Override
public void dispose() {
    stage.dispose();
    atlas.dispose();
    skin.dispose();
}

}

Help is greatly appreciated!


texts:
I have a game where each "tile" of the terrain is a triangle (Settlers 2). Those are placed next to each other and in way creating an infinite world (right/bottom jumps back to left/top). There is a 3D component (each triangle point has a height) but that gets translated into an Y-position offset, so everything can be considered 2D.

Everything (texture coords, screen coords, color (white<->black, FoW)) is put into VBOs already and usually does not change (FoW may disappear which updates the color VBO, but rarely)

When drawing I iterate over the visible tiles (currently in view) and collect "runs" of tiles with the same texture. After that I do:

Bind current texture
Draw current run (offset into VBOs + num of same textured tiles)
Repeat until all runs are drawn

To reduce the number of texture switches I wanted to create a texture atlas. But the problem: Some textures are animated (texture animation so all tiles use the same frame of the animation at any given time) and those animations may be different.

To give some numbers:

~30 textures, pretty small (~30-60px each)
8 are animated, rest static
animation length is 4-8 frames
animation frame time is constant

How would I best go with those animations?

Put all static textures into 1 texture, animated ones into separate ones?
Unroll animations so I have ~8 textures (possibly 24 if I have 8 frame and 6 frame animations) where each texture is 1 frame (so static textures are copied into those unmodified)
Repeat all textures into 1 texture and do some U-coordinate shifting in a shader (not used ATM, but will add soon) -> again possible waste
Some shader magic?

Using OpenGL 2.1, C++.

Visualization of 3 textures: Triangles cut out from squares in any position (in fact only 6 are possible: Top to bottom, top to middle, top to middle rotated by 135° and their mirrored counterparts). Shown is 1 of 2 triangles per square, the other one is mirrored horizontally. All tiles may have different sizes


texts: How to implement level-player collisions resolution?

texts:
I want to create simple collision response system (physical simulation is not required now). It is needed just that player can't go through walls.

I consider some variants:
- Just create a set of primitive colliders (like AABB, OBB, Spheres) and check collisions in every frame (this approach is impemented now)
- Create a BVH for the big level mesh and check collisions with small set of triangles.
- Combine these two approaches and use BVH for determine which colliders I need to check.

But, probably, these variants are wrong. What algorithms and appoaches would you advice for this purpose?


texts: Are there any companies that offer jobs based on games or app development by an individual in his profile, with out any certificate from any institution ?


texts: Box2d Javascript Disable Contact Between 2 Objects

texts:
I want two objects, when collided, to not effect each other in velocity or force.

I have looked up guides and they say to change the PreSolve so that b2Contact.SetEnabled is false... which in code is

b2Contact.SetEnabled(false);

However, SetEnabled is a prototypal method for b2Contact, which means I have to instantiate a new b2Contact each time in order to call SetEnabled.

This does not make any sense to me and the code is wrong as right now all the objects in my world still collide with each other, even though I set that every single object will not collide with every other object:

This is my modified PreSolve method:

 B2.b2ContactListener.prototype.PreSolve = function (contact) {
        var a = contact.GetFixtureA().GetUserData();
        var b = contact.GetFixtureB().GetUserData();

        if (a instanceof Entity.Rock && b instanceof Entity.Player) {
            new B2.b2Contact.SetEnabled(false);
        }

        if (a instanceof Entity.Rock) {
            new B2.b2Contact.SetEnabled(false);
        }

    }.bind(this);

Any tips on how to use this API would be much appreciated!


texts: For dynamically batched objects the `unity_ObjectToWorld` shader variable is always set to default?

texts: I'm using the standard render pipeline and the unity_ObjectToWorld variable for some calculations in my shader. After I enabled dynamic batching these calculations got broken. It seems that unity_ObjectToWorld is set to default when the objects are being batched. Is it by design? I didn't find anything in the documentation.


texts: How do I remove the window border in Godot?

texts: I want to show my Godot engine game in a borderless window, but not fullscreen. I want to just have the game view visible on screen with no title bar or window chrome.


texts: Modern Compilers Inlining and Header and Implementation Practices in Game Development

texts:
I was taught that in general practice its best not to try to beat the compiler, at least until its proven to be stupid. So in general, and since I was told that its generally only used as a suggestion to the compiler, the inline tag has never been a priority for me to use because I was taught that the compiler is pretty good when it comes to understanding the trade offs your system will have to make when it comes to inlining vs. looped calls to a function pointer for example.
But then I just read that functions cannot be inlined unless they are defined in the header file because otherwise the compiler won't see it when it starts to work on other header and cpp files. I did some more research and I found that some people were saying that this is the old way things worked and that modern compilers perform "Whole Program Optimization" or "Link-Time Code Generation" which is responsible for the construction of the obj files that I'm used to seeing which can then be linked together and optimized further such as allowing the compiler to see functions in the obj file that were once "hidden" in the cpp file and then inline optimize them where appropriate. This sounds great but I'm wondering which source to trust and was wondering if I could get an additional opinion on the matter.
On the other hand I was reading up on header only implementations and how they tend to be used in libraries to increase compiler optimizations and was wondering if its was also a standard practice in game development or if it was typical to separate declaration and implementation into different files when developing a game engine.


texts: How do I represent a MD5-mesh bone (quaternion orientation)

texts:
Going off this link about the MD5Mesh file format, I see a bone is represented as:

"[boneName]"   [parentIndex] ( [xPos] [yPos] [zPos] ) ( [xOrient] [yOrient] [zOrient] )

Since xOrient,yOrient,zOrient make up an orientation quaternion and not a vector, I don't know how to illustrate them. I'm still trying to get a grasp of bones and mesh manipulation.

How is the following represented in file?:

Two bones of a simple stick figure (origin as "a" & left(or right) leg as "b")
groin of model is at origin with the head in the positive y-axis direction
arm wing span goes across x-axis
leg is facing down and 2 unit out on the x-axis from the origin


texts:
I've recently started game development in C++ and decided to make an ASCII based snake game. To hold the values of the snake tail I decided to use a linked list due to its flexibility when it comes to manipulating it.

Each node holds the x and y coordinates of a segment of the snake's tail.

The linked list is successful in holding data, creating a new node whenever the snake eats the fruit, but I do not know how to implement this data into my draw function.

I am aware of the issue being caused by a logical error in my program due to the while loop breaking my if else sequence. I just don't know how to fix it.

Here is my current draw function:

void draw() {
    system("cls");
    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << endl;

    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            if (j == 0)
                cout << '#';
            if (i == posY && j == posX)
                cout << 'O';

            Node *current = head->next;

            while (current != nullptr) {
                if (i == current->y && j == current->x)
                    cout << 'o';
                current = current->next;
            }
            if (i == fruit.y && j == fruit.x)
                cout << 'F';
            else
                cout << ' ';
            if (j == width-1)
                cout << '#';
        }
        if (i != height-1)
            cout << endl;
    }
    cout << endl;

    for (int i = 0; i < width+2; i++)
        cout << '#';
    cout << endl;

    cout << "Score: " << score << " || Tail len: " << tailLen << endl;

}

As you can see I've tried to retrieve the values from the nodes via a while loop. Unfortunately by doing so extra spaces are added and the frames are extremely glitchy. I've been racking my brain over this issue for ages. Any suggestions would be appreciated, thanks.

Screenshot:


texts: How to deal with objects placed in the root nodes of a quad tree?

texts:
I've implemented a quad tree where points and axis aligned rectangles can be put.
It works fine, except for one issue that I'll try to describe.
When you put a rectangle in the tree and this rectangle collides with quadtree's node borders, than your rectangle is put in parent node of that node.
It's ok! That's how it should work!

Let's consider I have a small rectangle (red) laying in quadtree's center (x: 0, y:0). And I would like to retrieve other rectangles near my rectangle (blue rectangles). But here's the problem, when I do that the algorithm will return all rectangles(blue + green), because my rectangle collides with quad tree nodes border and is put in quadtree's root node. I don't need green rectangles and I can't allow myself to have such an overhead.

How can I avoid such problem? What would be the easiest way to implement solution to this problem?

The current Retrieve method recursively walks to each subnode of the node where red rectangle is positioned.

I've heard about overlapping node borders solution, but I guess it won't help in case if red rect would be 3x time bigger?!


texts:
I'm trying to make a tactics game using python and the infamous pygame library. I use threading for networking and pathfinding. The game uses a p2p lockstep architecture, with one of the players acting as a host. The server starts 2 threads (send / receive) for every connected player. All the connected clients also start 4 threads during their lifetime, 2 for networking, one for the main game loop and a new temporary thread for each pathfinding request.

My problem is that the program uses a lot of CPU and memory, even for very small maps, even when not blitting any sprites with transparency or running any pathfinding algorithms the program is slow and CPU intensive.

The map in my game is built out of tiles, which are 96x96 pixel pygame surfaces, which map sprite images are blitted to

# draw the map
for element in self.atlas.all_objects:
   try:
       self.map_surf.blit(self.map_sprites[element.sprite], element.rect)
   except:
       pass

The map, along with any units are finally blitted to the screen, simply

self.screen.blit(self.map_surf, self.map_surf_rect)

A very small map surface, with 8x8 tiles will make my CPU (amd 8 core 3.10ghz) run at 25%, with 70mb memory used per client (the cpu-fan goes crazy). The frame rate is still normal at this point.

A slightly larger map, 16x16 tiles shows a drop in frame rate, down from the desired 60 to around 48.

A map of what I'd want to be small/normal size for a real game, 40x40 tiles, brings the fps down to 12 and uses a surprising 215mb memory (all the spritesheets combined are 22mb, and I'm only using a basic green tile for testing), with the same CPU utilization as before.

On the same 40x40 map, replacing the image sprites with blank 1x1 pygame.Surface objects results in a frame rate of 27 (it's set to 60)

My basic question is this: Is the problem likely to be in my code, or is pygame itself horribly inefficient? If the latter, is there anything short of learning to code c++ that can replace pygame for these purposes?

If the problem is more likely to be in my code, how can I find out what it is?

EDIT:
I profiled my code, and here are some of the highest numbers

map size 40 x 40 tiles:

4606119 function calls (4606113 primitive calls) in 145.974 seconds

ncalls  tottime  percall  cumtime  percall filename:lineno(function)

127128    0.225    0.000    0.225    0.000 vec2d.py:18(__len__)
218530    1.406    0.000    1.406    0.000 geometrical.py:64(__init__)
253534    0.544    0.000    0.544    0.000 vec2d.py:21(__getitem__)
1400934    2.309    0.000    2.309    0.000 {method 'append' of 'list' objects}
4626   20.189    0.004   20.189    0.004 {method 'fill' of 'pygame.Surface' objects}
2086545   64.417    0.000   64.435    0.000 {method 'blit' of 'pygame.Surface' objects}
1289   10.843    0.008   95.724    0.074 bullet_client.py:714(draw)

So it appears a lot of time is spent appending items to lists, but I'm sure not what kind of other, more efficient method of organizing my game there is. As expected however, blitting pygame surfaces trumps the other functions by a huge factor, as shown by the cumtime (whatever that is).

So I guess the question is the same, can pygame be replaced by something, or might there be a more shallow problem in my code still?


texts: Why do I get "UObject" has no member "BeginPlay" errors?

texts:
I loaded up UE4 to work on a new project. I created two C++ classes, one for a bullet, one for a cannon. Upon loading into Visual Studio 2015 I immediately get the error:

  "UObject" has no member "BeginPlay"

Keep in mind I have not written a single line of code. This error just popped up. I have not written a single comment, a single variable, I don't even get to enter some white space so that I have room for new code. I just get the error. I tried remaking the project with different settings (like a blank project, third person, et cetera) and I keep getting that error.


texts: Can using different vertex-buffers for each vertex-attributes be good in certain scenarios?

texts:
Is there scenarios where this is actually good practice? Or does it slow down performance?

Example:

//Vertex format is:
//X, Y, U, V
var myXYs:Vector.<Number> = new <Number>[
  -1, -1,
  1, -1,
  1, 1,
  -1, 1
];

var myUVs:Vector.<Number> = new <Number>[
  0, 0,
  1, 0,
  1, 1,
  0, 1
]

//Create actual VertexBuffers....
// ...yaddiyaddiyadda...

//Set context3d's vertex-attributes:
//Assign 'va0':
context3D.setVertexBufferAt(0, bufferXY, 0, Context3DVertexBufferFormat.FLOAT_2);
//Assign 'va1':
context3D.setVertexBufferAt(1, bufferUV, 0, Context3DVertexBufferFormat.FLOAT_2);

Would the GPU have to constantly internally 'swap' between bufferXY and bufferUV to process the vertex-data? Or does it handle it just as good as a single vertex-buffer?

NOTE: My goal is to figure out a way to minimize uploading data from CPU to GPU for a large number of objects (more than the 128 limit with vertex-constants in Stage3D) by manipulating a list of vertices only responsible for the position of objects rather than the entire geometry + color and/or UV coordinates.


texts: How can a programmer learn to draw 2D assets?

texts: Are there any good tutorials for someone who wants to create 2D graphical game assets? Drawing classes for absolute beginners, preferably teaching skills that can be as relevant as possible to games - drawing characters sideways/top-down, isometric, drawing textures and such.


texts: Raycast check for Collisions across XZ coords without Y rotations / Unity C#

texts:
I'm really new to Unity/C# (I have a bit of experience in GML but far from professional) and I am currently building out my first prototype.
I originally copied THIS script to get a cube that rotates face-to-face along one of its bottom edges.
Currently, the state of the game is the cube "rolling" around on a 10x10 grid. The grid currently has a border of walls. I want the cube to shoot a rayCast in the direction the cube is moving towards, check if there is a wall, and decide whether the cube can move in that direction.
This is the way I had it set up previously:
Vector3 up = new Vector3(0, 0, 0.5f);
Vector3 right = new Vector3(.5f, 0, 0);
Vector3 down = new Vector3(0, 0, -0.5f);
Vector3 left = new Vector3(-.5f, 0, 0);
Vector3 currentDirection = Vector3.zero;

bool Valid()
{
    Ray myRay = new Ray(transform.position + currentDirection, transform.forward);
    RaycastHit hit;

    Debug.DrawRay(myRay.origin, myRay.direction, Color.red);
    if (Physics.Raycast(myRay, out hit, rayLength))
    {
        if (hit.collider.tag == "Wall")
        {
            return false;
        }
    }
    return true;
}

currentDirection is set to when movement keys "WASD" are pressed. I know one issue that I am running into is that transform.forward does not work because the Y-rotation of my cube never changes.
Gif format not supported so heres a link showcasing the problem:
Movement & Clipping: https://i.imgur.com/XxlEx1G.gifv
Overall, I was wondering how to get the raycast to shoot in the appropriate direction based on movement.
Sorry if the answer is incredibly easy and I'm just missing it.
Thanks for the help,
Kalfin


texts: Given a 3d goal point and a turn rate in radius, find max speed to reach goal

texts:
I'm working on a 3d space sim with AI agents flying ships through space. I am trying to get them to follow a waypoint path nicely, which involves figuring out how fast they can be travelling and still manage to pass through the waypoint.

Given a point in 3d space and an an agent that only travels forwards and has a given turning rate in radians / second and an acceleration rate, how can I find the maximum speed the ai can travel and still manage to face the point before overshooting it?

Can any math wizards lend a hand?

public class AIPilot { //relevant fields from my class
   float turnRate_radians;
   float acceleration;
   Transform transform;

  public float FindMaxSpeedToFace(Vector3 goal) {
    //trying to fill the body of this method
  }
}


texts: Getting solid black color when texture is added to GLSL

texts:
I'm trying to apply the default badlogic.jpg image to a .obj I have. I'm currently loading the texture from AssetManager and creating a material with a texture attribute (as a diffuse).

In my fragment shader, I try to get the texture value and output it but it just results in a solid black. I outputted v_texCoord (as a vec4) and I could see different colors that resemble what they should be (which should mean that the texture coordinates are correct). But yet
I still get a solid black color.

I don't understand why the texture is not coming through. Am I missing something?

Code:

/.../
model = assetManager.get("mesh/Sting-Sword-lowpoly.obj", Model::class.java)
texture = assetManager.get("badlogic.jpg", Texture::class.java)

val m = ModelInstance(model)

val mat = Material()
mat.set(TextureAttribute.createDiffuse(texture))
m.materials[0] = mat

/.../

Vertex Shader:

attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord0;

uniform mat4 u_projViewWorldTrans;
uniform sampler2D u_diffuseTexture;

varying vec3 v_normal;
varying vec2 v_texCoord;

void main()
{
    v_texCoord = a_texCoord0;
    v_normal = normalize(a_normal);
    gl_Position = u_projViewWorldTrans * vec4(a_position, 1.0);
}

Fragment Shader:

uniform sampler2D u_diffuseTexture;
varying vec2 v_texCoord;

void main()
{
    //Get color
    vec4 color = texture(u_diffuseTexture, v_texCoord);

    gl_FragColor = color;
}


texts: First-person camera script for space game jitters when rotating diagonally

texts:
I am working on a first-person shooter that is set in space. Since its set in space, the characters must be able to rotate in 2 directions at once. Currently, I am using 2 transform.rotates which causes my character to jitter whenever you try to move horizontally and vertically.
Edit: my current idea is to combine the two-axis(x and y) into one rotation
public float mouseSensitivity = 100f;
public float xRotation = 0f;

// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void FixedUpdate()
{
    //horizontal
    float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    this.transform.Rotate(Vector3.up, mouseX);
    print(mouseX);
    //vertical
    float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
    xRotation -= mouseY;
    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
}

Thanks


texts: Architectural advice - websockets javascript/php integration

texts:
Myself and a friend have started making a game, he's likely to be using impact.js for the user interaction etc, but we need multiplayer functionality so some form of websockets for TCP connections etc. So we were thinking impact.js into socket.io and node.js. However, user accounts, ecommerce, session handling and social media integration will all be handled with Codeigniter (PHP), my question is, is it wise to have node.js running in parallel with Codeigniter, or if this is even possible? If not, if you were to create a multiplayer online game utilising ecomms to buy credits and user accounts, how would you go about this from a structural position and what engines/frameworks would you recommend? I'm new to this site so I apologise in advance if I'm posting something inappropriate.

Cheers,

Ewan


texts:
These are my ccTouch__ methods. Note that I am using the singular form of the functions (ie. ccTouchBegan v. ccTouchesBegan (don't know if that has anything to do with it, but it can't hurt to point it out)).

-(BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event{
    //NSLog(@"1");

    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CTouch* newTouch = [[CTouch alloc] initWithStart:touchLocation];
    [touches addObject:newTouch];

    //Right now the UILayer takes all touch events and handles them
    return YES;
}

-(void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event{
    //NSLog(@"2");

    //Get the touch's location and previous location
    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CGPoint lastTouchLocation = [GameScene previousLocationFromTouch:touch];
    //Check which CTouch has been moved and move it
    for (CTouch* ct in touches){

        if ([ct checkSameTouch:lastTouchLocation]) {
            [ct setCurrentPosition:touchLocation];
        }
    }

}

-(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event{
    NSLog(@"3");

    //Get the touch's location
    CGPoint touchLocation = [GameScene locationFromTouch:touch];
    CGPoint lastTouchLocation = [GameScene previousLocationFromTouch:touch];
    //The CTouch object to be removed
    //You can't remove an object from the array while its being enumerated
    CTouch* removeTouch;

    //Check and hold which CTouch has ended
    for (CTouch* ct in touches){

        if ([ct checkSameTouch:lastTouchLocation]) {
            removeTouch = ct;
        }
    }

    //Remove the touch
    [touches removeObject:removeTouch];
}

For some reason, the way I'm checking which CTouch object in touches to move in the ccTouchMoved function works fine, but when I try the exact same thing in ccTouchEnded, it doesn't work.

EDIT: I take it back. The "if" statement to update ct in ccTouchMoved only works the first time. I think this might be the real problem. Because the CTouch object isn't being updated, its information isn't the same as the UITouch object's by the time the touch ends.

I have tried the "if" statement in ccTouchEnded with both the lastTouchLocation and touchLocation and neither of them work. The "if" statement is never true and removeTouch is, therefore, always empty.

The lastTouchLocation and touchLocation in ccTouchEnded are always wildly different from the ct.lastPosition. Just to make sure I cover everything, here's a sample set:

ct.lastPosition:     84,125
ct.currentPosition:  85,125

lastTouchLocation:   155,131
touchLocation:       174,132


texts: How to solve conflicting OnValidate() functions

texts:
I have two OnValidate() functions in two scripts, one attached to the Enemy (EnemyScript) game object and the other to the Enemies(EnemiesScript) game object.

In OnValidate() in EnemyScript I have the following:

    void PrepareEnemyType(EnemyType enType) {

    // by default hasHibernated = false
    if (!hasHibernated) {
        if (enType == EnemyType.Green) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greenEnemy");

        }
        else if (enType == EnemyType.Red) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/redEnemy");

        }
    }

    else if (hasHibernated) {
            gameObject.GetComponent<SpriteRenderer> ().sprite = Resources.Load<Sprite> ("Sprites/greyEnemy");

    }
}

In OnValidate() in EnemiesScript I have the following:

for (int i = 0; i < enemies.Length; i++) {
        if (!enemies [i]. hasHibernated) {
            enemies[i]. hasHibernated = true;

        }
    }

based on the above all the enemies should change sprite to greyEnemy sprite, but that doesn't happen. Before I run the application all of them change to greyEnemy sprite initially, then after I run the application some of them change back to their original sprites, and when I stop running the application they sprites remain the same as when the application was running (different sprites). At this point, the only time that they all become grey again is when I make some other edit to either one of the scripts and save it. Then the above transition repeats.
I suspect there could be some conflict with the two OnValidate() functions, not certain though. How can I resolve this?


texts: coloured 3d models rendering issue while running on android

texts:
I am using Godot 3.2.2 stable (GLES2) along with kenney 3d nature asset pack (glb) for prototyping a 3d game. Everything works just fine on my desktop computer, but when I deploy the game to my android device, the colours stop rendering correctly and show weird patterns instead of plain colours as on the picture (only for imported models, meshes created from Godot work just fine).

It also seems that the sky is blending into the models like some sort of transparency.
Is that just a configuration issue? Or is there something I missed?
Update 1:
Another interesting information, the pattern does not move when the game is in motion, it just show on top of all imported objects but stay at the same position on the phone screen.
Update 2:
Here is how the models render in godot and the surface/materials configuration:

And here is how the same object render once the game running on android:

Note that the floating platform has been imported in godot as an obj (not gltf) and is rendering correctly. the issue seems to be related to the GLTF format.


texts: Why is depth test not working properly in my code?

texts:
http://jsfiddle.net/w9WqJ/31/

When rotating the camera, some pieces that are supposed to be hidden are displayed. Should I create more triangles or what did I do wrong here?


texts: Track two objects on the screen at the same time

texts: I want to keep two objects visible at the same time. My current idea is to calculate a bounding box that contains the two objects and then zoom and rotate the camera so the whole box is visible, is there a different way to approach this problem?


texts: Best practices XML data files and xml compression for Flash Games?

texts:
I am working on a game, and the xml files are getting to be a few megs, and the final game might have a hundred megs of uncompressed xml. If I zip the xml files up I can get something that is about 3 megabytes to be under 100kb which shows that compressing the files will yield good results. How can I get the XML files compressed, and how would I uncompress them on the client's game?

I am planning to keep all my bullet patterns in one file, and planning to keep all the levels in one file. I am not to concerned about the files becoming undwieldy to edit, as I can add my own xml tags as categories to group data, and use a xml editor that can collapse tags. Is there a better way to do this?


texts:
We game developers appear to be a pretty big community. But how big is that community exactly?

How many developers, professional as well as amateur, are working on games all around the world? Do sources to get that number even exist?


texts:
How can I map a normal non T form image to a cube map?

and if there is no manner with which to do this, is it possible to, via DX11, split the image, as the image may be generated on the fly?

Cheers.


texts:
I'm working in Unity3d 2019.2.0f1 and I'm trying to make a chasing bot that follows a certain GameObject with the "Player" tag.

I'm not yet attempting a field of view approach.

How the Script works:

Step 1 : Overlap a sphere on the Bot AI's transform.position and put all the things in the sphere inside a Collider[].

Step 2: Go through each collider in ColliderArray and look for a GameObject with the tag "Player".

Step 3: If found shoot a Raycast to said GameObject with tag.

Step 4: If the Gameobject hit does not have the "Player" tag, then the "Player" is being blocked by a obstacle therefor not in the line of sight,
if the GameObject isn't blocked by an obstacle then we set the destination of the referenced Navmeshagent.

The problem I'm finding (with about 3000 Debug.Logs) is that the Raycast only shoots around 7 times and then just stops, also the "Player" needs to stand in a very specific random location (even tho the "Player" is in plane sight).

What am I doing wrong here?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
    NavMeshAgent agent;

    public float LookRadius = 20; //unity units

    void Start()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    // Update is called once per frame
    void Update()
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, LookRadius);

        foreach(Collider Object in colliders)
        {
            if(Object.transform.CompareTag("Player"))
            {
                RaycastHit hit;

                if(Physics.Raycast(transform.position, Object.transform.position, out hit, Vector3.Distance(transform.position, Object.transform.position)))
                {
                    //if not true the we hit a obstacle.
                    if(hit.transform.CompareTag("Player"))
                    {
                        agent.SetDestination(hit.transform.position);
                    }
                }
            }
        }
    }
}


texts:
Hi I have studied c# for good few months and I'm at intermediate level at the moment.
And few days ago I decided to make simple 2D Games like "Mr Jump" after studying Unity.
So my question is as follow :

1)Should I study database to make simple mobile games? and if so what would be good language to study?

2)And if you have played "Mr.Jump", can you tell me if that game required complicated database coding and a lot of knowledge?

3)Also when we play the game, our best score and new characters get saved in our phone. Is that something to do with database?

4)Could tell me examples of database in games?

5)Should I study database as much as c#?


texts: Differences between particles and using shader in creating effects

texts:
I'm working with particles and little bit with shader.
Both of them can do the same task like creating effects of flame, snow, glowing ...

So which one is better and what are differences between them?


texts: How can I customize/remove the caret from Input Fields in Unity?

texts:
Goal
Change the caret to a non-blinking asterisk.
Description
I'm using the TextMeshPro variant of the InputField, and my Unity ver. is 2019.3.
Potential Solutions
Remove Caret
I could remove the caret and manually add an asterisk at the end — and remove it upon submission.
Problem: I don't know how to do that. Caret width doesn't go below 1, and I've yet to see an option to disable it.
Change Caret
Self-explanatory. However, it doesn't appear that customizing the caret character is an option.
Shove The Input Field Off-Scree And Copy Its Value + * To Text On-Screen
I can still use the Input Field (and I need to), but hide it off-screen and put a simple Text field in its place, which will display the Input Field's text + the caret (*).
This could work, but I'm hoping there's a less hacky solution.


texts: ContentSerializerRuntimeType required in content pipeline?

texts:
I have a problem at the moment loading in a texture for a larger model in the content pipeline. Now it seems that I need to make a proxy object, which is fine, however looking at the SpriteSheet example provided by Microsoft they seem to use the ContentSerializerRuntimeType attribute to bind the proxy class to the real class for use at runtime.

The problem is they sprinkle serialization attributes all over the runtime class, so I was wondering if you HAVE to do it this way or if it is just a recommendation, and is there any other way of getting your proxy class to the real instance?

Ideally I dont want to have to put attributes all over my classes and would be more than happy to write the serialization code myself if there was a way to, but it seems to be an unknown as far as the documentation goes for this area...

So anyone know a way round this, or is this just the only way to do it?


texts: Creating a weighted mesh from skeleton data

texts:
I am trying to wrap my head around animation, but I am having some problems.
The lower body looks ok, but upper body is still very wrong. I think my problem is that I have introduced some scaling somewhere, but I dont know where or how. Any ideas? If I dont apply the animation data to the mesh, the mesh is the correct size relative to the skeleton.

This is how I am building my animation data:
public static AnimationInformation Create(Animation animation, SkeletonModel skeletonModel)
{
    AnimationInformation model = new AnimationInformation();
    for (int frameIndex = 0; frameIndex < animation.Frames.Count(); frameIndex++)
    {
        var animationKeyFrameData = animation.Frames[frameIndex];
        var currentFrame = new AnimationFrame();

        // Copy base pose
        for (int i = 0; i < skeletonModel.Bones.Count(); i++)
        {
            currentFrame.BoneTransforms.Add(new AnimationKeyFrame()
            {
                Transform = (skeletonModel.Bones[i].Position),
                BoneIndex = skeletonModel.Bones[i].Index,
                ParentBoneIndex = skeletonModel.Bones[i].ParentIndex
            });
        }

        // Apply animation translation
        for (int i = 0; i < animationKeyFrameData.Transforms.Count(); i++)
        {
            var index = animation.posIDArr[0][i];
            var pos = animationKeyFrameData.Transforms[i];
            var temp = currentFrame.BoneTransforms[index].Transform;
            temp.Translation = new Vector3(pos.X, pos.Y, pos.Z);
            currentFrame.BoneTransforms[index].Transform = temp;
        }

        // Apply animation rotation
        for (int i = 0; i < animationKeyFrameData.Quaternion.Count(); i++)
        {
            var animQ = animationKeyFrameData.Quaternion[i];
            var q = new Microsoft.Xna.Framework.Quaternion(animQ[0], animQ[1], animQ[2], animQ[3]);
            q.Normalize();

            var mappingIdx = animation.RotationMapping[0][i];
            var translation = currentFrame.BoneTransforms[mappingIdx].Transform.Translation;
            currentFrame.BoneTransforms[mappingIdx].Transform = Matrix.CreateFromQuaternion(q) * Matrix.CreateTranslation(translation);
        }

        // Move into world space
        for (int i = 0; i < currentFrame.BoneTransforms.Count(); i++)
        {
            var parentindex = currentFrame.BoneTransforms[i].ParentBoneIndex;
            if (parentindex == -1)
                continue;

            currentFrame.BoneTransforms[i].Transform = currentFrame.BoneTransforms[i].Transform * currentFrame.BoneTransforms[parentindex].Transform;
        }

        // Mult with inverse bind matrix, in worldspace
        for (int i = 0; i < skeletonModel.Bones.Count(); i++)
        {
            var inv = Matrix.Invert(skeletonModel.Bones[i].WorldPosition);
            currentFrame.BoneTransforms[i].Transform = Matrix.Multiply(inv, currentFrame.BoneTransforms[i].Transform);
        }

        model.Animation.Add(currentFrame);
    }

    return model;
}

And this is how its applied to the mesh:
for (int index = 0; index < lodModel.IndicesBuffer.Length; index++)
{
    var vertIndex = lodModel.IndicesBuffer[index];
    var vertex = lodModel.VertexArray[vertIndex];

    var combinesTransformationMatrix = Matrix.Identity;

   foreach (var boneActingOnVertex in vertex.BoneInfos)
   {
       var boneTransform = currentFrame.BoneTransforms[boneActingOnVertex.BoneIndex];
        var weightedMatrix = boneTransform.Transform * boneActingOnVertex.BoneWeight;
       combinesTransformationMatrix += weightedMatrix;
   }

    Vector3 animatedVertexPos = Vector3.Transform(new Vector3(vertex.X, vertex.Y, vertex.Z), combinesTransformationMatrix);

    Vector3 normal = new Vector3(vertex.Normal_X, vertex.Normal_Y, vertex.Normal_Z);
    vertices[index] = new VertexPositionNormalTexture(animatedVertexPos, normal, new Vector2(0.0f, 0.0f));
}


texts: How is data written from two different gpu cores to the same memory?

texts: Does each core’s data get written to the shared memory one at a time or both at the same time? For instance, when two cores that are next to each other need to write to the same memory spot does the gpu write the core from the left first, then the next core or does it happen at the same time? I’m asking because I want to know if I can get the 2nd core to check a value that the 1st core changed before writing the data.


texts: Game Server Framework / Engine that supports AMF?

texts:
I am looking for a server technology that supports AMF (because I plan on using an as3/flash front end).

I would like to develop game logic / simulations that run on the server.  Small number of users and logic at first, but that will grow.

I might use this for some simple turn based / simple tests, but I am hoping this will also support some tougher real time (RTS) or even MMO style games and simulations.

So far I have been looking at (in order of what I think is most promising so far):

WebORB - Looks the most promising so far, appears to be well supported and developed, lots of features, yet sells itself as easy.  Looks like they have a community open source/free version

Cubeia Firebase - Looks really good, only thing that worries me is their statement that it does not work well for real time style games, but is ideal for turn-based.  It might be ok for now, but what if I need to scale the game up?   Open Source/Free

BlazeDS - Looks promising, supported by adobe, I should be able to develop game logic in the BlazeDS server and has amf support.   Open Source/Free

Red5 - No release since 2010, some activity though. (has amf)  Open Source/Free - however have not been able to locate any good 'game' examples / tutorials.

FlashMOG - looks interesting, but I am not sure if it is robust enough to act as an actual game server with continuously running logic.  No release since 2010,  Uses PHP as a socket server.  Open Source/Free

RedDwarf (used to be SGS/Project Darkstar) -- no release since 2010, is this active?  Has AS3 library, but it is out of date too?  Open Source/Free

Cirrus,
Wowza,
FMS - these are more of a media server?

SmartFox,
Electroserver - these are nice, but are not open source/free.  I believe they have limited connection versions available and while I am hoping to scale my project above those limitations I do not expect to be drawing an income to pay for the licenses at that point

LCDS (live cycle data services) - similar to blazeDS, not free

Any other options or clarifications??


texts: Best practice for toggling between ragdoll and CharacterController

texts:
One feature of the game I'm working on is that if a character is hit with a certain amount of force, it will temporarily ragdoll, then get up off the ground after a small period of time. This character is moved by a CharacterController (CC) component. At the moment, I have the model as a child of an object with a CC component and movement script. My issue is that when the ragdoll is activated/animator is disabled, the model moves independently of the CC - if it ragdolls with some arbitrary force in any direction, the CC does not move with it (as you'd expect). This would be fine if the ragdoll wasn't meant to be re-enabled, but it is. At this stage, the model teleports/moves to where the CC is, and it looks very weird.
I have tried a few different methods to synchronize the two:

Decoupling the CC and model. Both objects are children of a shared parent, and I added them both to an PhysicsIgnoreLayer (for now - eventually if I go with this I'll probably add all the ragdoll colliders to an array and ignore them individually). When the ragdoll state is enabled in the parent, the CC is disabled and the object is teleported to the root bone every frame. When the CC is enabled, the model is teleported to the CC object every frame. See here. The issue here is that setting the position means extra Update() calls and it lags behind the controller a little. Also, because the model isn't a child of the controller, it doesn't inherit the velocity of the controller, so it needs to be manually applied.
Changing the parented GameObject at runtime. Depending on the state of the character, the CC/model will be parented to each other - if the CC is active, the model is set as its child and vice versa using SetParent. I couldn't get this one working (the local position variable was a little confusing to me, but no configuration I tried worked for me).
Conjoined CC and model. I placed the CC on the same object as the model. This isn't really ideal for me because I want greater control over the rotation and presentation of the model. I couldn't get this one working either - I don't know how I could set the position of the CC without moving the whole thing.

Is there a more effective way of doing this? If so, what? I feel like I am greatly overcomplicating this. Any help would be great. In an ideal situation, I could have the model as a child of the controller (or behave that way) and move the CC when it is inactive without affecting the model position.


texts:
My test FBX mesh is a cube. From what I surmise, it seems that the cube is on the extreme end of this issue, but I believe that the same issue would be able to occur in any mesh:

Each vertex has 3 normals, each pointing a different direction. Of course loading in any type of mesh, potentially ones having thousands of vertices, I need to use indices and not duplicate shared verts. Currently, I'm just writing the normals to the vertex at the index that the FBX data tells me they go to, which has the effect of overwriting any previous normal data. But for lighting calculations I need more info, something that's equivalent to a normal per face, but I have no idea how this should be done. Do I average the 3 different verts' normals together or what?


texts:
I am developing a quest system for a game and am looking for the most abstract way to go about connecting the system to the NPC conversation system. This isn't much of a question about the code to do it, but more looking for input on designs for it.

Structuring of the quest system and NPC conversation system has already been completed. What I'm trying to figure out is with my current NPC system, what is the best way to integrate the conversations and quests for the NPC.

Assume that, given my conversation system, the Conversation object holds a tree of all conversation nodes that the user will go through. I assume that each NPC will be given a Conversation object to go through in some way (whether this is directly or through a quest object is what I'm trying to decide). Some NPCs may have a standard conversation they have with a user and other NPCs might have a quest which contains conversations within it that the NPC should step through dependent on their current step in the quest. But then some NPCs might have a standard conversation and a quest or even an NPC with multiple quests and a standard conversation.

What I'm trying to figure out is what is the best way to "connect" these systems so that is abstract, dynamic, and clean. Any suggestions to help me think it out would be great.


texts: Entity-System Architecture; Pools and Factories

texts:
I'm creating a 2D game based on entity-system architecture using C++, the C++ port of Artemis, and SFML. I've had to jump through a few hoops, but it's been fairly smooth until now.

In this game, I have an EntityFactory class which basically just makes artemis::Entity objects, does some processing (such as creating sprites or setting the position of the entity) and returns that artemis::Entity. This is represented by a static class, something like this:

class EntityFactory {
public:
    //Creates the player, should only be called once
    static artemis::Entity CreatePlayer(artemis::World& world, sf::Vector2f pos);
    //Creates a bullet, can be called many times
    static artemis::Entity CreateBullet(artemis::World& world, sf::Vector2f pos);
    //Creates a static image
    static artemis::Entity CreateStatic(artemis::World& world, sf::Vector2f pos, std::string imgLoc);

    //Some more entities...
}

It's fairly essential that I call these functions to create the entities; the class does a lot of boilerplate stuff, like adding all the necessary components to the entity.

Lately, I've been thinking about implementing a particle system in the game as well. In addition, I'd like to be able to reuse my bullet entities instead of creating &  destroying them all the time. To this end, I figured I'd create a Pool class that holds entities, and disables/enables entities as needed - a common pattern. Here's the basic layout that I was thinking of:

class Pool {
public:
    //Enables/returns a disabled entity, or creates a new
    // one and returns it if there are none available.
    artemis::Entity& get(/*Some data about the object*/);
    //Disables an entity, and marks it as reusable.
    void disable(artemis::Entity&);
private:
    //Data structures for holding the active/disabled entities...
    Function_of_some_sort createEntity;
}

Alright, that's all well and good, except for the one sore spot - that ambiguous Function_of_some_sort. I'd like to let the Pool create its own Entity objects in  Pool::get() . Obviously, I want to use the EntityFactory, since it does a bunch of work; however, to do so, I'd need to be able give the Pool a function with an arbitrary number of arguments and be able to pass Pool::get() the same number of arguments.

As I see it, I have these options:

Limit my functions to a single signature and use a function pointer, eliminating possibilities like EntitySystem::CreateStatic (above).
Implement arbitrary, generic callbacks as described here, sacrificing some typesafety.
Give up the idea of an arbitrary-entity Pool, and make a Pool class for each entity I need. Might be ok, since I don't really have that many classes that need a Pool, but I'm only changing a single function call in each Pool class...
Refactor EntityFactory somehow so that I don't need function callbacks. Probably the best solution, but I haven't been able to come up with a good way to do it.

I feel like there has to be some elegant way of pulling this off, as these are two fairly common patterns that I'm sure have been used in conjunction before. I'm stuck in analysis paralysis; does anyone have examples or experience to offer on the subject, or just some suggestions?


texts: How do you deal with transitions in animating walking?

texts:
I'm pretty new to this whole animating models thing. Just learning the ropes. I got a nice walking animation going, which I can loop while a character is walking, but what about when they stop walking?

I mean, they could be at any point in the animation at the time the player stops walking. How do I get them to smoothly return to a standing still position without having them snap into that position? The same goes for starting walking from a standing still position. Do you need a separate animation? How is this dealt with?


texts: I am trying to develop an card game for Android Can anyone suggest me how to write code for effectively shuffling the playing cards?


texts: FBO rendering different result between Galaxy S2 and S3

texts:
I'm working on a pong game and have recently set up FBO rendering so that I can apply some post-processing shaders. This proceeds as so:

Bind texture A to framebuffer
Draw balls
Bind texture B to framebuffer
Draw texture A using fade shader on fullscreen quad
Bind screen to framebuffer
Draw texture B using normal textured quad shader

Neither texture A or B are cleared at any point, this way the balls leave trails on screen, see below for the fade shader.

Fade Shader

private final String fragmentShaderCode =
        "precision highp float;" +
        "uniform sampler2D u_Texture;" +
        "varying vec2 v_TexCoordinate;" +
        "vec4 color;" +
        "void main(void)" +
        "{" +
        "   color = texture2D(u_Texture, v_TexCoordinate);" +
        "   color.a *= 0.8;" +
        "   gl_FragColor = color;" +
        "}";

This works fine with the Samsung Galaxy S3/ Note2, but cause a strange effect doesnt work on Galaxy S2 or Note1. See pictures:

Galaxy S3/Note2

Galaxy S2/Note

Can anyone explain the difference?

edit

Folowing VinceFR's comment, we've tried adding the following. When the renderbuffers are initialised they are briefly bound to the framebuffer and set the background to a uniform buffer with:

    GLES20.glClearColor(backgroundColor[0],backgroundColor[1],backgroundColor[2],backgroundColor[3]);
    GLES20.glClear( GLES20.GL_DEPTH_BUFFER_BIT | GLES20.GL_COLOR_BUFFER_BIT);

The result is unchanged on the S3, on the S2 it has improved a certain amount, but problems still exist:

note the 20 in the bottom right corner is supposed to be there.


texts: How to interop between DirectX11 in C++ with XAML&C# or should I turn to SharpXD

texts:
I'm writing a UWP program and I want to write the general UI in C#. But there would be some graphic demonstrations using DirectX on some SwapChainPanels in the app. I have found less than enough documents of how I can interop between these two parts in two languages. And problem occurs such as how I should instance a C++ class from another project from C#.
I might need a frequent calling between the two part for the demonstration(It's actually a scatter plot). And some suggested that this could cause a great performance damage.
So should I turn to SharpXD? And what should I do if I don't.
Thank you.


texts:
I'm trying to make an 64x64 tilemap using Super Tilemap Editor & Unity but my tiles looks terrible. I did my research about pixel perfect 2D and all of the solutions were for pixel art, they didn't work for me.

I have the following tileset I made in Adobe Illustrator as an example

Tiles looks like this when placed in game (1x zoom)

I'm pretty sure they're not 64x64 in game, they also look pixelated probably because they're smaller than they actually are on camera.

So my question is, how can I calculate the correct camera size for 64x64 tiles and do I have to make any changes in order to make sprites look pixel perfect? I'm currently using 1080/64/2=8.4375 (vertical resolution / PPU / 2) as camera size.


texts: How can I render extremely large models?

texts: I'm trying to build a game in Unity similar to the game Kerbal Space Program where there are large celestial bodies that the player can orbit. I'm running into a few problems though. My first issue is that the larger I make a sphere, the slower the game gets. Secondly, whenever the sphere exceeds a certain size, the rendering engine cuts off part of the planet, which means I can only see half the model. How can I do this at the size that KSP has?


texts: glReadPixels with GL_DEPTH_COMPONENT into PBO is slow

texts:
I need to read depth buffer back to cpu memory. It may be few frames old, so I use glReadPixels with a buffer bound to GL_PIXEL_PACK_BUFFER. I use several buffers and ping-pong them. Finally, I read from the PBO with glGetBufferSubData. I have tried creating the buffers with GL_STATIC_READ, GL_DYNAMIC_READ and GL_STREAM_READ all with same results. Unfortunately, all this is still horribly slow.

class DepthBuffer
{
private:
    static const uint32 PboCount = 2;
    Buffer buffer;
    uint32 index;
    uint32 pbo[PboCount];
    uint32 w[PboCount], h[PboCount];

public:
    DepthBuffer();
    ~DepthBuffer();

    void performCopy(uint32 fbo, uint32 w, uint32 h);

    // returns 0..1 in logarithmic depth
    float valuePix(uint32 x, uint32 y); // pix in 0..(cw/ch-1)
    float valueNdc(float x, float y); // ndc in -1..1
};

DepthBuffer::DepthBuffer()
    : index(0), pbo{ 0, 0 }, w{ 0, 0 }, h{ 0, 0 }
{
    glGenBuffers(PboCount, pbo);

}

DepthBuffer::~DepthBuffer()
{
    glDeleteBuffers(PboCount, pbo);

}

void DepthBuffer::performCopy(uint32 fbo, uint32 paramW, uint32 paramH)
{
    // copy framebuffer to pbo

    glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[index]);
    if (w[index] != paramW || h[index] != paramH)
    {
        glBufferData(GL_PIXEL_PACK_BUFFER,
            paramW * paramH * sizeof(float),
            nullptr, GL_STREAM_READ);
        w[index] = paramW;
        h[index] = paramH;
    }

    glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
    CHECK_GL_FRAMEBUFFER(GL_READ_FRAMEBUFFER);
    glReadPixels(0, 0, w[index], h[index],
        GL_DEPTH_COMPONENT, GL_FLOAT, 0);

    CHECK_GL("read the depth (framebuffer to pbo)");

    // copy gpu pbo to cpu buffer
    index = (index + 1) % PboCount;

    float *depths = nullptr;
    {
        uint32 reqsiz = w[index] * h[index] * sizeof(float);
        if (buffer.size() < reqsiz)
            buffer.allocate(reqsiz);
        depths = (float*)buffer.data();
    }

    glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[index]);
    glGetBufferSubData(GL_PIXEL_PACK_BUFFER, 0,
        w[index] * h[index] * sizeof(float), depths);

    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

    CHECK_GL("read the depth (pbo to cpu)");
}

float DepthBuffer::valuePix(uint32 x, uint32 y)
{
    if (w[index] * h[index] == 0)
        return nan1();
    assert(x < w[index] && y < h[index]);
    return ((float*)buffer.data())[x + y * w[index]];
}

float DepthBuffer::valueNdc(float x, float y)
{
    assert(x >= -1 && x <= 1 && y >= -1 && y <= 1);
    return valuePix((x * 0.5 + 0.5) * (w[index] - 1),
        (y * 0.5 + 0.5) * (h[index] - 1));
}

The glReadPixels is taking all the time (on cpu). Am I doing something wrong? I thought that reading into the PBO should be asynchronous.
Thanks.


texts:
I am trying to get the coordinates or positions that are generated at the time I draw with linerenderer, but it gives me an error.

This may be a rookie mistake and I am not using the Linerenderer's methods well. I would be very grateful for your help.

LineRenderer.GetPosition index out of bounds!
UnityEngine.LineRenderer:GetPosition(Int32)
sendData_Figura:Trazo(Int32) (at Assets/sendData_Figura.cs:115)
sendData_Figura:Update() (at Assets/sendData_Figura.cs:93)

public LineRenderer  line;
public static int contadorTrazo = 0;

void Update(){
    Trazo();
}

void Trazo() {
    line = line.GetComponent<LineRenderer>();
    Debug.Log("Trazo : "+line.GetPosition(contadorTrazo));
    contadorTrazo++;
}