texts: Box2D Libgdx removing bodies in case of simultaneous collisions

texts:
I am making a clone for the BreakOut game. I'm using Box2D and Libgdx for it. In the game, one scenario is that there could be 2-3 balls at one time. Now the problem occurs when 2 or more balls collide with the same object at the same instant. I'm simulating this by creating 2 balls overlapping each other and having velocities in both directions same, so they move like one body. When they collide I get this error : AL lib: alc_cleanup: 1 device not closed. I searched a little and modified my code by putting the condition if (!world.isLocked()). Now it just gets stuck and I have to end the process using task manager. Here is my code inside collision listener :

if (contact.getFixtureA().getUserData() instanceof Ball) {

        Ball ballTemp = (Ball) contact.getFixtureA().getUserData();

        if (contact.getFixtureB().getUserData() instanceof Brick) {
            brickTemp = (Brick) contact.getFixtureB().getUserData();

            if (brickTemp.getPower() != null)
                brickTemp.getPower().update();

            if (ballTemp.getX() > brickTemp.getPosition().x
                    + brickTemp.getWidth()) { // collision on the right
                ballTemp.goRight();
            }
            if (ballTemp.getX() < brickTemp.getPosition().x
                    - brickTemp.getWidth()) { // collision on the left
                ballTemp.goLeft();
            }
            if (ballTemp.getY() > brickTemp.getPosition().y
                    + brickTemp.getHeight()) { // collision on the top
                ballTemp.goUp();
            }
            if (ballTemp.getY() < brickTemp.getPosition().y
                    + brickTemp.getHeight()) { // collision on the
                                                // bottom
                ballTemp.goDown();
            }
            bodiesToDestroy.add(contact.getFixtureB());
        }
    }

I have another if statement where fixtureB is Ball and fixtureA is Brick with similar code.
And the part in MainScreen.java where I'm doing the cleaning up job is :

world.step(TIMESTEP, VELOCITYITERATIONS, POSITIONITERATIONS);

    if (!world.isLocked()) {
        destroy(MyContactListener.bodiesToDestroy);

        if (MyContactListener.removeBall != null) {
            balls.removeValue(MyContactListener.removeBall, true);
        }

        if (MyContactListener.power) {
            MyContactListener.powerBrick.applyPower(delta);
            powerStartTime = System.nanoTime();
        }

    }
    public void destroy(Array<Fixture> bodiesToDestroy) {
    Array<Fixture> temp = new Array<Fixture>();
    for (Fixture bodyToDestroy : bodiesToDestroy) {
        if (bodyToDestroy.getBody() != null) {
            world.destroyBody(bodyToDestroy.getBody());
            temp.add(bodyToDestroy);
        }
    }
    MyContactListener.bodiesToDestroy.removeAll(temp, true);
    temp = null;
}

applyPower method just creates two new instances to Ball class with the same co-ordinates and velocities.
bodiesToDestroy is defined as public static Array<Fixture> bodiesToDestroy = new Array<Fixture>();

It's unlikely that two balls collide with the same object just at the same instant, but nonetheless I have to take care of such an occurrence. Please suggest how this should be handled.


texts: Are mathematical models a good way to test strategy games?

texts:
I am currently working on a simple strategy game. The game is a space exploration game where the player has to try to keep the game going for as long as possible to score as many points as possible. To go from planet to planet the player needs to use resource points; each explored planet also gives the player points (decreases gradually with time), yet a small expense in resource points is also added for each explored planet. Therefore, the player has to keep exploring to avoid running out of points.

The knowledge points allow the player to try to discover more planets, before exploring them.

I am looking for a methodical way to test the game. At the moment I keep adjusting the formulas used for the points given by each planet, or the expenses, or the travel/exploration costs, yet this trial and error method is pretty tedious and not really efficient. At the moment my "strategy" game seems more like a "click as much as you can" kind of game.

Since each type of planet has its own advantages and inconveniences, I'd really like that to show in the game play.

I was thinking of using mathematical models in Excel, by inputting all my formulas and adjusting the parameters there, but the more I think about it the more I think I will have to use some "randomness" to reflect the player choices, which defeats the purpose of testing the game for its "strategic" aspect.

Here's a screenshot of the game:


texts: How can I get the force of a collision in Love2D?

texts: Is it possible to get the force of a collision between two objects in Love2D/Box2D? If so, how?


texts: In Unity, how can I cause something to happen on a specific frame of an animation?

texts:
I have a GameObject "enemy" with an Animator and several states, like "idle", "walk", and "attack".

I want to activate the "hitbox" when an animation "attack" starts. The problems is that the sword does not fall down immediately: it takes about 2 frames.

Is there a way to know what frame of the animation is currently being run?


texts: How to handle platform collisions in a 2D game?

texts:
If I have a map in my platformer game and I want my character be able to jump on some platform, for example. Is there an easy way to tell the game where the platforms are and where the player can jump to and start jumping from?

Also, for games like Super Mario Bros and such, are the maps made in .txt files ? I watched a tutorial for maps and he said all professional game developers make a .txt file for the map and write numbers for example using...

111111111111111111111
111111111111111111111
111111111111111111111
111111111111111111111
222222222222222222222

...to create a map. Is this correct or how did the developers do the maps in the Super Mario Bros or MegaMan games?

What I am wondering is, if I want my player to be able to jump up on some platform or something, how do I do it?


texts: SDL render surface from byte array efficiently

texts:
In my current project I need to fill a 256x224 screen with the pixel values from an array. The array is declared this way:
uint8_t *vram = new uint8_t[7168];

So as you might have noticed, every bit in this array represent one pixel in the screen (256 x 224 / 8 = 7168). My current attempt to render a screen looks like this: (it is executed at 60hz)
int x = 0;
int y = 0;
for (int i = 0; i < 7168; i++)
{
    //read the byte
    uint8_t b = vram[i];
    for (int j = 7; j >= 0; j--)
    {
        //read 1 bit from the original byte
        bool pixel = (b >> j) & 1;
        SetPixel(x, y, pixel);

        //if end of line reached, go to next line
        if (((x + 1) % 256) == 0)
        {
            x = 0;
            y++;
        }
        else
        {
            x++;
        }
    }
}

and my SetPixel function:
void SetPixel(int x, int y, Uint32 pixel)
{
    Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * 4;
    *(Uint32 *)p = pixel;
}

My window and surface declarations:
window = SDL_CreateWindow("Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 256, 224, SDL_WINDOW_OPENGL);
surface = SDL_GetWindowSurface(window);

Currently I have two big problems:

My surface isn't been changed, doesn't matter what I try
I'm not even sure if this method is efficient, looking at profiling data from Visual Studio it doesn't seem to be

So, how could I render a black and white screen from an byte array in a somewhat efficient way?
Any help will be very appreciated!


texts:
I have a game, but I have to make a decision about audio.
Should I preload an audio pool, or create cloneNode when played?
Which is better in terms of best loading and better performance?


texts:
In my RPG, all Food objects should be possible weapons. For instance, I want the player to be able to to try kill bunnies with a cherry or a watermelon.

The problem is that the easiest way to do this is a bit counter-intuitive (and ugly, IMHO):

Item < Weapon < Food

(superclass < subclass)

I wrote an interface (IWeapon) and made Weapon and Food implement it, but the amount of repeated code was ridiculously huge (what indicates that they should share a common class, right?).

I do not think that I want Potions, for instance, to be usable as weapons (I don't want to let the player hit the target with a filled vial).

How should I solve my current problem? Should I use inheritance or program to the interface?

What about extensibility? Does it make sense to let all items have attributes such as damage, hitRate, integrity, etc.?


texts: Photon2 billboards take a long time to face the camera

texts:
I'm using PUN2 and trying to use nametag billboards for my players, but they are not facing forward correctly and I have to wait more than 20 seconds to make the name tag of player return to facing forward.
here's my code for my BillBoard Script:
public class BillBoard : MonoBehaviour
{
    protected Transform ThisCameraPlayerBillBoard ;

    private void Start()
    {
        ThisCameraPlayerBillBoard = GameSetup.GS.ThisCameraToBillBoard.GetComponent<Camera>().transform;

    }

    private void FixedUpdate()
    {
        transform.LookAt(transform.position + ThisCameraPlayerBillBoard .rotation * Vector3.forward,
            ThisCameraPlayerBillBoard .rotation * Vector3.up);

    }
}


texts: In unity how can I make a checkpoint system

texts:
I have a 2D platformer and if my player dies, he goes back to the start, but I want there to be checkpoints.
My current Respawn script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Respawn : MonoBehaviour
{
    public GameObject PlayerPrefab;
    public Transform SpawnPoint;

    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.tag == "Trap")
        {
            PlayerPrefab.transform.position = SpawnPoint.transform.position;
        }
    }

}

I don't know how to implement checkpoints into this.


texts: How do I make a quest requiring a certain number of a specific item?

texts:
I'm trying to create a quest (in RPG Maker MV) where the player has to collect 35 berries.  But when I go to create the conditional branch, this is what I see:

It does not let me add a number limit, so basically all the player has to do
is collect 1 berry to complete the quest.

How can I change this so the player has to collect 35 berries in order to complete the quest? Is this a limitation of RPG Maker MV?


texts: SerializedProperty to UnityEvent in a Custom Editor

texts:
I am making a Custom Editor for a type that includes a UnityEvent property.

I'm currently facing an issue in converting a SerializedProperty to get that UnityEvent.

Here is how I declare the event in the type I want to edit with this custom editor:

public class SomeComponent : MonoBehaviour {

    public UnityEngine.Events.UnityEvent EventToAdd;

    //...
}

And this is my Editor script

[CustomEditor(typeof(SomeComponent))]
public SomeComponentEditor : Editor {

    private SerializedProperty _Events;
    private void OnEnable()
    {
        _Events = serializedObject.FindProperty("EventToAdd");
    }

    public override void OnInspectorGUI()
    {
        TwitchTVGui TGUI = (TwitchTVGui)target;

        this.serializedObject.Update();
        EditorGUILayout.PropertyField(serializedObject.FindProperty("EventToAdd"), true);

        this.serializedObject.ApplyModifiedProperties();
    }
}

And then I need to get the UnityEvent out of the serializedObject _Events somehow


texts:
I have a simple OpenGL program that renders terrain with a texture. It exhibits some strange behaviors (see video) that look similar to depth test issues. However, I have already enabled depth test. Where else can I look to solve this problem?

https://www.youtube.com/watch?v=WHTFa3tMSyQ

This is the relevant setup code

glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

... VBO and texture setup ..

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

projectionMatrix = glm::frustum(-2.0, 2.0, -2.0, 2.0, 1.0, 10000.0);

... rendering stuff ...

glFlush();
swapEGLBuffers();


texts:
I'm really new in Unity.
I want to make a curved GUI by myself. How would I make one?

I'm using Unity 5.6.


texts:
i am developing a game where user has to find target number using 5 given numbers and 4 operators. the score depends on the type of operators and number of operators used and time.

score = typeOperators + noOfOperators + timeScore

where typeOperators is the sum of score for each type of operator, 1 pt for +,* 2 pt for -, and 3 pt for /.

if all the three operators are used once, typeOperators will be 13.
currently, i am thinking of

timeScore = max(0, x - timespent)

But, the game should avoid the situation where the user finding target number with worst solution but with minimum time gets higher scores.
so the more weightage should be on the typeOperators rather than timeScore.

can there be any better approach?


texts: Grid collision - finding the location of an entity in each box

texts:
I am trying to implement grid-based collision in a 2d game with moving circles. The canvas is 400x400 pixels. Below you can see the code for my Grid class. What I want it to do is check inside which box the entities are located and then run a collision check if there are 2 or more entities in the same box.

Right now I do not know how to find the position of an entity in a specific box. I know there are many tutorials online, but I haven't been able to find an answer to my question, because they are either written in C/C++ or use the 2d array approach.

Code snippets and other help is greatly appreciated. Thanks.

public class Grid {

ArrayList<ArrayList<Entity>> boxes = new ArrayList<>();
double boxSize = 40;
double boxesAmount = 10;
...
...
public void checkBoxLocation(ArrayList<Entity> entities) {

      for (int i = 0; i < entities.size(); i++) {
// Get top left coordinates of each entity
            double entityLeft = entities.get(i).getLayoutX() - entities.get(i).getRadius();
            double entityTop = entities.get(i).getLayoutY() + entities.get(i).getRadius();

// Divide coordinate by box size to find the approximate location of the entity
            for (int j = 0; j < boxesAmount; j++) {   //Select each box
                if ((entityLeft / boxSize <= j + 0.7) && (entityLeft / boxSize >= j)) {
                    if ((entityTop / boxSize <= j + 0.7) && (entityTop / boxSize >= j)) {
                        holdingBoxes.get(j).add(entities.get(i));
                        System.out.println("Entity " + entities.get(i) + " added to box " + j);
                    }
                }
            }
        }
    }
}


texts: How can story and gameplay be artfully merged?

texts:
Let me give some context. Three of my friends and I have a pretty good game idea cooking. It's based off of a prototype I made that's evolving into a cool game mechanic. The mechanic itself is a toy that's fun on its own, but we haven't designed any puzzles around it yet. We have a design document going, and we are answering a lot of questions about what's in the game.

It's become clear early on that everyone (including myself) likes the characters and the story a lot. Considering what our favorite games are, this is unsurprising. A story driven game makes sense to me. I like the emphasis that Paper Mario: The Thousand-Year-Door, Portal 2, and Tomb Raider place on story, and I imagine our game will have a similar feel (lots of dialogue, plot twists, lovable characters). These games, IMO, have very successfully merged gameplay and story, so I know it's possible to do this successfully.

However, one team member raised this point in the design doc:

  I am feeling like [fleshing out the story] is our biggest hurdle right now for making more design decisions - like more specific decisions about levels etc. Is this true?

I am uncertain about working on the story extensively before gameplay, and my uneasiness was reinforced when I read this question about story vs. gameplay.

Main Question

My team and I want to design a puzzle-adventure game, such that (in the final version of the game) the puzzles and other gameplay sequences integrate with the story as naturally as possible (the gameplay should, of course, be fun on its own), while the story itself (including plot, characters, events, etc...) does not feel contrived. In light of this goal, in what order should the design of gameplay and story be carried out? And more importantly, what tasks can/should be completed in parallel (by different team members)? Is there anything we need to be wary of during development?


texts:
I have a particle system where instead of tracking the time each particle is alive, I just track the time of the oldest particle and the time of the youngest particle. Basically, the oldest particle is guaranteed to die first, so once the time since it spawned has passed, the particle is 'killed off' and that time is subtracted by the time between particle spawn (1 / rate). And for spawning particles, the time since the spawn of the youngest particle is tracked. Once this time exceeds the time between particle spawn (1 / rate), then a new particle is spawned and this time is subtracted by the time between particle spawn (1 / rate). However, there seems to be some  bug in my code that I can't seem to find. The emitter seems to spawn only a few particles which move for the duration of their lifespan and then just stop and stay visible. The visibility of the particles is dependent on the index of the particle being within the range of the particleStartIndex and the liveParticleCount (These do wrap around and have been accounted for). I am testing with an emitter with 100 max particles. Here is my code:

inline void Update(float t)
{
    timeSinceFirstLiveParticle += t;
    timeSinceLastSpawn += t;

    //Kill Live Particles
    while (liveParticleCount > 0 && timeSinceFirstLiveParticle >= lifespan)
    {
        particleStartIndex = (particleStartIndex + 1) % maxParticleCount;
        liveParticleCount--;
        timeSinceFirstLiveParticle -= timeBetweenFire;
    }

    //Update Live Particles
    for (int i = 0; i < liveParticleCount; i++)
    {
        int idx = (i + particleStartIndex) % maxParticleCount;
        particles[idx] = particles[idx] + direction * speed * t;
    }

    //Spawn New Particles
    while (timeSinceLastSpawn >= timeBetweenFire)
    {
        int idx = (particleStartIndex + liveParticleCount) % maxParticleCount;
        timeSinceLastSpawn -= timeBetweenFire;
        particles[idx] = position + direction * speed * timeSinceLastSpawn;
        liveParticleCount++;
    }

    valid = false;
}

Any ideas?


texts: Only StartCoroutine of Update on child prefab functions

texts:
I have a script attached to a prefab.  That prefab attached to a child and I want it to rotate the root transform.

The Update of the script executes nothing but the Coroutine of a class I wrote.
Attached is the hierarchy of the outside and inside of playmode as well as the script on the prefab and the class.

From the Editor, Not on Playmode.

and in Plamode

uiTurnTileScropt.cs

//THIS SCRIPT IS CURRENTLY ON THE CCW PREFAB

using UnityEngine;
using System.Collections;

public class uiTurnTileScript : MonoBehaviour {
public float rotSpeed = 7.0f;
public float degree = 36.0f;
public float waitTime = .3f;
private bool rotate = false;
private Quaternion newRotation = Quaternion.identity;
BlockButton clickTapBlocked ;

void Start(){
    clickTapBlocked = gameObject.AddComponent<BlockButton>();
    clickTapBlocked.bttnName = "clickTap";
    clickTapBlocked.setFalse();
}
void Update () {
    Debug.Log (transform.name);
    if(Input.GetButtonDown (clickTapBlocked.bttnName) && (!clickTapBlocked.blocked)  ){
        Debug.Log("MouseDown");
        StartCoroutine(clickTapBlocked.forTime(waitTime));
        newRotation = Quaternion.AngleAxis (transform.root.rotation.eulerAngles.z - degree, Vector3.forward);
        rotate = true;
    }
    RotateSetAmount ();
}
void RotateSetAmount(){
    Debug.Log ("In Rotate function");
    if (rotate){
        this.transform.rotation = Quaternion.Lerp(transform.root.rotation, newRotation, Time.deltaTime * rotSpeed);
        if (transform.root.rotation.eulerAngles.z <  newRotation.eulerAngles.z){
            transform.root.rotation = newRotation;
            rotate = false;
        }
    }
}
}

and the referenced class BlockButton in uiTurnTileScript.cs

using UnityEngine;
using System.Collections;

/*  This class is more intuitive if you name thie instance created ("buttonValue" +     blocked)
 *  Example: for a button in the Input Project settings with a string of Fire1  I     would name the instance fire1Blocked
 *  Declare with your other variables

    BlockButton fire1Blocked

void Start(){
    //
    Fire1Blocked = gameObject.AddComponent<BlockButton>();
    Fire1Blocked.bttnName = "Fire1Blocked";
    Fire1Blocked.setFalse();
}
 */
public class BlockButton  : MonoBehaviour  {

public string bttnName;
public bool blocked = false;

public bool setFalse(){
    blocked = false;
    return blocked;
}

public bool setTrue(){
    blocked = true;
    return blocked;
}

public IEnumerator forTime(float duration){
    Debug.Log ("I was called");
    float dur = duration;
    blocked = true;
    yield return new WaitForSeconds(dur);
    blocked = false;
}
}

In my output,no matter what I click, I get nothing but the code from the BlockButton Instance.  No debug from the Update() happens but the coroutine happens.  I am not understanding how that happens and how to implement this properly.  Any help is appreciated.


texts: Network Communication For Multi-Player Turn-Based Game

texts:
I'm attempting to develop a multi-platform turn-based game that [I suspect] follows the general client-server pattern. For this question, let's assume I only care about communications inside of a "battle" right now.

Here are the relevant mechanics of a battle: there are some number of "soldiers" in each battle. Each soldier is under the control of a player and a player may be in control of multiple soldiers in a given battle. Each turn only 1 soldier makes an action, the server will contain logic to determine which soldier that is. There are no time limits on turns. The player in control of that soldier select an action for that soldier which is sent to the server. The server will then determine the result of that action and send that information to every client.

This diagram can hopefully show my intended flow of information:

With each communication to client I was expecting to send a json of a ClientBattle object that holds all the data a client needs. On communications to the server, I was expecting to send a json of an Action object that contains all the info the server needs to calculate the outcome and advance the battle.

Unfortunately, I'm not quite sure how I would go about implementing this.

An approach that I would know how to implement that mimics this behavior would be to have each client HTTP GET a turn number from the server at a regular interval of ~3 seconds. If the turn number matches the client's data it does nothing until asking the server again in 3 seconds. If the number doesn't match, then the client HTTP GETs new battle data from the server and uses that to update its display. On client to server communication I'd send a HTTP POST request.

How would I clean this up - or - how could I implement it as in the diagram?


texts: Unity - Code is fine in the editor, has error on android

texts:
Right. Im running into some weird issue with android unity. I have this bit of code

function OnTriggerStay (other : Collider)
{

        if(die.GetComponent(DieScript).sideUp ==6 ||die.GetComponent(DieScript).sideUp ==2 || die.GetComponent(DieScript).sideUp ==4)
    {

       parSys.startSpeed = -5;
        if (other.attachedRigidbody)
        {
        var direction = -(other.attachedRigidbody.transform.position - transform.position*1.5);
            other.attachedRigidbody.AddForce(direction);
        }

        }

Now, this runs fine in the unity editor. More then fine, It runs perfectly. However on android the whole OnTriggerStay method fails, and I get this error from logcat

I/Unity   (29199): NullReferenceException: Object reference not set to an instance of an object

I/Unity   (29199):   at ZoneScriptDie.OnTriggerStay (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

I/Unity   (29199):

I/Unity   (29199): (Filename:  Line: -1)

I/Unity   (29199):

I/Unity   (29199): NullReferenceException: Object reference not set to an instance of an object

I/Unity   (29199):   at ZoneScriptDie.OnTriggerStay (UnityEngine.Collider other) [0x00000] in <filename unknown>:0

I/Unity   (29199):

Why is it failing in android? The whole object freezes up, the particles just hang in place like a frozen snowglobe.


texts: Lists of concrete types show up in inspector, but not lists of interfaces

texts:
In one of my custom C# classes in Unity, I need to expose a List of objects in the inspector, and they need to conform to a specific interface.

Below are two lines from my class definition. Card is a concrete type in my game, and CellObserver is an interface. Multiple classes may implement this interface, so I'd like to define it this way if possible.

public List<Card> currentCards;
public List<CellObserver> observers;

The list of Card objects shows up in the inspector just fine, but lists based on CellObserver don't. It's not unique to this interface either - I also have one on another class that behaves the same way.

The code builds just fine, and as far as I can tell, this is valid in C#. Is there something else I need to do in Unity to implement this list? Or is this simply not an option in Unity?


texts: Legality, implementation, and viability of using the BSP map format in a procedurally generated XNA game?

texts:
First off, this is not a "which technology should I use" type of question, but rather a question about the viability (And legality, and how to implement) BSP maps into an XNA game.

The legality part - is the BSP map format (NOT bsp trees) an open format? I can find very little information on the map format, and what little I can find, is regarding Q3BSP - which makes me think that it's either closed, license-only, or GPL.
Is it viable, or wise to use BSP maps for a procedurally generated (I.e. Random dungeon) 3d world, in XNA? BSP is the first format that came to mind since Valve and Id seem to use it for all their games and it works well there. Are there more modern, or otherwise better methods out there? I've seen people using BSPs to generate random dungeons/maps before, but there always seemed to be lighting problems. I'm not sure if that was an issue with the engine (Quake 3), or the format.


texts: adapting a Unity gravitational script to allow moons

texts:
I'm using this script: http://wiki.unity3d.com/index.php/Simple_planetary_orbits

to get a solar system going in Unity, but it doesn't seem to support creating bodies that orbit other moving bodies (or I am using it incorrectly).

Any idea about how to modify it so that it does (or just use it correctly)? I've been beating my head against this problem for a couple hours, and I really don't feel like I have any idea what I'm doing.

Thanks in advance.


texts: Why can't we put GameObject's into a NativeArray and pass them to a Job?

texts:
I just started using the Unity Job System.

It has a lot of limitations. You have to use NativeArray with it and NativeArray doesn't allow many types, notably GameObject's. It says there is a bug that you have to use non-nullable types. Why can't the job system operate directly on game objects?


texts:
The near plane clips at exactly the value I set just fine but instead of clipping at 1000 the far plane clips at 1.

Here is the code for the projection matrix:

public static Matrix4f perspective(Matrix4f dest, float fov, float aspectRatio, float near, float far) {
    if (dest == null)
        dest = new Matrix4f();

    float tanHalfFOV = (float) Math.tan(fov / 2);
    float range = near - far;

    dest.m00 = 1.0f / (tanHalfFOV * aspectRatio);
    dest.m10 = 0;
    dest.m20 = 0;
    dest.m30 = 0;
    dest.m01 = 0;
    dest.m11 = 1.0f / tanHalfFOV;
    dest.m21 = 0;
    dest.m31 = 0;
    dest.m02 = 0;
    dest.m12 = 0;
    dest.m22 = (-near - far) / range;
    dest.m32 = 2 * far * near / range;
    dest.m03 = 0;
    dest.m13 = 0;
    dest.m23 = 1;
    dest.m33 = 0;

    return dest;
}

The near plane is 0.1 and the far plane is supposed to be 1000.


texts: JWJGL Multi-threading to separate update and render

texts:
Introduction:

I am currently designing a game in Java using the LWJGL 3.0, with Gradle. I have quite an advanced knowledge on multi-threading, and I am aware how GLFW does/doesn't implement multi-threading from this guide. Currently, I have one class Updater with a loop for updating, and another class Renderer for rendering, each extending Runnable with their own loops and time calculations. Below is a diagram showing the structure of the classes and update and render methods. I have also set up a lock system, using the Java Lock class (again below).

My Problem:

Despite setting each thread as the current context before each loop executes its window call, and setting the current context to null at the end, I still get the error Exception in thread "RENDERER" java.lang.IllegalStateException: GLFW error [0x10008]: WGL: Failed to make context current: The requested resource is in use. Any idea as to why? Been at this for a few hours now.

Loop class:

private void threadLoop() {
    try {
        lock.lock();
        locked = true;
        loop();
        TPS++;
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
        locked = false;
    }
}

@Override
public void run() {
    init();
    long lastTime = System.nanoTime();
    double ns = SECOND / (MAX_TPS/2);
    double delta = 0;
    long timer = System.currentTimeMillis();
    while (running) {
        long now = System.nanoTime();
        delta += (now - lastTime) / ns;
        lastTime = now;
        while(delta >= 1) {
            threadLoop();
            TPS++;
            delta--;
        }
        if(System.currentTimeMillis() - timer > 1000) {
            finalTPS = TPS;
            timer += 1000;
            TPS = 0;
        }
    }
    stop();
}

Thread Manager:

public void update() {
    if (window == null) return;
    window.setThread();
    window.update();
    window.nullThread();
}

public void render() {
    if (window == null) return;
    window.setThread();
    window.render();
    window.nullThread();
}

Renderer:

@Override
protected void loop() {
    if (state != null) state.render();
    threadManager.intermediateCode();
    threadManager.render();
}

Updater:

@Override
protected void loop() {
    if (state != null) state.update();
    threadManager.intermediateCode();
    threadManager.update();
}

Window:

public void setThread() {
    glfwMakeContextCurrent(getID());
}

public void nullThread() {
    glfwMakeContextCurrent(NULL);
}

public void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glClearColor(0.0f, 0.3f, 0.8f, 0.0f);
    glfwSwapBuffers(ID);
    System.out.println("Rendered window");
}

public void update() {
    glfwPollEvents();
    System.out.println("Updated window");
}


texts: Unity Sound effect playing too many times

texts:
In the class PlayerControl I have this

if (Input.GetKey("space"))
    {
        soundManager.PlayBleep();
        sword.SetActive(true);
    }

In my soundmanager I have this

   public void PlayBleep()
{
    if (!audio.isPlaying) {
        audio.PlayOneShot(SwordWhip2);
    }
}

At the moment I am getting the sound like 10 times each time I press space creating horrible soundeffects. How could I get it not to play until the sound has finished?


texts: Engine programming, is it supposed to be enjoyable?

texts:
Now this might sound like a silly question and I apologize if this sort of question is not suited for stackexchange. But I am genuinely wondering this, and I feel like I get alot more proffesional awnsers on here.

I'm getting into game development and have only worked solo since my study is not primairly about games.
I'm only interested at 2D games atm, so am not really in need of any external engines for physics and rendering and such. So usually write the engines myself.

I absolutely hate writing things as quadtree's and pathfinding algorithims, most of the time I wish I could just skip those parts and move on to programming the actual gameplay elements. Things that happen in the background don't really interest me at all. But at the same time, I can't stand it I don't know whats/how everything is happening in the background.

My dislike might be explained by my weak mathematical skills. My motivation gets me through, but it can take alot of time before I grasp the technical solution behind a problem.

Now is it normal to have such a dislike towards engine programming? Or do you (people who also work solo) enjoy programming the engine?


texts: JOGL Hardware Shadow Mapping Transparent Shadow Texture

texts:
I'm using hardware shadow mapping on JOGL based on the demo(HardwareShadowMapping) supplied by the distribution. After generating the shadow texture from lights point of view, I apply it to my scene with no problems.

What I'm looking for is soft shadows instead of pitch black shadows. Is there any way that I can change the alpha values while applying the shadow/depth texture? Btw I'm not an expert on OpenGL especially about custom shaders and I don't want to spend more time on understanding and developing custom shaders instead of the game.

Here's a screenshot of the application in case you come up with another solution to what I'm trying to achieve. The game is actually a hack&slash RTS hybrid.Here's the pseudo code of the gl event listener attached to shadow pbuffer.

  gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
  gl.glPolygonOffset(polygonOffsetFactor, polygonOffsetUnits);
  gl.glEnable(GL.GL_POLYGON_OFFSET_FILL);
  //render shadow casting geometry
  gl.glDisable(GL.GL_POLYGON_OFFSET_FILL);
  gl.glBindTexture(GL.GL_TEXTURE_2D, lightViewTextureID);
  gl.glCopyTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, 0, 0, textureSize, textureSize);
  //I sense here a way of updating alpha values of this texture


texts: Achieving smooth movement curves & correct collision detection with a google app realtime multiplayer game server

texts:
I'm an hobbist game developer. I'm trying to make a clone of a game like this: http://superhex.io/ to experiment with multiplayer online.

First of all I'm not sure if there is a better way to implement server-client comunication. So far I have implemented a server which updates the game state every 0.5 seconds and sends the information to all the clients.  You can try my current prototype here: https://hexpose.appspot.com

With respect to local development where the 0.5 seconds rounds are very regular, playing on the public server you see that the pace is not regular... I think this is due to a variable latency in server-client comunication.

Suppose I have many players moving on an arena like in this game. The superhex original gameplay is very fluid, you see enemies move on smooth curves. How this can be achieved? The position of enemies is known later (because of client-server-client latency) than the position of my player. But collision are anyway correctly detected. Is it just a matter of very slow latency and good server infrastructure or it depends on game logic implementation?


texts: Separation of game logic - extending game state to include location information?

texts:
I'm currently making a conversion of a board game I have - I don't intend to release it, it's merely to sharpen up skills. I'm currently refactoring it to completely separate game logic from everything such as rendering, getting user input, etc. The game logic is now in a library independent of the project that is actually run.

However, I've come across the problem that, if I don't store piece positions in the game state (as the game logic does not need to know about these), I'm struggling to think of how to store this information in the project that deals with rendering/user input stuff, so that it may render pieces.

Game State

The game state looks like this within the game logic - each district used to have a Vector2 indicating where the trouble marker would be displayed, and each piece would also have a Vector2 indicating their position on the board. They do not at the moment, as I wish to only have such things in the game project, as opposed to the logic project

Environment
    City
        District
        District
            Trouble
            Piece(s)

I have thought of creating a clone of this structure but adding position information, or of trying to use inheritance. But both of these methods seem extremely painful to do in the situation, and I'd really prefer to keep the game logic completely unknowing of things like this.

How would I go about doing this cleanly? Is it possible, or do I need to do a complete rethink of things?


texts: How to animate a flip of a card in Cocos2d?

texts: I am working on a card game and would like to ask if someone could advice me how to implement a flip of a card in Cocos2D?


texts: In a simple raycasting engine, why is the distance between player and projection plane constant?

texts:
According to this article about making a simple raycasting engine (like the one that was used in Wolfenstein3d), the distance between the player and the projection plane will be constant.

For example, suppose we are using a projection plane of dimension 320 X 200, and player's field of view (fov) is 60 degrees. Then the distance from the player to the projection plane is going to be

160 / tan(30 degrees) = 277 units

I can understand the trigonometry, but I can't understand why would the distance remain constant througout the game? Why wouldn't the distance change when the player moves closer or farther away from the projection plane?


texts: How do I properly implement zooming in my game?

texts:
I'm trying to implement a zoom feature but I have a problem. I am zooming in and out a camera with a pinch gesture, I update the camera each time in the render, but my sprites keep their original position and don't change with the zoom in or zoom out.

The Libraries are from libgdx.

What am I missing?

private void zoomIn()
{
    ((OrthographicCamera)this.stage.getCamera()).zoom += .01;
}

public boolean pinch(Vector2 arg0, Vector2 arg1, Vector2 arg2, Vector2 arg3)
{
    // TODO Auto-generated method stub
    zoomIn();
    return false;
}

public void render(float arg0)
{
    this.gl.glClear(GL10.GL_DEPTH_BUFFER_BIT | GL10.GL_COLOR_BUFFER_BIT);
    ((OrthographicCamera)this.stage.getCamera()).update();
    this.stage.draw();
}

public boolean touchDown(int arg0, int arg1, int arg2)
{
    this.stage.toStageCoordinates(arg0, arg1, point);
    Actor actor = this.stage.hit(point.x, point.y);

    if(actor instanceof Group)
    {
        ((LevelSelect)((Group) actor).getActors().get(0)).touched();
    }

    return true;
}

Zoom In

Zoom Out


texts: I can't import player relative controls in unity

texts: I'm developing a mobile game in Unity 5 but I can't find player relative control asset anywhere.Can you help me with this?


texts:
I want to make a pause button on the scene. If I press the button it will show the guiTexture with a variety of buttons with each different script. So what steps should I take?
1. How do make it so if I press the pause button on a scene it will show guiTexture?


texts: Detecting tile with height in isometric game

texts:
I'm trying to create an isometric tile-based game (for iPhone) and I'm having trouble with height in tiles.

What I currently do (without heights) is apply some mathematic transformations to my 2D-matrix (which represent the tiles) so that I know where in the screen (x,y) should I place the isometric tile. Then, when the user clicks somewhere in the screen, I take that values and pass them through a function (kind of f^-1) to get which tile it belongs to.

This works perfectly. My problem is: imagine that I want some tiles to have a different height from others. In order to draw the tile itself its pretty simple, since the z-coordinate has no transformation in the isometric approach used in games (z'=z). BUT what if I want to calculate the tile coordinate (defined by X-tile and Y-tile) from the touch coordinates (x,y)? Any guess?


texts: How to compute the area of an irregular shape?

texts:
I have a room object defined by a collection of looping line segments that I need to calculate the area for. The classes can be described as follows (in pseudo-code):

class Point {
    float x;
    float y;
    ...
    float distanceFrom(Point p);
}

class Segment {
    Point start;
    Point end;
    ...
    float length();
}

class Room {
    List<Segment> walls;
    ...
    float area();
}

The walls of a room can never intersect anywhere but at the endpoints of the segments and any "sub-loops" created will also be separated into a new room. The solution does not need to be perfectly accurate (10% margin of error is acceptable) and is also not computed very often (<1/s).


texts: Java creating random pipes from an image

texts:
Im trying to make a simple clone of flappy bird game. The tutorial that i watched used only rectangles for all the objects. But the thing is im trying to do it with nicer images. I have handled the bird and its movements but i can not generate pipes from images and terminate them after they get out of the screen.

The way i want to do is just like the tutorial. He made an arraylist of rectangles, and simply adding rectangles to that list with the position and dimension variables. When they go out of the screen, he deletes the pipes and add the new ones with "arraylist.add(new Rectangle())", and simply draws them with Graphics.fillRect(). But i cant do it with BufferedImage type or neither the Graphics2D.

Could anyone help please? I want to be able to generate random pipes like rectangles, and wanna be able to add them to an arraylist and draw them. Its pretty like creating blocks from an image in mario game

Any help would be appreciated!


texts: Editing sprite shading to change perspective?

texts:
I'm currently developing an RPG in Java with some of my friends, and one of my tasks is to do the pixel art. I'm a beginner at it, but I know that I'll get better in time.
I recently finished the concept of our main character (after many, many revisions), however, because the game is going to be in a 3/4 top down perspective; how would I edit the shading of the sprite to show this? Obviously a frontal view will not look right. My shading skills are not the best though, even with this sprite (some parts appear to be flat).

Below I have the sprite attached.

I did read something that said it would be harder to make higher resolution sprites for beginners (tile size is 32 x 32, MC is almost 2 tiles tall); however, it is a difficulty I am willing to deal with.

Thanks,
Nelson


texts: Spherical fractal noise generator in shader

texts:
I have a growing sphere in space, and I thought of having a procedural generated texture over it. Since it is growing, I thought a fractal would be a great choice, because more details would be visible the larger the sphere get (and I could mess with some parameter over time to have it animated).

A quick Mandelbrot implementation in GLSL showed it would be too expensive to have it in the devices I am targeting; also, I don't know how to map a cool looking fractal over complex plane onto a sphere without distortions (I expect the players to fly around this sphere in every direction, so there should be no "glued" edges or collapsed points), neither I have the background to devise/project a fractal over the spherical surface myself (probably was done before, but I could not find).

So weighting the requisites of the procedural texture:

Fast to run, for low-end/mobile GPU;
Over a spherical surface domain;
Growing in details with growing in size;
Possible to animate (BONUS);
Cool looking (of course);

then I thought it might be impossible within the constraints. But since I am no expert in this fractal thing, I thought I could ask it here first before scraping out the idea.

Maybe it is really not a fractal I need, and there is some other kind of noise with growing details I could use. Do you know of such noise generation procedure?

Do you know of any noise generator with uniform distribution over spherical sufaces, or any fractals whose domain is a sphere?

Can you suggest any alternatives for my situation?


texts: Does Overlap2d have its own frustum culling or do I have to implement my own?


texts: Interpolation gives the appearance of collisions

texts:
I'm implementing a simple 2D platformer with a constant speed update of the game logic, but with the rendering done as fast as the machine can handle. I interpolate positions between actual game updates by just using the position and velocity of objects at the last update. This makes things look really smooth in general, but when something hits a wall/floor, it appears to go through the wall for a moment before being positioned correctly. This is because the interpolator is not taking walls into account, so it guesses the position into walls until the actual game update fixes it. Are there any particularly elegant solutions for this?

Simply increasing the update rate seems like a band-aid solution, and I'm trying to avoid increasing the system reqs. I could also check for collisions in the actual interpolator, but that seems like heavy overhead, and then I'm no longer dividing the drawing and the game updating.


texts:
I am working on Unity 2D game. I used PlayerPrefs to save the level of the scene. As I go from one level to the next, the levels become unlocked and it works fine. But, after unlocking a few levels, when I go back to the lowest level, all the levels above become locked. What is the problem in my code?

Here is the LevelSelector class:

public class LevelSelector : MonoBehaviour {

public void Update ()

  {
    {
        int myLevel = PlayerPrefs.GetInt ("LevelPassed",1);

        for (int level = 0; level < myLevel; level++)
        {
        levelButtons[level].interactable = true;
        }
     }
   }
}

Here is the Score script:

public class Score : MonoBehaviour {

    void Update ()
    {

        UpdateScore ();

    }

    public void UpdateScore ()
    {

        if (sceneOne.isLoaded && meshLevel != null) {

            zLevel = 1;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 1);
        }

        else if (sceneTwo.isLoaded && meshLevel != null) {

            zLevel = 2;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 2);
        }

        else if (sceneThree.isLoaded && meshLevel != null) {

            zLevel = 3;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 3);
        }

        else if (sceneFour.isLoaded && meshLevel != null) {

            zLevel = 4;
            meshLevel.text = "Level  " + zLevel;
            PlayerPrefs.SetInt ("LevelPassed", 4);

        }
    }
}


texts:
I have a bunch of randomly generated boids flying around on my screen, but I want a function that can give them a field-of-view where they can "see" other boids or obstacles.
The code I wrote gets all the pixels around the boid in a circle of some size. Then I try to filter through them to find only the ones in front of the boid within a 30 degree cone-shaped field of view.
I am making this project in Unity using compute shaders written in HLSL.
For each boid, I gave a float2 position and a float angle. In my kernel, I run a function that tries to set the color of all the pixels inside my cone to red. Here's the code:
for(int x = -viewDistance; x <= viewDistance; x++){
    for(int y = -viewDistance; y <= viewDistance; y++){
        float2 sample = float2(x, y);
        float d = length(sample);

        if(d <= viewDistance && d > 0){
            // sensorAngle is an angle in radians defining the "view margins" of my cone.
            float minAngle = boid.angle - sensorAngle;
            float maxAngle = boid.angle + sensorAngle;

            float theta = acos(sample.x / d);
            if(theta >= minAngle && theta <= maxAngle){
                float2 p = sample + boid.position;
                Result[int2(p.x, p.y)] = float4(1, 0, 0, 1);
            }
        }
    }
}

As you can see I get all the pixels within a certain boundary and filter out ones that are too far away. This works perfectly in retrieving all pixels within a circle around my boid. My problem is with checking if the pixel is within my boid's view-cone.
I tried following this explanation for that code. This works perfectly, but it seems to "mirror" my cone over the x-axis like this:
Also, my boids get generated with a random number between 0 and 360 as their angle. I multiply this angle with PI / 180 to convert degrees to radians (This all happens on my C# side and then I send a ComputeBuffer through to my Compute Shader). However, I noticed that when the angle is generated larger than 180 degrees, the cone doesn't even render at all.
What might be a better method to go about calculating this FOV cone for each of my boids?


texts:
Possible Duplicate:
  How can I get involved with open source game projects?

I am trying to get involved in working on an open sourced basic game, but I've never attempted this before. I haven't the slightest clue how to go about this, what I should know (not programming-wise, just in general) and such...

Not sure if this question fits your Q/A format but, what do you suggest? Are there any really good well documented open source games that are basic that I could work on, preferably something that is RTS? And if I've never done this before, is there anything I should look in to that applies to open source projects in general?


texts: Shader only rendering 1/4th of the screen

texts:
I've asked the same question on SO here and they suggested I should ask here instead.

I'm currently trying to create a gaussian blur shader, and while I've successfully created the blur effect my shader only renders the lower right quarter of my screen like the image shows: And just to make it clear; it has NOT re-scaled the image, it just doesn't render the rest of it.

Here's my shader code with comments of my thoughts:

Vertex (horizontal, vertical almost identical. See below)

#version 400

in vec2 a_texCoord0; //My tex coords

out vec2 blurTextureCoords[11]; //Sample 11px (i.e, 5 right 5 left of center)

uniform float u_width; //Width of the screen. Used to calculate pixel size

void main(void){
    gl_Position = vec4(a_texCoord0, 0.0, 1.0);
    vec2 centerTexCoords = a_texCoord0 * 0.5 + 0.5; //Maybe this is somehow wrong?
    float pixelSize = 1.0 / u_width; //This is kind of interesting, because my shader sometimes tells me that "no uniform value was found with name 'u_width', but it still seems to work as if I change the values manually (ex. set it to 1920) it still looks normal.

    for(int i=-5; i<=5; i++) {
        blurTextureCoords[i+5] = centerTexCoords + vec2(pixelSize * i, 0.0); //I also thought that it might be because I multiply a float with an integer, but if I do float(i) instead of just i it still looks the same.
    }

}

Fragment

#version 400
#ifdef GL_ES
precision mediump float;
#endif

in vec2 blurTextureCoords[11];

out vec4 out_colour;

uniform sampler2D u_texture;

void main(void){
    //The actual bluring
    out_colour = vec4(0.0);
    out_colour += texture(u_texture, blurTextureCoords[0]) * 0.0093;
    out_colour += texture(u_texture, blurTextureCoords[1]) * 0.028002;
    out_colour += texture(u_texture, blurTextureCoords[2]) * 0.065984;
    out_colour += texture(u_texture, blurTextureCoords[3]) * 0.121703;
    out_colour += texture(u_texture, blurTextureCoords[4]) * 0.175713;
    out_colour += texture(u_texture, blurTextureCoords[5]) * 0.198596;
    out_colour += texture(u_texture, blurTextureCoords[6]) * 0.175713;
    out_colour += texture(u_texture, blurTextureCoords[7]) * 0.121703;
    out_colour += texture(u_texture, blurTextureCoords[8]) * 0.065984;
    out_colour += texture(u_texture, blurTextureCoords[9]) * 0.028002;
    out_colour += texture(u_texture, blurTextureCoords[10]) * 0.0093;
}

Additional code

Creating a shader:

//I also have one for the vertical shader, it's almost exactly the same.
horizontalShader = new ShaderProgram(
    Gdx.files.internal("graphics/shaders/post-processing/blur/horizontalBlur.vert"),
    Gdx.files.internal("graphics/shaders/post-processing/blur/blur.frag"));
horizontalShader.pedantic = false;
horizontalShader.begin();
horizontalShader.setUniformf("u_width", Gdx.graphics.getWidth());
horizontalShader.end();

if (horizontalShader.getLog().length() != 0) {
    System.out.println("Horizontal shader! \n" + horizontalShader.getLog());
}

Rendering to FBO then to screen:

// Horozontal blur
horizontalFBO.begin();
spriteBatch.begin();
spriteBatch.setShader(horizontalShader);
background_image.draw(spriteBatch);
spriteBatch.end();
horizontalFBO.end();

// Vertical blur
verticalFBO.begin();
spriteBatch.begin();
spriteBatch.setShader(verticalShader);
spriteBatch.draw(horizontalFBO.getColorBufferTexture(), 0, 0);
spriteBatch.end();
verticalFBO.end();

// Normal FBO (screen)
spriteBatch.begin();
spriteBatch.setShader(null);
spriteBatch.draw(verticalFBO.getColorBufferTexture(), 0, 0);
spriteBatch.end();

Additional info

I use two FBOs, but it seems that those are not the root of the problem, as the problem still persists if I just render directly to the screen using these shaders.

I have two vertex shaders, one for the horizontal and one for the vertical blur. The only difference is the uniform name u_width becomes u_height and the  blurTextureCoords[i+5] = centerTexCoords + vec2(pixelSize * i, 0.0); becomes  blurTextureCoords[i+5] = centerTexCoords + vec2(0.0, pixelSize * i);


texts: Legally possible to re-create/remake an old game?

texts:
Recently I started remaking an old game on Unity. Basically I want to remake an old RPG that was released for Playstation 1. I'm not ripping anything from the old game, all the assets are being created by me. I'm creating everything from the scratch, music, 3D models, gameplay however I will keep the (copyrighted ?) names, I will try to create the characters and maps/levels as they were in the original version of Playstation 1 but with better graphics.

I'm not planning on selling it or adding in on a platform like Steam (for obvious reasons, copyrights etc), just giving it for free. But I wanna know when I will finish the development, can I share the game on public with other people so they can download it?

Can the company that made the original game sue me/fine me because of copyrights reasons even though I'm not planning on selling for money?

tl;dr Remake an non-profit game of PS1 from the scratch, can the company that holds the copyrights of the game sue me/fine me?


texts: How to create offsetting lines that draw across the screen in Monogame?

texts:
I'm trying to create an effect on the screen like the gif below. Basically lines that are offset by 1 pixel draw across the screen from either side which then eventually creates a solid color.

I'm using Monogame for this and I'd prefer a shader doing it. The only resolution I'd need to support is 240x160.

I've delved a bit into a scanline shader to see if I could adapt it, but so far it doesn't look like it's going to work.


texts:
We are making game using Entity Systems. And we with my colleague have different opinions about what approach is better when doing AI.

Basically, he thinks that everything should be a system, where I'm not.

That is his way:

Systems:
 - Sensor System (look for a target)
 - Pathfinding System (find a path to a target which will be colliding between agents with high probability)
 - Attack System (attack target if in attack range)
 - Movement System (advance path to target, resolve colliding if can't advance)

There is my proposal:

Systems:
 - Attack System (find a target with hp > 0, write to Target component and attack if in range)
 - Movement System (find a path to target (if there isnt already) and advance)

Utility classes:
 - Sensor
 - Pathfinding

There is problem with first approach. For example, 10 units all choosed one target and attacked it (simly because it was closer). But in reality 3 units are sufficient to kill that target in an instant. So, why other 7 should attack this target too? When they choosed their target they doesn't known yet that 3 unit would suffice. They know now that target hp <= 0 but they can't choose another, because Sensor System finished his work already. If we want to fix it then problem will be in unreasonable complexity of Sensor system.
Where in latter approach we simply wouldn't select target if hp already <= 0.

Similarly, in first approach pathfinding will find paths which are colliding between them. When one unit taken grid cell another can't take it. That means he must forget his path. But he can't build a new, because Pathfinding system already finished his work. So, he advances one cell in direction of target. In latter approach, we will build path in respect to new positions of units.

Maybe there are another problems in both approaches which we couldn't foresee. So, please say something if you know.

Which way are better (both clear code and good AI)? Maybe both are wrong then please advice what is right way to make it.


texts: What are some effective methods for implementing downsampled transparency?

texts:
It seems that some games have managed to implement downsampled transparency, and presumably gained a significant performance boost. (Examples: Uncharted 2, Crysis 2) A while back I attempted to implement a form of this based off of an article in GPU Gems 3, but we found that it wasn't quite fast enough to be a win for us.

I'm looking for information on other techniques of implementing downsampled transparency, especially targeting the PS3 and Xbox360.


texts: How can player actions be "judged morally" in a measurable way?

texts:
While measuring the player "skills" and "effort" is usually easy, adding some "less objective" statistics can give the player supplementary goals, especially in a MUD/RPG context.

What I mean is that apart from counting how many orcs were killed, and gems collected, it would be interesting to have something along the line of the traditional Good/Evil, Lawful/Chaotic ranking of paper-based RPG, to add "dimension" to the game.

But computers cannot differentiate good/evil effectively (nor can humans in many cases), and if you have a set of "laws" which are precise enough that you can tell exactly when the player breaks them, then it generally makes more sense to actually prevent them from doing that action in the first place.

One example could be the creation/destruction axis (if players are at all allowed to create/build things), possibly in the form of the general effect of the player actions on "ecology".

So what else is there left that can be effectively measured and would provide a sense of "moral" for the player? The more axis I have to measure, the more goals the player can have, and therefore the longer the game can last. This also gives the players more ways of "differentiating" themselves among hordes of other players of the same "class" and similar "kit".


texts: How did older games manage their sprites?

texts:
I’m aware that older games would reuse sprites as much as possible (Like the bushes and clouds in Mario, or slime and red slime in dragon quest), how did they manage their sprites? Did they preload everything at the beginning, or did they load and unload as needed?

I had assumed the latter, but many games on the seas genesis, snes, gbc, etc have a sprite test mode which leads me to believe that they simply preloaded everything. Or is it possible that they used a combination of the two?


texts: Is AGS outdated for Point & Click Adventures?

texts:
I am working on a Point and Click Adventure game being coded on the AGS engine, and just recently, the question of 'is this outdated?' has come up.

I'll admit, AGS is a rather old, and kind of went out of style with the P&C genre itself, but I have not found anything quite like it that specializes in this specific format of games.

So, is it outdated, and if so, is there a better alternative?


texts: Advice for programming a lobby for a network multiplayer game?

texts:
I'm working on learning network programming. I'm working on a simple card game. The basic idea is:

Players enter the lobby
Players see tables
Players sit at an empty seat

Once they sit, they do not need any information from the lobby, they see the card table and the data about the other players and so forth.

I've programmed the server portion for the game itself. The clients connect to my server object and the server then receives and sends messages; quite simple.

The tricky concepts for me are:

What's a good way to run many tables at the same time?
What's a good way to keep the lobby consistently updated for each person in the lobby (eg: MSG_TABLE_FILLED, 22)

Ideally I'd like to have 1 server exe for all of this and to have to deal with multithreading as little as possible.

I'm going to use the enet library.

I was thinking that each time a game session starts, I push a new Game and I map the client IPs to that table, then I just route messages from those clients to that Game.

Since enet supports channels I was thinking of using 2 channels per table, one for the game messages and one for in game chat.

Would something like this work?

Does anyone have any advice / design ideas for a game with a lobby and many tables?
Is there a usual way this is done that I'm overlooking?

Any conceptual ideas or even c/c++ code examples would be very helpful.

Thanks


texts:
Is there a way to crop a texture having a list of triangles which represent the part to be kept?
For instance, I have a rectangular texture and I want to obtain a texture shaped by the triangle list I have.


texts: Textures rendering upside down and small with Pixel Shader in Mono Game but not XNA

texts:
I'm new to HLSL, attempting to use MonoGame to do some simple post processing effects.

Here is my HLSL file, taken from one of rbwhitaker's xna tutorials (I would post the link, but can't post more than two with my current reputation).

//------------------------------ TEXTURE PROPERTIES ----------------------------
// This is the texture that SpriteBatch will try to set before drawing
texture ScreenTexture;

// Our sampler for the texture, which is just going to be pretty simple
sampler TextureSampler = sampler_state
{
    Texture = <ScreenTexture>;
};

//------------------------ PIXEL SHADER ----------------------------------------
// This pixel shader will simply look up the color of the texture at the
// requested point, and turns it into a shade of gray
float4 PixelShaderFunction(float2 TextureCoordinate : TEXCOORD0) : COLOR0
{
    float4 color = tex2D(TextureSampler, TextureCoordinate);

    float value = (color.r + color.g + color.b) / 3;
    color.r = value;
    color.g = value;
    color.b = value;

    return color;
}

//-------------------------- TECHNIQUES ----------------------------------------
// This technique is pretty simple - only one pass, and only a pixel shader
technique BlackAndWhite
{
    pass Pass1
    {
        PixelShader = compile ps_4_0 PixelShaderFunction();
    }
}

The only line I've changed is the compiler version from ps_2_0 -> ps_4_0, since MonoGame needs 4.0 (I think?)

I'm using MonoGame 3.4, and I've changed nothing from the initial project template except the following:

protected override void LoadContent()
{
    // Create a new SpriteBatch, which can be used to draw textures.
    spriteBatch = new SpriteBatch(GraphicsDevice);
    // TODO: use this.Content to load your game content here
    BlackAndWhiteEffect = Content.Load<Effect>("BlackAndWhite");
    Image = Content.Load<Texture2D>("smiley");
}

private Effect BlackAndWhiteEffect
{
    get;
    set;
}

private Texture2D Image
{
    get;
    set;
}

protected override void Draw(GameTime gameTime)
{

    GraphicsDevice.Clear(Color.CornflowerBlue);

    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, BlackAndWhiteEffect);
    //spriteBatch.Begin();

    spriteBatch.Draw(Image, GraphicsDevice.Viewport.Bounds, Color.White);

    spriteBatch.End();

    base.Draw(gameTime);
}

Here is the result of the code executing in monogame:

And here is the result from an identical project created in XNA (except for ps_2_0 in the shader, as mentioned before):

Would appreciate any help. I can upload both solution files if needed.


texts:
I need to implement voice recognition in my game, the target is that the user speaks into the microphone and the game responds accordingly to some commands.

What libraries could help me with such task? I need them for C++ and as lightweight as possible to plug into the game(it will be used in mobile games).

An ideal usage would be having it capture input sound or receiving the audio samples, and outputting strings with the recognized text.

Thanks


texts: Instantiated prefabs dont trigger ontriggerEnter while prefabs created not on runtime, do

texts:
I am new to unity and trying to make a bouble trouble game. I have enemy prefabs with BoxCollider with is triggered checked. I also have a shooting script. when I am trying to instantiate the enemy prefabs on runtime, they dont seem to trigger the OnTriggerEnter function, but if I am placing an Enemy prefab not ingame, it does trigger the funtion. I have no idea why.
The on run-time instantiate:
public class CreateBalls : MonoBehaviour
{
    public Rigidbody prefab;
    public Transform position1;

    void Awake()
    {

        for (int i = 0; i < 1; i++)
        {
            float random = Random.Range(-45.08f, 44.41f);
            Vector3 vec = new Vector3(random, position1.position.y, position1.position.z);
            Rigidbody ball= Instantiate(prefab, vec, position1.rotation) as Rigidbody;

        }
    }
}

The funtion not being called:
public class DestroyBalls : MonoBehaviour
{
    public Rigidbody potion;
    public Transform posToSpawn;

    private void OnTriggerEnter(Collider other)
    {
        if (this.gameObject.tag == "Enemy"&& other.gameObject.tag=="Bullet")
        {
           //a code not relevent
        }
    }
}

Any idea of why the funtion isnt being called? the bullets are tagged "Bullet" and the Enemies are tagged "Enemy"

Update:
The funtion is triggered when colliding with another Enemy tagged, but not being trigged after collision with anyother tagged object
Also, I have another component on the Enemy Prefab, which also instantiates enemies on run-time and these trigger the function perfectly fine. very wierd.
the code:
public Rigidbody ballToSpawn;
    public Transform spawnPoint;

    private void OnTriggerEnter(Collider other)
    {
        if (this.gameObject.tag == "Enemy" && other.gameObject.tag == "Bullet")
        {
            if (this.gameObject.GetComponent<Size>().size > 1)
            {
                Rigidbody small;

                for (int i = 0,y=-1 ; i < 2; i++,y+=2)
                {
                    Vector3 vec = new Vector3(spawnPoint.position.x+y, spawnPoint.position.y, spawnPoint.position.z);
                    small = Instantiate(ballToSpawn, vec, spawnPoint.rotation) as Rigidbody;
                    small.gameObject.transform.localScale = new Vector3(1, 1, 0);
                    small.gameObject.GetComponent<AutoMoveForBall>().GoToX = this.gameObject.GetComponent<AutoMoveForBall>().GoToX;
                    small.gameObject.GetComponent<AutoMoveForBall>().GoToY = this.gameObject.GetComponent<AutoMoveForBall>().GoToY;
                    small.gameObject.GetComponent<Size>().size = this.gameObject.GetComponent<Size>().size - 1;
                }
            }
        }
    }


texts: Rotating certain particles in a particle system in Unity

texts:
I'm working on a visual effect using particle systems.
I'm trying to rotate newly created particles according to some object's velocity at that time.
Currently, I'm rotating the entire particle system and I use the "Align To Direction" option in the "Shape" options.
It works fine, until I change the velocity of the object - then it rotates every existing particle too.
How can I rotate particles when they are created?


texts:
I'm currently developing a HTML5 Canvas Multiplayer Game using NodeJS and Socket.IO. My current setup using a logic loop on the NodeJS Server-end and sending update information to all Clients in this loop 60x a second. For obvious reasons, this isn't feasible, and even with one player, it doesn't work as I'd like it to.

I'm not a networking genius nor am I an experienced Game Dev, but is there any way for Node and my Client(s) to "share" variables so that I'd have no need to send packets like this? Or any way in which I could improve my current situation?

Current workflow:

Client sends keypress action to the Server via a packet
Server adds it to a queue and in the Logic loop will calculate movement and update the server-side Player Entity accordingly
Game loop also sends these updates to all other Players in the same Socket.IO Room at 60x a second
Client takes their finger off the movement key(s) and sends this action to the server
Logic loop removes the movement from the queue

Thanks in advance, please let me know if there is anymore information you'd need


texts:
I have a 2D grid based movement. To move, I stop key inputs until the character has reached a tile. Because of this, if you make a new directional input midway from one tile to another tile, nothing will happen as the unit has not reached the tile yet.

This seems like a fundamental challenge for grid based movement and I am wondering how people generally handle it, if they handle it at all.

One solution I had was to make the tile sizes smaller (From 32x32 to 16x16) so that the distance between each tile was smaller, but I don't really want to use 16x16.

Thanks


texts: What's a good way to store a series of interconnected pipe and tank objects?

texts:
I am working on a puzzle game with a 6 by 6 grid of storage tanks that are connected to up to 4 tanks adjacent to them via pipes. The gameplay is concerned with combining what's in a tank with an adjacent tank via the pipe than interconnects them.

Right now I store the tanks in a 6x6 array, vertical pipes in a 5x6 array, and horizontal pipes in a 6x5 array. Each tank has a reference to the object that contains both tanks and pipes and when a pipe needs to be animated filling with liquid, the selected tank just calls a method on the container object telling it to animate the pipes it is connected to (subtract 1 from row or column to find connected pipes).

This feels like the wrong way of doing it, as I've also considered just giving each tank references to the pipes connected to it to access directly.


texts: Finding the nearest object, considering obstacles

texts:
For the purposes of this question, we'll assume it involves a Janitor assigned to clean up trash in a building.  Given that it is a building, it is safe to assume there are one or more rooms, walls, etceteras that act as physical obstacles.

It's time for the janitor to earn his paycheck, and he heads to the nearest piece of trash to clean up.  We can resolve this in two ways:

The cheap way.  Simply do a distance check and head to the nearest.
The expensive way, Path-find to pieces of trash and pick the one with the easiest/shortest route.

Now, (1) is cheap computationally but can give false results.  A piece of trash could be on the other side of a wall but only 3 "squares" away - it'll actually take the janitor a lot more time to get there then say, a piece of trash in the same corridor 5-squares away.

(2) would give more accurate results, but requires a metric-ton more computation.

Are there better approaches to "nearest thing", or would you just have the janitor wander around on a pre-set route that covered "as much as possible" and just have him clean up as he goes?


texts: Examples of RESTful Web Services for Browser Games

texts:
Can anyone point me towards examples of Browser Games / Browser Game Sites that use RESTful web services?

I have been convinced time and again that building web sites using RESTful principles is a good idea. And I agree.  But I just can't wrap my head around what RESTful means when the service you're providing is just a single (or a few) games.

Any ideas or thoughts would be nice, but I'd also love to see some solid examples.


texts:
I am really frustrated because my cbufer isn't updating.
This is my VS:

cbuffer MatrixBuffer: register(b0)
{
float4x4 worldViewProj;

};

struct VertexIn
{
float4 Pos : POSITION;
float4 Color: COLOR;
};

struct PixelIn
{
float4 PosH : SV_POSITION;
float4 Color: COLOR;
};

PixelIn VS (VertexIn vin)
{
PixelIn vout;

vin.Pos.w = 1.0f;

vout.PosH = mul(vin.Pos, worldViewProj);

vout.Color = vin.Color;

return vout;
}

PixelIn VS1(VertexIn vin)
{
PixelIn vout;

vin.Pos.w = 1.0f;
vout.PosH = vin.Pos;

vout.Color = vin.Color;

return vout;
}

When using VS1 it draws correctly, but when using VS it doesn't draw anything?

Here is my CBUFFER update code

bool Game::UpdateShaders()
{
    HRESULT result;
    D3D11_MAPPED_SUBRESOURCE mappedResource;
    MatrixBufferType* dataPtr;

    worldViewProjM = worldM * viewM * projM;
    worldViewProjM = XMMatrixTranspose(worldViewProjM);
    result = md3dDeviceContext->Map(mMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
    if (FAILED(result))
    {
        MessageBoxW(mMainWnd, L"FAOE:", 0, 0);
        return false;
    }

    dataPtr = (MatrixBufferType*)mappedResource.pData;

    dataPtr->worldViewProj = worldViewProjM;

    md3dDeviceContext->Unmap(mMatrixBuffer, 0);

    int NBuffers = 0;

    md3dDeviceContext->VSSetConstantBuffers(0, 1, &mMatrixBuffer);
    //md3dDeviceContext->PSSetConstantBuffers(0, 1, &mMatrixBuffer);

    return true;
}

Here is my MATRIXBUFFERTYPE struct:

struct MatrixBufferType
{
        XMMATRIX worldViewProj;
};

This is called after I clear my depth stencil view and render target view.
Does somebody know why my CBUFFER isn't updating?

Thanks in advance.


texts: Can I use a shader with 2 different textures in Cocos2D (x)?

texts:
We are evaluating a variety of different graphic engines for use in our game and we want to be able to use 2 different textures for many of our sprite maps. One sprite map would be the standard RGBA values and the other sprite map would contain normal data for these sprites. To be clear, these are not 3D models. The normal map would just help the flat 2D sprites better react to lighting.

I've done this exact thing in OpenGL ES 2.0 and I imagine the shader code would work in Cocos2D, but I'm wondering how I go about doing this in Cocos2D? I know you can assign shaders to sprites, but how would I specify a secondary texture?


texts: What are normal, tangent and binormal vectors and how are they used?

texts:
I would like to find out the following information:

What are they?
Example usage in game development (the area they are used in)

About the following vector types:

Normal
Tangent
Binormal

A simple game development centric explanation would suffice.


texts:
I plan on creating my own kill cam system for a sandbox tool set.  After thinking about the mechanics of the kill cam itself, however, I'm quite lost.  I'm trying to recreate the ones commonly seen in call of duty games that show, from the view of the killer, the actual killing scene.

My Thoughts:

-I can't just keep in memory when people kill others because I wouldn't know when to start the 'recording process'.  There is on way for me to accurately determine when somebody is 'about' to kill someone.

-My only real idea so far is to have a complete duplicate of everything loaded off to the side copying all the movement from the original world but with a 10 second delay.  That way, all the kill cams would be 10 seconds long and the persons camera would just be moved to the second world of their killer.

My Questions:

Is there already an accepted way to do this?  Does anybody have any good ideas for something like this?  Thanks if you can!


texts: How to get x in radius percentage value?

texts:
How to find the percentage value from A to B when I know the X value in between these two points?

I created this picture to kind of illustrate what I mean better.

I wrote this function which gets the percentage, but how do I also include the center offset?

private float GetPercentage(Vector2 point, float radiusOffset, float centerOffset)
{
    float radius = Math.Min(circle.rect.width / 2f, circle.rect.height / 2f);

    radius *= radiusOffset;

    return 1f - (Math.Max(Math.Abs(point.x), Math.Abs(point.y)) / radius);
}

The radius offset is from 0-1, 0 being the 0,0 position and 1 full radius. The center offset is from 1-0, 1 being the 0,0 position and 0 being the radius border.


texts: Unity - How can I make my player's gun point at the cursor, not the player itself?

texts:
I'm making a 2D top-down shooter in unity. Currently, I'm using the code below to point my player towards my cursor at all times, this works but isn't exactly what I want.

//Find the mouse position on the camera view
Vector3 mousePoint = theCamera.ScreenToWorldPoint(Input.mousePosition);

//Find how the mouse relates to the object's position
Vector3 difference = mousePoint - transform.position;
difference.Normalize();

//Find wanted angle of rotation
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
Quaternion newRotation = Quaternion.Euler(new Vector3(0.0f, 0.0f, rotZ + adjustmentAngle));

//Apply wanted angle of rotation
transform.rotation = Quaternion.Lerp(transform.rotation, newRotation, Time.deltaTime * smoothing);

While this works, my player's gun isn't in the centre of my player so when the gun fires it actually skims past the cursor missing slightly.

How can I get my player to rotate so his gun is what points towards the cursor rather than himself? I have a child GameObject at the end of the barrel of his gun used to Raycast and stuff which I figure can be used?


texts:
The faster an object goes, the slower it will accelerate, going from 0 to 50 takes a lot less time then going from 50 to 100,

How do I calculate that, though?

EDIT: Extra details,

This specific scenario is about a space ship, here is the code I'm using for giving it a constant acceleration, which I'd like to rewrite so that the faster it goes, the slower it accelerates.

EDIT2: Thanks to Sam Hocevar the code I showed was flawed, I've updated the code.

var dx = this.x - this.destination.x,
    dy = this.y - this.destination.y,
    r = Math.atan2(dx, dy) * -1,

this.speed += this.acc;
if(this.speed > this.maxSpeed){ this.speed == this.maxSpeed; }

this.x = Math.sin(r) * this.speed + this.x;
this.y = (Math.cos(r) * this.speed * -1) + this.y;

Old code.

this.sx += (this.destination.x > this.x) ? this.acc : -this.acc;
this.sy += (this.destination.y > this.y) ? this.acc : -this.acc;

if(this.sx > this.maxSpeed){ this.sx = this.maxSpeed; }
if(this.sx < -this.maxSpeed){ this.sx = -this.maxSpeed; }
if(this.sy > this.maxSpeed){ this.sy = this.maxSpeed; }
if(this.sy < -this.maxSpeed){ this.sy = -this.maxSpeed; }

this.x += this.sx;
this.y += this.sy;


texts: How to limit velocity of object on touchDragged event?

texts:
I am using the current code to handle the movement of the player ship in my libGDX game:

if (playerShipTouched)
{
  position.x = screenX - touchOffset;

  // limit movement to screen bounds
  if (position.x < 0)
  {
    position.x = 0;
  }
  else if (position.x > (globals.VIRTUAL_WIDTH - playerShipSprite.getWidth()))
  {
    position.x = globals.VIRTUAL_WIDTH - playerShipSprite.getWidth();
  }
}

This gives me 1:1 screen to touch movement of the ship. However, I would prefer to limit the movement velocity so the ship can't just skip to the other end of the screen if the user moves their finger fast enough. I tried something like this:

position.x = position.x + Math.signum(screenX - position.x) * 800 * Gdx.graphics.getDeltaTime();

The movement is correctly restricted, but is jerky. Any ideas?

edit

Additional overridden touch methods:

@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button)
{
    touchPos.x = screenX;
    touchPos.y = screenY;
    touchPos.z = 0;

    camera.unproject(touchPos, globals.resizeViewport.x, globals.resizeViewport.y,
            globals.resizeViewport.width, globals.resizeViewport.height);

    // Did the player touch the ship?
    touchRect.x = position.x;
    touchRect.y = position.y;

    if (touchRect.contains(screenX, screenY))
    {
        playerShipTouched = true;
        touchOffset = screenX - position.x;
    }
    return false;
}

@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button)
{
    playerShipTouched = false;
    return false;
}


texts: I decided to make my application for free but introduce donation button. For this I would use paypal. What are the advantages of this monetization model and what are other models to consider? My application is kinda educational so that's why I am thinking to make it free as I will try to send it to schools.


texts: How to get a reflex edge on a non-convex mesh

texts: I am trying to implement a convex decomposition and I need to find the convex vertex on a mesh. Is there a algorithm that I can use to find the convex vertex on a mesh.


texts: Is precomputed pathfinding still relevant?

texts:
Context

Old Lucas Arts (ScummVM era) point and click graphic adventure games used precomputed pathfinding. Here's a rough outline of the technique.

Step 1

The floor in each room was divided into what they called "walk boxes", which were pretty much equivalent to nodes in a navigation mesh, but limited to trapezoid shapes. E.g:

 ______ _____ _________ _____
\   A  |  B  |    C    |  D   \
 \_____|     |         |_______\
       |_____|         |
             |_________|

Step 2

An offline algorithm (e.g. Dijkstra or A*) would calculate the shortest path between each and every pair of nodes, and store the first step of the path in a 2D matrix, indexed in each dimension by the starting and ending node used. E.g. using the walk boxes above:

      ___ ___ ___ ___
     | A | B | C | D | <- Start Node
  ___|___|___|___|___|
 | A | A | A | B | C |  ---
 |___|___|___|___|___|     |
 | B | B | B | B | C |     |
 |___|___|___|___|___|     |-- Next node in shortest path
 | C | B | C | C | C |     |   from Start to End
 |___|___|___|___|___|     |
 | D | B | C | D | D |  ---
 |___|___|___|___|___|
   ^
   |
End Node

As you may guess, the memory requirements increase quickly as the number of nodes increase (N^2). Since a short would usually be large enough to store each entry in the matrix, with a complex map of 300 nodes that would result in storing an extra:

300^2 * sizeof(short) = 176 kilobytes

Step 3

On the other hand, calculating the shortest path between two nodes was extremely fast and trivial, just a series of lookups into the matrix. Something like:

// Find shortest path from Start to End
Path = {Start}
Current = Start
WHILE Current != End
    Current = LookUp[Current, End]
    Path.Add(Current)
ENDWHILE

Applying this simple algorithm to find the shortest path from C to A returns:

1) Path = { C }, Current = C
2) Path = { C, B }, Current = B
3) Path = { C, B, A }, Current = A, Exit

Question

I'm suspecting that with today's powerful hardware, coupled with the memory requirements of doing this for every level, any benefits this technique once had are now outweighted by simply performing an A* at runtime.

I've also heard that nowadays memory lookups might even be slower than general computation, which is why creating sine and cosine look up tables is not as popular anymore.

But I must admit I'm not yet too knowledgeable on these matters of low-level hardware efficiency though, so I'm taking this chance to ask the opinion of those more familiar with the subject.

On my engine I also needed the ability to dynamically add and remove nodes to the graph at runtime (see this) so the precomputed route only made things more complicated, so I scrapped it (not to mention my runtime A* solution was already running perfectly). Still, I was left wondering...

Bottom line, is this technique still relevant nowadays in any scenario?


texts: Working but flawed bullet spread (vector math)

texts:
I'm trying to implement random bullet spread into my game, and I've managed something that works, but is consistently flawed.
The spread doesn't vary depending on the distance the mouse is from the player, it does however vary depending on the combined mouse position, aka top left is the maximum amount of spread (20 degrees I think, as I have my GetSpread( ) return 10) and top right is no spread at all.

void Player::StartShooting( float mouse_x, float mouse_y )
{
    for( unsigned int i = 0; i < activeFirearm.bullet.size( ); i++ )
    {
        if( activeFirearm.bullet[i].GetActive( ) == false )
        {
            activeFirearm.bullet[i].SetOrigin( GetPosition( ).x + GetHitbox( ).x / 2,
                                               GetPosition( ).y + GetHitbox( ).y / 2 );
            sf::Vector2f projEndNorm = vectorNormal( { mouse_x - activeFirearm.bullet[i].GetOrigin( ).x,
                                                       mouse_y - activeFirearm.bullet[i].GetOrigin( ).y } );
            float ratio = tan( activeFirearm.GetSpread( ) * 3.141592 / 180 );
            float random = static_cast<float>( randomNumberGenerator( static_cast< int >( ratio * -100000 ),
                                                                      static_cast< int >( ratio * 100000 ) ) ) / 100000.f;

            //projEndNorm.x += random;
            //projEndNorm.y += random;
            projEndNorm = vectorNormal( { projEndNorm.x + random,
                                          projEndNorm.y - random } );
            if( projEndNorm.x == 0 &&
                projEndNorm.y == 0 )
            {
                if( mouse_x < GetPosition( ).x + GetHitbox( ).x / 2 &&
                    mouse_y == GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = -0.999f;
                    projEndNorm.y = -0.001f;
                }
                else if( mouse_x > GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y == GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = 0.999f;
                    projEndNorm.y = 0.001f;
                }
                else if( mouse_x == GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y < GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = -0.001f;
                    projEndNorm.y = -0.999f;
                }
                else if( mouse_x == GetPosition( ).x + GetHitbox( ).x / 2 &&
                         mouse_y > GetPosition( ).y + GetHitbox( ).y / 2 )
                {
                    projEndNorm.x = 0.001f;
                    projEndNorm.y = 0.999f;
                }
            }
            activeFirearm.bullet[i].SetPosition( activeFirearm.bullet[i].GetOrigin( ) + projEndNorm );
            activeFirearm.bullet[i].SetVelocity( vectorNormal( activeFirearm.bullet[i].GetPosition( ) - activeFirearm.bullet[i].GetOrigin( ) ).x * activeFirearm.GetInitialVelocity( ),
                                                 vectorNormal( activeFirearm.bullet[i].GetPosition( ) - activeFirearm.bullet[i].GetOrigin( ) ).y * activeFirearm.GetInitialVelocity( ) );
            activeFirearm.bullet[i].SetActive( true );
            activeFirearm.bullet[i].SetStep( 0 );
            break;
        }
    }
}

I'm not sure what I should do to make it work.


texts:
I have an application where I have a 3d collision voxel space (passable or non-passable at each point) and I want to plot a short unobstructed path between two points.  There are no gravity constraints, so the shortest unobstructed path is a straight line between two points.

I know that A* can be generalized to 3-space, but this is a bit slow for my purposes.  In my particular application, the collision space changes infrequently and there is a finite number of permutations, so what I'd like to do is automatically pre-process the voxel and generate a set of 'waypoints' with the following properties:

Each waypoint has a set of connected waypoints; the straight line path between any two connected waypoints is unobstructed.
For every passable point in space, there is an unobstructed straight line path to at least one waypoint.  I'll probably store a lookup table to make this easy to find.
Ideally, the waypoints are generated so that the paths are still reasonably close to optimal, but I don't need to find the absolute optimal path.

If it's relevant, my collision space mainly consists of a few large contiguous 'blobs'; all empty spaces should be accessible, but the 'blobs' do have concave areas and holes allowing passage.  Also, since I'm precomputing this, I can live with relatively long running times (though I'd prefer an upper bound of minutes, rather than hours or days.)

Is there a well-known algorithm for doing this?  My first thought is some sort of repeated A* for random point pairs and looking for 'choke points' (regions through which a lot of paths go), but I'm guessing this is a problem that has already been studied.


texts: 2D Rope with verlet and Semi-implicit Euler integration

texts:
I'm trying to create 2D rope. Chain based solution is not working pretty well, so I'm looking for new approach. Every good looking rope implementation is based on verlet integration, but this method is not good for rigid body based system.
Is there any save method to combine these methods - ropes with verlet and rigid bodies with Euler?
Basic requirement for method I'm looking for is proper (or good enough) collision detection for both of simulated bodies.


texts: How can I check the multisample quality level count?

texts:
I can check it with ID3D11Device::CheckMultisampleQualityLevels(). So to use it I need to create the device: D3D11CreateDeviceAndSwapChain(). To call it I need to fill the DXGI_SWAP_CHAIN_DESC which, among others, specifies... the multisample quality level. Vicious circle.

Do I have to split D3D11CreateDeviceAndSwapChain() into creating the device and the swap chain separately? Or what?


texts:
I am planning on making a game in c#. It will be a turn based, space exploration game. I want the turns of the different players to be able to happen at the same time though. I have been researching for what type of server to use for hours and I cannot find one that works the way I want it to.

I have heard of listening servers, dedicated servers, and peer to peer.
-the peer to peer I have heard are almost gone, and obsolete for the most part
-dedicated servers are expensive, in terms of resources (lots of data)
-and there are listening servers which seem to be the best option.

Also is there a way for the server to run under the same exe as the client? like how minecraft does it? where each game is internally run in a server though 2 windows do not appear?

EDIT:

I know that I need to create my own server, and I am pretty sure I can do it in c# ( i made a small client and server that doesn't do much but it works) but I want to know what structure of server I should create


texts: LibGDX/Java - Trying to find the vector from one object to another

texts:
I want to add springs in my game that work like the ones in sonic - i.e. if you can't get over an obstacle you have to hit a spring which sends the main character flying towards another spring that gets him over that obstacle. I drew a little diagram below to demonstrate what I mean (yellow arrows represent the direction the player will go towards and the red - are the springs).

In my Spring class I have created a method:

//The detection area (blue rectangle in the diagram)
public Rectangle broadPhaseDetection() {
        broadPhaseRectangle = new Rectangle(getxPos() - broadPhaseLength, getyPos(),
        broadPhaseLength, broadPhaseLength);
        return broadPhaseRectangle;
    }

If the Player collides with a Spring, I check to see if there's ANOTHER Spring within the blue area and if there is - calculate the vector that takes you towards that spring and send the player in that direction.

This seems like a very simple concept which has probably been done loads of times before, but I couldn't find any good examples online for some reason. Does anybody know how I can get the vector I need?

Any insight is highly appreciated, thanks.


texts: How can I increase text using scale and keep the text smooth in libgdx?

texts:
I found that I can use DistanceFieldShader from here and found an example
but I couldn't make it work. First my whole screen becomes white, all the other actors that I have on screen disappears. second, the text that supposed to be smooth becomes to be black squares. whats wrong with my code? Or maybe someone can give me an example that suits my needs.

This class represents score in the game. (Maybe this should be actor and needs to be Label)

public class Score extends Actor {
    private int scoreInt;
    private BitmapFont scoreBitmapFont;
    private int x, y;
    private DistanceFieldShader distanceFieldShader;

    private Texture distanceFieldTexture;
    private BitmapFont distanceFieldFont;

    float scale = 1.5f;
    float smoothing;

    public Score(int x, int y) {
        this.x = x;
        this.y = y;
        scoreInt = 0;
        scoreBitmapFont = new BitmapFont();
        scoreBitmapFont.setColor(Color.BLACK);
        scoreBitmapFont.scale(scale);

        distanceFieldTexture = new Texture(Gdx.files.internal("default.png"), true);
        distanceFieldFont = new BitmapFont(Gdx.files.internal("default.fnt"), new TextureRegion(
                distanceFieldTexture), true);
        distanceFieldFont.setColor(Color.BLACK);

        distanceFieldShader = new DistanceFieldShader();

        // set filters for each page
        Texture.TextureFilter minFilter = Texture.TextureFilter.MipMapLinearNearest;
        Texture.TextureFilter magFilter = Texture.TextureFilter.Linear;

       scoreBitmapFont.getRegion().getTexture().setFilter(Texture.TextureFilter.MipMapLinearNearest, Texture.TextureFilter.Linear);
    }

    public void inc(int inc) {
        scoreInt = scoreInt + inc;
        if (scoreInt < 0) scoreInt = 0;
    }

    @Override
    public void draw(Batch batch, float alpha) {
        String scoreStr = String.format("Score: %d", scoreInt);
        smoothing = scoreBitmapFont.getBounds(scoreStr).width;
        batch.setShader(distanceFieldShader);
        scoreBitmapFont.draw(batch, scoreStr, x, y/* + scale * getBaselineShift(scoreBitmapFont)*/);
        distanceFieldShader.setSmoothing(smoothing / scale);

//        y += scoreBitmapFont.getLineHeight();
    }

    public int getScoreValue() {
        return scoreInt;
    }

    private float getBaselineShift(BitmapFont font) {
        if (font == distanceFieldFont) {
            // We set -8 paddingAdvanceY in Hiero to compensate for 4 padding on each side.
            // Unfortunately the padding affects the baseline inside the font description.
            return -8;
        } else {
            return 0;
        }
    }
}


texts: Shadowmapping with multiple light sources

texts:
I am using shadow-mapping to add shadows to my world.
Currently, I use one lightsource, which means I have to draw my world twice: once in the lightview, once in the camera view.
I want to add more light sources to the world, I want at least 2 sources, maybe 3 or 4.
My world geometry is large, roughly 1M triangles, so drawing them comes at a large cost.
Are there any shortcuts I can take to avoid drawing the geometry for every light source?
Would it be possible to write to multiple depth textures in a single pass? E.g. pass several lightview matrices to a vertex shader and somehow write several framebuffers in one go?
I am using OpenGL core profile.
What I've tried: I looked at Multiple Render Targets, but it seems that every attached buffer will share the same vertex transformation, which would not help in my situation: every light view has a different transformation.


texts: Multithreading MMO Server. A thread per area OK?

texts:
As a personal project, I'm setting up a MMO, and writing the server in C#/.NET Core.

As of now my architecture is as follows: The world exists of different areas ( you can go from area to area trough portals ). An area is called a 'room' on my server. Each room has it's own list of clients ( players, each with their TCP stream ).

Now I was wondering if it was ok that I run each room on it's own thread. Each room will manage it's own update cycle ( game loop / room ), as it's independant of other rooms.

My worry is that as the game grows, I will get lots of areas and that a thread per area isn't that great of an idea.

So my question is: Am I doing something wrong or non-benificial in the future ? Am I better off having 1 thread for the game logic for all the rooms ? Or is it ok to have a thread per room ?


texts:
I am learning the basics of iPhone frame animation.  I have code that loops through 15 images to do an animation:

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(40, 40, 95, 70)];
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    for(int i = 1; i <=15; i++){
        UIImage *img = [UIImage imageNamed:[NSString stringWithFormat:@"someImage_%02d", i]];
        [arr addObject:img];
    }
    iv.animationImages = arr;
    iv.animationDuration = 1.0 / 2;

    [self.view addSubview:iv];
    [iv startAnimating];
}

I want to load images of Link from a picture I found on the internet.  How can I take this image (available as a png) and load the unique parts of the image?  I have heard of people putting multiple images into a single PNG to improve performance. How do I extract the individual images into an array for use in code like the above?

Please keep in mind this is my first time doing frame animation.  I realize this code can likely be improved.  I'm trying to keep things simple.