texts: QuadTree Checking Collision With Different Levels of Nodes

texts:
I am making a QuadTree for a 2D Platformer. Researched on it and I managed to make a pretty good one where each node stores its 4 SubNode and there's a MAX_OBJECTS for each Node and MAX_LEVELS which represents the amount of Levels my Tree has, with 0 being the root.

So, I get my object and I try to store it into the Deepest Node possible. If I can't, then I'll store it in the Parent Node instead.

Then when I check for Collision, I'll see which Nodes have Possible Collisions with my Object, get the Objects in those Nodes and add it to a List of my Collision Checks.

My problem is this Checking for Collision. I am quite confused.
For example, I have an ObjectA at Level 1 Node and it will collide with objects within its node. I have another ObjectB at Level 0 (Root Node) and it overlaps ObjectA's node so there is a possible Collision.

This is where it gets tricky, just from the paragraph above, I can see that Objects in the Parent Node have a chance to to collide with the Objects in the SubNode. So when I check for the Possible Collisions, do I check the Parent Nodes + SubNodes of my Object's Node...I'm not really sure as to how you choose which node to check.

There will be Nodes of Different Levels won't there?
An Object of Level 1 can have  Collision Checks with Level 0, Level 2, Level 5...etc(or is this wrong). It's hard to grasp what the criteria is of checking a specific node...To put it simply, a Tree has so many different Levels...

For all I know, there might be an ObjectA(x,y) at Level 0 and ObjectB(x,y) at Level5. Completely same coordinates, but different node levels. If I were to check Collisions for ObjectC(x,y) at Level 0, I'd put ObjectA in the List cause same Node, but what about ObjectB whose in a different Level, but same coords.

So just from the above theory/explanation or whatever you may call it.
Can I conclude that the Nodes I check for Collisions should include Nodes from Root til the Node My Object is in + the SubNodes of Node my Object is in.

You might ask why not just store it in the same Level, well I heard from others that it's better if I store those overlapping ones at the parent node and it'd be good if I limit the amount of objects per node. So if the level is full, I need to send it up.

I'm sorry if this might be an easy question, it's just that I've pondered on this for 6 days now but I still can't figure it out. Please help! This is my last hope!


texts: What is the most effective way to work with a friend on the same game?

texts:
We need something where we can check files out, edit them, check them back in and then build from the them.

Something like Google Docs where we can edit the same code at the same time would be a ideal.

We are both using Visual Studio 2010.


texts: Reflections based on distance from plane

texts:
Let's consider, for example, a surface like the volleyball court, we can see that legs and shoes of the players are reflected, with a blur effect, but body and stadium don't (as each object not near to the court).

I've already made a reflection effect, but it works as a specular reflection, and I need to achieve an effect like the photo above. So, I would like to make a reflection that is based on the distance between the object and the plane, in this manner a close object would reflect more than an object that is positioned far away from the plane.

What is the best way to achieve this effect? My first idea was to use the depth value (taken from the reflected camera), and use that value to blend between reflection and court. But I don't know if it's a correct way.

Edit: as rendering engine I use Ogre that already provides a reflections system: reflecting the camera through a plane (obviously I can select the models to draw from the reflected camera). After a render to texture pass I can blend the reflected texture with the original plane. So, if possible, I'm looking for a way that best suits my system.


texts: Rotating plane to be parallel to given normal via change of basis

texts:
I have two planes and their respective normals. I would like to rotate the second plane, planeB, so that it is parallel to the first, planeA.

To do this, I am using a change of basis to rotate each vector of planeB. To create the new axes, I do the following:

cAxis = planeA.normal;
aAxis = planeA.normal parallel to yAxis ? then xAxis else yAxis;
bAxis = aAxis cross cAxis

I create a rotation matrix from these new axes as such:

| aAxis.x  aAxis.y  aAxis.z |
| bAxis.x  bAxis.y  bAxis.z |
| cAxis.x  cAxis.y  cAxis.z |

I then multiply each vector of planeB by the rotation matrix to get their new coordinates. I think that this is the correct method for rotating the plane, but I don't believe the new axes that I am creating are correct. The results are correct when planeA's normal is parallel to the z axis, but not otherwise. Is there a standard formula for creating the new axes?


texts: How to compute the moves amount in a match-3 game?

texts:
I have a match-3 mobile game, similar to these popular games in the store.
Mechanics are different, but the gameplay stays the same:

NxN board
X moves
Y objectives to complete to win
tons of different levels. When you complete a level, you unlock a new one

When you run out of moves, you have to buy moves or try again, so you have to think on each move.
And the problem is in the moves, I'm trying to calculate the amount of moves required for each level. I want it to be be slightly lower than the average, so it takes 3-4 attempts for an average player to complete.
I discovered that "being stuck" 2 or 3 times on a level makes it a lot more fun, than completing levels each time with a single attempt.
My current solution
I have couple hundred players and with them - some statistics.
With each level attempt (lost or won) I save it on my server to use it for calculations:
ID | Level Number | Used Moves | Lost/Won

Then, each week, I compute a sum of attempts on each level, and I do this for all players. Then, I compute a mean average on each level:
avg_lvl_attempts = sum_level_attempts / player_count

So if 3 people took level 10, all of them with 4 attempts, it would be:
avg = (4 + 4 + 4) / 3 = 4

Which means that it takes the players 4 attempts, on average, to complete level 10. Then, based on that, I increase the amount of moves on level 10 by a small amount, so it's a little bit easier for them (because I want to achieve 3 on average). And I do that for each level.
The problem with that solution is that it can produce strange results, for instance if someone had 130 attempts (it happens sometimes).
The question
Is there any algorithm, or mathematical trick to do these kind of things more accurately, like excluding edge cases etc?


texts: Best methodology to prepare 3d models for avatar customization?

texts: I know preparing mount points and the like. But what's the best way to prevent Z fighting with customizations close to moving parts like elbows and knees?


texts:
We have released our new game to a closed alpha group. It's a browser-based MMO RTS, however some aspects of the game are slightly different from the "standards" you'd expect to see in traditional RTS' due to it being persistent, browser-based etc. For this reason, we have a new player tutorial which helps players through some aspects of the game that differ from the "norm", such as the way you acquire territory and the way you move large groups of units.

I think that every game I've played has had a "skip tutorial" option during the tutorial, so we put that option in as well. However, this has now caused us a dilemma: looking at the player stats in our database, there is an almost perfect correlation between those players who have played through the tutorial and have progressed through the game, and those who haven't. Basically, if you don't play the tutorial, you pretty much don't know what to do next and stop playing the game after not doing anything meaningful for a few minutes.

I'm really torn here between "best practice" / user experience (which probably dictates that players should have an option to not play the tutorial), and clear evidence which shows that if players don't play the tutorial, they likely will quit the game early.

Is it reasonable in this situation to "force" players to play the tutorial? I.e., don't give them a "skip tutorial" option? Could we dress it up as "missions", where the first 10 or so missions are compulsory to progress, but actually those "missions" are simply the current tutorial steps?


texts: How can I avoid a stack overflow when recursively checking adjacent game objects?

texts:
I am building a simple game on Unity to learn the system. I am using C#.

The game is a basic "blocks" game, whereby when the player clicks on a block, the block and its neighbours of the same colour all disappear (get destroyed).

My process is this:

To keep a track of which blocks are neighbours of the same colour, on each refresh each block checks their details on the event OnCollisionEnter and adds these collision neighbours to a List of valid neighbouring gameobjects.
When a block is clicked, this list is checked and each neighbour has its own neighbours list checked, after list checking each block is distroyed.

Somehow, this process is causing a StackOverflowException

  StackOverflowException
  UnityEngine.GameObject.GetComponent[setupscript] () (at
  C:/buildslave/unity/build/artifacts/generated/common/runtime/GameObjectBindings.gen.cs:35)
  setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:86)
  setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
  setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
  setupscript.checkNeighbours () (at Assets/scripts/setupscript.cs:87)
  ....

Here is my script, first my List establishment:

 private List<GameObject> neighbours = new List<GameObject>();

Next, here is how the neighbours list is populated:

void OnCollisionEnter (Collision other)
{
    Rigidbody other_rb = other.rigidbody;
    if(rb.velocity.magnitude < 1f && other_rb.velocity.magnitude < 1f
        && other.gameObject.tag == tagName && !neighbours.Contains(other.gameObject)) {
    /***
     * Same tag so add to list of valid neighbours
     ***/
        neighbours.Add(other.gameObject);
    }
}

Now, there are four conditions [above] to check when adding to the list:

Is the current block stationary.
Is the "other" colliding block stationary (so they're at rest next to each other).
do these blocks have the same tag (so they're the same type/colour)
does this block not already exist in this list.

So once all four conditions are met, the block GameObject is added to the List.

( On conditions of OnCollisionExit blocks are removed from the List in a  similar fashion.  )

Now, my CheckNeighbours() script:

public void checkNeighbours(){
    if (neighbours.Count > 0) {
        foreach (GameObject othercube in neighbours) {
            setupscript otherCubeScript = othercube.GetComponent<setupscript>();
            otherCubeScript.checkNeighbours();
        }
    }

    Destroy (gameObject);
}

This should, as far as I understand it, run once through each List element and check that element for any neighbours who match.

As I write this question out I think I'm realising that the issue is that we're in a loop as block 1 references neighbour block 2, which references neighbour block 3, which references neighbour block 1, etc. etc.

But my StackOverflow exception occurs when there are only two blocks, so one refers to the other, refers to the first, etc. But as they should destroy after running the reference, this shouldn't (ideally) be an issue? Do I need to make the checkNeighbour() a Corountine to allow it to not hold up destroying the GameObject?

If this [repetition cycling] is indeed what's going on, what would be the best way of getting each neighbour to be checked only once? Or checking that the GameObject referenced in the List still exists in the game itself?

I have a quick edit here:

foreach (GameObject othercube in neighbours) {
    if (othercube != null){
        setupscript otherCubeScript = othercube.GetComponent<setupscript>();
        otherCubeScript.checkNeighbours();
    }
}

But I'm not sure this will work as I feel this List will purely be a reference rather than the actual GameObject in the level?


texts: How can I use the gap range attribute slider to add/remove gaps between the units?

texts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GenerateStairsUnits : MonoBehaviour
{
    [Header("Stairs Units Prefab")]
    public GameObject stairsUnitsPrefab;
    [Space(5)]
    [Header("Settings")]
    [Range(1, 2000)]
    public int numberOfUnits = 1;
    [Range(10, 100)]
    public int gap = 10;

    private int oldNumberOfUnits = 0;
    private int oldGapValue = 0;
    private List<GameObject> units = new List<GameObject>();
    private GameObject unitsParent;
    private GameObject Unit;

    // Use this for initialization
    void Start ()
    {
        oldNumberOfUnits = numberOfUnits;

        unitsParent = GameObject.Find("Stairs Units");
        for (int i = 0; i < numberOfUnits; i++)
        {
            Unit = Instantiate(stairsUnitsPrefab, unitsParent.transform);
            Unit.transform.localPosition = (i + 1f) * new Vector3(gap, 0, 0);
            Unit.name = "Stairs " + i.ToString();
            Unit.tag = "Unit";
            units.Add(Unit);
        }
    }

    private void Update()
    {
        if(gap > oldGapValue)
        {
            for(int i = 0; i < numberOfUnits; i++)
            {
                units[i].transform.position = (i + 1f) * new Vector3(gap, 0, 0);
            }

            oldGapValue = gap;
        }

        if (numberOfUnits < oldNumberOfUnits)
        {
            var res = oldNumberOfUnits - numberOfUnits;
            for (int i = 0; i < res; i++)
            {
                Destroy(units[units.Count - 1]);
                units.RemoveAt(units.Count - 1);
            }

            oldNumberOfUnits = numberOfUnits;
        }
        else
        {
            for (int i = oldNumberOfUnits; i < numberOfUnits; i++)
            {
                Unit = Instantiate(stairsUnitsPrefab, unitsParent.transform);
                Unit.name = "Stairs " + i.ToString();
                Unit.transform.localPosition = (i + 1f) * new Vector3(gap, 0, 0);
                units.Add(Unit);
            }

            oldNumberOfUnits = numberOfUnits;
        }
    }
}

I tried inside the Update this :
I want that if I move the gap slider range to the right that it will add more gaps between the existing units and new units if adding new units.
if(gap > oldGapValue)
            {
                for(int i = 0; i < numberOfUnits; i++)
                {
                    units[i].transform.position = (i + 1f) * new Vector3(gap, 0, 0);
                }

                oldGapValue = gap;
            }

but this part of code does nothing it's not adding any gaps and I'm not sure also how to remove gaps if moving the rang slider to the left for example if the gap value is 50 and I removed it to the left and now the gap value is 23 then the gaps should be now 23 between the existing units and if adding new units then add 23 gap between each new unit.


texts: Cannot use sprite sheet to add texture to RawImage?

texts:
I am basically trying to recreate this sample image

from this sprite sheet

(Source)

I split the sprite sheet in the sprite editor of unity, now I want to use the top left texture for ground. But when I add UI->Raw Image, I cannot add the split texture to the texture source. How do I add it as a texture? In the source it does not show the split assets but the full sprite sheet.

How do I add this one single texture? That I have already split in the unity sprite editor.


texts: I have to do a project for my math class in which I choose a topic and connect concepts we learned to it. I chose video games, and I was hoping someone could help me. Possible concepts: Quadratics, statistics, probability, vectors, trigonometry, etc. Or, if this is a terrible topic to write a minimum of 6 pages on, please tell me. P.S. I know absolutely nothing about code, programming, any of that.


texts: Unity 2D UI Scrollview Stretch settings not staying

texts:
So I'm trying to make a Scrollviewer and inside that will be aload of boxes stacked on top of each other (the boxes have information in them - like the boxes in this screenshot here but they will always be the same size).

My problem is that whenever (in Unity's UI) I set where the Text UIs (in-game) should be, they will revert to some random place whenever I start the game.

For example: I set the X: 0 Y: 50, start the game changes are made and it looks right. But when I exit game mode the X: Some random number between 0-1000 Y: Also the same, some random number between 0-100.

Anyone know why this is happening?


texts: Best practice for handling "dead" objects and their particles

texts:
I'm developing a side-scrolling run'n'gun game (but with planes! :P). I'm an experienced coder, but new to game development.

When an enemy plane collides with a friendly missile, I start an explosion particle emitter on the enemy plane. The emitter is accessible as a private property of the plane object and its flow is controlled by the plane's update function (which is called from the game update function). The particle emitter's "render-update" method is called directly from the game renderer class.

I don't like these things:

When the enemy plane is destroyed, I can't simply remove the object from my game's "enemyPlanes" array, as this would result in the particle sequence not completing itself.
If I continue with this scheme, I have a very complex if statement in every execution of the render function, that will
(a) check if the enemy is not shot down (b) check if the emitter is active (c) remove the plane as well as the emitter (if both previous conditions are met)
The particle system is both accessed from the GameRenderer and from the plane object. I mean, I call something like plane.getParticleEmitter().update(blabla).

Is there a better way to do this?

EDIT: The library I'm using is libgdx (Java).


texts:
I am using the Möller-Trumbore method as part of my (still very basic) collision detection system.

The information I'm craving about is the distance from the ray origin and intersection point. The intersection point would be fine too obviously.

I probably wrongly assumed t in the code below is actually the distance from the ray origin to the intersection point. If it actually is, then I don't know what's wrong with my code.

I have got a simulation with a mesh and "bullets", sometimes firing a collision acurately, and sometimes not (bullets passing thru mesh, or firing a colision before it actually should hit).

bool rayTriangleIntersect(const XMFLOAT3 &orig, const XMFLOAT3 &dir, const XMFLOAT3 &v0, const XMFLOAT3 &v1, const XMFLOAT3 &v2, float &t, float &u, float &v) {
// http://www.scratchapixel.com/lessons/3d-basic-rendering/ray-tracing-rendering-a-triangle/moller-trumbore-ray-triangle-intersection

    float kEpsilon = 0.000001f;
    XMFLOAT3 v0v1 = v1 - v0;
    XMFLOAT3 v0v2 = v2 - v0;
    XMFLOAT3 pvec = XMFLOAT3Cross(dir, v0v2);

    float det = XMFLOAT3Dot(v0v1, pvec);

    if (det < kEpsilon) return false;

    float invDet = 1.0f / det;

    XMFLOAT3 tvec = orig - v0;
    u = XMFLOAT3Dot(tvec, pvec) * invDet;
    if (u < 0 || u > 1) return false;

    XMFLOAT3 qvec = XMFLOAT3Cross(tvec, v0v1);
    v = XMFLOAT3Dot(dir, qvec) * invDet;
    if (v < 0 || u + v > 1) return false;

    t = XMFLOAT3Dot(v0v2, qvec) * invDet;

    return true;
}

Is t really the distance im looking for ? If not how do I get it, or the intersection point. I've heard of baricentric coordinates in a triangle related to u and v - is it the way to go ? If yes I'd be thankful for an example or link related to the Möller-Trumbore method.

Thanks!


texts:
I'm making a racing game akin to F-Zero and Mario Kart 8 with AG mechanics. I currently have a vehicle that is a rigidbody with normal gravity pointing down. True to AG games, I want the gravity to always be applied against the surface of the track (e.g. the player will stick to the surface of an upside-down track). I figure I have two options:

Shoot a raycast below the vehicle that returns the normal of the surface. Apply gravity in the direction of that normal.

Have several "checkpoints" that determine the direction of gravity in that area. When inside, the vehicle is affected by that new gravity.

The issue with option #1 is that it may not work if I wanted ramps or airtime. I could possibly extend the raycast down a lot further to get the normal even in the air, but that could lead to a lot of glitches. There's also the instance that there is no floor below the player. I noticed MK8 even had gliding sections in anti-gravity where you would twist in the air back to normal gravity, which leads me to believe they had something like #2. The issue with #2 however is that it may require a LOT of checkpoints to be manually placed.
I'm wondering if anyone has an idea to some simpler alternative?


texts:
I'm creating a dungeon crawler in C++ and I'm almost done but I need to make the monster move and I'm at the end of my wits.

This is my map:

Char Map[10][10];

and this is how I initialize the positions of the monsters:

void fieldinfo::RandomizeMonsterPositions()
{
    amountEnemies=10;
    srand(time(0));

    for(i=0; i<amountEnemies; i++){
        map[rand()%9][rand()%9] = enemy;
    }
}

fieldinfo is the name of my class.

Each time the player moves, the map is redrawn with the updated players position and I need the monster to move every time the player does (randomly or not I don't care).


texts:
So I have this giant Texture2D (4096 * 4096, don't ask why) and all its data stored in an array of Colors. When I hit left MouseButton I create a blue 64 by 64 square at the cursor's position using the following code.

        int dx = Mouse.GetState().X + (int)camera.Pos.X - graphics.PreferredBackBufferWidth / 2;
        int dy = Mouse.GetState().Y + (int)camera.Pos.Y - graphics.PreferredBackBufferHeight / 2;

        for (int x = dx; x < dx + 64; x++)
        {
            for (int y = dy; y < dy + 64; y++)
            {
                textureData[x + y * texture.Width] = Color.Blue;
            }
        }

        texture.SetData<Color>(lvlData);

Sadly this hangs the program for a split second. So I thought, maybe it's possible to run that piece of code in a different thread.

Is it possible to multi-thread that and if so, how would I go about doing that? Or is it another way to optimize this?

Thanks for any help!


texts: Why doesn't my projectile move in my code?

texts:
My projectile currently has a create event with the following code:

//move towards mouse
move_towards_point(mouse_x,mouse_y,30);

My main character has a glob left button event with the following code:

instance_create(0,0,main_shuriken);

For the output, the shuriken appears at the top left of the screen, and does not move. I've noticed that if I tick off physics world in the "rooms" category, my shuriken seems to work fine.

Why doesn't my projectile move with move_towards_point and create_instance commands?


texts: How do I implement a score database in Android?

texts:
I making a 2D game for Android using OpenGL-ES technology. It is a space shooting game where the player shoots enemy ships.

I want to keep a track of score for the amount of enemy ships destroyed and a record of a local highscore. The score should be incremented whenever an enemy is destroyed. I also want a way of displaying both the current score and highscore on the game screen. I am not familiar with databases at all and I will appreciate a clear answer or a link to a good tutorial for my cause. Thanks.


texts: Preventing boredom creep with hobby projects

texts:
This question is directed more towards the hobbyist developer rather than professional game developers.  Quite frequently while developing a game I'll get bored staring at the same exact game scene after days or weeks of work (while new features only slowly creep in) that I find myself abandoning projects and starting new ones, never really finishing what I've started.

How do you prevent yourself from getting bored with a hobby or side project?  What tips/tricks/techniques do you use to keep yourself motivated to actually finish a project?


texts: How do I detect how much of an object has been "cleaned" by the player?

texts:
I want to let the player wipe some dust off of a book, then start a short animation.

Here's what it looks like:

I'm using a clipping region on the "dusty" book bitmap image to progressively hide the dust as the player mouses over it.

However, I'm stuck with how to detect when the dust is all gone. What's a good way of tracking how much is left?


texts:
I have a code that allows me to move the camera on the x-axis. I need it to move on the y-axis as well as the x.

    using UnityEngine;
using System.Collections;

public class orbit : MonoBehaviour {

    public float turnSpeed = 4.0f;
    public Transform player;

    private Vector3 offset;

    void Start () {
        offset = new Vector3(player.position.x, player.position.y + 8.0f, player.position.z + 7.0f);
    }

    void LateUpdate()
    {
        offset = Quaternion.AngleAxis (Input.GetAxis("Mouse X") * turnSpeed, Vector3.up) * offset;
        transform.position = player.position + offset;
        transform.LookAt(player.position);
    }
}


texts: How far back should I move my camera to fit a given GameObject in frame?

texts:
In Unity with C#, I want to calculate the minimum distance that my perspective camera has to be from a given GameObject (a procedurally generated mesh), so that the object is fully framed by the camera and leaving the least space possible around it in the screen. In other words, fully framed means that there is no part of the object outside the view area.

To make things easier, my camera does not need to rotate or move - it's fully static, with the exception of one axis to zoom in or out in order to frame the target object. So, in fact, we could summarize my problem as a zoom problem (not using FOV to zoom) where I need to frame a procedurally generated mesh whose size varies considerably.

Would anyone be kind enough to point me in the right direction with code snippets, suggestions, etc?


texts: How to handle runtime exceptions that occur on a loading process delegated to newly spawned thread

texts:
I am looking to multi-thread the resource allocation routines (i.e world loading) in my game so that they can occur in the background whilst rendering a loading screen etc... The problem is, I used to have code like this (pseudo)

void foo()
{
    ...
    try
    {
        mWorld = world.create(...)
    } catch(EntityNotFoundException e)
    {
        ...
    }
}

However, now that the world is being loaded on another thread, I need to register a listener that will recieve notification when the world is ready. The problem is that if an exception occurs inside of the newly created thread, I cannot surround it in a try-catch like I have here. How is this problem solved?

I am thinking of having the loading thread interface with a handler that looks like this:

public interface IInitializationMonitor<T> extends IInitializationProgressMonitor
{
void begin();
void completed(T item);
void failed(Throwable error);
}

The problem being that error would need to be tested against multiple times with instanceof, or rethrown inside of a try block. I am curious if there is a more elegant solution...

Thanks.


texts: How can I refactor my code to use fewer singletons?

texts:
I started a component based, networked game (so far only working on the server). I know why singletons can be bad, but I can't think of another way to implement the same thing. So far I have:

A GameState singleton (for managing the global state of the game, i.e. pre-game, running, exiting).
A World singleton, which is the root entity for my entity graph
An EntityFactory
A ComponentFactory
I'm thinking about adding a "MessageDispatcher" so individual components can subscribe to network messages.

The factories do not have state, so I suppose they aren't so bad. However, the others do have global state, which is asking for trouble. How can I refactor my code so it uses fewer singletons?


texts: How do I change a background in movement in Unity?

texts:
I'm developing a game and the background is moving and I wanna change to another image without losing the current speed of the movement.
File:
public class BackgroundMovement : MonoBehaviour

Material material;
Vector2 offset;
GameManager gameManager;
UIManager uiManager;
SpawnManager spawnManager;
public float speed = 0.3f;

private void Awake()
{
    material = GetComponent<Renderer>().material;
    gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
    uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
    spawnManager = GameObject.Find("SpawnManager").GetComponent<SpawnManager>();
}

// Update is called once per frame
void Update()
{
    offset = new Vector2(speed, 0);
    if(gameManager.gameOver == false)
    {
        GameSpeed();
        material.mainTextureOffset += offset * Time.deltaTime;
    }
}

In Unity, I added to the material of the background a shader "unlit/transparent" and added the background in it. The object that this material is in, is a quad.
I tried to change creating a list of background images that I wanted on the game. One of the times I tried, I managed to change the background, but the image didn't move, only the first.
This is the inspector of the background.


texts:
I'm trying to get a grasp on the A* pathfinding algorithm. Using the image I attached.

If the green square represents the start, and red represents the end. wouldn't the algorithm bring me up towards the top of the grid, and then circle me back around, because of the wall?

It would seem the algorithm would never start by moving downward first because the F cost would initially appear more expensive?

Is this a problem with the basic manhattan heuristic? Or am I just missing something?


texts: Controlled rotation on 3D object with mouse movement

texts:
I've a scene with a cube that I can rotate around yaw, pitch and roll. I do this by click the circles and drag the mouse on x/y-axis. I want similar functionality as the Unity rotation tool in editor mode.

My problem is that I can't figure out how to transform the mouse movement so the rotation doesn't become reversed if the cube is rotated 180 degrees in some axis. And how to use correct mouse direction depending on how the cube is rotated.

An image of the cube:

Here I get the mouse input

var direction = InputHandler.GetMouseDirection();
Vector3 diff = new Vector3(direction.X, direction.Y, 0);

if (selectedIntersect == Intersect.Yaw) //green
    block.Rotate2(diff.X, 0, 0);

else if (selectedIntersect == Intersect.Pitch) //blue
    block.Rotate2(0, 0, diff.Y);

else if (selectedIntersect == Intersect.Roll) //red
    block.Rotate2(0, diff.Y, 0);

Here I rotate the cube:

public void Rotate2(float yaw, float pitch, float roll)
{
    Quaternion yawrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Up), MathHelper.ToRadians(yaw));
    Quaternion pitchrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Right), MathHelper.ToRadians(pitch));
    Quaternion rollrotation = Quaternion.CreateFromAxisAngle(
        Vector3.Normalize(this.WorldRotation.Forward), MathHelper.ToRadians(roll));

    Quaternion.Concatenate(ref orientation, ref yawrotation, out orientation);
    Quaternion.Concatenate(ref orientation, ref pitchrotation, out orientation);
    Quaternion.Concatenate(ref orientation, ref rollrotation, out orientation);
}


texts: Maintaining/Updating Large Amount of Player States

texts:
I am developing a fighting game to practice my skills in Java and I would like to know what would be the best approach for figuring out how to easily expand the amount of states a player can have without fiddling with a large amount of code. With a small amount of states such as, inAir, isHurt, isRunning, I can hard code all the conditions I need. Things like 'jumping' can only occur when '!inAir', etc. However, for my project there are a large amount of states I do not know how to organize. Here is a small diagram I redrew:

My approach is to make an enumeration called State and do a switch case between them. I am not sure if this is a good way of doing this and I am trying to learn a better method if there are any.


texts: What is the correct way to make an Installed Build?

texts:
I am trying to use the Automation tool, following the documentation.

To create an Installed Build:
Run the Installed Build Script by invoking the AutomationTool with the
following command line, replacing [PLATFORM] with either Win64 or Mac.
BuildGraph -target="Make Installed Build [PLATFORM]"
-script=Engine/Build/InstalledEngineBuild.xml -clean

However, I am getting this error.

ERROR: Target 'Make Installed Build [Win64]' is not in graph

I am not sure what I should put as the platform.
I searched the config file, but don't see any specified platforms.


texts: Do I need to keep the old ID3D11Device around after querying for ID3D11Device5?

texts:
When attempting to create a directx11 device using the newer ID3D11Device5 interface the compiler complains that ID3D11Device5** is incompatible with ID3D11Device**.

Research via docs.microsoft (RIP msdn) says that the proper way to create a version 5 device is to call QueryInterface on a ID3D11Device to get a ID3D11Device5.

Do I need to keep the pointer to a temporary ID3D11Device around after calling QueryInterface to get a ID3D11Device5 or can I release it as shown below?

#include <array>
#include <vector>

struct AdapterInfo {
    IDXGIAdapter4* adapter = nullptr;
    DXGI_ADAPTER_DESC3 desc{};
    void Release() noexcept {
        if(adapter) {
            adapter->Release();
            adapter = nullptr;
        }
    }
};

//...

struct DeviceInfo {
    D3D_FEATURE_LEVEL highest_supported_feature_level{};
    ID3D11DeviceContext* dx_context = nullptr;
    ID3D11Device5* dx_device = nullptr;
};

//...

DeviceInfo CreateDeviceFromFirstAdapter(const std::vector<AdapterInfo>& adapters) noexcept {
    //Snip Error handling...
    DeviceInfo info{};

    unsigned int device_flags = 0U;
#ifdef _DEBUG
    device_flags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
    device_flags |= D3D11_CREATE_DEVICE_BGRA_SUPPORT;

    std::array feature_levels{
    D3D_FEATURE_LEVEL_12_1,
    D3D_FEATURE_LEVEL_12_0,
    D3D_FEATURE_LEVEL_11_1,
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_3,
    D3D_FEATURE_LEVEL_9_2,
    D3D_FEATURE_LEVEL_9_1,
    };

    auto first_adapter_info = std::begin(adapters);

    //Snip Debug/Logging output...

    auto first_adapter = first_adapter_info->adapter;
    bool has_adapter = first_adapter != nullptr;

    //Create a temporary "old" device
    ID3D11Device* temp_device{};
    auto hr_device = ::D3D11CreateDevice(has_adapter ? first_adapter : nullptr
        , has_adapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE
        , nullptr
        , device_flags
        , feature_levels.data()
        , static_cast<unsigned int>(feature_levels.size())
        , D3D11_SDK_VERSION
        , &temp_device
        , &info.highest_supported_feature_level
        , &info.dx_context);

    //Snip error handling...

    //Ask old device for newer interface.
    auto hr_dxdevice5i = temp_device->QueryInterface(__uuidof(ID3D11Device5), (void**)&info.dx_device);

    //Snip error handling

    //Release old device.
    temp_device->Release();
    temp_device = nullptr;
    return info;
}


texts: Very slow motion smooth rendering - cocos2d-x

texts:
I have a a white circle that I move on a black background very slowly. When I look very carefully, I see that the while moving the edge of the circle is jittering. In my opinion it is because the next row/col of pixels becomes white from black where the circle should be rendered and as the pixel has some width I see some abrupt advance of the edge toward the direction. Ideally, this should not be visible if I would not have pixel discretization. But on the other hand a have a video sample with such a slow motion and my monitor renders it without any jumps on the edge. Hence, I think that it is because of not the fact that pixel have finite sizes but I render wrongly. How I can solve the problem? Any trick, flag?

EDIT: Here is the code I have used:

Sprite* bg = Sprite::create("gfx/letter_background.png");
addChild(bg, 100);
bg->runAction(MoveBy::create(80, Vec2(500, 500)));

wherer the .png I have used is a white circle attached below:

You don't see the image above as it is white :)


texts:
I am trying to setup a system for utilizing uvs to tile a texture and reduce draw calls. I'm using Unity. I create a texture which records the x index of the tile from a tileset into the red channel and try to use it in the shader. Here's the shader code:

        sampler2D _TilemapTex;
        sampler2D _MainTex;
        float _MaxIndex;
        vector _TilesetDim;
        vector _TilemapDim;

        struct vertexInput {
            float4 vertex : POSITION;
            float2 texcoord: TEXCOORD0;
        };

        struct vertexOutput {
            float4 pos : SV_POSITION;
            float2 texcoord: TEXCOORD0;
        };
        vertexOutput vert(vertexInput v)
        {
            vertexOutput output;

            output.pos = UnityObjectToClipPos(v.vertex);
            output.texcoord = v.texcoord;
            return output;
        }
        float4 SampleMap(float2 texcoord) {
            return tex2D(_TilemapTex, texcoord).r * 255;
        }
        float4 GetUv(int index, float2 texcoord) {

            int xpos = index;
            int ypos = _TilesetDim.y - 1;
            float2 uv = float2(xpos/_TilesetDim.x, ypos);
            float xoffset = frac(texcoord.x * _TilemapDim.x) / _TilesetDim.x;
            float yoffset = frac(texcoord.y * _TilemapDim.y) / _TilesetDim.y;
            uv += float2(xoffset, yoffset);
            float4 main = tex2D(_MainTex, uv);
            return main;
        }
        float4 frag(vertexOutput i) : SV_Target
        {
            int index = tex2D(_TilemapTex, i.texcoord).r * 255;

            return GetUv(index, i.texcoord);
        }`

I'm a beginner with shaders so maybe I'm missing something simple. Here's the result:

It looks interesting but I expected it to fill entire tiles.


texts:
I'm having trouble understanding the behaviour of my OpenGL program; and in drawing my Z-Buffer out to the screen.

It will probably be best to just start with code, here is my GLSL shader:

in vec3 vVertex;
smooth out vec4 vSmoothColor;

vec4 vPosition;

uniform mat4 MVP;

void main() {
    vPosition = MVP * vec4(vVertex, 1);

    float z = abs(vPosition.z);
    vSmoothColor = vec4(z, z, z, 1);

    gl_Position = vPosition;
}

My assumption was thus, after reading completely through the OpenGL SuperBible (blue book) and several other resources; I was under the impression the vPosition.z above should be mapped to [-1, 1]; which is then clamped to [0, 1] by the driver (assumedly).

My results were different, I expected; while using vSmoothColor as my output color; and a box moving along the Z axis from 1.f to 100.f, and the perspective matrix set up with a near and far of 1.f and 100.f, that my colors should have corresponded to the following (assuming Z mapped to [0, 1]):

Z Coord.    vSmoothColor
10          0.1, 0.1, 0.1, 1
20          0.2, 0.2, 0.2, 1
...
80          0.8, 0.8, 0.8, 1

Instead, my color values (ie my clipspace coordinate "vPosition.z") corresponded to almost exactly the world space Z coordinate value:

Z Coord.    vSmoothColor
10          10, 10, 10, 1
20          20, 20, 20, 1
...
80          80, 80, 80, 1

If that is the result in vPosition.z (ie the clipspace Z), how does the driver clamp the depth values for representation?

Although its been verified as correct against other implementations, here is my perspective matrix creation code:

inline Matrix4 perspective(float fovy, float aspect, float n, float f) {
const float t = n * tanf(radians(fovy / 2));
const float r = t * aspect;

const float d = f - n;

return Matrix4(
    n / r, 0, 0, 0,
    0, n / t, 0, 0,
    0, 0, -(f + n) / d, -1,
    0, 0, -(f * n * 2) / d, 0
);

}

Ref: http://www.songho.ca/opengl/gl_projectionmatrix.html


texts:
I am using a single VBO to store vertices in the follow format:

v1X, v1Y, v1Z, v1R, v1G, v1B, v2A,
v2X, ...

Vertex positioning is fine, shapes show up where expected, however instead of using the colour provided, all shapes show up red.

The code given below simply draws two triangles to form one square ground shape.

Buffer data preparation method

public void prepare(float[] data) {
    glBindBuffer(GL_ARRAY_BUFFER, vboID);
    FloatBuffer dataBuffer = RenderUtils.fArrayToBuffer(data);
    if(dataLength != data.length) {
        glBufferData(GL_ARRAY_BUFFER, dataBuffer, GL_STATIC_DRAW);
        dataLength = data.length;
    } else {
        glBufferSubData(GL_ARRAY_BUFFER, 0, dataBuffer);
    }
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 7*4, 0);
    glVertexAttribPointer(3, 4, GL_FLOAT, false, 7*4, 3*4);
}

Render code

floorObj.prepare(new float[]{
    -5, 0, -5,   1, 0, 0, 1,
    5, 0, -5,   0, 1, 0, 1,
    -5, 0, 5,   0, 0, 1, 1,

    5, 0, -5,   1, 0, 0, 1,
    5, 0, 5,   0, 1, 0, 1,
    -5, 0, 5,   0, 0, 1, 1,
});
glDrawArrays(GL_TRIANGLES, 0, 6);

Vertex shader

#version 330 core

in vec3 position;
in vec4 i_color;
out vec4 color;

uniform mat4 transform;

void main(){
    gl_Position = transform * vec4(position, 1);
    color = i_color;
}

Fragment shader

#version 330 core

in vec4 color;
out vec4 f_color;

void main(){
    f_color = color;
}

As previously stated, vertex positions work fine, however colour does not.
Just ask if any other code would be useful to determine the problem.

Thanks, - Jasper


texts: How to correclty play the sounds in a 3D enviornment?

texts:
I'm currently working on an XNA game with C#. I've been looking into 3D Sounds recently as this is the next objective on my list. I've found several tutorials online and they don't work to the standards I'm after.

What I've found is that even when the player moves, the sounds don't or when the play looks around the sound doesn't change where it's being projected from in my earphones. (When I look at the sound source, I expect to hear it and in front of me, or if I have my left turned to it, then I expect to hear it on my left etc...)

My Code so far:

//Decleration
    private Cue cue;
    private AudioEmitter emitter = new AudioEmitter();
    private AudioListener listener = new AudioListener();
    private AudioEngine engine;
    private WaveBank waveBank;
    private SoundBank soundBank;
    private float angle = 0;

//load content
        engine = new AudioEngine("Content/music/footsteps/footsteps.xgs");
        waveBank = new WaveBank(engine, "Content/music/footsteps/Wave Bank.xwb");
        soundBank = new SoundBank(engine, "Content/music/footsteps/Sound Bank.xsb");

//update
                listener.Position = Vector3.Zero;
                emitter.Position = new Vector3(10, 10, 10);
                cue.Apply3D(listener, emitter);
                cue = soundBank.GetCue("pl_step1");
                cue.Apply3D(listener, emitter);
                cue.Play();

My code works fine in that the sounds are being played and I can hear them, they are just not realistic and so I'm asking if anyone could help me how I could make the sound move around so that it sounds like it does in real life. (If the source/emitter is on my left, the main sounds should be coming through my left earphone.)


texts: How do I deform a procedurally generated terrain?

texts:
I was looking at this method of generating complex procedural terrains using the GPU: Generating Complex Procedural Terrains Using the GPU.

Has anyone had any luck actually using the algorithm ? If so how do I add the capability to  create holes or caves in the terrain at runtime ?

I would think that all that would be needed is to convey to the GPU some information about where the density function should be ignored so as to create gaps or voids, probably via textures.


texts: 1D Simplex Noise Returns Same Generation

texts:
I've been using 1D Simplex Noise to create a random world surface, and it keeps generating with the same looking surface terrain, with some minor variations.  Here is my sample code-

Tile[][] tiles = new Tile[rows][];
for (int i = 0; i < rows; i++)
{
    tiles[i] = new Tile[cols];
    for (int x = 0; x < cols; x++)
    {
        tiles[i][x] = new Tile(0, new Vector2(x, i), scale);
    }
}

int left = Main.rand.Next(rows / 4, rows / 2);

double seed = Main.rand.NextDouble();
for (int i = 0; i < cols; i++)
{
    int height = left + (int)(Noise.Generate((float)seed) * 10);
    height = (int)MathHelper.Clamp(height, 0, rows - 1);
    tiles[height][i] = new Tile(2, new Vector2(i, height), scale);
    //FillLower just fills everything under the top tile
    FillLower(tiles, height, i, scale);
    seed += .05f;
}

My question is am I doing something wrong with the Simplex Noise method?  How should I generate it so it'll look different?

Images for reference- http://imgur.com/I0g98z8,M61UBfb,tYPflb7


texts:
I am learning AndEngine. I am displaying Hello world using this code:

public class myactivity extends SimpleBaseGameActivity
{

 private final int CAMERA_WIDTH = 320;
 private final int CAMERA_HEIGHT = 480;

 private Camera  m_Camera;
 private Scene  m_Scene;

 private Font  font;
 private Text  text;

 @Override
 public EngineOptions onCreateEngineOptions()
 {
  m_Camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
  EngineOptions en = new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(
    CAMERA_WIDTH, CAMERA_HEIGHT), m_Camera);

  return en;
 }

 @Override
 protected void onCreateResources()
 {
    //determine the density
 WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
 Display display = windowManager.getDefaultDisplay();
 DisplayMetrics displayMetrics = new DisplayMetrics();
 display.getMetrics(displayMetrics);
 int density = (int)(displayMetrics.density);

 //scale desired size 25 by density
     int fontSize = (int) (25 * density);
  font = FontFactory.createFromAsset(this.getFontManager(), this.getTextureManager(), 1024, 1024, this.getAssets(),
    "times.ttf", fontSize, true, android.graphics.Color.BLACK);
  font.load();

//Texture fontTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
//font = new Font(fontTexture, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), fontSize, true, Color.WHITE);
//mEngine.getTextureManager().loadTexture(fontTexture);
//mEngine.getFontManager().loadFont(font);

 }

 @Override
 protected Scene onCreateScene()
 {
  m_Scene = new Scene();
  m_Scene.setBackground(new Background(Color.WHITE));

  text = new Text(0, 0, font, "Hello Android", this.getVertexBufferObjectManager());
  m_Scene.attachChild(text);

  text.setPosition(CAMERA_WIDTH/2 - (text.getWidth()/2), CAMERA_HEIGHT/2 - (text.getHeight()/2));
  return m_Scene;
 }

}

It is displaying the font like this:

As you can see that pixels are stretching and font is looking ugly with too much pixelation. How do I display proper font text with no pixelation or add anti-aliasing to the font?


texts: Adjust bitmaps according to screen ratios on android

texts:
I always thought that pixels were square... it turns out i'm wrong, and I am quite worried by this.
This means that if I draw a circle, it will be round on my screen but it could be an ellipse on someone else's.

My first question is: How common is that? Should I bother to take this in consideration when I draw my graphics/ scale my bitmaps? Or are such weird pixel shapes only used in not-intended-for-gaming screens like hi-tech washing machines?

And my second question is: How can i programmatically get the exact screen size in millimeters (both width and height) of my custom SurfaceView?


texts: I am using OpenGL ES 2.0 to create a 2D game for Android 2.2 and was planning on using LibRocket for the GUI.  Does anyone have any links or knowledge they would share on how to integrate LibRocket with the android platform?  I know that it is a c++ library that would need to go through the NDK, however I rather not change my OpenGL rendering code to the NDK unless I have to.


texts: Why do I get an infinite loop created by a subtraction in Unity3D?

texts:
Does anyone have a solution to this ?
When I do the subtraction , it makes a loop that does not stop.

  if ((lamp.activeSelf == true)&&(test == true))
    {
            money = money - 50;  // <---- This is the problem
            test = false;
    }


texts: Do I need to worry about game name trademark when making a FLOSS game?

texts:
I am planning to do a small game using only FLOSS software (Free Libre and Open Source Software like Godot, Blender, Krita...).

I am going to put it on Github with an MIT license so everyone can download it and modify it.

I wanted the name of my game to be "Seed" but I saw that there was already a game called like that

My question is: do I need to worry about creating an open source game who uses the same name as a proprietary one?


texts:
I'm currently making a 2D topdown dungeon crawler using pure ECS and Data Oriented Design. So I only use structs of arrays for all my components. I have now added tilemap generation, but was wondering what option to pick for tile collision. Should I add the tile collisionbox as an entity or somehow include it in my CollisionSystem?

I am already using collision boxes to check collision for entities. But In my mind, doing so for every tile against every entity might get pretty laggy.

I currently store my terrain data in a linked graph like this:

struct Tile{
    struct Tile* up;
    struct Tile* right;
    struct Tile* down;
    struct Tile* left;

    Position pos;
    bool walkable;
};

I am not using chunks.


texts: iOS Facebook SDK, Games Start Playing post

texts:
im trying to implement a method in my native iOS game the publish a story on face book such as this photo

most games that is integrated with facebook share stories like this in the activity section on the timeline

any good example especially for iOS 6


texts:
I have a widget component inside of my character:

// ABCharacter.h

...
UPROPERTY(VisibleAnywhere, Category = UI)
    class UWidgetComponent* HPBarWidget;
...

// ABCharacter.cpp
...

AABCharacter::AABCharacter()
{
     // Set this character to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
    PrimaryActorTick.bCanEverTick = true;

    HPBarWidget = CreateDefaultSubobject<UWidgetComponent>(TEXT("HPBARWIDGET"));
    HPBarWidget->SetupAttachment(GetMesh());
}

I checked HPBarWidget is null and it wasn't:

if (HPBarWidget == nullptr) {
    UE_LOG(ArenaBattle, Error, TEXT("NULL"));
}

HOWEVER, When I try to get the widget object, it said it's null.

if (HPBarWidget->GetUserWidgetObject() == nullptr) {
    UE_LOG(ArenaBattle, Error, TEXT("NULL"));      // it printed NULL
}

What causes this returns null? I can clearly see I have a WidgetComponent that exists in my character's tree, and HPBarWidget wasn't null too.

I struggled this already hours and couldn't find any related issues. What did I wrong?

Using 4.24.3.


texts: How many Fringe/Base layers in a 2D map editor?

texts:
I'm creating a highly flexible 2D tile-based map editor in XNA to make some of my future projects easier (will work for side-scrollers and top-down games). This editor can work with any sized tile.

This editor is based on a standard system. It has pre-determined layers such as Base, Fringe, and Collision. However, I've run into a bit of a problem. I don't know how many Fringe layers to use.

I'll be working with fairly detailed tilesets and will want enough Fringe layers to be able to render a wide variety of fairly complex scenes (e.g., forests with lots of trees overlapping).

I'm also considering having multiple Base layers to enable things like a player walking both over and under a bridge.

So my question is this: Is there a "right way" to approach this situation, and if so, what is it? Just lots of Fringe and Base layers? If you were a map editor, how would you expect/want this situation to be approached?

Also, while I have this question here, is storing layered maps in 3D arrays a good way to go about things? Meaning the first level is an array of layers, the second is an array of tile columns within the layer, and the third is the array of tile rows within the column.


texts: How do you support different VR platforms?

texts:
I created an Android app for Gear VR in Java (using the GearVR framework) that I now want to port to Unity, so it can also be used for Microsoft's semi-new Mixed Reality headsets (for Windows; not HoloLens, though).

I've never worked with Unity (or C#) before, that's why I have a question:

How would you set up something like that? Can you simply create a single project and then put it on your (Android) phone/compile it on your PC depending on where you want to test it, or do you need separate projects for different platforms?


texts: In MonoGame, how can I disable font anti-aliasing?

texts:
I am building a game with a "low resolution" aesthetic, so I would like to disable the default font anti-aliasing. The text is drawn using the built-in SpriteFont and SpriteBatch classes.

Here is what it currently looks like:

Here is what I would like it to look like:

(Please ignore the particles)


texts:
I am making a gamemaker multiplayer game using 39dll's tcp sockets. As I want to host the server (and my javascript knowledge is a lot better), I use node.js for the server. I have already got gamemaker to connect to the server and send data, but now I have a problem with receiving data. After reading a lot, it seems that I need to do that like so: sock=tcpaccept(global.tcpConnection,1);. If sock is a negative number, the creation of the 'listening' interface failed. It returns me the number -10022. I can not find much information about it, so if anyone knows why this problem occurs and how to fix it would be very nice.

I am just making a normal gamemaker 8.1 game, no HTML5 game (I'd rather script that myself, not with gamemaker as I am really disliking it).

My server code:

var net = require('net');
var server = net.createServer(function(socket){
    console.log('connection made');
    socket.on('data', function(d){
        console.log(d.toString());
        socket.write(d.toString());
    });
    socket.on('error', function(e){console.log(e)});
    socket.on('close', function(){console.log('Socket closed');});
    socket.write('hhhaaannbikbkm');
}).listen(process.env.VCAP_APP_PORT||8080);

GML code (in the game start event):

dllinit(0,true,true);
global.username = get_string("Gebruikersnaam:","");
global.serverip = get_string("Server IP:","127.0.0.1");
global.serverport = get_integer('port', 8080);

global.tcpConnection = tcpconnect(global.serverip, global.serverport, 1);
setformat(2, '<!SEP!>');
if(!tcpconnected(global.tcpConnection)){
    show_message("Connection failed");
    game_end();
} else {
    setnagle(global.tcpConnection,1);
    clearbuffer();
    writestring(global.username, false);
    sendmessage(global.tcpConnection, 1, 1);
    while(true){
        var sock, size, cnt;
        sock=tcpaccept(global.tcpConnection,1);
        show_message(sock);
        //if (sock <=0) break;
        setsync(sock,0);//block untill new package
        size = receivemessage(sock, 0);
        show_message(size);
        //setsync(sock,1);//unblock socket
        cnt = readstring(0, '<!SEP!>');
        if(cnt!=''){
            show_message(cnt);
            clearbuffer();
            writestring(cnt, false);
            sendmessage(global.tcpConnection, 1, 1);
        }
    }
}


texts: How to design a Skill/Monster/Item etc. dictionary for a game?

texts:
I am trying to build a turn-based RPG where party members and enemies can cast skills and use items. How could I implement a modular list of skills/items/monsters (and maybe character classes, if I get there) so that each PartyMember or Enemy could choose a skill/item from the list and cast it?

My first attempt was this:

public static Dictionary<int, Skill> SkillDictionary = new Dictionary<int, Skill>
{
    {1, new Skill1()},
    {2, new Skill2()},
    {3, new Skill3()},
};
public abstract class Skill
{
    int skillIndex;
    public abstract void CastSkill();
}
public class Skill1 : Skill
{
    public Skill1(){skillIndex = 1;}
    public override void CastSkill(){};
}
public class Skill2 : Skill
{
    public Skill2(){skillIndex = 2;}
    public override void CastSkill(){};
}
public class Skill3 : Skill
{
    public Skill3(){skillIndex = 3;}
    public override void CastSkill(){};
}

As my code currently stands, each skill is instantiated only once, before Main (due to the dictionary being static). Is there a way to do lazy loading so I won't have to instantiate the skill until called? Is lazy loading favorable to what I have so far? (in case I get to the point where I have LOTS of items, monsters, etc.) Furthermore, suppose I were to make a MonsterDictionary. Then would it be wise to call a Clone method in order to make a new instance of a monster? Perhaps:

public Monster
{
   string name;
   int otherStats;
   public Monster(Monster clone)
   {
      this.name = clone.name;
      this.otherStats = clone.otherStats;
   }
}

And to create a new instance of the monster in battle, for example:

Enemy e = new Monster(MonsterDictionary["Slime"]);

Or - the golden question - is there a better design pattern altogether? Would an Enum be adequate instead of a dictionary in some of these cases? I'm relatively new to C# and game development, so I would like some feedback if possible. I'm curious to see how others organized their game data.


texts: Are there any reasons or situations one would use in their shader float(1) over just 1.0 ?


texts: relationship between eye height and collision body in UDK

texts:
We are using the UDK in a research lab setting so we must understand exactly how tall users feel in the virtual world (camera position). By Googling and digging through code, we have discovered the BaseEyeHeight parameter and also the dimensions of the collision cylinder (CollisionHeight). We attempted to set these using Remote Control and could not deduce the relationship between the variables.

For one thing, it seems that BaseEyeHeight has a ceiling. We cannot set it arbitrarily high but the height that is allowable seems to be dependent on the height of the collision cylinder, though it can be higher than the cylinder. Is there a ceiling for the eye height?

Secondly, the height we set for the collision cylinder does not seem to match the height of an object in the world that should be the same height. Is the collision cylinder in the same units as the rest of the world? Is there some padding that I am not accounting for?

Finally, BaseEyeHeight does not seem to be the height from the ground. I read somewhere that it should be the height from the center of the cylinder. Is this true? I would expect the eye height to be a bit lower than the actual collision height (as in the real world). Is this the case?

The big picture problem is that we cannot find a diagram or detailed description of how these numbers relate to one another. Is there a comprehensive source we've missed?


texts: I have to use XNA 3.0 for a class at school, and every solution to this problem I've found only works in XNA 4. I am rendering several 3D models, and the one that's drawn last is always on top. How do I make the depth decide this?


texts: Uniform not being applied to proper mesh

texts:
Ok, I got some code, and you select blocks on a grid.

The selection works. I can modify the blocks to be raised when selected and the correct one shows.

I set a color which I use in the shader. However, I am trying to change the color before rendering the geometry, and the last rendered geometry (in the sequence) is rendered light.

However, to debug logic I decided to move the block up and make it white, in which case one block moves up and another block becomes white.

I checked all my logic and it knows the correct one is selected and it is showing in, in the correct place and rendering it correctly. When there is only 1 it works properly.

Video Of the bug in action, note how the highlighted and elevated blocks are not the same block, however the code for color and

My Renderer is here (For the items being drawn)

    public void render(Renderer renderer) {
    mGrid.render(renderer, mGameState);

    for (Entity e:mGameEntities) {
        UnitTypes ut = UnitTypes.valueOf((String)e.getObject(D.UNIT_TYPE.ordinal()));
        if (ut == UnitTypes.Soldier) {

            renderer.testShader.begin();
            renderer.testShader.setUniformMatrix("u_mvpMatrix",mEntityMatrix);
            renderer.texture_soldier.bind(0);
            Vector2 pos = (Vector2) e.getObject(D.COORDS.ordinal());
            mEntityMatrix.set(renderer.mCamera.combined);
            if (mSelectedEntities.contains(e)) {
                mEntityMatrix.translate(pos.x, 1f, pos.y);
                renderer.testShader.setUniformf("v_color", 0.5f,0.5f,0.5f,1f);
            } else {
                mEntityMatrix.translate(pos.x, 0f, pos.y);
                renderer.testShader.setUniformf("v_color", 1f,1f,1f,1f);
            }
            mEntityMatrix.scale(0.2f, 0.2f, 0.2f);
            renderer.model_soldier.render(renderer.testShader,GL20.GL_TRIANGLES);
            renderer.testShader.end();
        } else if (ut == UnitTypes.Enemy_Infiltrator) {
            renderer.testShader.begin();
            renderer.testShader.setUniformMatrix("u_mvpMatrix",mEntityMatrix);
            renderer.testShader.setUniformf("v_color", 1.0f,1,1,1.0f);
            renderer.texture_enemy_infiltrator.bind(0);
            Vector2 pos = (Vector2) e.getObject(D.COORDS.ordinal());
            mEntityMatrix.set(renderer.mCamera.combined);
            mEntityMatrix.translate(pos.x, 0f, pos.y);
            mEntityMatrix.scale(0.2f, 0.2f, 0.2f);
            renderer.model_enemy_infiltrator.render(renderer.testShader,GL20.GL_TRIANGLES);
            renderer.testShader.end();
        }
    }
}

        String vertexShader = "uniform mat4 u_mvpMatrix;                   \n"
            + "attribute vec4 a_position;                  \n"
            + "attribute vec2 a_uv;                  \n"
            + "varying vec2 v_uv;                  \n"
            + "void main()                                 \n" + "{                                           \n"
            + " v_uv = vec2(a_uv.x,1.0-a_uv.y);\n"
            + "   gl_Position = u_mvpMatrix * a_position;  \n" + "}                            \n";
        String fragmentShader = "#ifdef GL_ES\n" + "precision mediump float;\n" + "#endif\n"
            + " uniform vec4 v_color;"
            + " uniform sampler2D tex;"
            + " varying vec2 v_uv;     \n"
            + "void main()                                  \n"
            + "{                                            \n"
            + "  gl_FragColor = v_color*texture2D(tex, v_uv);\n"
            + "}";
      testShader = new ShaderProgram(vertexShader, fragmentShader);


texts: Creating a large ground texture for mobile

texts:
Does anyone has any insight on creating / texturing a large mesh that will be used for a mobile game's level map?

Specifically, I was wondering how games like Vainglory achieve this.

I am familiar with the idea of splat maps, however this is where my knowledge of the subject ends...

Is the use of splats on mobile a good solution? Should the mesh be broken down into small sections which are UV'd and textured separately? Neither of these things?


texts: Console vulnerabilities in javascript-based game

texts:
Been toying around with a basic browser-based game for a while now, and getting deep into the vulnerabilities of client-side script. I know enough to understand that no client-side script is ever safe. Ever. But I don't fully understand to what degree.

Using, say, Chrome's developer tools, I know I can set variables at will - even Object.freeze and Object.seal can be overcome. I also know I can put in breakpoints at key points and use the console to read variable values. Now, let's say I have a function checkStep() that fires each time the player moves on the grid. It sends a blank ajax request, and the server returns only a boolean to signify if a random battle has started or not. If a user is able to rewrite/disable this checkStep(), they can effectively eliminate random battles. Is there a way to redefine or disable functions from the console command line? If you were bent on preventing this function from firing, how would you do it? Could you even do it?

EDIT Clearly I worded this poorly. Going to accept the current answer and re-post.


texts: Enabling OpenGL lighting seems to disable blending

texts:
I have the following code to set up for some 2D drawing using OpenTK. I originally wrote it without any lighting considerations, but later added the lighting block. This version of the code uses GL.Disable(EnableCap.Lighting); to disable the lighting and show the rendering the way it looked before I added lighting.

 GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate);
 GL.Enable(EnableCap.Blend);
 GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
 GL.Disable(EnableCap.PolygonSmooth);
 GL.Enable(texCap);
 GL.Disable(EnableCap.DepthTest);

 float d1=(float)Math.Cos(Counter.FrameCounter.CurrentValue / 10.0f);
 float d2=(float)Math.Sin(Counter.FrameCounter.CurrentValue / 10.0f);
 GL.Light(LightName.Light0, LightParameter.Position, new float[] { 100.0f, 100.0f, 50.5f, 1.0f});
 GL.Light(LightName.Light0, LightParameter.SpotCutoff, new float[] { 30.0f });
 GL.Light(LightName.Light0, LightParameter.SpotDirection, new float[] { d1, d2, -0.5f });
 GL.Light(LightName.Light0, LightParameter.SpotExponent, new float[] { 2.0f });
 GL.Light(LightName.Light0, LightParameter.Diffuse, new float[] { 1.0f, 0.0f, 0.0f, 1.0f });
 GL.Light(LightName.Light1, LightParameter.Position, new float[] { 300.0f, 400.0f, 150.5f, 1.0f});
 GL.Light(LightName.Light1, LightParameter.Diffuse, new float[] { 1.0f, 1.0f, 1.0f, 1.0f });
 GL.Disable(EnableCap.Lighting);
 GL.Enable(EnableCap.Light0);
 GL.Enable(EnableCap.Light1);

 GL.Disable(EnableCap.Dither);

 GL.BindTexture(texTarget, texture.Texture);
 GL.Begin(BeginMode.Quads);

That renders like this:

After switching lighting on (GL.Enable(EnableCap.Lighting);) the translucency (blending?) seems to have been disabled. How to I keep both features active? (Note that in addition to the translucent blue message appearing opaque white, the background in the first image contains a graphic equalizer, which is also no longer visible in the second image because it was behind a translucent layer.)


texts: Beginner question about vertex arrays in OpenGL

texts:
Is there a special order in which vertices are entered into a vertex array?  Currently I'm drawing single textures like this:

glBindTexture(GL_TEXTURE_2D, texName);
glVertexPointer(2, GL_FLOAT, 0, vertices);
glTexCoordPointer(2, GL_FLOAT, 0, coordinates);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

where vertices has four "xy pairs".  This is working fine.

As a test I doubled the sizes of the vertices and coordinates arrays and changed the last line above to:

glDrawArrays(GL_TRIANGLE_STRIP, 0, 8);

since vertices now contains eight "xy pairs".  I do see two textures (the second is intentionally offset from the first).  However the textures are now distorted.  I've tried passing GL_TRIANGLES to glDrawArrays instead of GL_TRIANGLE_STRIP but this doesn't work either.  I'm so new to OpenGL that I thought it's best to just ask here :-)

Cheers!


texts: Does using LWJGL and Slick2D yield promise for the future of my project?

texts:
I've been looking around the net for months now in an attempt to find the most appropriate tool for my needs. I haven't had a lot of time to devote to the creation of systems that could possibly already exist, however, now I do.

That being said, I've been drawn to 2 or 3 APIs/Engines thus far. The bulk of my experience lays with Java due to the exposure during my time in high school and college (of which I am currently a senior in, if any of you are wondering!) but I have used Python, C, C++, C#, and even a little Ruby and PHP for site needs.

Now, I've sought the power of OpenGL and LWJGL because of the platform independence and the obvious success of things such as Minecraft being used in a Web, Linux, Mac, and Windows environment. This is all due to Java, LWJGL, and a very interesting game concept. I've used the Slick2D API which is built upon LWJGL and I would like to continue with it if there is promise of no limitations on what I intend to create. I need a powerful, platform-independent 2D/3D graphics library, an input-monitoring system with perhaps even controller support, and networking capabilities beyond that of the standard (Java, or other language) library.

I've also looked into both the Torque Game Engine as well as the UDK and, to be honest, the UDK looks quite perfect. However, my goal for the end of this project is for the user to be able to host a multiplayer session which other players can join via IP or hostname, the world be a unique generation for each "new game", but still not limit the game in such a way that would not allow complex system to be implemented. Now, nothing would be limited if I simply used the UDK source, but I will not make such a commitment without first consulting the experts.

TL;DR - This is not intended to be a, "Which engine should I use? I like Java but wahhh I'm scared to write real code!" I have written my own engine (2D) and it has not been as successful as current ones, but it's done what I wanted it to. My only question is: Is the UDK sufficient for my needs; if not, I believe that the Slick2D API could be. I'm an aspiring Computer Science major from Michigan Tech, so learning and developing something new would not crush my world, haha. I would just like to hear what the beating heart of SE has to say on such topics. My plan for this project was 2D purely to control scope creep and not overwhelm myself.

Thanks!

PS - Also, I've done research on all programming topics associated with this development: creating standalone listening servers, PCG, complex item/inventory/reward systems, advanced dynamic RPG level systems and dynamic storyline systems. I'm not a super-noob. Just a curious individual.


texts: How to determine if an object is within field of view given xyz of object, player position, and 3D vector for player view?

texts:
I only have the object's position, the player position, and the vector representing the player's view, and I have the FoV (120 degrees horizontal/60 on each side, and 60 degrees vertical/30 on each side).

As I'm dealing with data that has already been recorded, I cannot use any Unity built-in functions and have to calculate it manually. My thoughts were to convert the 3D coordinates into 2D vectors, so that I can calculate if an object is in the horizontal plane first (by taking the X and Z values) and then if it is, check if it is in the vertical plane (take the Y and Z coordinates).

After, I calculate the the angle between the object and the player view to see if the absolute value of that is within the field of view (for example, if the object is on the left side of the player view, and the horizontal FOV is 120 degrees, then if the absolute value of the angle is less than or equal to 60 degrees it is within view).

Is this on the right track? I've been getting strange results (like only one of the four objects I'm looking for shows as visible throughout a log of values even though they should all at some point be visible).

Here is some code to show what I'm doing:

    public static Double angle(Vector2D obj, Vector2D bodyPos, Vector2D headDir) {

    Double result = 0.0;

    // Get the vector between the body position and the object
    Vector2D temp = Vector2D.subtract(obj, bodyPos);

    // First find dot product
    Double dotProduct = Vector2D.dotProduct(headDir, temp);

    // Now find the length of each vector and get the product of them
    Double lengthProduct = Vector2D.vectorLength(headDir)*Vector2D.vectorLength(temp);

    // Find the intermediary result
    result = dotProduct / lengthProduct;

    // Apply arc cos to find the angle between the vectors
    result = Math.acos(result);

    // Convert angle to degrees
    result = (result * 180)/Math.PI;
    System.out.println("The angle is: " + result);

    return result;
}

And here is the code that determines if something is in view by using that angle function:

    public static boolean isInView(bodyPosition objPos, bodyPosition bodyPos, headDirection headDir){

    boolean inView = false;

    Double h_angle = 0.0;
    Double v_angle = 0.0;

    // Create 2D vectors for both the horizontal and vertical FOV measurements
    Vector2D h_objPos = new Vector2D(objPos.getDirectionX(), objPos.getDirectionZ());
    Vector2D v_objPos = new Vector2D(objPos.getDirectionY(), objPos.getDirectionZ());

    Vector2D h_bodyPos = new Vector2D(bodyPos.getDirectionX(), bodyPos.getDirectionZ());
    Vector2D v_bodyPos = new Vector2D(bodyPos.getDirectionY(), bodyPos.getDirectionZ());

    Vector2D h_headDir = new Vector2D(headDir.getDirectionX(), headDir.getDirectionZ());
    Vector2D v_headDir = new Vector2D(headDir.getDirectionY(), headDir.getDirectionZ());

    // determine angle of FOV+
    Double iHFOV = FOV_H_MID * 0.5;
    Double iVFOV = FOV_V_MID * 0.5;

    // Check horizontal FOV first; if it is within that, then check the vertical
    // If both pass, then it is in view
    h_angle = Vector2D.angle(h_objPos, h_bodyPos, h_headDir);
    v_angle = Vector2D.angle(v_objPos, v_bodyPos, v_headDir);
    if ( Math.abs( h_angle ) <= iHFOV) {
        if ( Math.abs( v_angle ) <= iVFOV) {
            inView = true;
        }
    }

    return inView;
}

I found some resources that I will be reviewing in the mean time, but any help is appreciated. I haven't done any linear algebra courses so I'm trying to wrap my brain around it.


texts:
I have a visual design created in Photoshop which is 1440 pixels wide and 3118 pixels heigh. I need to import the assets in Unity and achieve the same layout that's done in Photoshop. I tried playing with the Pixels per Unit setting for the sprites but didn't have any success getting the same sizing I see in Photoshop.
What I'm trying to do is, get the same horizontal layout in Unity and calculate the vertical layout manually and scale the sprites based on mobile device screen resolution.
What's the calculation method to achieve this?

UPDATE:This is what I've done so far:

Design resolution is: 1440x3118

Camera ortographic size = 8

This makes 1 unit = 390 pixels

A 100 pixel heigh sprite in Photoshop has 0.25 units in Unity

Pixel per unit should be 195 in Unity to achieve the same sizes in Unity (390 / 2 taking camera ortographic size into consideration)

Is this calculation correct? The output seems somewhat ok to me but I haven't tried this on various devices.


texts: Is it feasible for a Server to send nothing more than a tile-based area to a Client?

texts:
To start, I have a good amount of background in networking (hardware, routers, ex.) but very little knowledge past the basics of network programming. This may seem like a stupid question, but I want to know what I am getting myself into while fathoming the implementation of multiplayer in my game.

I am creating a tile-based world, which is generated through a simple 2D Array. Let's say something like World[100][100], for simplicity's sake.

Currently, the render method only renders the tiles based on the resolution of the window, plus one tile (for smooth rendering during movement.) No matter how large the world is, (10x10, 1million x 1million) the rendering is flawless in performance.

The gameplay needs nothing more than to know what is in the currently visible (rendered on screen +1) and at the most possibly SOME information of tiles in an area around the player.

So anything more sent by the Server wouldn't be the full tile information.
Ex. Items laying on the ground, ground type, trees, etc. would not be important in the area outside the player's view, but would only be what the Client/Player needs to know about in those tiles. (Ex. Ultima Online's 'incoming names' where players could know a Character [player or monster] was just beyond the tiles in their rendered view.)

I do not know very much about networking, so perhaps as I learn this might answer my question. However, I am curious if this is a feasible solution or if the idea is simply laughable.

The information being sent would be about a 10x15 area of tiles, and each tile holds information about what is on the tile.
More efficiently, everything would be an Object, where the tile holds all the Objects on the tile. Ex. Tile[4][4] holds Sword#23452, Rock2, Tree5, Player3, Monster4.

Empty tiles would send nothing more than terrain type [Grass, Sand, Water] if not already loaded during Initialization/Load. Some tiles would have a handful of objects [Tree2, Sword#924, Gold, Corpse, Rock3].

So I cannot imagine that a tile would have very much information to send to the Client from the Server, since the Client mainly only needs to know the Texture that needs to be loaded and Position to place it on screen. Position being only two integers and Texture being one integer for a list of files to tell the client to render.

At the craziest, the Server would have to send 150 tiles with information of only a handful of Objects OnLOAD, and from then on update only changes to tiles (if any) and any new tiles (10 to 15 everytime a player moves in a direction) and the direction of movement for characters on screen (so the client can simulate smooth movement between tiles).

I assume I am correct in thinking this is an incredibly low amount of information being sent over the internet or between peers, so it should have little problems with performance even over laggy connections? Or am I so ignorant of networking that my mind will be blown when I finally get around to opening up my book on multiplayer networking?

If it is a very low amount of information being sent between Client/Server, would it make more sense to simply load the entire World on Initialization? Or 'Map' if the World is excessively large. And then after LOAD, send only tiles which are updated?

I am still pondering how I should specifically deal with data. The book I am using as reference wants me to have a Linked List, where I add and remove objects, so everything is a bool. "Is there a Character? Is there a Tree?"

I was thinking of a different approach, such as a container which holds objects, and Server logic that sends only what is required to tell the Client what to render. Possibly with objects that hold networking information within itself, which is sent out when called for by the Server.


texts: How to handle different resolutions in SDL2?

texts:
What is the easiest way to set different resolutions with SDL2?

I was trying to use the SDL_RenderSetScale() function first, but for some reason it alters the physics of the game (jumps are higher or smaller for example). My other guess was to use SDL_RenderSetLogicalSize(), since it was mentioned in another similar question here, but I'm not quite sure how it is supposed to work.

What I would simply like to do:

Let's say I have the game world seen in 320x240. Then no matter the resolution of the window, what we see in 320x240 is simply "scaled up". So for example: what is supposed to be 1 pixel in the "original view", becomes 4 pixel in 640x480 and so on, but all the logic still happens in 320x240. So when I move something by 1 pixel, it will move seemingly 4 pixels in 640x480, but only 1 logically.


texts: Role of an entity state in a component based system?

texts:
Component-based entity systems are all the rage these days; everyone seems to agree they are the way to go, but no one really has a definitive implementation of such a system. I was wondering, what role do entity states (walking-left, standing, jumping, etc) have in a CBS? Do they act like controllers (i.e. they handle events and change the entity's attributes based on those events)?

What about cases where a state would, for example, require that the entity enters no-clip mode? Should, that state, when it enters, maybe set the CollisionComponent of the entity to a null pointer or something? (Then, on exit, the state should restore the entity's CollisionComponent to its previous state.)

Also, I guess it's the current state's job to change the entity's state to something else, right?


texts: How to transform only part of an array in OpenGL ES?

texts:
I have one texture atlas of which I select the "non-animated textures", I put all vertex and UV coordinates in two array:

vertices = new float[] {
            // background
            0.0f, 1920f, 0.0f,
            0.0f, 0.0f, 0.0f,
            1080f, 0.0f, 0.0f,
            1080f, 1920f, 0.0f,
            // character
            240f, 760.0f, 0.0f,
            240f, 14.0f, 0.0f,
            770f, 14.0f, 0.0f,
            770f, 760.0f, 0.0f,
            // object (Will be transformed)
            360f, 800f, 0.0f,
            360f, 600.0f, 0.0f,
            500f, 600.0f, 0.0f,
            500f, 800f, 0.0f,
    };

uv = new float[] {
            // background
            0.50f, 0.25f,
            0.50f, 0.75f,
            1.0f, 0.75f,
            1.0f, 0.25f,
            // character
            0.0f, 0.25f,
            0.0f, 0.75f,
            0.25f, 0.75f,
            0.25f, 0.25f,
            // object
            0.0f, 0.75f,
            0.0f, 1.0f,
            0.25f, 1.0f,
            0.25f, 0.75f
    };

My vertex shader:

uniform mat4 matrix;
attribute vec4 vPosition;
attribute vec2 a_texCoord;
varying vec2 v_texCoord;

void main() {
    gl_Position = matrix * vPosition;
    v_texCoord = a_texCoord;
}

And my fragment shader:

precision mediump float;

varying vec2 v_texCoord;
uniform sampler2D a_texture;

void main() {
    gl_FragColor = texture2D(a_texture, v_texCoord);
}

I don't know how to animate just a part of the arrangements, also I try to create one more texture but when I run the app I only see the last texture.


texts: Calculating specific coordinate along a path

texts:
Let's say I have a path comprised of a sequence of points that are connect by lines and arcs. The entire path has some specific length. Let's call that length 100.

What would be the mechanism to determine the exact x,y coordinate for any given point on that path?

meaning...

 Path path = new Path();
//fill in various lineTos and arcTos to the path here
....

Point p = getCoordsFromPath(path, 50.0f); //get the coords at the half way point on the path

Point getCoordsFromPath(Path inP, float position){
    Point ret;
    //do some magic and get the x,y at the point in the path
    //that is the position distance from start

    return ret;
}

TIA


texts: Javascript: world tile generator bug? collision not working, player falls down?

texts:
Hi I have a serious problem here, When I generate my tile map from an array with numbers [0,4, ...] (0 > for air, 4 for solid) inside of generateWorld()... the collision it doesn't work, and my player falls when l walk to the left and keeps collide with that block... just keep trying until you see it, it will fall passing throught the block.

But the weird part is when l generate my world manually generateWorld2() my collision works very well.

This is located almost at the end of the code. Inside window.onload function

Please tell me why is that, lm not using jquery or others libraries... lm doing this game from 100% scratch. Thanks so much !


texts: What are some free online game design courses?

texts: I have an MComp in Computer Science. I would like to specialize in game programming. What online free video game design courses are there? I as thinking something similar to coursera.org


texts:
Framework: LibGDX

IDE: Android Studio

Game based on Kilobolt tutorial

While debugging, the frame delta time i get using Gdx.graphics.getDeltaTime()continues to increment so when i stop debugging and return to application, everything is fast (it is related to runTime, so delta time too)

runTime is calculated in GameScreen class, which increments it with deltaTime and then passes it to GameWorld and GameRenderer methods calls.

How can i stop it while debugging?


texts:
I am only just dipping my toe in the water of game development, so forgive my ignorance if you will:

Regarding console AAA titles with massive open-world settings: How do all of the art assets and game data fit on a double-layer Blu-ray Disc with around 55GB of available space?

I have a game idea that would utilize street data from Open Street Maps, but the single file for the world's street data seems to large to fit, much less anything else like code or art.  Is the secret here compression, or just that 55GB is typically not a concern because games aren't using file sets as large as the entire world's road maps?


texts: Decomposing a collision grid into a set of boxes

texts:
I'm looking for a decent algorithm to decompose a collision grid (e.g. bool[w,h])...

...into a non-overlapping set of boxes (e.g. List<Rectangle>).

The solution does not have to be the best all the time, as long as it is simplified enough (otherwise I would just create one box per tile).


texts: How do I blend 2 lightmaps for day/night cycle in Unity?

texts:
Before I say anything else: I'm using dual lightmaps, meaning I need to blend both a near and a far.

So I've been working on this for a while now, I have a whole day/night cycle set up for renderers and lighting, and everything is working fine and not process intensive.

The only problem I'm having is figuring out how I could blend two lightmaps together, I've figured out how to switch lightmaps, but the problem is that looks kind of abrupt and interrupts the experience.

I've done hours of research on this, tried all kinds of shaders, pixel by pixel blending, and everything else to no real avail. Pixel by pixel blending in C# turned out to be a bit process intensive for my liking, though I'm still working on cleaning it up and making it run more smoothly. Shaders looked promising, but I couldn't find a shader that could properly blend two lightmaps.

Does anyone have any leads on how I could accomplish this? I just need some sort of smooth transition between my daytime and nighttime lightmap. Perhaps I could overlay the two textures and use an alpha channel? Or something like that?


texts: Export Blender 2.59 models with animations to XNA 4

texts:
Whats the best way to export from Blender 2.59 for XNA 4? I have heard you can use the DirectX to export to .x instead of .fbx which works better with animations?

Unfortunately all the tutorials out there are a bit dated and go on about the quirks with older versions..


texts: Question about Monster Rancher/My Brute generators

texts:
I want to build a system based on the idea of Monster Rancher's monster generation system.

First, is it legal per se?

Obviously, I don't know how they built theirs and I will be generating my own "generator". But the idea itself of being able to randomly create a character or monster based on something..is it copyrighted? patented?


texts: Is there a way to rotate an Ellipse in libGDX for collision detection purposes?

texts:
I'm trying to avoid having multiple overlapping Circles for a UFO-shaped sprite.

Two Ellipse objects will perfectly cover the shape of my UFO, but I want to tilt/rotate the UFO when flying left and right, while still maintaining collision areas that match the locations of the graphics.

The Ellipse reference page doesn't have anything listed for rotation options, just wondering if anyone has ever tried to do this before (and succeeded).


texts:
I am new to algorithms but currently creating a little game with the need for some.

I have a 2d grid/board with a start and a finish field. Between those two fields are several platforms which can be entered. Each platform has a counter on it. When going on a platform the counter is decreased by one. If the counter reaches zero the platform is gone. The goal is to go to the finish field AND destroy every platform field. A little exmaple:

0 1 0
1 2 1
1 0 F
S 0 0

S being the Start field and F being the finish field the right path would be going UP, UP, RIGHT, UP, DOWN, RIGHT, DOWN.

All I could find so far were algorithms getting paths for mazes without counter. Do you have any tips for a algorithm that can decide, if the current maze if solvable or not and maybe even get the correct path?

Thanks in advance!


texts: Insufficient memory on creating vertex buffers

texts:
I'm building a voxel world generator with XNA where the voxels are rendered as polygonal cubes. The world is divided into 1024 chunks of 32x32x256 cubes each (as 32 chunks by 32 chunks), and each chunk has its own index and vertex buffer. Since each chunk is different, vertex buffer size is determined on runtime.

To prevent massive stalling on opening the program, only one chunk is re-built per frame until all chunks are built. Occasionally the program crashes with an "insufficient memory" related error that is caused by the line that creates the vertex buffer. Here is how I set them up:

 vb = new VertexBuffer(
      device,
      VertexPositionColorNormal.VertexDeclaration,
      nextIndex,
      BufferUsage.None
 );

 ib = new IndexBuffer(
      device, IndexElementSize.ThirtyTwoBits,
      nextIndex,
      BufferUsage.None
 );

My vertex structure is not very large, using only a Vector3 for position and Byte4 for color and normal lookup info:

public struct VertexPositionColorNormal : IVertexType
{
    public Vector3 Position;
    public uint Data;

    public readonly static VertexDeclaration VertexDeclaration = new VertexDeclaration
    (
        new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
        new VertexElement(12, VertexElementFormat.Byte4, VertexElementUsage.TextureCoordinate, 0)
    );

    VertexDeclaration IVertexType.VertexDeclaration { get { return VertexDeclaration; } }
}

NextIndex is the number of vertices and indices allocated to the buffers (always 1 index per vertex).

Am I making too many buffers? It crashes despite the GC showing only about 12 MB of usage so I guess memory fragmentation is a problem when creating lots of buffers in a short time? Should I use a smaller amount of buffers that store more data and have several chunks share them?

EDIT: I estimate roughly 0.75 to 1 GB of memory used in the vertex buffers. My graphics card has 2GB of VRAM. Though I also know sometimes not all the vertex data may be stored in VRAM at one time.


texts: Optimizing Collision Detection in a 2D Game

texts:
I am optimizing my "little" Java (LibGDX) shooter game, and perhaps unsurprisingly, collision detection is a "bottleneck"; I've kind of reached my performance goals already, but I want to tweak the game anyways.

Every monster in the game can collide with every other monster + friendly bullets.
The game is a single-screen shooter. I am using a QuadTree.

In my Sprite/Entity-class, I have a method:

public boolean canCollideWith(Sprite s) {
    return true;
}

This method is called twice in a loop within a loop, meaning that when enough Sprites are added, it gets called a lot. It shows up as a high HotSpot in VisualVM.

I override the method in various sub-classes, e.g. in the Bullet-class:

@Override
public boolean canCollideWith(Entity e) {
    if (friendly) {
        return (e instanceof Monster && !(e instanceof Player))
                        || e instanceof Missile;
    }
    else
        return e instanceof Player || e instanceof Warp;
}

...and in the Monster-class:

public boolean canCollideWith(Entity e) {
    return e instanceof Bullet && ((Bullet) e).isFriendly() || e instanceof Monster || e instanceof Tagger || e instanceof Flower || e instanceof Shockwave;
}

I don't really like these instanceof's in the first place... what would be an elegant and a fast solution to optimize this (hopefully both :)?

Excluding the QuadTree part, here's my whole collision detection method:

public static void collisionDetection(Array<? extends Sprite> sprites) {
        for (int i = 0; i < sprites.size; i++) {

            Sprite s1 = sprites.get(i);

            if (!s1.isCollidable()) continue;

            for (int k = i + 1; k < sprites.size; k++) {

                Sprite s2 = sprites.get(k);

                if (s1 == s2) continue;

                if (!s2.isCollidable()) continue;

                if (!s1.canCollideWith(s2)) continue;
                if (!s2.canCollideWith(s1)) continue;

                boolean intersects = s1.intersects(s2);

                if (intersects) {
                    s1.fireIntersectionEvent(s2);
                    s2.fireIntersectionEvent(s1);

                    s1.intersectsWith(s2);
                    s2.intersectsWith(s1);
                }
            }
        }
    }

Thanks for any ideas.


texts: How do i prevent my player from walking through mesh collider

texts:
I have a character being moved using rigidbody.moveposition and I have an floating lowpoly island with a mesh collider. When my player walks into a steep slope or a wall, it passes right through. I assume this is because the mesh collider isn't thick enough but there must be a pretty simple fix. If anyone knows how to fix this it would be much appreciated.

Here's the code for the movement of my character.

private void Movement()
{
    if (AnimController.GetInteger("AnimPar") != 3)
    {
        if (Input.GetKey(KeyCode.LeftShift))
        {
            walkSpeed = initialWalkSpeed * 2;
        }
        else
        {
            walkSpeed = initialWalkSpeed;
        }

        if ((Forward && Right) || (Forward && Left) || (Backward && Right) || (Backward && Left))
        {
            walkSpeed *= .7f;
        }

        if (Forward)
        {
            Delta += transform.forward * walkSpeed * Time.deltaTime;
        }

        if (Backward)
        {
            Delta -= transform.forward * walkSpeed * Time.deltaTime;
        }

        if (Right)
        {
            Delta += transform.right * walkSpeed * Time.deltaTime;
        }

        if (Left)
        {
            Delta -= transform.right * walkSpeed * Time.deltaTime;

        }

        rb.MovePosition(new Vector3(Delta.x, transform.position.y, Delta.z));
    }
}


texts: Threading/Streaming files while rendering the scene

texts:
I am writing a game engine and am trying to wrap my head around data streaming while rendering. What I mean by this is being able to load resources (however slow it may be) while rendering and not slowing it down visibly. My engine is not a state of the art engine by any means and renders Quake3 style maps. The files needed to load are not super large and can be easily loaded in a few seconds but I want to ability to load in as quick as possible and load connected maps while playing without slowdown. What I am looking for is a sort of functionality where I can start a function and have it either run on it's own thread or just run for a specific amount of time every frame. In other words, I give it maybe a maximum running time of 0.01 and it will return control after that amount of time, meaning I can keep my FPS completely solid. Does such a functionality exist?

I know you can use threading for something like this but I need clarification on the concept. When people use the expression "UI thread" or "I/O thread", what does this mean? Is it a thread that is always being used on a specific core so that it always has priority? Do they have a thread running for the entirety of the engine that just handles specific logic?


texts: How to select a sprite with the mouse in c# XNA?

texts: I'm attempting to create a chess game, for the movement I need to be able to click on a piece with the mouse, and then the square I'd like to move it to. Each piece on the board is a sprite, and I'm struggling to find a way to select a sprite in order to then move it, what would be the best way to do this? I'm programming in c# with XNA framework btw. Thanks in advance :)


texts: Multiplayer Network Game - Interpolation and Frame Rate

texts:
Consider the following scenario:

Let's say, for sake of example and simplicity, that you have an authoritative game server that sends state to its clients every 45ms.  The clients are interpolating state with an interpolation delay of 100 ms.  Finally, the clients are rendering a new frame every 15ms.

When state is updated on the client, the client time is set from the incoming state update.  Each time a frame renders, we take the render time (client time - interpolation delay) and identify a previous and target state to interpolate from.  To calculate the interpolation amount/factor, we take the difference of the render time and previous state time and divide by the difference of the target state and previous state times:

var factor = ((renderTime - previousStateTime) / (targetStateTime - previousStateTime))

Problem:  In the example above, we are effectively displaying the same interpolated state for 3 frames before we collected the next server update and a new client (render) time is set.

The rendering is mostly smooth, but there is a dash of jaggedness to it.

Question:  Given the example above, I'd like to think that the interpolation amount/factor should increase with each frame render to smooth out the movement.  Should this be considered and, if so, what is the best way to achieve this given the information from above?


texts:
I have read that you can define your OpenGL unit by using glViewport.
As far as I understood if you use something like glViewport(0,0,600,600) then 1 OpenGL unit = 600 pixels. Now my problem is what happens if the 2 sizes aren't equal? How do you calculate your OpenGL unit?