texts: Game Rooms Server Architecture - ENet CSharp

texts:
My team and I are working on an upcoming online fighting game using ENet-CSharp (A C# ENet implementation created by nxrighthere), and we're currently designing the architecture of the server. We would be very glad to hear your suggestions concerning a couple of issues we have been struggling with.
Our current plan is to host a dedicated server for the game, which will handle the logic and game loop of each game instance, and the MonoGame clients will simply deliver the user's commands to the server, and present the updated game state received from it. However, we are not sure how to correctly use ENet with our division of independent game rooms.
Let's say, I have 100 concurrent users connected to the server, and 10 independent game rooms, consisting of 10 players each. At first, we thought that we should have a single ENet Host which will handle all of them, and a single independent ENet thread that will simply receive packets from all ends, alerting the corresponding game room to handle it within its game logic. However, it seems a bit unsafe to have one I/O thread shared by multiple different and parallel instances of the game, so our plan is as such:

For each game room (10 players for that matter), a unique ENet Host will be created, and 2 independent threads will run - one for the game loop, and one for the ENet event polling.
The ENet thread will call the Service method with a small timeout, expecting to poll one "Receive" event at each iteration, and will queue the commands received from the players.
The game loop, at the start of each iteration, will dequeue the commands that have been collected since the last iteration, apply them within the game logic, and so on.

Would you guys say this is a good solution to go by?
A question that rose with that:
Correct me if I'm wrong, but as far as I understand, the send rate of the outcoming packets corresponds to the rate of calls to either the "Service" or the "Flush" methods. How can I ensure that at the end of each game loop, the new game state will be broadcasted immediately to the clients? Calling the "Flush" method at the end of each iteration seems logically appropriate, but unsafe at the same time (since it will be called outside the ENet dedicated thread).
Any piece of advice would be more than welcome. Thanks in advance!


texts: Unity: Is there any alternative to facebook SDK for facebook ads attribution?

texts:
We have a Unity mobile game.
We will be showing ads for it on facebook audience network.
Now in the past when we tried this, the CPI started out good and then got terrible.. Facebook have told us that to avoid this we need to have the facebook sdk installed in our game.
But the facebook Unity SDK is the bane of my existence. In every project Ive added it to over the years, I have spent so many days bashing my face against the brick wall of getting it to build and run, and when it does the weird workaround solution is incredibly fragile.
My question is.. Do we really need the SDK? What do devs using game engines without an SDK provided by facebook do? Is there an API we can call? Surely the SDK itself is calling some api to do the attribution which allows facebook to optimise the CPI for the ads. Can we just call that?
At this point I would try any alternative.


texts: Steamworks SDK achievement de-synchronization

texts:
The development of my game is coming to an end and I'm now looking into getting a hold of a publisher and publishing my game to Steam. To do this I'm also preparing my game for the use of the Steamworks SDK that handles general Steam business like achievements among other things.

The thing is my game already has a built-in achievement system and I'm worried that my achievement system and the Steam achievement system might get de-synchronized for one reason or another - as in the achievement is unlocked locally in the built-in system but not unlocked in the Steam API. This seems to have happened to several users (Plants vs Zombies example) and Steam has made it clear that this is the developer's responsibility.

How should I be a responsible developer and prevent de-synchronization or deal with it if it occurs?


texts: How to use multiplication operation in game render delta time?

texts:
We are using delta time like this:

private static final float SPEED = 200f; // Moving pixels in one second

@Override
public void render(float delta) {
    myObject.vx += SPEED * delta;
    myObject.vy += SPEED * delta;

    myObject.move();
}

So I am using this update method to apply friction on my object:

private static final float FRICTION = 0.98f;

@Override
public void render(float delta) {
    //...

    myObject.vx *= FRICTION;
    myObject.vx *= FRICTION;

    myObject.move();
}

I know this is wrong:
myObject.vx *= FRICTION * delta

I want to use friction with "multiplication operation" not "minus".

So how can I implement the delta time to my FRICTION variable?


texts: How do you write an unlit shader which supports Ambient Occlusion?

texts:
For performance reasons, a scene might use Unlit shaders only.
Is there an Unlit shader which supports Ambient Occlusion?
What is the best way to achieve this look, for moving and static objects, while prioritising performance?


texts: Why can't I expose a Plane variable in my unity script?

texts:
I've got a script which creates raycasts. I wanted to use the (presumably less expensive) Plane.Raycast rather than the GameObject.Collider.Raycast (because the gameobject one has a distance parameter so that's one more check)

I can expose the plane gameobject in my scene easily by simply making a public gameobject variable like this:

public GameObject floor;

however when I turn it into this:

public Plane floor;

It doesn't expose in the scene. Why is this?


texts: Increasing the rotation angle on a quaternion makes the rotation stop at a certain angle

texts:
I'm using the following code to change the rotation of an object:

Quaternion rot = getRotation();
setRotation(make_quaternion_axis_angle(rot.v,rotationSpeed*dt)*rot)

This code works as expected until a certain angle where it suddenly stops.

Why does it stop?


texts: How can I optimise collision checks for a large number of AI units?

texts:
Let's say I got 100 Orcs in my 3D world and they all aim to kill each other.

That means for every 1 Orc I have to check for collision with the 99 others. That will give me 99^2 which is about 10,000! That many collision checks every update (24-60 times a second) only for the AI will probably use my whole GPU + CPU.

How can I handle such a large number of AI?

How is this is done in games with large numbers of NPCs (e.g. Skyrim, Fallout, Red Dead Dedemption...).


texts: Player with navmeshagent keeps moving back to the last mouse position clicked

texts:
On my FPSController I have two scripts, Player Controller and Agent Controller.

Player Controller is for using the keys WSAD for moving the player around.

Agent Controller uses a NavMeshAgent to move the player to a position clicked with the mouse (like point and click ).

Everything is working fine, or was working fine until I tried to move the player around using the keys WSAD after clicking the mouse.

I clicked the mouse on the ground (terrain) or on a cube no matter what I clicked on and the player is moving to this position. Now at that position the player stops. Now I'm trying to move the player with the keys WSAD, but even if I click on S for example long time the and player is far away from the last mouse clicked position when I leave the S key the player automatically moves back to the mouse clicked position.

The player should stay at where I move him with the keys WSAD but he keeps moving back to the last clicked mouse position.

On the FPSController I have a Rigidbody and NavMeshAgent and the two scripts Player Controller and Agent Controller.

The original Agent Controller script was:

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

public class AgentController : MonoBehaviour
{
    public Camera camera;
    public NavMeshAgent agent;
    public bool agentControl = false;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update ()
    {
     if (Input.GetMouseButtonDown(0) && agentControl == true)
        {
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit hit;

            if (Physics.Raycast(ray, out hit))
            {
                agent.SetDestination(hit.point);
            }
        }
    }
}

And the Player Controller script:

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

public class PlayerController : MonoBehaviour
{
    public float speed = 10.0f;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float translatioin = Input.GetAxis("Vertical") * speed;
        float straffe = Input.GetAxis("Horizontal") * speed;
        translatioin *= Time.deltaTime;
        straffe *= Time.deltaTime;

        transform.Translate(straffe, 0, translatioin);

        if (Input.GetKeyDown("escape"))
            Cursor.lockState = CursorLockMode.None;
    }
}

The main goal is to use either the Agent Controller for point and click with the navmeshagent or using the keys WSAD to move around.


texts:
I'm looking for an efficient way to render multiple object with unique texture sets each.

Right now I combine multiple objects into a single static vertex and index buffers in the way like this:

std::vector<Verts> v(m_vsize);
std::vector<uint32_t> ind(m_isize);

// SKIPPED: adding vertex and index data to "v" and "ind" vectors

D3D11_BUFFER_DESC vertexBuffer_desc = {};
vertexBuffer_desc.Usage = D3D11_USAGE_IMMUTABLE;
vertexBuffer_desc.ByteWidth = sizeof(Verts) * m_vsize;
vertexBuffer_desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vertexBuffer_desc.CPUAccessFlags = 0;
vertexBuffer_desc.MiscFlags = 0;
vertexBuffer_desc.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA vertexData = {};
vertexData.pSysMem = &v[0];
vertexData.SysMemPitch = 0;
vertexData.SysMemSlicePitch = 0;

HRESULT hr = m_d3dDevice->CreateBuffer(&vertexBuffer_desc, &vertexData, &m_vertexBuffer);
if (FAILED(hr))
    return;

D3D11_BUFFER_DESC indexBuffer_desc = {};
indexBuffer_desc.Usage = D3D11_USAGE_IMMUTABLE;
indexBuffer_desc.ByteWidth = sizeof(uint32_t) * m_isize;
indexBuffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
indexBuffer_desc.CPUAccessFlags = 0;
indexBuffer_desc.MiscFlags = 0;
indexBuffer_desc.StructureByteStride = 0;

D3D11_SUBRESOURCE_DATA indexData = {};
indexData.pSysMem = &ind[0];
indexData.SysMemPitch = 0;
indexData.SysMemSlicePitch = 0;

hr = m_d3dDevice->CreateBuffer(&indexBuffer_desc, &indexData, &m_indexBuffer);
if (FAILED(hr))
    return;

After that I pass my buffers to Render() method and render everything with a single DrawIndexed() call:

// some stuff
m_d3dContext->IASetVertexBuffers(0, 1, m_vertexBuffer.GetAddressOf(), &stride, &offset);
m_d3dContext->IASetIndexBuffer(m_indexBuffer.Get(), DXGI_FORMAT_R32_UINT, offset);
// some more stuff
m_d3dContext->DrawIndexed(m_isize, 0, 0);

Where m_isize is a count of total indices.
So what I'm looking for is how do I draw multiple objects separately?
 - Create individual buffers per each object (object count is unknown at startup)?
 - Create dynamic buffers and use those?
 - Keep using static buffers with re-assigning pointers to new objects and call DrawIndexed() per object instead of per frame?
 - A common solution? (Obviously unknown to me).

Basically all I need to find out is the name of pattern/technique commonly used to draw unknown amount of objects effectively.
My approach doesn't work because I merge all groups into single vector variable and so I can't give various texture sets to various objects.


texts: How to store 3D entity position, offset, and transformation data for parent and children?

texts:
I am looking for a cleaner pattern to storing character position data, offsets, and transformations. I currently have a character with a vec3 for position.

Entity{
 position: vec3
 rotation: vec4Quaternion
 velocity: vec3
}

I use this position vector as the world coordinate. So that when Y=0 I imagine the characters feet are on the ground. This makes it easier to think about where the entity is in world space.

The problem I am having is that mesh entities like colliders or the skin mesh will assume a position vector at the center of the mesh.  This is causing me to have to do a bunch of transformation juggling. I can't 1-to-1 map these meshes to the entities world position.

I will update my characters 'ground position' when they move. then have to calculate the new 'center position' which is calculated like

centerPosition = [
groundPosition.x
groundPosition.y + entityHeight/2,
groundPosition.z
]

I"m wondering if there is a better pattern for this. Maybe I assume the entities position vector is a 'center position' as well? but not clear to me how to handle the ground offset in that case.


texts: Why are the app analytics for iTunes Connect so wrong?

texts:
I've developed a mobile game and have it listed both at Google Play and the Apple App Store. The install stats from Google Play are very close to my own stats, but the stats iTunes Connect shows are WAY off -- it shows nearly 1,000 "app units" (which I assume means installs) when there's only about 120.

Most of their "installs" come from China.

I'm trying to figure out 1) why iTunes Connect is counting all of these bogus "installs" and 2) what possible benefit someone could have from performing all of these fake installs.

Thanks in advance for your insight.


texts: How to configure A* for large 2D Grid based pathfinding, where paths could be long or short?

texts:
I thought A* was Optimal, meaning I'd always get the quickest path.

I have written a generic Pathfinding implementation here:
https://github.com/mGuv/mGuv/blob/PathPerformanceExperiment/mGuv/mGuv/Pathfinding/Pathfinder.cs

It's a bit messy/weird as I've branched off my original to fix some issues and experiment.

I wrote a testing class that can read in an image file that uses Black for Obstacles, Blue for start, Green for goal. It too is a little messy but I'm just debugging again.

http://hastebin.com/wikejexige.avrasm

So it uses Euclidean Distance and Orthogonal movement to attempt to path.

It then generates an output image, with Black for Obstacles, Blue for the Path found, Orange for the Nodes Expanded, and Cyan for the Open Set.

Given the input image:

It outputs:

Which is less than Optimal?

I've tried tweaking the cost/heuristic functions and their weighting.

Eventually I can get something like:

But now look at that open set, it's essentially turned in to Dijkstra's Algorithm.

I also believe I have the "Breaking the tie" problem, as an input like:

Will expand way more nodes that necessary:

I've tried to follow the Wikipedia article on A* to come up with better cost handling but most of those assume you know the estimated path length. Which is difficult for me as I will be using this to path find on giant (1024x1024+) grids that are dynamic. From tiny (<10 step paths) to huge (> 10000 step paths).

I'm a little lost now as to where I'm going wrong. I don't know if there's a bug or a misunderstanding. I apologise for the tiny images, it was just easier to work a pixel basis.


texts: How to fix edge scrolling on a 2d scrolling camera?

texts:
Afternoon all,
I just cannot get this to work properly and I'd really appreciate any help. I have a camera that follows the player around a 2d tile based map. However, I want the camera to move only when the player touches the outer edge and at that point to only move enough to get the player out of the edge. So if the player is 2 tiles into the left most edge then move the camera 2 tiles to the left.
I currently have the following bugs:

The camera doesnt move to the player on game start, until the player moves.
The camera doesnt render differing amounts of tiles around the edges.
The camera follows the player at all times, rather than scrolling when at the edge.

The camera's movement code seems to work fine so I believe the issue is in the way I am assigning the target or obtaining the offset. Here's the specific code for that.
def set_target(self, position: Tuple[int, int], ignore_edge: bool = False):
    """
    Set the target position.
    """
    x, y = position

    # centre the target
    half_width = (self.columns // 2) - 2  # -2 to offset against the rounding of row/columns
    half_height = (self.rows // 2) - 2

    if self.is_in_camera_edge(position) or ignore_edge:
        offset_x, offset_y = self.get_edge_offset(position)

        new_x = x + offset_x
        new_y = y + offset_y

        self.target_x = clamp(new_x - half_width, 0, self.map_width - half_width)
        self.target_y = clamp(new_y - half_height, 0, self.map_height - half_height)

    self.is_dirty = True

    def get_edge_offset(self, target_pos: Tuple[int, int]) -> Tuple[int, int]:
        """
        Determine how far the player is into the edge of the camera
        """
        x, y = target_pos
        edge_size = self.edge_size
        dir_x = 0
        dir_y = 0

        if x < self.start_x + edge_size:
            dir_x = x - (self.start_x + edge_size)

        elif x > self.end_x - edge_size:
            dir_x = x - (self.end_x - edge_size)

        if y < self.start_y + edge_size:
            dir_y = y - (self.start_y + edge_size)

        elif y > self.end_y - edge_size:
            dir_y = y - (self.end_y - edge_size)

        return dir_x, dir_y

And here's the code in full.
I would really appreciate any suggestions or thoughts. I am pulling my hair out after days of getting nowhere with this.


texts: How to save one color channel, taking only 1 byte per pixel?

texts:
How can I save only one color channel, such that it would only take 1 byte per pixel?

I only want to save the alpha channel and apply colors later using a custom shader. But all the formats I tried so far take more memory than necessary. For instance, 8x8 image should only take 64 bytes. Is there any image format that allows this?


texts: Will the inclusion of LGBT characters in my game detract from possible sales?

texts:
As we all know, the inclusion of LGBT characters has been a mighty controversial topic in recent film and literature (Beauty and the Beast probably being the premier example). Some love it with every fiber of their being, while others absolutely detest the very thought of it. Now, keep in mind that I am not here to start a political firestorm nor am I here to preach my own personal beliefs regarding this, I'm simply asking the question: will the inclusion of LGBT characters decrease potential sales?

In our game, a pseudo-'90s JRPG, one of our main story writers added two consuls (of a civilization with heavy Roman influence, but with different laws), both female, married. Originally hailing from an area in which LGBT relationships are looked down upon, I was quick to note that it may be too much controversy, but it truly depends on where you live—for him it was almost completely normal.

As I see it, we have three choices.

We can keep the characters just as they are.
We can keep the characters, but only imply their relationship.
We can alter the relationship entirely, changing one to a male.

Right now, our main goal is to satisfy the general public while still strongly appealing to those who actually played JRPG's such as Dragon Quest or Final Fantasy back in the day. Which of these three options should we choose to best enhance our sales, or, if it's not up there, what is the wisest way to go about doing this? I am looking for facts and data if possible and/or applicable.

EDIT: Our target audience is Everyone! Like we said, we’re aiming to satisfy the general public while still appealing to those who played JRPG’s back in the ‘90s.

EDIT II: Wow. Every almost answer here contained a wealth of information, and I'd like to formally thank all that contributed. I will be using the information from just about all of these answers, and I'm sure may others facing this issue may as well.

EDIT III: If you have comments that aren’t answers or you’d like to further discuss this, please refer to the official chat room as opposed to commenting. Thanks!


texts: (Unity) How to show a texture on a model at a specific Pixels Per Unit?

texts:
I'd like to use flat 3D models alongside pixel art sprites, but I have no idea how to make the textures applied to these models have the same Pixels Per Units as the sprites.

How can I achieve this effect in Unity?
thank you


texts:
Update 2 (see below)
I'm writing a turn-based game. During setup phase time scale modifier equals to 0, what prevents running of any physics-based code and FixedUpdates. User have freezed action and may make decisions.
The problem is that sometimes I cannot select objects during the setup mode. I'm doing selection in the following way:

I obtain mouse position ray
I run RaycastAll against this ray without limitations
I check for hit objects, which has Selectable script on them. Then rest of the logic happens.

Mouse handling looks like following:
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

(...)

RaycastHit[] hits = Physics.RaycastAll(ray);

// DEBUG
string debug = "Raycast all gave " + hits.Length + " hits:";
for (int i = 0; i < hits.Length; i++)
    debug += hits[i].collider.gameObject.name + "; ";
Debug.Log(debug);
// END DEBUG

Sometimes though I'm not getting valid results from RaycastAll. Take a look at the following example:

I clicked top-left blue ship. You may see a small sphere on it - I wrote a debug code, which generates a series of spheres along the ray to make sure, that it is valid. Since you see only one sphere here, it seems like everything's OK (note that I added this code to diagnose the problem. Spheres surely aren't causing it)
The scene view looks like following:

It should be clear on this image, that ray hits the ship's box collider. In this specific case, a couple of units next to ship is an explosion, which has bigger sphere collider.

You can also see debug log from the session, which clearly says, that RaycastAll only hit explosion and it missed the ship, which is just next to it.
Now the question is: why RaycastAll doesn't return the ship along with the explosion?
Note, that this problem happens more often and without near objects with colliders, sometimes I just cannot select a ship and all I have to do is to move camera, such that object is closer to center of the screen.

Edit: Now this gets interesting!
I added some debugging. After the RaycastAll, I manually go over all colliders in the scene and verify the raycast. The code now looks like following:
        RaycastHit[] hits = Physics.RaycastAll(ray);

        // DEBUG
        string debug = "Raycast all gave " + hits.Length + " hits:";
        for (int i = 0; i < hits.Length; i++)
            debug += hits[i].collider.gameObject.name + "; ";
        Debug.Log(debug);

        var colliders = GameObject.FindObjectsOfType<Collider>();
        foreach (var collider in colliders)
        {
            RaycastHit temp;
            if (collider.Raycast(ray, out temp, float.PositiveInfinity))
            {
                Debug.Log("Manually verified, that ray hits " + collider.gameObject.name);
            }
        }

        // END DEBUG

And when I try to click the "un-raycastable" object, I get:
Raycast all gave 1 hits:MissileExplosion(Clone);
Manually verified, that ray hits MissileExplosion(Clone)
Manually verified, that ray hits Falcon(Clone)

A bug in Unity engine?

Edit: Yup, a bug in Unity engine.

Hey,
We have been able to reproduce this bug and have sent it for resolution with our developers.
Regards,
Unity QA


texts: How do you lock the camera down in ZBrush?

texts: I'm trying to sculpt a tileable mesh on a flatplane and I keep inadvertently moving the camera when I go off canvas. Is there a way to lock the camera in place?


texts: An algorithm to make one object follow another on a 2D grid

texts:
I am using Greenfoot, but this can apply to pretty much any 2D engine.

So my question is a basic one that I somehow couldn't find an answer to already. Basically, if I have an enemy and the player, how can I make the enemy follow them? The player can move in all 4 directions, and the enemy can move in any direction, whichever one is faster. It would be done using a method that accepts an integer for speed, and an in-game object to move towards (an Actor in Greenfoot). It shouldn't simply teleport there but move closer by however much the value for speed is. And this would have to be done without rotating the image of the enemy.

This is in Java but if the answer you provide is in pseudo-code or a similar language (such as c++ or c#) I can still use it.


texts: To canvas, or not to canvas, when building browser-based games?

texts:
Background: I have extensive development background, but the last time I coded a game was many years ago. My Javascript skills are quite limited, and I intend to improve them by building a simple game — Tetris, Pac-man, or something of that complexity level.

Question: It seems to me that a fundamental choice I need to make is whether I should render on a <canvas> element or not.

With a canvas, I have basic tools for rendering points, lines, and more complex things on top of that. Presumably there are, or will be, also various frameworks to help with this.

Without a canvas, I could keep my objects in the DOM-tree, like a regular webpage, only quite complex, with many overlapping elements.

Is one approach better than the other? Are they mutually exclusive? How do I know which to pick?


texts:
I have the following code.

void Update () {

        if (Input.GetAxis("Vertical")!=0)
        {
            GetComponent<Rigidbody2D>().AddForce(-transform.right);
        }

        if(Input.GetAxis("Horizontal")>0)
        {
            GetComponent<Rigidbody2D>().transform.Rotate(Vector3.forward * rotationSpeed);
        }

        if (Input.GetAxis("Horizontal") < 0)
        {
            GetComponent<Rigidbody2D>().transform.Rotate(Vector3.forward * rotationSpeed*-1);
        }
    }

This obviously moves my sprite in an asteroids fashion. What I really want is the sprite to track the direction it is facing (ie like a car) so as you rotate the sprite it continues its movement in the direction it is facing rather than the initial direction the force was applied.


texts: How to write a good functional spec for a game?

texts:
I am basically (shamelessly) copying a question that has appeared on SO few years ago. The answers are good, but I would like to get more on this topic, so I'm trying a more specialized subreddit substackexchange. What I'm secretly hoping for is an answer from Byte56, I wonder if he has wrote a spec for AoG? :)

I'm trying to write a functional spec for a game according to Joel's article series (who wouldn't love anything this genius guy writes) and I'm not happy with my current approach. It's much easier to write a functional spec for a web application, or a website (my full-time job is still web app development) where I can describe every possible screen in a separate chapter, and also scenarios are easier to come up with.

The game is a turn-based logic/puzzle game, but it's fast and fun enough to play for many audiences, so:

Should I write scenarios based on various gamer types (e.g. nervous FPS players, macro-obsessed strategy guys, solitaire loving housewives, etc.) and try to describe what will they expect from the game and how will they use it?
What should represent "screens" in the spec; the game screens (e.g. menu, loading screen, main game screen, etc.) or should I rather describe all different possible in-game situations as screens (e.g. my turn, waiting for opponent's turn, possible turns, what happens if I make a invalid move, etc.)?

Just writing this question helped me to settle my thoughts about the spec, but I'm submitting it to see if I can get any good answers from this great community.


texts:
In my game, the server generates a procedural map, after send generation seed to generate it on the client. The client generates exactly the same map. In the map, I need to synchronize objects with NetworkIdentity. Therefore, after the map is generated on clients, the server will spawn all map's objects with NetworkIdentity on the client using NetworkServer.Spawn on server. In theory, it sounds normal, but in practice, objects on the server that have a NetworkIdentity component can not be obtained with GetChild from the object of the generated map. Unity do not see them. This probably means that they are not active on the server. How to fix it? And if it will fix, will the objects with NetworkIdentity be spawned on the client as children of the map? If this is not possible, is it possible to use something other than the UNET?

That's what I did:

On start server:

public static short index = 0;
public const int getGenIndex = 99; // OnGetGen
public const int spawnGenIndex = 100; // OnSpawnGeneration
public const int spawnObjIndex = 101; // OnSpawnNetworkObjects

private void Start() {
    if (isServer)
        NetworkServer.SpawnObjects();
    if (isServer) {
        GenerationInfo generation = InitScane.instance.GetGeneration(InitScane.rnd.Next()); // generate map
        InitScane.instance.seedToSpawn = InitScane.rnd.Next();
        GenerationManager.SpawnGeneration(RoomLoader.loadedRooms, generation, InitScane.instance.seedToSpawn, true); // spawn map on server with objects
        NetworkServer.SendToAll(spawnGenIndex,new StringMessage(GenerationManager.currentGeneration.Seed + "," + InitScane.instance.seedToSpawn)); // send message for spawn on client
    }
    else
        NetworkManager.singleton.client.Send(getGenIndex, new EmptyMessage()); // the client requests the seed to generate the map
}

public void OnGetGen(NetworkMessage msg){
    msg.conn.Send(spawnGenIndex,new StringMessage(GenerationManager.currentGeneration.Seed + "," + InitScane.instance.seedToSpawn));
}

public void OnSpawnGeneration(NetworkMessage msg) {
    string[] data = msg.ReadMessage<StringMessage>().value.Split(',');
    GenerationInfo generation = InitScane.instance.GetGeneration(int.Parse(data[0])); // generate map
    GenerationManager.SpawnGeneration(RoomLoader.loadedRooms, generation, int.Parse(data[1]), false); // spawn map without objects with NetworkIdentity
    msg.conn.Send(spawnObjIndex, new EmptyMessage()); // send request for spawn objects with NetworkIdentity and spawn player
}

public void OnSpawnNetworkObjects(NetworkMessage msg) {
    GenerationManager.SendAllObjectsToClients();
    GameObject player = Instantiate(InitScane.instance.LocalPlayer);
    GenerationManager.TeleportPlayerToStart(player);
    NetworkServer.AddPlayerForConnection(msg.conn, player, index);
    index++;
}

All network message I register in Awake on client and server. This is how I spawn objects for clients:

public static GenerationInfo currentGeneration;
    private static GameObject[,] spawnedRooms; // the map consists of many rooms that are separate GameObjects

    public static void SendAllObjectsToClients() {
        for(int x = 0; x < currentGeneration.size.x; x++)
            for(int y = 0; y < currentGeneration.size.y; y++)
                SendObjects(spawnedRooms[x, y]);
    }

    public static void SendObjects(GameObject roomObject) {
        Transform objectParent = roomObject.transform.Find("Objects"); // all room objects are stored in the parent "Objects"
        for (int i = 0; i < objectParent.childCount; i++)
            if (objectParent.GetChild(i).GetComponent<NetworkIdentity>() != null)
                NetworkServer.Spawn(objectParent.GetChild(i).gameObject);
    }

The latter method does not find objects with NetworkIdentity, although they are spawned in the editor. If you put them to the array when spawning, they will turn into null


texts: XNA 2D Spritesheet drawing rendering problem

texts:
I'm making a tile-based game, using one spritesheet containing all tile graphics.

Each tile has a size of 32x32 pixels.

The main problem is: when I draw the tile to the screen, if the tile position x and y are not rounded or if scale is activated in spriteBatch.Draw() method (scale != 1.0f), I get some lines of adjacent tiles on the spritesheet into the current tile drawed.

I already tried setting SamplerState to PointClamp, removing AntiAlias, but still doesn't work.

Here I'll show images of some tests that I made, with a test sprite sheet that I've created (I made a 9x9 spritesheet, with each sprite of size 32x32 containing a unique solid color).

Tests:

SpriteSheet used:

Already tried to remove anti-alias, set PointClamp as sampler state, but still getting this issue, XNA keeps drawing part of the adjacent pixels of the texture on the screen.

What I want is to get the correct area of the tilesheet texture (as seen in the first test, that gets just the yellow pixels).

My question is: Is there any way that I can fix this, WITHOUT adding tile spacing or any other modification involving the tilesheet?

Maybe disabling a texture filtering that is done by XNA, or something like that.


texts: Ray picking - get direction from pitch and yaw

texts:
I am attempting to cast a ray from the center of the screen and check for collisions with objects.

When rendering, I use these calls to set up the camera:

GL11.glRotated(mPitch, 1, 0, 0);
GL11.glRotated(mYaw, 0, 1, 0);
GL11.glTranslated(mPositionX, mPositionY, mPositionZ);

I am having trouble creating the ray, however. This is the code I have so far:

ray.origin = new Vector(mPositionX, mPositionY, mPositionZ);
ray.direction = new Vector(?, ?, ?);

My question is: what should I put in the question mark spots? I.e. how can I create the ray direction from the pitch and roll?

Any help would be much appreciated!


texts:
I'm working on a game engine using the Entity System and I have some questions.

How I see Entity System :

Components : A class with attributs, set and get.

Sprite
Physicbody
SpaceShip
...

System : A class with a list of components. (Component logic)

EntityManager
Renderer
Input
Camera
...

Entity : Just a empty class with a list of components.

What I've done :

Currently, I've got a program who allow me to do that :

// Create a new entity/
Entity* entity = game.createEntity();

// Add some components.
entity->addComponent( new TransformableComponent() )
            ->setPosition( 15, 50 )
            ->setRotation( 90 )
        ->addComponent( new PhysicComponent() )
            ->setMass( 70 )
        ->addComponent( new SpriteComponent() )
            ->setTexture( "name.png" )
            ->addToSystem( new RendererSystem() );

My questions

Did the system stock a list of components or a list of entities ?
In the case where I stock a list of entities, I need to get the component of this entities on each frame, that's probably heavy isn't it ?
Did the system stock a list of components or a list of entities ?
In the case where I stock a list of entities, I need to get the component of this entities on each frame, that's probably heavy isn't it ?


texts: Really simple video games, how to design games for the non-gamer market?

texts:
With the boom of mobile and social games reaching more and more people and new technologies like the wii, kinect and geolocation hardware and gadgets appealing to a bigger market than the hardcore gamer, the indie game development has a new challenge: create simple games.

This might seem easier, but I think its really way harder. Game developers are usually fans of RPGs, FPSs, massively complicated games with complicated goals, mechanics and stories. That is not what the usual casual player is looking for, and getting into the mind of a unknown market is really hard.

So, how to design games for the casual, non gamer market?

I know its a very broad question, but I would love to know how people design, playtest and deliver this sort of games.

A very big point for me is that somethings while trying this exercise of designing simple games I get a feeling that it is TOO simple or even non challenging when it might be complicated and challenging enough for that market.


texts: What shapes interlock solidly like cubes?

texts:
What basic geometric shapes, besides cubes, interlock "minecraft" style like cubes?

A small edit to make question more suited to Game Dev:

I am experimenting with game dynamics to create geometric solids interlock seamlessly on their faces much the way the cubes do in minecraft. The objective is to create an interlock system that is also memory efficient consistent enough to maintain interlock over the course of many connections without deviating from the main grid.


texts: Models from 3ds max lose their transformations when input into XNA

texts:
I am making models in 3ds max. However when I export them to .fbx format and then input them into XNA, they lose their scaling. It is most likely something to do with not using the transforms from the model correctly.

Is the following code correct using XNA 3.0?

Matrix[] transforms = new Matrix[playerModel.Bones.Count];
playerModel.CopyAbsoluteBoneTransformsTo(transforms);

// Draw the model.
foreach (ModelMesh mesh in playerModel.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
        effect.World =
            transforms[mesh.ParentBone.Index] *
            Matrix.CreateScale(Vector3.One*20) *
            Matrix.CreateTranslation(position);

        effect.View = view;
        effect.Projection = projection;
    }
    mesh.Draw();
}

It also seems to work if I export it in .obj format, which is probably vertex only format, then import it back into 3ds max and then export it to .fbx for XNA.

Here's an image reference in case you don't understand what I am saying. The left is in XNA and the right in 3ds max.


texts:
I want to load a texture when I need it, so I'd need a method in order to do so.

      LoadTexture(string fileName)

I'd only use that one parameter, but what would I put in the method? So far I've only ever loaded content at startup with something like

    content.Load<Texture2D>("blah");

But I want to move away from loading everything at startup and only load content when I need it.

EDIT: In order to explain what I'm going for, I'll give more detail. Say I have a chunk of blocks 50x50x50. Most of these won't be drawn, so it doesn't make sense to load the texture for the cubes not drawn. This is why I want a method that I can call whenever the  texture needs to be loaded for the cube. Instead of loading 6 textures for 6 sides for 125,000 cubes, I cut back the amount of loading to only the visible cubes.


texts: Box2D Body creation causing performance issues

texts:
I have at max 10 dynamic bodies in my world at any time. they are created at random and fired up from below they screen. when a new body is being created, the fps falls from 59 - 61 to about 35- 40 and then jumps back up again straight away which obviously causes the other dynamic bodies that are moving about the screen to stick for a split second. i am creating the bodies like below...

private void addBadger(){
    badgerCount++;
    //dimensions
        //pix
            float badgerWidthPix = RandomNum.randFloat(screenWidth/16f, screenWidth/16f);
            float badgerHeightPix = badgerWidthPix;
        //meters
            float badgerWidthMet = badgerWidthPix*pix2met;
            float badgerHeightMet = badgerHeightPix*pix2met;
    //position
        //pix
            float badgerXPosPix = RandomNum.randFloat(0, screenWidth-badgerWidthPix);
            float badgerYPosPix = -badgerHeightPix;
        //met
            float badgerXPosMet = badgerXPosPix*pix2met;
            float badgerYPosMet = badgerYPosPix*pix2met;
    //Image
        Badger badger = new Badger(badgerAliveTexture, badgerShotTexture, badgerXPosPix, badgerYPosPix, badgerWidthPix, badgerHeightPix, String.valueOf(badgerCount), manager, tweenManager, this, screenWidth, screenHeight);
        badgerArray.add(badger);
        badgerGroup.addActor(badger);
    //body
        //get object from json
            jsonBodyLoader = new BodyEditorLoader(Gdx.files.internal("json_objects/badger.json"));
        //define body
            bodyDef = null;
            bodyDef = new BodyDef();
            bodyDef.position.set(badgerXPosMet, badgerYPosMet);
            bodyDef.gravityScale = 1;
            bodyDef.fixedRotation = false;
            bodyDef.type = BodyType.DynamicBody;
        //set velocities
            float xVel = RandomNum.randFloatPossNeg(0.25f, 1f);
            float yVel = RandomNum.randFloat(11.5f, 14f);
            float rotation = RandomNum.randFloat(1, 5);
            if(xVel < 0){ rotation = -rotation; }
            bodyDef.linearVelocity.x = xVel;
            bodyDef.linearVelocity.y = yVel;
            bodyDef.angularVelocity = rotation;
        //define fixture
            fixtureDef = null;
            fixtureDef = new FixtureDef();
            fixtureDef.density = 2;
            fixtureDef.friction = 0.5f;
            fixtureDef.restitution = 0.25f;
            fixtureDef.filter.categoryBits = CollisionCategories.BADGER;
            fixtureDef.filter.maskBits = CollisionCategories.BADGER;
        //create body
            Body badgerBody = world.createBody(bodyDef);
            badgerBody.setUserData(badger);
        //attach fixture
            jsonBodyLoader.attachFixture(badgerBody, "Badger", fixtureDef, badgerWidthMet, 1, 1);
        //set body to image
            badger.body = badgerBody;

//call new badger
    //get interval
        badgerCreationInterval = (RandomNum.randFloat(minAddBadgerDelay, maxAddBadgerDelay));

the filtering I am using on the Images is mipmap.LinearNearest, Nearest


texts: What does the number in TextMesh.lineSpacing refer to?

texts:
I have a TextMesh with some text, and mutliple lines.

The 4 examples have these settings:

lineSpacing = 220, characterSize = 10
lineSpacing = 220, characterSize = 25
lineSpacing = 220, characterSize = 30
lineSpacing = 110, characterSize = 25

I don't understand what the lineSpacing number signifies. It's not pixels. As the relative spacing between lines stays the same with different character sizes, it doesn't seem to be proportional to characterSize either.


texts:
I've implemented basic 3D functionality and made little "2.5D" demo in orthographic projection using OpenGL ES 2 and Box2D.

Now I want to make completely two-dimensional game (using sprites) and consider 2 variants:

Implement 2D graphics separately from 3D in separate layer, leave 3D stuff in background, draw 2D using various simplified algorithms (disable depth testing, simplified culling etc.)
Leave everything as is and use billboards for sprites

Currently I use hierarchical system of entities with matrix transformations. I know about computational complexity of 3D and 2D graphics and believe first method should result in faster code, though it's my first engine and my google-fu fails me this time, so I'm not sure about it.

Engine is Desktop/Mobile.

What method would you recommend? Does implementing first method worth it (in performance aspect)?


texts: What is a quaternion, and do how they work? Also, what advantages do you gain using three points on a 2D plane? Finally, when is it considered good practice to use quaternions?


texts: Decreasing distance for a Configurable Joint at run-time | Unity

texts:
I have written a script that uses ConfigurableJoint to connect a ball to a hing so that it moves in a fixed circular path around the hinge. The problem is that I want to decrease the distance between hinge and ball with time. In other words, I wamt to reduce the radius of circular path on which the ball is moving.

I have created a rough image to demonstrate what I'm trying to do

And below is the code that I am using to create the joint:

     joint = gameObject.AddComponent<ConfigurableJoint>();

     joint.anchor = transform.transform.InverseTransformPoint(closestHinge.position);

     joint.xMotion = ConfigurableJointMotion.Locked;
     joint.yMotion = ConfigurableJointMotion.Limited;
     joint.zMotion = ConfigurableJointMotion.Locked;


texts: Target a specific Entity in a Component-Entity design

texts:
I'm starting to work on a game with Entity-Component Model Architecture (Artemis in C#).
I'm beginning with something pretty simple, entities which are living things, with HealthComponent, PositionComponent, SpriteComponent, MoveComponent. I want them to be able to target other entities (for example other Living things or even other entities of the game (like say inerts objects)) for them to move to them and grab them or be able to do other actions with them.

I can find which entity they will target by going through the mechanic of searching through all entities having the good components (PositionComponent, TargetableComponent) but i don't see how I can store the information of the target except by saving somewhere the ID of the entity.

So I would have a TargetComponent which is basically the ID of an entity that has for exemple a PositionComponent

That does not seem right, does it?


texts: How to handle "game missions/flights" across the world map

texts:
Sorry if my title is a little vague, I wasn't entirely certain how to word this specific question.

I'm developing a small little MMORTS game, and in this game is the world map which consists of thousands of tiles (the view on the client is an isometric grid). The world map data is stored in a MySQL database table. This table stores each individual tile and the tile data. So when the player visits the world map screen, the server will load a chunk (12x12) of the world map at a time  for the client to render.

Now, it's come to the point where I need to allow players to send planes from their cities that are on the world map, to other tiles around the world map. For instance, a player that owns City 1, which is located on tile 100,100, wants to send a plane to an oil well on tile 60,60.

How can I show the movement of that plane from the city -> destination in real time across all clients in the most efficient manner? Let's assume each game server can have hundreds of players, so we can expect thousands of flights across the world map at a time.

When a flight is created, it would be stored in the database with data such as destination_x, destination_y, origin_x, origin_y, flight_speed.

And when a client loads a chunk of the world map at whatever coordinates, I can query the database on each chunk load to see if any flights are currently crossing this chunk. However, how can I do this? With the data I just mentioned that would be stored for a flight, how could I determine if a flight is currently in a given chunk? Let's assume a chunk is 12x12 tiles.

How should I go about doing this, and is my current thought-out method the most efficient approach to this problem?

~~~~~~~~~~~~

If context helps, here is a picture of the world map:

I would like for flights to show up across this world map as they are heading to a destination from a given origin. The plane should only load if it's crossing this viewed chunk by the client.

~~~~~~~~~~~

I apologize if this question is still too vague, I tried my best to explain my current situation and problem. If you have any questions, please ask. Thanks!


texts: Using Jump Flooding Alghorithm for pathfinding?

texts:
I am creating a distance-to-river texture. I am using the Jump-Flood Alghorithm in a compute shader to do this using simple distance() and it works well. See code below.
I want to augment this by adding blockers/walls so raw distance-to-seed might be blocked by pixels inbetween. I need to adapt it to a more pathfinding alghorithm.
Is this possible to do with JFA? Or do I need some other solution?
cbuffer JFAConstants : register( CBUFFER_REGISTER_EXTRA )
{
    int2 gSampleOffset;
}

RWTexture2D<uint2> gJumpFloodRiverMap : register( UAV_REGISTER_0 );

void UpdateClosest( inout int2 currentValue, int2 currentTexcoord, int2 jumpTexcoord )
{
    int2 jumpValue = gJumpFloodRiverMap[ jumpTexcoord ];
    if ( IsZero( jumpValue ) )
    {
        return;
    }

    float jumpDistance = distance( (float2)currentTexcoord, (float2)jumpValue );
    if ( IsZero( currentValue ) )
    {
        gJumpFloodRiverMap[ currentTexcoord ] = jumpValue;
        currentValue = jumpValue;
        return;
    }

    float currentDistance = distance( (float2)currentTexcoord, (float2)currentValue );
    if ( jumpDistance < currentDistance )
    {
        gJumpFloodRiverMap[ currentTexcoord ] = jumpValue;
        currentValue = jumpValue;
    }
}

[numthreads(TERRAIN_NORMAL_THREADS_AXIS, TERRAIN_NORMAL_THREADS_AXIS, 1)]
void cs_main(uint3 groupID : SV_GroupID, uint3 dispatchTID : SV_DispatchThreadID, uint3 groupTID : SV_GroupThreadID, uint groupIndex : SV_GroupIndex)
{
    int2 texCoord = dispatchTID.xy;
    int2 currentValue = gJumpFloodRiverMap[ texCoord ];

    int2 texCoordT = texCoord + int2( 0, gSampleOffset.y );
    int2 texCoordTR = texCoord + gSampleOffset;
    int2 texCoordR = texCoord + int2( gSampleOffset.x, 0 );
    int2 texCoordBR = texCoord + int2( gSampleOffset.x, -gSampleOffset.y );
    int2 texCoordB = texCoord + int2( 0, -gSampleOffset.y );
    int2 texCoordBL = texCoord - gSampleOffset;
    int2 texCoordL = texCoord + int2( -gSampleOffset.x, 0 );
    int2 texCoordTL = texCoord + int2( -gSampleOffset.x, gSampleOffset.y );

    UpdateClosest( currentValue, texCoord, texCoordT );
    UpdateClosest( currentValue, texCoord, texCoordTR );
    UpdateClosest( currentValue, texCoord, texCoordR );
    UpdateClosest( currentValue, texCoord, texCoordBR );
    UpdateClosest( currentValue, texCoord, texCoordB );
    UpdateClosest( currentValue, texCoord, texCoordBL );
    UpdateClosest( currentValue, texCoord, texCoordL );
    UpdateClosest( currentValue, texCoord, texCoordTL );
}


texts: How do I save files with libgdx so that users can't read them?

texts: Writing my game in libgdx, I arrived at the point when I need to save the player stats and the info of the levels. However, in libgdx it's not allowed to write the file inside folder of the application, only external (on the SD) is allowed. The point is that I don't want the file to be seen by anyone, or if they can see it, how can I convert it to a binary file so it's not human readable? I just want to hide the file.


texts: How can I obtain a triangle ID during rasterization?

texts: I want to know the triangle ID of each rendered pixel is coming from. Is there a way to do this in OpenGL?


texts: ECS as part of the rendering pipeline of an engine

texts:
I'm trying to integrate ECS design into my game engine.

Currently I'm trying to mimic the components of unity (although not pure ECS) with MeshFilter (holds Mesh object) and MeshRenderer (holds various attributes such as castShadows, receiveShadows etc..) components.

I also have MeshRenderer system which I defined such as that it gets all entities with MeshFilter and MeshRenderer components so it could basically render these meshes.

The logic of the MeshRenderer system would basically be:

iterate the entities
grab the Mesh from the MeshFilter
grab the Material from the Mesh
use relevant Textures and Shaders from the Material to draw the mesh

This is all fine but I wish to represent lights as entities as-well. I've made relevant components such as DirectionalLight, SpotLight etc.. that holds relevant information such as attenuation, color, shadow map (another object that holds RenderBuffer object of the shadow map) etc..

Now it seems to me that this MeshRenderer system should also take into account any entity with XXXLight components as-well since part of the rendering of an object is to also take into account any lights in the scene and also generate relevant shadows from/upon it.

Problem is that the system is defined to operate on entities with MeshFilter and MeshRenderer component and I'm not sure what to do. Should I make it so systems could operate on a list of entities with relevant components? Wouldn't it make the logic of the system's Update method a mess which entity is render-able mesh and which is light and then plug it all together?

I'm wondering what would be the best course of action here, what can I do?


texts: When/where should a game state transition take place?

texts:
I'm in the process of redesigning some of my state management code (there are several features I've grown to dislike in practice..) which was based on this tutorial and others. The issue I'm having right now has to do with state transitions.

Where and when should state transitions occur? Should they be executed immediately, or should they be delayed to the end of the current frame, after the current state has finished its work for that frame?

Let's say my states can implement handleEvents, update, render, pause and resume methods, among others that are not relevant for this question.

My thoughts so far are the following:

If the transition is done at the end of the frame, then when I pause the game I might see an update during that same frame I clicked to pause. The Pause State will only appear after the current state has executed the rest of the frame (events, update and render). Perhaps that extra update should not have been done.
If the transition is done immediately I have to be careful to not to delete the current state while it is still executing its method, let's assume the handleEvents method. But even so, if I were to pause a game in the handleEvents function, then the game would immediately pause and the game state update function would not be executed that frame.

The second options is more appealing to me, because as a player I would probably notice that extra bit of movement after pressing to pause the game. What if the player died during that frame? The delayed state change would be unwarranted. But then, the game state itself should probably disable updates if a game pause was requested.

On the other hand it might make more sense to delay state transitions to after the current state has fully executed its functions for the current frame. Maybe the Pause state should be a sub-state of the Game state and not a state of its own.

Is it simply a matter of preference or is one of the approaches clearly superior for a different reason?


texts:
I have a spherical clipmap based planet terrain. The entire planet is made from a ring geometry of 1 unit which the vertex shader moves to cover the entire planet of 6 million unit radius. But the planet gets culled whenever the starting point for this geometry isn't in the camera's view (which is 99.9999% of the planet).

What's the best solution for making sure the planet is viewable even when the original mesh isn't?

This is based on WebGL and Three.js.


texts:
I've read Valve + Gafferon and hundreds of pages from Google, but for whatever reason I can't get my head around client prediction.

To my understanding, the basic problem is:

Client A sends input at T0
Server receives input at T1
All clients receive the change at T2

At T2 however, using client prediction, Client A is now at a position appropriate to T4.

How do you ensure that the Client A, when predicting that the server will accept the movement request, won't be ahead of the server? Obviously all the time they are ahead, this results in snapping back to where the server last saw them. With all corrections I've tried, this is still noticeable when you stop, because the server stops behind you


texts: How to reduce the CPU usage during the state preservation phase in my MMO?

texts:
I'm writing small MMO using Boost library. I want to make it non-target game, but I'm having trouble saving the previous game state. I don't know how to implement the game world, NPCs', and players' states. Currently, I'm copying all my NPCs, players and map in main game cycle, but it consumes too much CPU usage, about 60-80%. Obviously it too much.

Example of code in my save game method:

void GameHistory::saveGame(game* g)
{
    if (player_history.size() == 64) {
        player_history.erase(player_history.begin());
    }
    if (map_history.size() == 64) {
        map_history.erase(map_history.begin());
    }
    if (npc_history.size() == 64) {
        npc_history.erase(npc_history.begin());
    }
    long long t = lib::GET_SERVER_TIME();
    players_obj_hash players;
    game::players_hash::iterator itp = g->__players_by_id__.begin();
    game::players_hash::iterator endp = g->__players_by_id__.end();
    for (; itp != endp; itp++) {
        players[itp->second->getId()] = (*itp->second);
    }
    player_history[t] = players;
    map_history[t] = g->map;

    npcs_obj_hash npcs;
    game::npc_hash::iterator it = g->npcs_by_id.begin();
    game::npc_hash::iterator end = g->npcs_by_id.end();
    for (; it != end; it++) {
        npcs[it->second->getId()] = (*it->second);
    }
    npc_history[t] = npcs;
}

I'm using map as grid, where every NPC or player "register" on which cell it's on for fast lookup of nearest entities.

Maybe there is another more light approach to save the game state?


texts:
I'm into shader language with Webgl and GLSL.
I've seen some tutorial about normal matrix and I don't really understand it.
I mean, I think I'm ok with the math such as:

modelViewMatrix = mat4.multiply(camera.view, modelMatrix);
inverseModelViewMatrix = mat4.invert(this.modelViewMatrix);
normalMatrix = mat3.fromMat4(inverseModelViewMatrix);
normalMatrix = mat3.transpose(this.normalMatrix);

But why do I need it? Where can I find a case where I can see the difference between using it and not using it? Ot when do I don't need it?


texts: The cube does not rotate with Vuforia virtual button in Unity3d

texts:
I added the cube on the image target of Vuforia. I also added the Vuforia virtual button on the image target. Now I want to rotate the cube by pressing virtual button. For this purpose I implemented the following script.

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

public class rotate : MonoBehaviour, IVirtualButtonEventHandler {

    public GameObject vbtn;
    public GameObject cube;
    public Renderer rend;

    // Use this for initialization
    void Start () {

        vbtn = GameObject.Find ("virtualbtn5");
        vbtn.GetComponent<VirtualButtonBehaviour> ().RegisterEventHandler (this);
        cube = GameObject.Find ("Cube");
        rend = cube.GetComponent<Renderer>();
    }

    public void OnButtonPressed(VirtualButtonBehaviour vb){

        Debug.Log ("Button pressed");
        cube.transform.Rotate (new Vector3(0,Time.deltaTime*1000,0));
        rend.material.color = Color.blue;

    }

    public void OnButtonReleased(VirtualButtonBehaviour vb){

        Debug.Log ("Button released");
        rend.material.color = Color.red;
    }

}

The button seems to be working because the Debug.Log ("Button pressed"); and rend.material.color = Color.blue; statements in onButtonPressed function are working fine. But cube.transform.Rotate (new Vector3(0,Time.deltaTime*1000,0)); for rotating cube does not work.

Simple is that the button can change the color of the cube but it does not rotate the cube.


texts: How can I efficiently load huge volumes of star systems?

texts:
I am working on a space exploration and combat game, and I can create galaxies, nebulas, solar systems, and load and unload them procedurally as needed. Meaning the stars that the player can see are exactly where they are. I have a coordinate system set up with meter-precision, meaning it's sufficient to map quite several galaxies, but also tiny missiles.
For now, I created a galaxy with 10.000.000 solar systems, and my SQLite database reached 5gb. It takes ~30 minutes to generate it, and I notice a slow-down as the size of the database increases in loading times. I did a lot of optimization, and while everything is running fine and well now, I seek to reach 200-300m solar systems if possible. The database would be stored locally on the user's drive, rather than downloaded from a server. I use a GlobalX/Y/Z (int64) and LocalX/Y/Z (double) for coordinates, and only the GlobalX/Y/Z is used to find large objects like stars and planets (I also use multiple chunk systems).
Elite Dangerous manages to store the data of 400 billion solar systems and has no issues with loading times, somehow. How can they display many stars in the background? How do they manage to store a lot more data than I already do?
For now, my data is quite minimalistic and comparatively minuscule in number, but they must have quite a lot of data for each stellar object even. What technical "tricks" can I employ to solve this problem in my game?


texts: How detailed and/or complete is/are your game design documents before starting a project?

texts:
What I'm wondering is how complete your design documents typically are before beginning the implementation of a project? I'm talking about medium to very small projects with a very small team here where even fully fleshed out the entire document may only be a few dozen pages.

Do you start with a rough framework and start fleshing out the details at the same time implementation is starting?

Do you completely flesh out every section completely before any implementation is even started? If so, what percentage change have you seen after implementation starts?

If you have experience with one of the two scenarios I outlined, I'd love to hear your opinion on what issues going that particular route caused and what obstacles you feel it helped you avoid.


texts:
Im working on a ledge climbing system in Unity. I am coding a method that takes a mesh and tries to generate a bunch of connected nodes that will help the player detect ledges that can be climbed.

This is what I have made so far:

The thing I need to do now is to remove connections that are not ledges (sorry if that doesn't explain much). This is the desired result:

So, basically, I need to convert those Tris to Polygons. I have no idea of how to do this. Each node stores its position, its normal, and what nodes it is connected to.

Thank you for reading!


texts: How can I keep two racing players synchronised?

texts:
I am working on a Unity mobile game, much like a multiplayer version of Temple Run. I'm seeing a fluctuating network latency (generally 200-500ms) because of the mobile platform.

The two player characters are shown as running along the same path and must do simple actions (jump, slide, powerup, etc.) to pass obstacles.

When a message comes late, the game assumes the remote player passed an obstacle. This usually works well, but in case a player is killed by an obstacle, I want the remote player to appear to die on the same obstacle/position as local player. Due to latency, the remote player appears to have crossed the obstacle before the message announcing their death even arrives.

How can I keep the players synchronised?

I tried moving the remote player back to the local players death position immediately as the death message arrives, it looks awkward visually and might raise other syncing issues.


texts: multi user web game with scheduled processing?

texts:
I have an idea for a game which I am in the process of designing, but I am struggling to establish if the way I plan to implement it is possible.

The game is a text based sports management simulation. This will require players to take certain actions through a web browser which will interact with a database - adding/updating and selecting. Most of the code required to be executed at this point will be fairly straightforward.

The main processing will take place by applications which are scheduled to run on the server at certain times. These apps will process transactions added by the players and also perform some automatic processing based on the game date.

My plan was to use an SQL server database (at last count I require about 20 tables) and VB.net for all the coding (coming from a mainframe programming background this language is the simplist for me to get to grips with). I will also need a scheduling tool on the server.

Can anyone tell me if what I am planning is feasible before I dive into the actual coding stage of my project?


texts: How often should multiplayer games communicate with the server?

texts:
I once heard that Runescape "ticks" every 0.3s, and that seemed like a very long period of time, although Runescape is kind of a slow game.

I'm building a more dynamic top-down shooter game, and I'm wandering, how often should I communicate with the server? ASAP, or every 0.1s? How do shooter games usually do it?

Both the server and the client are written in Javascript, node.js and socket.io are being used.


texts: HTML canvas, Node WebSocket and multiplayer game like slither.io. How to send visual data over websockets?

texts:
Where to start creating a multiplayer game like slither.io, agar.io, etc.

I need only learn how to draw live positions and other data of all players into one fullscreen HTML5 canvas with update frequency +/-100ms.

I already have websocket server but that is only chat. I dont know sending images of players and positions. My first idea is sending every 100ms array of all players positions, current position on the map and all other data of players.

var worldSize = [10000,10000]; //width and height in px
var currentPosition = [5000,5000]; //center on the map
var players = new Array();
//on player join
players.push({
    id: 1,
    name: "test",
    position: [1234,850], //random position on the map
    points: 100 //example points
});

//on player eat point find that player, update players[index].points+1 etc.

This is only my (bad) idea and I not tested it because I dont know how start, how to send visual game data via websockets. How?

Update

I checked slither.io game WebSocket console and all frames is Binary Frame (Opcode 2) and Binary Frame (Opcode 2, mask). This is short version of array of all players and their positions and all other data? Or?

For example if game play 1000 peoples, that array will be too long. This will lag browser?


texts:
Possible Duplicate:
  XNA Tile from Screen Location

I have a tile based game that is in a semi-isometric view created by a transformation. The tiles are created by a Texture2d rendered on a 3d surface.

My map Image: http://balancedcms.com/Capture.PNG

I am using the following code for my transformation:

View = Matrix.CreateLookAt(new Vector3(0, -1.1f, 1.6f), new Vector3(0, 0, 0), new Vector3(0, 53, 0));
Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.Pi - 2.4f, 4.0f / 3.0f, 1, 500);

quadEffect = new BasicEffect(device);

quadEffect.World = Matrix.Identity;
quadEffect.View = View;
quadEffect.Projection = Projection;
quadEffect.TextureEnabled = true;

quad = new Quad(new Vector3(0, 0, 0), Vector3.Backward, Vector3.Up, 3, 3);

My problem comes along when I attempt to get the current tile that I am hovering the mouse over. I have a mouse X and Y however I can't seem to figure out how to transform these screen coordinates into a tile X and Y. The tiles are 128px by 128px; however, after the camera transformation they are smaller on the top and larger on the bottom(to create the isometric view)

I've tried transforming the mouse X and Y with the same projection matrix. However, this didn't work. I think it is due to the view matrix not being taken into account... sample below:

Vector3.Transform(new Vector3(Mouse.GetState().X, Mouse.GetState().Y, 0), Projection);

This image may provide more information... is also shows the hours I've put into figuring this out: http://balancedcms.com/1111.png


texts:
I'm starting to learn C++ (I have a very basic programming background) and I have in mind to create an old-school ASCII-looking roguelike. I know it may be easier in Python, but it has to be in C++. I'm using Windows 10.

I want some eye candy beyond basic ASCII, I've seen libtcod 1.5.1 offers a lot of possibilities so I wanted to try it and follow this tutorial. The problem is I'm stuck right at the beginning, because the libtcod demo "samples_cpp.exe" works but not the example code:

#include "libtcod.hpp"

int main()
{
   TCODConsole::initRoot(80, 50, "libtcod C++ tutorial", false);
   while ( !TCODConsole::isWindowClosed() )
   {
       TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS, NULL, NULL);
       TCODConsole::root->clear();
       TCODConsole::root->putChar(40, 25, '@');
       TCODConsole::flush();
   }

   return 0;
}

If I launch the .exe compiled with the command:

g++ src/*.cpp -o tuto -Iinclude -Llib -ltcod-mingw -static-libgcc -static-libstdc++ -Wall

by double-click, it opens and closes a window very fast, and if I execute it from the console I get the in-console message:

24 bits font.
key color : 0 0 0
character for ascii code 255 is colored

Any clues of what I'm doing wrong? The project has all the proper .dll and include folder. This should be pretty easy :/

Thanks a million!

UPDATE:
Ok, I got some new info, gdb says this:

[New Thread 7468.0x1f24]
[New Thread 7468.0x203c]
[New Thread 7468.0x1bdc]
[New Thread 7468.0x190c]
[New Thread 7468.0x108c]
24 bits font.
key color : 0 0 0
character for ascii code 255 is colored
Using SDL renderer...

Program received signal SIGSEGV, Segmentation fault.
0x65e70d9f in TCODConsole::clear (this=0x1) at src/console.cpp:196
196     src/console.cpp: No such file or directory.

Not sure what that means, the console.cpp file of libtcode at line 196 has the following:

void TCODConsole::clear() {
    TCOD_console_clear(data);
}


texts: Doing object movement in a loop in unity

texts:
I have a Game Object at position (0, 0, 0). To move it to position (2, 2, 2), I'm using this code below -

void Update () {

Vector3 TargetPosition = new Vector3(2, 2, 2);

transform.position = Vector3.MoveTowards(transform.position,TargetPosition,

23 * Time.deltaTime);

}

How do I put this movement in a loop like behavior so that whenever the Game Object reaches position (2, 2, 2), it again starts moving from (0, 0, 0) to (2, 2, 2) ?


texts: How do I create a third Person View using DXUTCamera in DX10?

texts:
I am creating a 3d flying game and using DXUTCamera for my view.

I can get the camera to take on the characters position, But I would like to view my character in the 3rd person.

Here is my code for first person view:

    //Put the camera on the object.

    D3DXVECTOR3 viewerPos;
    D3DXVECTOR3 lookAtThis;
    D3DXVECTOR3 up         ( 5.0f, 1.0f, 0.0f );
    D3DXVECTOR3 newUp;
    D3DXMATRIX matView;

    //Set the viewer's position to the position of the thing.

    viewerPos.x = character->x;   viewerPos.y = character->y;
    viewerPos.z = character->z;

    // Create a new vector for the direction for the viewer to look

    character->setUpWorldMatrix();
    D3DXVECTOR3 newDir, lookAtPoint;
    D3DXVec3TransformCoord(&newDir, &character->initVecDir,
                                  &character->matAllRotations);

    // set lookatpoint

    D3DXVec3Normalize(&lookAtPoint, &newDir);
    lookAtPoint.x += viewerPos.x;
    lookAtPoint.y += viewerPos.y;
    lookAtPoint.z += viewerPos.z;

    g_Camera.SetViewParams(&viewerPos, &lookAtPoint);

So does anyone have an ideas how I can move the camera to the third person view? preferably timed so there is a smooth action in the camera movement. (I'm hoping I can just edit this code instead of bringing in another camera class)


texts: How to deal with collision in a networked game?

texts:
In my game, my own character is extrapolated with client side prediction for smooth input response and all the other objects are interpolated. So Let's say I was at (20, 10) according to server and a bullet hits me at that position. But my client displayed rendered myself at predicted position (23, 10), which leads to a discrepancy - I got hit by the bullet even though it looked like I wasn't hit.
How can I deal with this problem?


texts:
I'm going through a book, and the example it gave me seems like is should work, but when I try and implement it, it falls short.

My Camera class takes three vectors in to generate View and Projection matrices.
I'm giving it a position vector of (0,0,5), a target vector of Vector.Zero and a top vector (which way is up) of Vector.Up.

My Three vertices are placed at (0,1,0), (-1,-1,0), (1,-1,0).

It seems like it should work because the vertices are centered around the origin, and thats where I'm telling the camera to look but when I run the game, the only way to get the camera to see the vertices is to set its position to (0,0,-5) and even then the triangle is skewed. Not sure what's wrong here.

Any suggestions would be helpful.

Just to make sure I've given you guys everything (I don't think these are important as the problem seems to be related to the coordinates, not the ability of the game to draw them):
I'm using a VertexBuffer and a BasicEffect.

My render code is as follows:

effect.World = Matrix.Identity;
effect.View = camera.view;
effect.Projection = camera.projection;
effect.VertexColorEnabled = true;

foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                {
    pass.Apply();

    GraphicsDevice.DrawUserPrimitives<VertexPositionColor>
         (PrimitiveType.TriangleStrip, verts, 0, 1);
}


texts: Unity3D | Cost of accessing a script via a static reference to the instance

texts:
I saw this pattern around and I was wondering what would be the pros and cons about it. Does this suffer performance issues ? If so what would be a better alternative?

using UnityEngine;
using System.Collections;

public class SomeClass : MonoBehaviour
{

    public static SomeClass instance;

    void Awake ()
    {
        instance = this;
    }

}

And in an other script use it like so:

SomeClass.instance.SomeMethod();


texts: How to prevent intepolated texture in fragment shader (Unity CG)

texts:
Think about minecraft - all the textures in minecraft have a very nice crisp pixelated look.  Well, I'm trying to write a shader that will do this but it appears "sampler2d" returns some sort of interpolation between pixels of the underlying texture.  I'm pretty new to shader writing and I'm not even sure if it can be done - but I'm hoping to get a nice crisp blow up of small textures rather than a blurry one like this:

If anyone knows a way to make a shader crisp rather than interpolated like this (using Unity), I'd be thrilled to know as this hitch is pretty detrimental to what I'm trying to accomplish...

Here's the subshader as it is right now (it's skipping all the light calculations and just outputting the sampler as I'm just trying to resolve the blurry texture sampling):

SubShader
{
    Pass
    {
        Tags { "LightMode" = "ForwardBase" }
        CGPROGRAM
        #pragma vertex vert
        #pragma fragment frag

        //user
        uniform float _BlendVal;
        uniform sampler2D _DiffuseTex;
        uniform sampler2D _NMTex;
        uniform sampler2D _PixelMap;
        uniform float4 _DiffuseTex_SV;
        uniform float4 _SpecColor;
        uniform float _SpecIntensity;
        uniform float4 _RimColor;
        uniform float _RimIntensity;
        uniform float _RimCoefficient;

        //unity
        uniform float4 _LightColor0;

        struct vI
        {
            float4 pos : POSITION;
            float3 norm : NORMAL;
            float4 uv : TEXCOORD0;
        };

        struct vO
        {
            float4 pos : SV_POSITION;
            float4 uv : TEXCOORD0;
            float3 worldPos : TEXCOORD1;
            float3 normDir : TEXCOORD2;
        };

        vO vert(vI i)
        {
            vO o;

            o.uv = i.uv;
            o.worldPos = mul(_Object2World, i.pos).xyz;
            o.normDir = normalize(mul( float4(i.norm, 0.0), _World2Object).xyz);
            o.pos = mul(UNITY_MATRIX_MVP, i.pos);

            return o;
        }

        float4 frag(vO i) : COLOR
        {
            float3 lightDir;
            float3 viewDir = normalize( i.worldPos - _WorldSpaceCameraPos.xyz);
            float atten;
            float3 normDir = normalize(i.normDir);
            float4 RimLight;
            float4 DiffuseLight;
            float4 SpecularLight;
            float2 UVCoord = i.uv.xy;

            float4 test = tex2D(_PixelMap, UVCoord);

            //float4 Clrx0 = lerp(

            //Directional Light
            if(_WorldSpaceLightPos0.w == 0)
            {
                lightDir = normalize(_WorldSpaceLightPos0.xyz);
                atten = dot(lightDir, normDir);
            }
            //point light
            else
            {
                float3 dist = i.worldPos.xyz - _WorldSpaceLightPos0.xyz;
                lightDir = normalize(dist);
                atten = (1/length(dist))*(dot(lightDir, normDir));
            }

            DiffuseLight = atten * _LightColor0;
            SpecularLight = atten * _LightColor0 * _SpecColor * _SpecIntensity * pow(max(0.0,dot(reflect(lightDir, normDir), viewDir)), 1)*(1-tex2D(_DiffuseTex, i.uv.xy).w);
            RimLight = atten * _LightColor0 * _RimColor * _RimCoefficient* pow((1-saturate(dot(-viewDir, normDir))),_RimIntensity)*saturate(dot(lightDir, normDir));

            float4 totalLight = DiffuseLight + SpecularLight + RimLight;

            float4 fin = float4(UVCoord.xy,0,0);

            return test; ///Fin * totalLight;
        }

        ENDCG


texts: Taking fixed direction on hemisphere and project to normal (openGL)

texts:
I am trying to perform sampling using hemisphere around a surface normal. I want to experiment with fixed directions (and maybe jitter slightly between frames). So I have those directions:

vec3 sampleDirections[6] = {vec3(0.0f, 1.0f, 0.0f),
                            vec3(0.0f, 0.5f, 0.866025f),
                            vec3(0.823639f, 0.5f, 0.267617f),
                            vec3(0.509037f, 0.5f, -0.700629f),
                            vec3(-0.509037f, 0.5f, -0.700629),
                            vec3(-0.823639f, 0.5f, 0.267617f)};

now I want the first direction to be projected on the normal and the others accordingly.

I tried these 2 codes, both failing.
This is what I used for random sampling (it doesn't seem to work well, the samples seem to be biased towards a certain direction) and I just used one of the fixed directions instead of s (here is the code of the random sample, when i used it with the fixed direction i didn't use theta and phi).

vec3 CosWeightedRandomHemisphereDirection( vec3 n, float rand1, float rand2 )
    float  theta = acos(sqrt(1.0f-rand1));
    float  phi = 6.283185f * rand2;

    vec3 s = vec3(sin(theta) * cos(phi), sin(theta) * sin(phi), cos(theta));

    vec3 v = normalize(cross(n,vec3(0.0072, 1.0, 0.0034)));
    vec3 u = cross(v, n);
    u = s.x*u;
    v = s.y*v;
    vec3 w = s.z*n;

    vec3 direction = u+v+w;
    return normalize(direction);
}

** EDIT **

This is the new code

vec3 FixedHemisphereDirection( vec3 n, vec3 sampleDir)
{
    vec3 x;
    vec3 z;

    if(abs(n.x) < abs(n.y)){
        if(abs(n.x) < abs(n.z)){
            x = vec3(1.0f,0.0f,0.0f);
        }else{
            x = vec3(0.0f,0.0f,1.0f);
        }
    }else{
        if(abs(n.y) < abs(n.z)){
            x = vec3(0.0f,1.0f,0.0f);
        }else{
            x = vec3(0.0f,0.0f,1.0f);
        }
    }

    z = normalize(cross(x,n));
    x = cross(n,z);

    mat3 M = mat3(  x.x, n.x, z.x,
                    x.y, n.y, z.y,
                    x.z, n.z, z.z);
    return M*sampleDir;
}

So if my n = (0,0,1); and my sampleDir = (0,1,0); shouldn't the M*sampleDir be (0,0,1)? Cause that is what I was expecting.


texts: How can I determine how much I need to rotate an object to face a point?

texts:
I have an object located at (208,608) in my 480x800 screen (portrait orientation). I can touch anywhere on the screen (where y < 608) and I will get touchX and touchY.

What is the angle I need to apply to my object so the it will face the point (touchX, touchY)?

I tried

double alfa = (float) Math.atan2(touchY-608,touchX-208) * 180 / PI;
myObject.setRotation(alfa);`

but this doesn't seem to work if I touch one half of my screen. I also think this might be because the point is located in different quadrants reletive to my start point?

The angle I am trying to get is the angle determined by the two points and the horizontal axis from the first point.  What I am trying to do is something like a bow facing my moving finger on the screen. Can anyone help me get the right angle please?

EDIT: I found the answer:

// Calculates an angle a body has to have to face a certain point in space

public static float rotateFromPointToPoint(float pFromPointX,float pFromPointY,float
                pToPointX,float pToPointY) {

        float k1 = (float) (pToPointY - pFromPointY);
        float k2 = (float) (pToPointX - pFromPointX);

        float tan = k1 / k2;

        float angle = (float) Math.atan(tan);
        float rotation = (float) Math.toDegrees(angle);

        if (pToPointX < pFromPointX) {
                rotation = (float) Math.toDegrees(angle) + 180;
        }
        return rotation;
}

Maybe someone else will find this usefull.


texts: Unity 4.6: sprite image automatically splits to single sprites when clicking

texts:
I'm viewing Unity tutorial. As in this tutorial, I see when author clicks to sprite image, they will automatically divide to each frame as below:

But in my Unity, I just can view this:

So. My question is: How can my sprite image automatically divides to each sprite.

Thanks :)


texts: Have VSync on or off while do a game profiling

texts:
I'm trying to profile the game using Unity Profiler in order to catch any potential performance issues. The graphics settings support VSync feature.

However, I am not sure which one is the best practice to have a better profiling insight, having VSync on or off?


texts:
I've been looking into generating lakes and rivers for a 2D infinite tilemap but I'm stuck with how to handle them for an infinite map.

I can use noise/heightmaps for determining the lakes and the starting points for rivers but for an infinite map I can't use the  "flow downhill" or "carve out" technique because the player could come across the river at any point.

If I have a river that's a max of 200 tiles long, I'd have to calculate noise/map values for 33x33 chunks (my chunks are 6x6 tiles) around the player which feels excessive and very inefficient.

I have not found a way to make noise alone work for this, rivers would always be too circular if I find a range narrow enough and they'd encircle lakes, not extend outward.

Calculating voronoi cells and putting rivers at certain edges, with some extra noise to make the paths more natural, might work.

I just can't seem to find any good examples where they aren't working with known-dimension maps.


texts:
I'm trying to implement font rendering and have got into some trouble with glyph metrics.
Here's the code where I get the metrics:

Glyph gl;
gl.width = face->glyph->metrics.width / 64;
gl.height = face->glyph->metrics.height / 64;
gl.character = i;
gl.advance = face->glyph->metrics.horiAdvance / 64;
gl.bearingX = face->glyph->metrics.horiBearingX / 64;
gl.bearingY = face->glyph->metrics.horiBearingY / 64;
gl.textureX = this->_textureWidth;

The value of gl.advance is way too small. Here is a picture of it:

If I'm dividing face->glyph->metrics.horiAdvance by 40, it looks like this:

The text is now readable, but the advance and X-, Y-bearing still don't look correct. This is what it should look like:

Here is my code where I draw the glyphs:

float aspect = this->_graphics->getMetrics().x / this->_graphics->getMetrics().y;

float offset = 0;
for(unsigned char c : str){
    Glyph g = this->_fonts[fontID]->getGlyph(c);

    vec2 pos = (position.getRelative() + vec2(offset, 0) + (vec2(g.bearingX, -g.bearingY) / SCALING) * scale - vec2(1, 1))
                * vec2(1, -1);
    glyphShader->setUniform("position", pos);
    glyphShader->setUniform("scale", (vec2(g.width, g.height * aspect) / SCALING) * scale);
    glyphShader->setUniform("glyphSize", vec2(g.width, g.height));
    glyphShader->setUniform("textureMetrics", this->_fonts[fontID]->getTextureMetrics());
    glyphShader->setUniform("textureOffset", vec2(g.textureX, 0));
    glyphShader->setUniform("image", 0);
    glyphShader->setUniform("color", color);

    this->_graphics->getMeshByID(guiInstance->_quadID)->drawMesh();

    offset += (g.advance / SCALING) * scale;
}

I'm doing some transformations on position to move the origin to the top-left corner and flipping the coordinate system on the X-Axis. Then I divide every pixel value by a constant factor, to have the font having the same size on every resolution. The ratio of the glyphs is correct, but not the alignment.
And here is my vertex shader:

#version 400

layout(location=0) in vec4 vertPosition;
layout(location=1) in vec2 vertUV;

uniform vec2    position;
uniform vec2    scale;
uniform vec2    glyphSize;
uniform vec2    textureMetrics;
uniform vec2    textureOffset;

out vec2 fragUV;

void main(void){
    gl_Position = vertPosition *
                  vec4(scale, 1, 1) +
                  vec4(position, 0, 0);

    fragUV = vec2(vertUV.x * (glyphSize.x / textureMetrics.x) + (textureOffset.x / textureMetrics.x),
                  -vertUV.y * (glyphSize.y / textureMetrics.y));
}

Why are the characters misaligned?


texts: My Ambient lighting is not working correctly

texts:
I'm having a problem when using ambient lights in my opengl game.

When I first started with my program, i had a positioned light, and the code was this:

GLfloat AmbientColor[] = {1.0f,1.0f,1.0f,1.0f};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT,AmbientColor);
    ////////POSITIONED LIGHT
    GLfloat LightColor0[] = {0.9f,0.9f,0.7f,1.0f};
    GLfloat LightPos0[] = {0.0f,900.0f,1000.0f,1.0f};
    glLightfv(GL_LIGHT0,GL_DIFFUSE,LightColor0);
    glLightfv(GL_LIGHT0,GL_POSITION,LightPos0);

When doing this, I had a well lit area with no problem.

Once I changed my matrix to GL_MODELVIEW, I noticed that my lights were not equal on each face.

I changed my code to look like this:

GLfloat AmbientColor[] = {1.0f,1.0f,1.0f,1.0f};
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT,AmbientColor);
    ////////POSITIONED LIGHT
    GLfloat LightColor0[] = {0.9f,0.9f,0.7f,1.0f};
    glLightfv(GL_LIGHT0,GL_AMBIENT,AmbientColor);

Once I used this code, only the mountains in my terrain were lit up, and anything perfectly flat was not lit at all(completely black...)

So my question is - How would I use my ambient light correctly?

Example code would be nice, thanks.


texts: Unity 5 Closing Menu On Multiple GameObjects When A New Menu is Opened?

texts:
I am trying to make a menu system for each GameObject, and when a GameObject is clicked it will close all other menus and open the one for that GameObject. I am using one script for this:

using UnityEngine;
using System.Collections;

public class BlockMenus : MonoBehaviour
{
Vector3 point;

public Transform block;
public GameObject activeBlock;

bool buttonActive = false;
bool activeBlockActive = false;

string hitObject = "";

void Update()
{
    point = Camera.main.WorldToScreenPoint(block.position);
}

void OnMouseDown()
{
    hitObject = this.gameObject.transform.tag;

    buttonActive = !buttonActive;
    activeBlockActive = !activeBlockActive;

    activeBlock.SetActive(activeBlockActive);
}

void OnGUI()
{
    if(buttonActive)
    {
        switch(hitObject)
        {
            case "mine":
                GUI.Box(new Rect(((point.x) * (1.08f)), ((Screen.height - point.y) * (0.1f)), (Screen.width * (0.3f)), (Screen.height * (0.5f))), "");
                GUI.Button(new Rect(((point.x) * (1.08f)), ((Screen.height - point.y) * (0.87f)), (Screen.width * (0.05f)), (Screen.height * (0.06f))), "Build Mine");
                break;
        }
    }
}
}


texts: How to decelerate Ship using Vector Objects in Java

texts:
I am developing an Asteroids type game in Java, using a custom Vector2D class for the Ship. I have a vector object for its position, direction and velocity. I am having an issue with the ship deceleration, currently when there is no thrust (forward key is released) then I multiply my velocity vector by the Drag constant which is 0.3. However the ships speed does not decelerate and will stop abruptly instead, upon releasing the thrust key.

Here is the update method in my Ship Class:

public void update() {
    velocity = new Vector2D(direction);

    if(ctrl.action().turn > 0) {
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }
    else if(ctrl.action().turn < 0){
        direction.rotate(ctrl.action().turn / STEER_RATE);
    }

    //Acceleration
    if(ctrl.action().thrust == 1) {
        velocity.addScaled(direction, DT).mult(MAG_ACC);
    }
    //Deceleration
    else if(ctrl.action().thrust == 0){
        velocity.mult(DRAG);
    }
    position.addScaled(velocity, DT);
    position.wrap(FRAME_WIDTH, FRAME_HEIGHT);
}

Contructor:

public Ship (Controller ctrl) {
    centerX = FRAME_WIDTH/2.0;
    centerY = FRAME_HEIGHT/2.0;
    this.ctrl = ctrl;
    position = new Vector2D(centerX, centerY);
    direction = new Vector2D(position).normalise();
    velocity = new Vector2D(direction);
}

I'd like to ask how I can slow the ship velocity rather than it losing all of its speed instantly. If more code is required I am happy to show it.


texts: Handle actor deletion undo in Unreal Editor?

texts:
I have some objects pointing to a scene component of an actor:

class MyObject
{
    USceneComponent* Component;
}

When the actor is deleted, all its components are also deleted. So when the delete action is undone (transaction undo), the component pointer (in MyObject) becomes invalid. This is not a problem, but the pointer must be updated after the redo (when the actor and its components are automatically re-created).

How can I detect which actor was created by the redo?


texts: SharpDX DirectInput Force feedback actuators are missing

texts:
I am using a simple code to read input from a DirectInput device. I would like to add force feedback to the device, however when I run this test, I cannot find any ForceFeedbackActuator, however my device supports rumble effects.

public void Test(Joystick joystick)
{
    joystick.SetCooperativeLevel(new WindowInteropHelper(Application.Current.MainWindow).Handle, CooperativeLevel.Background | CooperativeLevel.Exclusive);
    joystick.Properties.AxisMode = DeviceAxisMode.Absolute;
    joystick.Properties.AutoCenter = false;
    joystick.Acquire();

    foreach (var deviceObjectInstance in joystick.GetObjects())
    {
        if (deviceObjectInstance.ObjectId.Flags.HasFlag(DeviceObjectTypeFlags.ForceFeedbackActuator))
        {
        }
    }
}

I checked the Microsoft specification but found nothing so far.

However my driver is null as well:

deviceInstance.ForceFeedbackDriverGuid

But this can be set from registry HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\MediaProperties\PrivateProperties\Joystick\OEM adding a new CLSID value for the current device.

Any help is appreciated.


texts: Algorithm for a dense crowd of people who avoid the player?

texts:
I want to make a game like this. When player moves other humans will move too. And other humans will push people around. Are there any algorithm for this ? How can i solve this very efficient way ?

I dont want to check all objects at scene with loop. And i dont want people overlap.

Video:

https://youtu.be/V5ZMicq05LQ


texts: Understanding animations of controllable characters

texts:
I am a newbie trying to learn basics of Unity3D (5) before starting to do the real thing. Even though I tagged it as Unity3D, the logic should be the same for every kind of game engine. So I will be glad if you share your experience even though you do not use Unity.

Assume that you are importing the "Lamp" character (fbx) of Pixar. (Jumping, moving forward by little jumps, etc..)

OR

Assume that you are basicly importing a humanoid model with animations from Unity Asset Store. (I know that they generally include controllers too, assume that there are no controllers)

In unity, I want to make the character jump so I use jump animation. But I really want to make it jump. Also when I move it forward I really want it to move forward by appying a force or setting it's velocity. These will probably will not match the animation and even if they match, my own physics manipulations will be mixed with the animation's transformations. Even if I put the animation/object into another GameObject, it changes the position and/or rotation of the parent gameobject. So, animation changes those values and I also change them myself... The result will be the combination of all which is very hard -if not impossible- to sync or calculate.

The same thing is valid for almost every animation including Jumping. For example, the animation jumps and I also make the object jump.. It will create a double jump.. If I only let animation does that, I won't be able to control how it really behaves and If I make the animation look like it's crouching (actually jumping, but transformed to 0,0 in every frame, so in Unity changing the vertical position will fix it...) it will be hard to sync too.

What am I missing here? What is the guideline here?


texts:
I want a 3D Mesh to come out of a flat portal. Only the part of the mesh that's coming out of the portal should be rendered, so the mesh should be cut off or sliced until it's fully outside the portal.

I thought about using discards in a fragment shader, but since I work on iOS OpenGL ES 2.0 I'd like to avoid that for performance reasons. Is there a performant way to do this?


texts: Help retrieving/sending data to/from a server on iOS (C#, Mono, .Net)

texts:
I'm sorry in advance if this is a silly question.

I'm currently working on getting something running where I can grab information from a server.  My goal is to make the data I'm retrieving (or sending, for that matter) as small as possible -- both for speed and bandwidth.

To make matters more complicated, I'll be needing two sets of data:

Global: Something that doesn't house a lot of data, but needs to be synced every time.  (News, status, etc.)

Personal: The user's data. (Points, scores, etc.)  This isn't a lot of data either, but I thought that a database would be ideal for this.  Doesn't this then mean that I'd have to retrieve the whole database, and then filter it?  (i.e. transmitting too much data)

The server would be as small as possible (for cost), so it should only house data, and not do any (or almost any) of the work itself, so it would essentially just be storing the files.

Is a database the best way to go about this?  Should I use two databases (global, personal)?

Would SQL be best for this?  Or could I use REST and just grab the data I need (not the whole file)?

I'm sorry if this seems like a lot.  I've been googling for a few days now, and I'm unsure of what I should do.  If this is unclear, please say so and I'll try to clear things up.  If it's too broad, I will narrow it down more.

EDIT: Thanks for the answers thus far, but they aren't quite what I'm looking for.  So, I'll go into more detail.

I'm thinking of using Amazon for the server, mainly because it's pay-as-you-need and scalable.  Furthermore, I've found this article which is specific to MonoTouch, but I'm still not sure what's easiest.  I will not have a ton of data, so if I can grab either a small file, or query a database, that would be great.  I'm all for using third-party libraries, if it's possible, but mainly I'm not sure how I should do what I want to do.

Sorry for being so thick.  Obviously I can understand it better with example code, but it's not a requirement for an answer.  (And I want to make it explicitly clear that I'm not asking for hand-outs.)


texts: Collision detection on a 2D hexagonal grid

texts:
I'm making a casual grid-based 2D iPhone game using Cocos2D. The grid is a "staggered" hex-like grid consisting of uniformly sized and spaced discs. It looks something like this:

I've stored the grid in a 2D array. Also, I have a concept of "surrounding" grid cells. Namely the six grid cells surrounding a particular cell (except those on the boundries which can have less than six).

Anyways, I'm testing some collision detection and it's not working out as well as I had planned. Here's how I currently do collision detection for a moving disc that's approaching the stationary group of discs:

Calculate ij-coordinates of grid cell closest to moving cell using moving cell's xy-position
Get list of surrounding grid cells using ij-coordinates
Examine the surrounding cells. If they're all empty then no collision
If we have some non-empty surrounding cells then compare the distance between the disc centers to some minimum distance required for a collision
If there's a collision then place the moving disc in grid cell ij

So this works but not too well. I've considered a potentially simpler brute force approach where I just compare the moving disc to all stationary discs at each step of the game loop. This is probably feasible in terms of performance since the stationary disc count is 300 max. If not then some space-partitioning data structure could be used, however that feels too complex.

What are some common approaches and best practices to collision detection in a game like this?

Edit - More info: This current implementation has a few bugs like discs will sometimes stick over an occupied grid slot. Also it's too difficult to get discs into small spaces. These are all fixable. I asked here just to learn about alternative approaches.


texts:
This contest looks pretty interesting but I'm having some concerns about the wording in the rules:

Once submitted, a prize winning Submission becomes the exclusive property of Sponsor and will not be acknowledged or returned.
You expressly agree that by entering into the Contest any rights you may own in respect to a prize winning Submission shall be transferred to Sponsor by means of this Agreement. You shall be obliged to perform any measures necessary in order to vest any intellectual property rights in the name of Sponsor in case required by any law or regulation. In such case, Entrant shall – at Sponsor’s first request – execute any deed or transfer or such other document as required in that effect. For the avoidance of doubt, Sponsor shall have the exclusive right to make any kind of sequels, spinoffs, changes and translating the prize winning Submission in any language , all in relation to the exploitation of the prize winning Submission on any kind of media now known or hereinafter developed, without territorial or time limitations. The responsibility to implement localizations made by Sponsor in up to 19 languages will be that of the developer.

So it sounds like they get full IP rights, but I can't read this law stuff. Anybody have any insight? Much appreciated!