texts: Scrolling with SDL2 & Box2d - My Camera isn't keeping up with my player

texts:
I'm trying to get a game on the google play store before I'm 40 (long held dream to publish a game since the days of the speccy), I have just over a month to go so it's not looking good! Foolishly I decided to use SDL2 and Box2d to write the game, both technologies I have little experience in & to compound my misery I'm a noob at C++ so please bear with me if I've made a common error.

Basically I've managed to get a simple physics simulation up and running and have sorted applying my SDL textures to the box2d collision boxes, that all seems to be fine and dandy, where I've come a cropper is my player moves along a ground entity on the X axis,

I've managed to implement a scrolling background but it doesn't keep pace with the player, in which I mean the player moves across the screen instead of remaining central as I'd like him to and the background scrolls behind him. I've probably completely mis-interpreted how to manage my requirements and after days of searching for reference code I'm now at a bit of a loss.

Hopefully some kind soul can help me realise my dream! I've posted what code I think is relevant but if theres something missing I'll add it.

Player movements

// Get the position and angle of the player
playerPos = player.pl_body->GetPosition();
playerDeg = player.pl_body->GetAngle();
playerVel = player.pl_body->GetLinearVelocity();

float velChange = desiredVel - playerVel.x;
float impulse = player.pl_body->GetMass() * velChange; //disregard time factor
player.pl_body->ApplyLinearImpulse( b2Vec2(impulse,0), player.pl_body->GetWorldCenter(), true );

SDL2 rendering

//Render current frame using clips
SDL_Rect* playerCurrentClip = &playerClips[ plAnimFrame / 2 ];

// Render player texture to x & Y of player entity
gPlayerTexture.render (playerPos.x - player.PLAYER_WIDTH/2, playerPos.y - player.PLAYER_WIDTH/2, playerCurrentClip, playerDeg, NULL, flipType);

Camera setup

// Setup a surface for the camera area
SDL_Rect camera = {0, 0, SCREEN_WIDTH, SCREEN_HEIGHT};
// Render background texture
gBackgroundTexture.render (0, 0, &camera, NULL, NULL, flipType);

Camera scrolling

//Center the camera over the player
camera.x = (playerPos.x + player.PLAYER_WIDTH / 2 ) - SCREEN_WIDTH / 2;

 //Keep the camera in bounds
 if( camera.x < 0 )
 {
     camera.x = 0;
 }
 if( camera.x > LEVEL_WIDTH - camera.w )
 {
     camera.x = LEVEL_WIDTH - camera.w;
 }


texts:
I'm using OpenGL. For my tiles, I'm using a display list and I'm just using immediate more for my player (for now). When I move the player, I want to center him in the center of the window, but allow him to jump around on the y axis and not have the camera follow him. But the problem is, is that I can't figure out how to center the player in the viewport! Here is the player update method:

public void update() {
    if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
        World.scrollx -= Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_RIGHT);
    }
    if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
        World.scrollx += Constants.scrollSpeed;
        setCurrentSprite(Sprite.PLAYER_LEFT);
    }
    move((Constants.WIDTH) / 2  + -World.scrollx, getY());
}

World.scrollx and World.scrolly are variables that I increase/decrease to move the tiles. move() is just a method that sets the player position, nothing else. I render the player at his current coordinates like this:

public void render() {
    glBegin(GL_QUADS);
    Shape.renderSprite(getX(), getY(), getCurrentSprite());
    glEnd();
}

Shape.renderSprite is this:

public static void renderSprite(float x, float y, Sprite sprite){
    glTexCoord2f(sprite.x, sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize() , sprite.y + Spritesheet.tiles.uniformSize());
    glVertex2f(x + Constants.PLAYER_WIDTH, y);
    glTexCoord2f(sprite.x + Spritesheet.tiles.uniformSize(), sprite.y);
    glVertex2f(x + Constants.PLAYER_WIDTH, y + Constants.PLAYER_HEIGHT);
    glTexCoord2f(sprite.x, sprite.y);
    glVertex2f(x, y + Constants.PLAYER_HEIGHT);
}

Pretty simple, I just render the quad at the current player's position. This is how I actually render everything:

public void render(float scrollx, float scrolly) {
    Spritesheet.tiles.bind();
    glPushMatrix();
    glTranslatef(scrollx, scrolly, 0);
    glCallList(tileID);
    glPopMatrix();
    player.render();
}

This is the part I'm confused on. I translate the tiles according to the scrollx and scrolly variables, and then I render the player at his current position. But the player moves faster than the tiles scroll, and he can escape out the side of the screen! How do I center the player with moving tiles?

Thanks for any help!


texts:
I'm learning directx in a master's degree and they taught us to have a GraphicsLayer class which is the one connecting with the direct3d library. That way this class is completly independent from the other classes (my game classes), meaning changing the renderer to OpenGL wouldn't require much effort but only changing the graphicLayer.

This classe has it's LoadAssets, Paint methods, but I have a question, they told us to load all the assets inside this class. This means all these methods will be in the loadAssets method:

D3DXCreateTextureFromFileEx(g_pD3DDevice,"tiles.png",0,0,1,0,D3DFMT_UNKNOWN,D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,NULL,NULL,NULL,&texTiles);
// And more resources to load
//...

texTiles as you see is a LPDIRECT3DTEXTURE9 instance which is declared in the graphicLayer.h.

So my question is, how do you manage all the resources? Do I have to declare in the .h all my game textures even if I'm not using them? How would you load only those resources there are in a scene and draw them in a code-strucured way?


texts: Is it ok to initialize an RB_ConstraintActor in PostBeginPlay?

texts:
I have a KActorSpawnable subclass that acts weird. In PostBeginPlay, I initialize an RB_ConstraintActor; the default is not to allow rotation. If I create one in the editor, it's fine, and won't rotate. If I spawn one, it rotates.

Here's the class:

class QuadForceKActor extends KActorSpawnable
    placeable;

var(Behavior) bool bConstrainRotation;
var(Behavior) bool bConstrainX;
var(Behavior) bool bConstrainY;
var(Behavior) bool bConstrainZ;

var RB_ConstraintActor PhysicsConstraintActor;

simulated event PostBeginPlay()
{
    Super.PostBeginPlay();

    PhysicsConstraintActor = Spawn(class'RB_ConstraintActorSpawnable', self, '', Location, rot(0, 0, 0));
    if(bConstrainRotation)
    {
        PhysicsConstraintActor.ConstraintSetup.bSwingLimited = true;
        PhysicsConstraintActor.ConstraintSetup.bTwistLimited = true;
    }
    SetLinearConstraints(bConstrainX, bConstrainY, bConstrainZ);

    PhysicsConstraintActor.InitConstraint(self, None);
}

function SetLinearConstraints(bool InConstrainX, bool InConstrainY, bool InConstrainZ)
{
    if(InConstrainX)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearXSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearXSetup.bLimited = 0;
    }
    if(InConstrainY)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearYSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearYSetup.bLimited = 0;
    }
    if(InConstrainZ)
    {
        PhysicsConstraintActor.ConstraintSetup.LinearZSetup.bLimited = 1;
    }
    else
    {
        PhysicsConstraintActor.ConstraintSetup.LinearZSetup.bLimited = 0;
    }
}

DefaultProperties
{
    bConstrainRotation=true
    bConstrainX=false
    bConstrainY=false
    bConstrainZ=false

    bSafeBaseIfAsleep=false
    bNoEncroachCheck=false
}

Here's the code I use to spawn one. It's a subclass of the one above, but it doesn't reference the constraint at all.

local QuadForceKCreateBlock BlockActor;

BlockActor = spawn(class'QuadForceKCreateBlock', none, 'PowerCreate_Block', BlockLocation(), m_PreparedRotation, , false);
BlockActor.SetDuration(m_BlockDuration);
BlockActor.StaticMeshComponent.SetNotifyRigidBodyCollision(true);
BlockActor.StaticMeshComponent.ScriptRigidBodyCollisionThreshold = 0.001;

BlockActor.StaticMeshComponent.SetStaticMesh(m_ValidCreationBlock.StaticMesh);
BlockActor.StaticMeshComponent.AddImpulse(m_InitialVelocity);

I used to initialize an RB_ConstraintActor where I spawned it from the outside. This worked, which is why I'm pretty sure it has nothing to do with the other code in QuadForceKCreateBlock.

I then added the internal constraint in QuadForceKActor for other purposes. When I realized I had two constraints on the CreateBlock doing the same thing, I removed the constraint code from the place where I spawn it. Then it started rotating.

Is there a reason I should not be initializing an RB_ConstraintActor in PostBeginPlay? I feel like there's some basic thing about how the engine works that I'm missing.

EDIT:
I found roughly the same initialize code in Whizzle, the Psyonix game made purely with UDK for which the source is available: http://developer.download.nvidia.com/udk/Whizzle_Creation_Document_1_2.pdf

EDIT 2:
The constraints are intialized by PostBeginPlay when loading the level, and that works for the placed objects. Just not for spawned objects.


texts: Two Gameloops instead of one, wouldn't it be better?

texts:
I have been thinking about this a lot and don't know if i'm thinking incorrectly.

Most games have one game loop that can be split into three functions.
A basic game loop would look something like this:

while(true){
    handle_Input();
    update();
    render();
}

It's good when the handle_Input() and update() function are called as often as possible to create more responsive controls. But there is no point in calling the render() function more often then your monitor refresh rate. You could of course limit the speed of the loop in order to hit your monitor refresh rate but it would make the controls less responsive.

Wouldn't it be better to create two game loops?

The first game loop would call the handle_Input() and update() function as fast as possible, while the second game loop would take the latest frame the first game loop calculated and only call the render() function.
The speed at which the secend game loop runs would be limited by the monitor refresh rate. In order for the concept to work, the game loops should be running on separate processor cores.

Wouldn't this create a lot less overhead for both the CPU and GPU by not wasting time on the worthless render() calls? And allow the game to either run with a higher fps count or better graphics? Wouldn't it also allow to give unbalanced systems, which have a weak GPU compared to the CPU, a more playable experience, because the weak GPU would only limit the fps you see but not the handle_Input() and update() calls?

I have never seen somebody implement a concept like which make me think something like this wouldn't work.


texts: OpenSceneGraph, multiple instances of a model

texts:
Im working on my first project using OpenSceneGraph. The project is a model flight simulator for one of my university courses,

I want to be able to load airplanes (consisting of multiple models) and then depending on what plane the user/users choose a new airplane (entity) is created that a user controls.

A loaded airplane will have the following structure. Main body and then the rudders/propellers translated using translation nodes to there right positions. There also needs to be a translation node for each of the rudders/propellers used to rotate the rudders depending on player input.

My problem is i dont know how i should structure it so that i dont need to load the whole model once for every instance of the same type of airplane or store the model parts of the airplanes multiple time.

The only thing that needs to be hard copied is the translation nodes so that the different instances of the same airplane can have rudders and things modified separetely from other planes.

If the planes would consist of only one model i would just create a entity class containing a translation node and add the model to that node so that all entities share the same model, but now the planes are more complex so i dont know how i should do it.

So if someone could give me a hint or a suggestion for further read i would appreciate it.

I hope someone understood what i was trying to describe.

Thanks for answers


texts:
Hey i have issue regarding jump sprite body. In my code i am using moveLeft and moveRight Button and when i am press moveRight Button using following code

if (moveRight.active==YES)
    {
            b2Vec2 force=b2Vec2(4,0);
            ballBody->SetLinearVelocity(force);
    }

Its move perfectly and When i release this Button than sprite body stop using following code

else
{
      b2Vec2 force=b2Vec2(0,0);
      ballBody->SetLinearVelocity(force);
}

But when i put this else part then jump can not done. My jump code is following

if (jumpSprite.active==YES)
                {
                    NSLog(@"Jump Sprite");
                    b2Vec2 locationWorld;
                    locationWorld=b2Vec2(0.0f,4.0f);
                    double force=ballBody->GetMass();
                    ballBody->ApplyLinearImpulse(force*locationWorld, ballBody->GetWorldCenter());
                }

If i remove else part then jump will perform complete but sprite body can not stop after release button.

So what to do??

Thanks in advance


texts: How does Lua work as a scripting language in games?

texts:
I'm a little hazy on what exactly Lua is and how a game that is programmed in C++ would use it. I'm asking primarily about how it is compiled and run.

For instance when you use a program written in C++ which uses Lua scripts: does the code in Lua just call to functions in the main program written in C++ and act as a uncompiled class waiting to be compiled and added to the memory heap of the C++ program?

Or does it act like a bash script in Linux where it just executes programs completely separate from the main program?


texts: Destroy the enemy only if the animation is played and touch the enemy

texts: I am using Unity. I want to attack an enemy with a knife. So I created an object (the knife) and put an attacking animation to it. Now I want to destroy the enemy only if the attacking animation is played and the knife touches the enemy. And if the animation is not played and the knife touches the enemy it should show a game over screen.


texts:
I was thinking that it could be cool to have an interactive game in a digital resume. For the sake of this question, and scope of this site, let's ignore whether or not this is a good idea.

Is it possible to embed a game or some sort of interactive window inside of a PDF document? This could be using any sort of language or framework. For example, having a small area of the PDF with a CAPTCHA in it.


texts:
I am using GLFW for a game, and I have a function which allows me to set the window title.

    // PROBLEM WITH INCREASING MEMORY USAGE
    void WindowSystem::setTitle( const string & title )
    {

        glfwSetWindowTitle( window, title.c_str() );

    }

This function is called once during every iteration of the main program loop, so that I can have a basic FPS counter. Under Xcode the program memory usage increases faster and faster. If I replace title.c_str() with a literal, the problem does not happen, i.e., the following does not cause the same memory usage growth.

        // DOESN'T CAUSE PROBLEM
        void WindowSystem::setTitle( const string & title )
        {

            glfwSetWindowTitle( window, "Hello world!" );

        }

This where the function is called.

    int SystemControl::update()
    {
        double time = glfwGetTime();
        double timeStep = time - control->lastUpdate;
        control->lastUpdate = time;

        float frameRate = 1.0f / timeStep;

        string windowTitle = std::to_string( frameRate );

        control->windowSystem->setTitle( windowTitle );

        control->physicsSystem->update( timeStep );

        return OK;
    }

The string title is allocated on the stack, and should be freed at the end of update. Could there possibly be a memory leak? I understand that the pointer for c_str() is internally managed, and does not need to be freed.


texts: How to find if an object is facing another object given position and direction as separate vectors

texts:
I found a very helpful post about exactly what I need here. It uses dot products to which is what I'm specifically looking for.

It talks about players facing monsters basically. They give a helpful picture here,

My question though, is what if you have a function with 3 arguments: the position of object 1, the position of object 2, and the direction object 1 is facing given as a unit vector. So the picture would look as so:

How would you find whether A is facing B?


texts: Attempting to create LOD variations of unity prefab

texts: Hey guys I am attempting to make some LOD variants of my prefab and am getting a strange result. I am using unity fbx exporter and blender version 2.80.7. Here is the model before and after but even without altering the model two of the plants look completely flat on import. Is there some common cause for this or could this be just the model?


texts: Is point texture filtering the same as nearest?

texts: Is point texture filtering the same as nearest (different names for the same technique)?


texts: Jumping up quicker? (Paper Mario style jump)

texts:
As shown here, Paper Mario's jump takes 8 frames go reach the max jump height and 12 frames to get back to the ground. This is pretty unusual, any idea how to jump up that quick with a rigidbody?
I tried to AddForce when rigidbody.velocity.y > 0, but that didn't work out.
Any help would be appreciated, thanks in advance!
//Jump when pressing button and on ground
//jumpForce is a public float variable

if (Input.GetButtonDown("Jump") && isGrounded)
{
    theRB.velocity += new Vector3(0, jumpForce, 0);
}


texts: creating model mesh and face explosions on Panda3d and Blender

texts:
I'm quite new to Panda3d and Python (1 year) and I've been trying for longer than 4 months to find out how to create a simple mesh explosion in Panda3d.
I've created lots of different explosions using Blender and they all look good and work fine in Blender but when I export them through .x or .egg files the animation is always blank. I know Panda3d normally uses armature to do animations but with a mesh explosion on a space ship or box or any static object it does not have armature and maybe this is why it never really exports the visual effect...
I've been trying so long now just to explode anything on Panda3d but cannot work out how to go about this. It's really getting me down as the particle effects panel is great for things like smoke and fire, etc but I want to see the actual mesh and faces explode into pieces, so I can continue working and learning how to create and develop games.
I've looked into everything on the web and Blender and Pand3d but can't find anyone or anything that has had this problem or solution.
I've got demo code but I'm not sure how to upload the models I've created. Do I need to include them here as it's not the code that is the problem but the .egg files and Blender...
The models I've created have separate animation files and I've tried animation files within the .egg. I've got other animated models to work so I know it's not that, like I said I've tried everything and all the different export settings and combinations to get my ship to explode.


texts: Synchronize objects' movements moved by coroutine function

texts:
I'm using Unity version 5.3.5.

I'm having problems to synchronize the movement of three different objects from point A to point B and vice versa. To move the objects I use the following code:

public float time;
public Vector3 endPos;
private Vector3 startPos;

 void Start()
 {
     startPos = transform.position;
 }

 void FixedUpdate()
 {
     if(transform.position == startPos)
     {
         StartCoroutine(Move(gameObject.transform, startPos, endPos, time));
     }
     if(transform.position == endPos)
     {
         StartCoroutine(Move(gameObject.transform, endPos, startPos, time));
     }
  }

 public IEnumerator Move(Transform thisTransform, Vector3 startPosition, Vector3 endPosition, float time)
 {
     float i = 0f;
     float rate = 1/(time);
     while(i < 1)
     {
         i += Time.deltaTime * rate;
         thisTransform.position = Vector3.Lerp(startPosition, endPosition, i);
         yield return null;
     }
 }

As long as all of the objects have the same "time" value, their movements is correctly synchronized regardless the distance that they have to cover. The problems arises when they all have different "time" value. For example, if they have to move backwards and forwards from startPos(0,0,0) and endPos(5,0,0) with the following "time" value:

Object A time = 1 second
Object B time = 2 second
Object C time = 4 second

After 4 second, they should all be again at the same start position. However, what happen is that the fastest object (Object A) has a delay over the other two and this delay increase over time.

How can i fix this problem?


texts: How do you ensure consistent experience across multiple graphics cards (or even driver versions)?

texts:
So I was writing a simple 2D game with OpenGL and SDL and had this problem when there was awful tearing when running in windowed mode (even though I explicitly asked SDL_SetVideoMode to use double buffering). Didn't worry about it all too much because most of the time the game grabs the entire screen, windowed mode is just for debugging.

Anyway, yesterday I updated my nVidia drivers and tearing disappeared, the game runs smooth and looks nice in windowed mode too. I can see how the problem may be in the graphics driver, but this leads to a question.

Obviously, professional game developers have to deal with a lot of different hardware/software configurations. What are the techniques they use to make sure the game looks the roughly the same on different graphics cards or even the same model of graphics card, but with different driver versions?


texts: Control sprite animation speed using Create JS

texts:
How can I control the animation speed of a sprite using create JS?

When you press right and left, the sprite will run through the frames... I'd like to leave the fps at 60, but alter how fast the frames are looped through without altering the main game FPS rate.

See a demo here. Press right and left arrow to see.

I thought changing the bmp animation frequency property would do the trick...

bmpAnimation.frequency = 2;

But it did  not work...

Or should I be using the jQuery animation?

Also, I noticed that each time I hit a random key, the animation plays 1 frame then goes back to first frame. Why is that?

Thanks!


texts: Stacking items, c# XNA: When item reaches maximum stack, new items added are also maximum stack

texts:
haven't used this site before so I'm sorry if I format my post badly.

I am trying to build a stackable inventory for my game in c# XNA and the problem I've encountered is when an item in my inventory reaches the maximum stackable count (10) and creates a second instance of the item in the second slot of my inventory the second instance retains the count value of the first item.

So 10 items in my inventory have a value of 10 in the first slot, but 11 items will have a value of 10 in slot 1 and 10 in slot 2

4 pictures illustrating my problem: http://imgur.com/a/KZ5EL

class Backpack
{
         // 25 Inventory Slots
    public int itemMax = 25;
    public List<Items> ItemList = new List<Items>();
    int end = 1;

         //Funtction to add new items
    public void Add(Items newItem)
    {

        if (ItemList.Count <= itemMax)
        {

               //this if statement makes a list item add if the list.count is zero
            if (ItemList.Count < end)
            {
                ItemList.Add(newItem);
            }

            for (int x = 0; x < ItemList.Count; x++)
            {

                if (ItemList[x].nameID == newItem.nameID)
                {
                        //Checks for stackable item and less than 10 counts of item
                    if (ItemList[x].isStackable && ItemList[x].Count < 10)
                    {

                        ItemList[x].Count += 1;
                        break;
                    }
                    else
                    {
                        ItemList.Add(newItem);

                        end += 1;
                        break;
                    }
                }
                else
                {
                    ItemList.Add(newItem);
                    end += 1;
                }
            }

EDIT for floAr - I access the function like this:

        Items i;
        i = new Items();

        i.nameID = 1;
        i.Name = "Hog Meat";
        i.Item = ItemClass.Useable;
        i.Description = "Regenerates 30% hunger.";
        i.isStackable = true;
        i.Image = Content.Load<Texture2D>("hogmeat");
        i.sRect = new Rectangle(0, 0, 16, 16);

       backpack.Add(i);


texts:
I need to get position marked as green X.
I have the helicopter's world position and the player's world position. I want X to always have an angle of 90 degrees.
Player heading is ignored.
How can I obtain the position X.


texts: The pros and cons - DX9 moving to DX11 render?

texts:
We are a "nano" game dev company working on REFUSION.
DX9 renderer is almost done and question is: Should we move it to DX11 or not?
Anyone have experience with this?

Here are some videos from dev progress from the very beginning:

Dev test videos

EDITED: I'm going to ask more fundamental. What about NextNextGen XBOX1080 or PS4?
        When? Resources? Architekture? PC DX11 -12 , next XBOX, next PS relations? Future?


texts: Can I include social networks' name and logo in game credits without incurring in legal issues?

texts:
I'm planning to release an alpha version of a video game I'm working on as a personal project. I'm also creating a "Credits" section, that is meant for me to give credit to used sources, and to other peoples whose work I've used, edited, or got inspired from (with their permission, of course); and obviously, my own name.

I'd also like to include links to social network pages, such as my Twitter profile, a YouTube channel, and eventually a GitHub page. As an indie developer, I want people who play my game to have the chance to contact me, tell me their impressions about my game(s), and stay updated on my progress as development goes on. It's another way to receive feedback and reach even more people.

I wonder if mentioning the names "Twitter", "YouTube", "GitHub", and any other, and including their original logo or an edited version, is somehow possible and/or allowed - perhaps including some sort of clause - and what are the limits I'm subject to when dealing with trademarked names and logos under copyright.


texts: The Google Earth solution for panning in a 3D world

texts:
About a year ago I made a solution for panning and zooming in a 3D world (Three.js) using a formula provided by @DMGregory. Here is the post: How to panning camera on XZ axis with different angles

The result is very cool, because it really feels like you are dragging the scene:
https://codepen.io/josema/full/zMeNry

The problem

It turns out that I have to implement a following-object feature. In other words, I have to change the position of the camera to any part of the scene without losing the pan/zoom feature. And I think is not possible with this solution, because in this case the camera.lookAt.y changes when you pan. And it should be 0 to achieve what I want.

This is an example of what I would need, but the "responsive feeling" is not the same. https://threejs.org/examples/misc_controls_orbit.html (right click for panning). In this solution, we can easily say that the camera.lookAt.y is always 0.

The perfect solution is implemented by Google Earth:
https://earth.google.com/web/@40.40420135,-3.6986483,622.13605706a,960.94224964d,35y,-4.92354397h,63.56373285t,0r
Because it has the responsive feeling and the camera.lookAt.y is 0 when panning.

Question

Is it possible to implement something similar to Google Earth easily? If not how would you implement the https://threejs.org/examples/misc_controls_orbit.html?


texts: How do I make my foreground tiles stand out more from the background?

texts:
(the background implemented in the game)

In the game that I work on, the background and the map tiles are pretty indistinguishable for new players, probably because they have similar colors and theme.

Are there any tips or tricks to make the background more like a background and be distinguishable from the map tiles?

The game has motion blur which kinda helps, when the player is running the background gets blurry therefore making it more distinguishable from the map tiles.
However, that is clearly not enough.

Any suggestions, tips or tricks will be greatly appreciated!

(purely the background)

EDIT: Thank you for the suggestions and the ideas! here are some variations of this background that I came with.

(darker and way more blurry)

(dawn colors and some blur)

(one of the coolest things I've done + blur)

(one of the coolest things combined with dawn colors + blur)


texts: How can I load a level using a sound file? [JAVA]

texts:
I'm trying to load a level from a music file (mp3, midi, etc, I'm not picky) for a rhythm-based game. I must be searching in all the wrong places because I can't seem to find any help on this topic.

(I am using Eclipse Luna, AndEngine, Android SDK Tools 20.0.5 and ADT 23.0.4)

My plan was to stream the music file at run-time and create objects when certain pitches, etc are reached, but I have no idea how to do this in Java? Are there any libraries, etc I should be using or is this just not possible?


texts: CCUserDefault, iOS/Android and game updates

texts:
My game uses cocos2d-x and will be published on iOS platform first, later on Android. I save a lot of things with CCUserDefault (scores, which level was completed, number of coins taken, etc...). But now I have a big doubt.

What will happen when the game will receive its first update?

CCUserDefault uses an XML file stored somewhere in the app storage space. This file is created and retained until one uninstalls the app. I am wondering what happens when the app is updated. Will the old XML file be maintained?

Because if not, how should I handle app updates (updates in the sense that 2, 3 or more new level packages will be added, but the informations about the old ones, like scores, which level was finished and which not, number of coins, etc., need absolutely not to be lost)?


texts: What is the fastest way of drawing simple, textured geomtries and keeping the depth test?

texts:
I'm looking for a fast way to draw simple 3D geometries - that will consist of up to 10 vertices. Each of them will have a texture (though varying between geometries). I also want to store the fragment depth for depth testing.

There will be no lighting and only very simple transformations (this actually is for isometric game).

So far what I did was trying to achieve top performance using OpenGL for drawing simple quads (what the problem actually boils down to). For my machine (from around 2008), I had the following results:

Using immediate mode 4800 quads took 120ms
Using vertex arrays and VBOs this took around 40 ms

What I see as a problem is the bottleneck of glDraw* calls. I want to somehow get below 4-5 ms , as there will be really a lot of objects on the screen. Any ideas about how could (or perhaps couldn't) achieve that?


texts: Identify controller/buttons using javascript Gamepad API

texts:
Using the Gamepad API, or possibly some third party device mapping, is there a way I can associate buttons (gamepad api gives buttons by a numeric key value) to their controller counterparts?

For example, when using an xbox one controller with the PC, the "x" key is given by chrome as 2. I'd like to use the controller id/key value to show a picture of that happen to help new users.

It seems like this isn't something native to the gamepad API, but I'm not seeing any third party libs for it.


texts:
So let's say you've got a spline-based racing AI.  Assume it can already handle the basics of braking and steering around the track.

How would you structure and implement collision avoidance, overtaking, drafting, blocking and other behaviours so your cars remain competitive but make interesting races?

Links to papers/implementations would be awesome.


texts:
I am developing a 2d mobile game that has a large deformable terrain (a lot like worms).  I am rendering the terrain using a gray scale bitmap (in a fragment shader) which serves as a texture position map. If the pixel in the bitmap is black i render the pixel with a ground (tiled) texture else i render the background texture.

This works very well but now i would like to add rocks and static images to the terrain. The rocks will look like this

So my idea was to extend the grayscale bitmap to a RGB bitmap and use the green channel to mark the rock shape and the blue channel to mark the location of static images (which are not tiled).

Since the static images are not repeatable i would have to create blue rectangles which are exactly the same size as the static image. Could this be done any other way?

For the rocks i would use a similar approach but with the green channel so if the pixel in the bitmap is green i would render that pixel with a rock texture (the bitmap shape is blurred on the edge to render the black border). The rock texture is the dark gray color close to the black border on the picture. But the problem is that the rock is now a solid color with a black border and i would like to get as close to the picture as possible. Is it possible to create a texture to get the same type of shading as on the picture? Or is there any other way of doing this?

Thanks!


texts: trouble getting correct transforms for multiple meshes from assimp importer

texts:
I have had excellent success in extracting almost everything i need from a collada file that i imported with assimp, however I am struggling to get the correct transforms for each mesh in the file. Each individual mesh has correct vertex data but is not transformed relative to the others.

At first I thought my issue was that I simply wasn't applying the hierarchy of transforms for the meshes, and i read http://www.assimp.org/lib_html/data.html based on an answer from another thread and implemented the void CopyNodesWithMeshes function that is given in pseudo-code there.  However I have found that this didn't help as each mesh is a child of the root node and has only the identity matrix transform for the root and each of the mesh nodes (thus the combined transform for each mesh is identity also).  The hierarchy in the scene appears as follows :

           sceneRoot (identity)
               |
-------------------------------------------------
|               |                  |            |
Mesh0           Mesh1           Mesh2           Skeleton
(identity)      (identity)      (identity)      |
                                                ------------
                                                |    |   (etc)....
                                                (not identity)

There is no reference in the Skeleton to any of the mesh nodes as far as  i can tell.  I have also extracted the skeleton and bones for animation and they work but each mesh is simply at my origin since i cannot extract their transforms.

So i tried to load the model directly with assimp viewer and the 3 meshes load correctly from the model file and are in their correct relative positions.  I even tried to step through the loader code of assimp viewer and as far as i could tell it was getting identity matrix transforms just as i was for the 3 meshes from the sceneNode hierarchy.  But somehow assimp manages to render the 3 meshes correctly.

I am stumped at this point - does anyone know what i might be missing here?

Thanks

I am calling the following from assimp

const aiScene* scene = aiImportFile (fullpath, aiProcess_Triangulate
    | aiProcess_FlipWindingOrder);

And using the following code that i wrote to extract the combined transform for each mesh (though it doesnt do me any good since i get the identity transform for each):

//based on pseudocode of assimp http://www.assimp.org/lib_html/data.html
void CopyNodesWithMeshes(const aiScene* scene, aiNode* node, Matrix& accTransform)
{
    Matrix transform;
    Matrix nodeTrans;
    convertAssimpMatrix(nodeTrans, node->mTransformation);
    //transform = node.mTransformation * accTransform;
    multiplyMatrix(transform, nodeTrans, accTransform);

    // if node has meshes, create a new scene object for it
    if( node->mNumMeshes > 0)
    {
        //new SceneObject
        SceneObj& so = s_sceneObjs[s_numSceneObjs];
        so.numMeshes = node->mNumMeshes;
        for (int i=0; i < node->mNumMeshes; ++i)
        {
            so.mesh[i] = scene->mMeshes[node->mMeshes[i]];
        }
        s_numSceneObjs++;
        assert(s_numSceneObjs < eMaxSceneObjs);
        memcpy(&so.transform, &transform, sizeof(so.transform));

    }

    // continue for all child nodes

    for (int i=0; i < node->mNumChildren; ++i)
    {
        CopyNodesWithMeshes(scene, node->mChildren[i], transform);
    }
}


texts: How can I avoid coupling between units and their environment?

texts:
Currently in the process of making a game like Dwarf Fortress, so without graphics. I'm mostly thinking about how I want to implement everything. While writing code I keep stumbling on general game implementation problems that are really annoying me. Assume this:
We have a Map class which stores Chunk classes which stores Tile classes which stores Players and Enemys currently on this tile.
class Map {
    public:
        std::vector<std::vector<Chunk>> chunks;
};

class Chunk {
    public:
        std::vector<std::vector<Tile>> tiles;
        std::vector<Player*> player_need_update;
        std::vector<Enemy*> needs_update;
};

class Tile {
    public:
        std::vector<Player*> players;
        std::vector<Enemy*> enemies;
};

Now let's say I want to move() a player to a different Tile. For this I created a needs_update vector storing entities that need to be updated on the game Map. Every game tick we loop all chunks and loop all entities needing an update.
I think (thought) this is a logical way of doing this because we can have a tile that is independent of a chunk that is independent of a map. Same for entities. So let's say we want to move an Entity:
void Entity::move(uint16_t move_x, uint16_t move_y) {
    x += move_x;
    y += move_y;

    changed() // Notify chunk that something changed about us
}

This is already where it is going wrong. To be able to notify the chunk we have moved, we need to know ourselves in which chunk we are Chunk *in_chunk; in class Entity. And this breaks the structure I wanted to achieve (independence across classes).
Another example, suppose we want to attack an Entity on a different Tile. We would need to know there is an entity in the first place, but we would also need to know things about the enemy to then decide whether to attack it or not.
Player::attack(Enemy &enemy /* ?? */) {
    // Attack
}

I think it is wrong to move a player by calling a function in Map:
void Map::movePlayer(Player &player) {
    // Do stuff to move player
}

So, how do you implement basic game structures like this, keeping things logically structured but while still being able to ie. move a player across the map?


texts: Have body resume constant velocity after collision

texts:
I want to have a body move at a constant velocity, but react to collisions.

My example game is a train, I want it to move at 1 meter a second. If an obstacle appears on the tracks, I want it to react by smashing through it (which will normally slow it down). But when the obstacle is cleared, I want the train to accelerate back to 1 m/s and continue on.

It seems like the applyLinearImpulse() and applyLinearForce() methods are the place to start, but those are one-shot methods.

Thanks


texts: What is a good way to determine if a vector is between two other vectors in 2D?

texts:
I could operate with the angles, but I do not have the angles calculated yet (and would like to avoid having to do that). It would be possible to calculate and cache the local-coordinate-frame angles, though.

This is a routine that is run on every vertex of every convex polygon within the convex decomposition of every physically simulated object, so it should be as fast as possible.

I've got a corner of a convex polygon, so I have a vector from vertex to vertex-1 and another vector from vertex to vertex+1. It is easy to see that for a convex polygon, the interior of the polygon lies in the direction of the average of these two vectors.

I want to determine given any vector whether it points into that region or outside of it. Can I accomplish this using only cross products and dot products and similar fast operations? I am thinking about eventually offloading these calculations to a vertex shader, but as it changes the number of vertices required depending on an object's velocity, I imagine the logic could get dicey. Either way, before I attempt a vertex or geometry shader implementation I had better get a CPU solution working correctly first.

Here's an example: I want to find if N is between A and B. A points right at -10 (=350) degrees, B is at 15 degrees. So it looks somewhat like the < symbol. Function should return true only if N is between -10 and 15, between 350 and 375, etc. This was just to paint a mental picture, the input to the function are vectors: I want to avoid operating on angles because I do not want to call atan2.

It may help if it is known that A cross B is always positive. This is the case because my polygon is CCW winded and convex.


texts: Do I have to compile Unreal 4's source myself in order to make games with it?

texts:
Now I understand the need for this if people want to make modifications to the engine itself, but if I want to use the engine as is and just program games with it, do I need to do all this?

I figured I needed to build the Engine because a UE4 programming tutorial said "I assume you have already downloaded the engine source from GitHub and compiled it in VS2013", nobody says why, nobody clearly states whether or not this is required to make a game in C++ using Unreal Engine 4.

Can anyone help?


texts: Bullet Physics stops detecting collision after a few steps

texts:
Let me start off by saying that the usage of Bullet here is slightly unconventional. I'm writing a server emulator for a game, and the server is only keeping track of the triggers, players and enemies. It doesn't do a full physics simulation like the client.

Thus, the gravity is set to 0. The client is authorative over the position of the player object, so the rigidbody is just moved around on the server as the player walks through the world.

The problem is that, while Bullet can detect the collisions, it'll stop after a few steps. I presumed this is because the objects went to sleep / toggled as inactive, but moving them, setting flags telling them not to sleep, or forcing reactivation doesn't fix it.

I've created a small program that shows the problem:

void updatePos(btRigidBody* rb, btVector3 position) {
    btTransform initialTransform;

    initialTransform.setOrigin(position);

    rb->clearForces();
    rb->setWorldTransform(initialTransform);
    rb->getMotionState()->setWorldTransform(initialTransform);
}

int main() {
    btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
    btBroadphaseInterface* overlappingPairCache = new btDbvtBroadphase();
    btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;

    auto* world = new btCollisionWorld(dispatcher, overlappingPairCache, collisionConfiguration);

    //Create our player:
    btDefaultMotionState* state = new btDefaultMotionState(btTransform(btQuaternion(), btVector3()));
    btCylinderShape* shape = new btCylinderShape(btVector3(1.0f, 1.5f, 1.0f));

    btVector3 localInertia(0, 0, 0);
    shape->calculateLocalInertia(1.0f, localInertia);

    btCollisionObject* rbPlayer = new btCollisionObject();
    rbPlayer->setCollisionShape(shape);

    //Create our trigger:
    state = new btDefaultMotionState(btTransform(btQuaternion(), btVector3(-227.5784454345703, 555.2715454101562, -73.29886627197266)));
    btBoxShape* trigShape = new btBoxShape(btVector3(5.0f, 0.5f, 2.5f));

    btCollisionObject* rbTrigger = new btCollisionObject();
    rbTrigger->setCollisionShape(trigShape);

    world->addCollisionObject(rbPlayer);
    world->addCollisionObject(rbTrigger);

    rbPlayer->setActivationState(ACTIVE_TAG);
    rbTrigger->setActivationState(ACTIVE_TAG);
    rbPlayer->setActivationState(DISABLE_DEACTIVATION);
    rbTrigger->setActivationState(DISABLE_DEACTIVATION);

unsigned int stepCounter = 0;

while (true)
{
    printf("step %i\n", stepCounter);

    world->performDiscreteCollisionDetection();
    if (stepCounter == 1) rbPlayer->getWorldTransform().setOrigin(btVector3(-227.0f, 560.0f, -73.0f));

    int numManifolds = world->getDispatcher()->getNumManifolds();

    for (int i = 0; i < numManifolds; i++)
    {
        btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
        const btCollisionObject* obA = static_cast<const btCollisionObject*>(contactManifold->getBody0());
        const btCollisionObject* obB = static_cast<const btCollisionObject*>(contactManifold->getBody1());

        int numContacts = contactManifold->getNumContacts();
        for (int j = 0; j < numContacts; j++)
        {
            printf("yes\n");
        }
    }

    stepCounter++;
    std::this_thread::sleep_for(std::chrono::milliseconds(16));

    if (stepCounter == 15) rbPlayer->getWorldTransform().setOrigin(btVector3());
    if (stepCounter == 30) rbPlayer->getWorldTransform().setOrigin(btVector3(-227.0f, 560.0f, -73.0f));

    rbPlayer->activate(true);
    rbTrigger->activate(true);

    if (stepCounter > 40) break;
}
}

I'm willing to bet it's some slight oversight that caused this, but I couldn't find anyone with the same issue as me online.


texts: How to check if NPCs are on ground or not?

texts:
I'm using Unity Engine. I see the common way to check if player is on ground is shooting a Raycast:

How to solve the ground check problem?

How to check if grounded with rigidbody

I have a simple scene with Unity's terrain  for ground (Game Object > 3D Object > Terrain). Imagine you have a lot of NPCs (like GTA), is it possible to check a character on ground without Raycast? Do you have to run loop to ray cast check each NPC?


texts: try to create CCSpriteFrame but get nil values

texts:
I'm trying to animate a CCSprite in cocos2d v3 following this question, but I'm getting the following error message in Log:

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM
 insertObject:atIndex:]: object cannot be nil'

This is my code:

NSMutableArray *animationFrames = [NSMutableArray array];
    int frameCount = 0;
    for(int i = 1; i <= 9; ++i)
    {
        CCSpriteFrame *spriteFrame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName: [NSString stringWithFormat:@"hero-%d.png", i]];

            [animationFrames addObject:spriteFrame]; //ERROR OCCUR THIS LINE

        frameCount++;
        if (frameCount == 8) break;
    }

The problem is that all spriteFrames are nil, but I don't why. I already tested the i values with NSLog, and also tried to add hero-1.png to a CCSprite object and works fine. I also tried to add all fixed hero-1.png in all frames to verify if the problem was with i variable. But didn't work also.


texts: How do I make collision detection more effective?

texts:
In the game I am developing, there are 220 circles that are not moving. One of the circles is moving and in every update, it iterates through an ArrayList that contains all the circles and check if it collides with them and if it does, then its velocity is set to 0.

Sometimes, it works perfectly. However,most of the time, when the moving circle collides with another circle, it stops late sometimes when the ball is already inside the other circle. How can I deal with this?

I am using LibGDX with Java.


texts: How is a gimbal connected with Euler rotation angles?

texts:
When I see any video that explains how gimbal lock occurs, they explain it using a gimbal machine and I totally understand the effect on that machine. What I don't understand is how Euler angles are related to the idea how gimbal machine works.

And my #1 confusion comes from the following:

Euler angles rotate the coordinate frame but the axes stay orthogonal.
Gimbal circles rotate so that two rotation axes become collinear.

Hence I don't understand how gimbal mechanism can show how Euler angles work.


texts: What is the ideal way to separate presentation and logic, and when is it OK to combine them?

texts:
I'm still somewhat new to "proper" design, but I'm trying to keep with it as much as possible. I thought I was OK but I've run across a slight dilemma: how should I be implementing the actual drawing and updating of entities?

For example, in my project I have a TextBox class. The 'easy' way, and the way that I usually see in tutorials across the Internet, are to give this class its own Update() and Draw() methods. But I don't think my textbox class should have to know anything about how it's being drawn, so I thought it might be good to make it implement some kind of Drawable interface, but even that still involves implementing drawing code.

So I thought of adding all my TextBoxes to a List<TextBox> that a drawing class would load to handle the drawing, but then I realized that my TextBox class itself doesn't (and shouldn't?) have a Draw() method within the class, so I would have to write a sister method in the graphics implementation somewhere as a DrawTextBox() or something like that. I guess this COULD work, but I can't shake the feeling that having to have this kind of coupling of classes is bad practice.

So where should I ultimately be placing the code to draw, and where should I have the logic behind it? A TextBox, for example, involves drawing multiple elements, and it's timed because it's a typewriter-style output, and I eventually want to add in-text commands for delays and sound. Should I include some of this stuff in the main class? Have a Draw method in some graphics class somewhere else? And then later dealing with timing and sound, how should I be separating all of it?


texts: I've been using XNA to learn game programming for some time, and I'm interested in moving to Android.  Having said that; the learning curve to get started seems to have ramped up exponentially.  I have a working knowledge of Java (started with it before learning C#).  Is there an intermediate step I should take in order to prepare myself for working with Android game programming?  And are there any resources that are geared toward moving from XNA to Android?


texts: Should I use textures that are the size of the object?

texts:
I've been reading but couldn't find an answer to my question:

If I have an object, let's say 30x30. Should I use a texture that is 30x30, 300x300, or even 3000x3000 or should I follow 'the powers of two' for textures?

I've been using 3000x3000 for a 30x30 object and it has been working, but I'm worried that it might not work for others.


texts: Performance tracking/monitoring in games

texts:
Let's say I have an online game with a downloadable client / browser plugin.
I want to track performance of my software and automatically send summary to the server. Let it be fps, latency, load time, physics step calc. time, whatever...
I also want tools to perform data analysis: per session stats, per hardware stats, avgs, totals, diagrams, etc.
So that I could see what are the real world hotspots / bottlenecks.

Is there any common out-of-the-box / SaS solution?


texts: How to apply blur effect to 2D textures using shaders?

texts:
I'm making a 2D game in Monogame and I'd like to learn how to apply the blur effect for layers that are "out of focus" in the deep background or very close in the foreground using shaders.

By manipulating the bitmap array of a Texture2D (it's pretty slow), I figured it would be better to draw each layer onto its own Texture2D and blur the whole thing instead of blurring individual textures. But then I learned there are shaders which are supposed to make this much faster. I've never used shaders for anything yet. How would I use shaders for the blur effect?

Most of the shader tutorials for monogame/xna I've seen so far deal only with 3D or do something I don't understand in 2D which doesn't seem to do the blur effect.

Following DMGregory's suggestion in the comments, I decided to try the second shader which is:

// Pixel shader applies a one dimensional gaussian blur filter.
// This is used twice by the bloom postprocess, first to
// blur horizontally, and then again to blur vertically.

sampler TextureSampler : register(s0);

#define SAMPLE_COUNT 15

float2 SampleOffsets[SAMPLE_COUNT];
float SampleWeights[SAMPLE_COUNT];

float4 PixelShaderF(float2 texCoord : TEXCOORD0) : COLOR0
{
    float4 c = 0;

    // Combine a number of weighted image filter taps.
    for (int i = 0; i < SAMPLE_COUNT; i++)
    {
        c += tex2D(TextureSampler, texCoord + SampleOffsets[i]) * SampleWeights[i];
    }

    return c;
}

technique GaussianBlur
{
    pass Pass1
    {
#if SM4
        PixelShader = compile ps_4_0_level_9_1 PixelShaderF();
#elif SM3
        PixelShader = compile ps_3_0 PixelShaderF();
#else
        PixelShader = compile ps_2_0 PixelShaderF();
#endif
    }
}

Populating it with some random floats and Vector2s in the range from 0 to 1, then 0 to 100, then -100 to 100 and it just doesn't produce any effect. I tried moving the line blurEffect.CurrentTechnique.Passes[0].Apply(); before and after all the drawing methods and in-between, but nothing happens.

I had trouble loading it at first but then I figured it out with the content folder thing, so that doesn't seem to be the issue, or else it would probably throw an exception on the loading methods.

I've seen the exception for setting the effect parameters  incorrectly, so seems like I'm doing that right too. I think the problem might be with the values themselves. I don't know what I'm supposed to use there and why the 15 samples and not some other number.

Ideally I would like a complete noob guide to shaders on this one example of gaussian blur applied to everything (or only to certain background textures).


texts: Creating a smooth transition between materials on large models using Unity and/or Blender

texts:
I'm not sure if this is possible or not but I would like to create a smooth transition (cross-fade) between two textures on a 3D model made in Blender that can be imported to Unity.

For example if I have a model with two materials, the edges where the materials meet is an abrupt change. How would I go about creating a smooth transition across the edge where the materials meet?

I've seen some tutorials on using cycles in Blender to achieve this, but to the best of knowledge the cycles rendering cannot be brought into Unity.  Projection painting in Blender using an image as the brush is also a possibility, but the models I'm trying to do this on are rather large and would lose resolution in their textures because of this.  Is something like Substance Painter by Allegarithmic what I need?


texts: Transforming 2D viewport coordinates after scaling the viewport (zoom in/out)

texts:
I've been getting started with personal experimentation and have been working on a project for a few days now using SDL2. It is a 2D game, and at this stage I have it rendering game objects in a fixed-size viewport that can navigate around the 'game world'.

I'm not terribly well-versed in linear algebra yet, so it's possible that the answer to this question is somewhere in that curriculum that I have yet to tackle.

The game space has its own coordinates, organized in the same way that they are on an SDL_Window. The "viewport" then has its own coordinates (indicated by it's top left corner) in the game space. Game objects are then given transformed coordinates in the viewport's own coordinate space, which corresponds to the SDL_Window's coordinate space i.e. they start at (0, 0) at the upper left, which is essentially an offset given the viewport's coordinates, e.g.:

Entity x's gamespace coordinates are (100, 200) and the viewport's gamespace coordinates are (20, 20), the entity's "viewport" coordinates would be (100 - 20, 200 - 20) or (80, 180).

I've started to think about implementing 'zoom' functionality. At the moment, all that means is that the viewport is scaled up or down (to certain size limits), and the game entity's dimensions are scaled up or down correspondingly. What isn't transformed are the coordinates.

Visually, this is the basic problem:

At maximum size, where the viewport's dimensions are the same as the game space's dimensions (they have the same aspect ratio), the positions of all objects in the viewport space would be the same as they are in the game space, but they would have to be positioned using completely different coordinates in the viewport space.

What are the mathematical techniques/principles I should be studying to figure this one out? Thank you!


texts:
What is the state of the art in terms of shadow rendering? My target is OpenGL 3.2, using a deferred rendering pipeline, if that matters.

It's been years since I looked into shadow rendering, and at that time there were numerous techniques available, from stencils to the various shadow mapping methods. At that time, rendering shadows required separate rendering passes, controlled by the CPU. But then recently I saw a demo where a scene was rendered entirely on the GPU, including shadows. I have no idea how that would have been accomplished, or if it is even a reasonable thing to do (beyond a tech demo).

Given the large amount of old info on the internet, I'd like to learn what methods people are using these days, and how much of it can be pushed to the GPU (assuming my target OpenGL version supports it).


texts: Vector games (Wireframe, Elite-like) theory and implementations?

texts:
I'm interesting in knowing more about how vector games like Elite and Star Wars Atari were built from grounds up. The question is not how to implement vector graphics with modern 3D APIs like OpenGL and DirectX, since doing it is quite easy and does not require to build a vector/matrix system from scratch like those games did.

Some things I presume about these games:

They work on an extremely low level and are written in ASM
They're actual 3D games and not faking it like After Burner. Not like Wolfenstein 3D, either. Afterburner used rotozoom/raster effects and Wolfenstein 3D used raycasting and 2D scaling and it's not really 3D, since you can't move up. Even if you could like the Build Engine that Duke Nukem 3D used, everything except the walls is just a sprite. Star Fox is closer to it, since uses actual 3D models, but the implementation uses SNES' Super-FX chip and probably employs scanline trickery. I know Elite probably uses said scanline trickery as well (at least on some implementations like Elite NES) but I'm not sure about SWA, since it used a custom-built arcade machine; either way, I'd like to know more about it.
Their 3D models are actual 3D models. They are defined as vectors and transformed according to the position of the camera.

I know the best thing to do would be to disassemble the source of Elite and see how things were done by myself but before doing that I want to know more about how they were made and if there are modern open-source projects that show similar techniques. I don't mean Elite remakes like Oolite (which uses OpenGL and Obj-C) but projects that use similar techniques and avoid using APIs like OpenGL directly - not necessarily low-level projects, though, using 2D library like SDL (without OGL) should be enough, at least for now.

I know that the source code to MESA3D probably contains many of the routines that games like Elite and SWA implemented - I just want to see them in the context of a game. I know that what Elite and SWA basically did was implement Rasterisation, create their format for models and a loader (I'm pretty sure that at least SWA had models built from modelers using tools, although it's not impossible to hard-code TIE-fighters it's hard to do so accurately) and many other things I may be unaware of. But it's really time-consuming to get into and I don't care about much of the stuff that is in it. Keep in mind that games like Elite were very lightweight due to the low ROM and RAM that computers and consoles had at the time.

I'm new to 3D graphics and all my assumptions are based on my limited knowledge of 3D Geometry and school level maths, sorry if I said any bullshit. But I'd really like to know more about how those games work in every detail, and possibly not just "buy X book" since I'm quite broke. Although I'd buy a book about the development of Elite or a similar game, if it existed. Some general suggestions would be enough.


texts: Pairing algorithm for the Elo rating system

texts:
Imagine a 1 on 1 (not teams) competition between AI bots, like the Google AI Challenge.  The various bots are assigned an ELO rating based on the outcome of the various versus matches.  The reason I specify AI bots as they can compete 24/7 without regard for player fatigue, geolocation, etc.

Given limited server resources only so many bouts can be run per day.  I'm looking for a heuristic (or an optimal algorithm) to choose which two bots should compete next.

All the past competitions have been tracked.  By this I mean that the algorithm has more to work with than just the ELO ratings.

The use cases I'm partitularly interested in:

The competition has been pairing randomly for while and now I want to make intelligent pairing decision.
The Elo rating have stabilized and a bot is updated.
The Elo ratings have stabilized and new bot is introduced to the competition.

Update:
I need to clarify.  I'm not looking for an algorithm that will provide fair matches.  I'm looking for an algorithm that will find matches most likely to update the Elo ratings of the bots to their "true" ratings with the least number of matches.


texts: Radiance arriving at or leaving a surface

texts:
I was reading this text about radiance and according to the next figure, both leaving and arriving radiances' solid angles are anchored on the surface point?

My logic tells me that the solid angle of the radiance arriving at a surface is supposed to be anchored somewhere in the "air" (say at the light bulb position). Something like this:

This way the radiance formula makes sense too, no? (irradiance per solid angle, meaning when the solid angle gets bigger the radiance at point gets smaller)

Can someone shed some light on this?


texts: Voxel (Marching Cubes) Terrain Creation / Terrain Editing

texts:
im working on a voxel based game in unity. the terrain(sphere-->planet) should be out of voxels and at first i built a minecraft like voxel plugin for unity. this means that i had a sphere out of cubes, but as you can imagine, a sphere out of cubes just doesn't look good :P (i made a level array which stored the material at [x,y,z]. --> so when "1" stands for stone, it means that level[x,y,z] = 1; was stone. but then i decided to use the marching cubes algorithm for my voxel planet.
so i learned the marching cubes algorithm and i realised that now i must have a density function, and not a level array with material information.

my density function looks like this:

x * x + y * y + z * z - rad - (noise.FractalNoise3D (x, y, z, oct, frec, amp) * scale);

The noise is made by a simplex noise generator script.
so far so good. i get a good sphere rendered with a little bit of noise. but when i try to edit the sphere (terrain editing) i run into problems.

i made a function which gets the collision coordinates(x,y,z) of the mouse and the sphere, and changes the density in the level array at these coordinates.:

void dig(){
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

    if (Physics.Raycast (ray, out hit)) {
        Debug.Log ("Dig...");
        Debug.DrawLine(ray.origin,ray.origin+( ray.direction*hit.distance), Color.green,2);
        editTerrain(hit);
    }
}

void editTerrain(RaycastHit hit){
    int xEn = (int) hit.point.x;
    int yEn = (int) hit.point.y;
    int zEn = (int) hit.point.z;

    level [xEn, yEn, zEn] += 1000;

    mesh = MarchingCubes.CreateMesh (level);
    mesh.uv = new Vector2[mesh.vertices.Length];
    mesh.RecalculateNormals ();
    GetComponent<MeshFilter> ().mesh = mesh;
    GetComponent<MeshCollider>().sharedMesh=mesh;
}

my problems/questions now:

-is the density function alone enough for my level array? did i understand terrain creation right so far?

-when i try to edit the terrain (add something to the density at levelArray[x,y,z], it just flats the surface, but doesn't dig holes.

-when i want to add materials to my voxel planet (stone, dirt, sand, etc...), can i make another array, which holds the material data at [x,y,z]? are there better possibilities?

-i also realised that when i turn my sphere in the unity editor, my colission detecten gets displaced. like when i want to edit the top of the sphere, the bottom of the sphere gets changed...

-btw...i know i didn't apply chunks to my voxel planet yet...this comes later...

i hope anybody can help me because i don't know what to do.


texts: How to build a C# library for Unity as a pure Visual Studio project

texts:
The aim is to build a relatively simple (2D) game in Unity with most of the game logic in a non-visual AI. The AI needs a lot of testing and debugging independently of any visuals (which is best done using VS tools), and the API connecting them is one class and a few methods/properties. [A future version might not even use Unity.]

So the question is how to set up a VS solution file to build the AI for testing and debugging while remaining compatible with the Mono build environment used by Unity. Yes, I know it has to be C# 4, but beyond that? At present I'm copying CS files around and that doesn't feel right.

Just to make it crystal clear, the AI has no dependency on Unity and will be built in a project that has VS testing and code analysis but no Unity tools or imports. In future it may be used with a different engine.


texts: How can I reflect a point about a line in Unity?

texts:
I am drawing a line using the line renderer in the following way:

public class MyLineRenderer : MonoBehaviour {
LineRenderer lineRenderer;

public Vector3 p0, p1;

// Use this for initialization
void Start () {
  lineRenderer = gameObject.GetComponent<LineRenderer>();
  lineRenderer.positionCount = 2;

  lineRenderer.SetPosition(0, p0);
  lineRenderer.SetPosition(1, p1);

}

}

From the image below, the line P0P1 is known and so is point A. How can a point B, which is the reflection of A about the line P0P1 be found?


texts: I'm developing a 2D shooter using AndEngine. At the moment I'm trying to make the camera follow the player. As I've understood the common approach is to use the SmoothCamera zooming it and setting the chased entity. The problem is that the camera follows the player WITH background moving also (RepeatingSpriteBackground), so it looks like the player doesn't move at all though the actual position changes. So I don't really get how to make the camera follow the player and have the background not moving. Thanks in advance.


texts: Do I need to build my scripts every time I go back into Unity from my script editor?

texts:
I saw a few Unity YouTubers who do not build their scripts when they are working.

But I always do it.

Do I have to?


texts: JsonUtility is throwing exception when there is \" in the string

texts:
The following is my JSON file:

{
    "data" : [
               {
                 "nameString" : "My name is \"Ansar\"",
                 "id" : 1234
               }
    ]
}

When I try to parse this JSON file using JsonUtility, it is throwing an exception because of the \" character. If I remove the character from the string, it works smoothly.

Exception:

ArgumentException: JSON parse error: Missing a comma or '}' after an object member.
UnityEngine.JsonUtility.FromJson (System.String json, System.Type type) (at /Users/builduser/buildslave/unity/build/Modules/JSONSerialize/Public/JsonUtility.bindings.cs:50)

Why this is happening? Is this a JsonUtility bug? Anyways to fix this?


texts: Are there any Java based libraries that provide game mapping features?

texts:
I'm working on a Java web based game in my spare time (springMVC / JSPs etc), and I'm wondering what are my options for dealing with the "game world" or mapping element.

My game will be 2d / text based, so I have no need for any OpenGL / Flash etc.

My initial idea was to use Google maps and provide a custom overlay, but I want to know if there are any alternatives?

For example, if I create a 2d map with all my zones, are there any libraries that will help me plot players, work out distances and so forth?

Regards


texts: Blender - Exporting and Replicating Bone Animation

texts:
I'm having trouble replicating Blender bone animation in my game.

Bones that have a vertical rest position (Euler(PI / 2, 0, 0)) are animated correctly (e.g. head, neck, torso, legs, shins), however bones that have horizontal rest positions (e.g. hips, shoulders, arms) appear slightly off.

I export each bone's rotation Euler value at each frame and reconstruct the rotation matrices in game. (exporting matrix values at each frame results in a larger file size)

I tried exporting quaternion values instead, but the resulting animation looked exactly the same.

I have successfully imported the model's resting mesh position and resting bone position. The issues happen during animation.

In Blender, the model's rest position is:

At a certain frame in Blender the model looks like this:

At the same frame in-game, the model looks like this:

As you can see, the hip bones are at more of a downward angle, and the "L.Shoulder" bone is at more of a downward angle.

The matrix I use to rotate each bone in-game is:

Matrix4.CreateTranslation(-bone.head) *
Matrix4.CreateXYZRotation(-bone.restingRotation) *
Matrix4.CreateXYZRotation(bone rotation at frame X) *
Matrix4.CreateTranslation(bone.parent.tail)

I obtain each bone's resting Euler rotation by decomposing PoseBone.bone.matrix_local, and obtain each bone's animated Euler rotation by decomposing PoseBone.matrix:

The commands above were run at the same frame as the images of the animated model. The resting Euler rotation of the right shoulder is similar to that of the left shoulder, however the animated Euler rotations are quite different.

The roll of the L.Shoulder bone is -14 degrees, and the roll of the R.Shoulder bone is 14 degrees.

Any help with this would be greatly appreciated.


texts: When to read/write to database with a game server

texts:
My question is fairly simple but maybe hard to answer. I'm currently building my own game server and I've done to login server now. So, on to the actual game server. I have a question for this server though. Say, a thousand players are moving around on this server, how do I manage this with the database (MySQL) that should hold the player positions and such?

I understand I can't query the database every time something small changes or a single player moves because that would be a huge load for that server. How is this done in real game servers? When do they read or write to the database?


texts: Animations in FBX exported from Maya are anchored in the wrong place

texts:
We are trying to export a model and animation from Maya into Unity3d.

In Maya, the model is anchored (pivot point) at the feet (and the body moves up and down). However after we have performed the FBX export, and imported the file into Unity the model is now appears to be anchored by the waist/head and the feet move.

These example videos probably help explain the problem more clearly:

Example video - Maya - Correct
Example video - Unity - Wrong

We have also noticed that if we take the FBX file and import it back into Maya we have exactly the same problem.

It seems to be that the constraints no longer work after the FBX is reimported back to Maya, which just kills the connection between the joints and the control objects.

When we exported the FBX we have tried checking the 'bake animations' check box.

The fact that the same problem exist when importing the FBX back into both Maya and Unity suggests that the source of the problem is most likely with the Maya FBX export.

Has anyone encountered this problem before and have any ideas how to fix it?


texts: Streaming webcam via websocket performance issues (Code included)

texts:
I finally figured out, how I can stream my webcam, but I'm getting not the best performance. In low resolutions it's working fine, but as soon as I turn the resolution up, the performance gets worse. I think Unity can't handle the decoding in that quality and speed so that the game is getting slowed down. Here is my Code :

Texture2D screenshot = new Texture2D(Screen.width, Screen.height, TextureFormat.ARGB32, false);
screenshot.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0);
screenshot.Apply();
ws.Send(System.Convert.ToBase64String(screenshot.EncodeToJPG(quality)));

Hopefully there is something to improve.


texts: How to define type-specific scripts when using a 'type object' programming pattern?

texts:
I am in the process of creating a game engine written in C++, using the C/C++ SQLite interface to achieve a 'type object' pattern. The process is largely similar to what is outlined here (Thank you Bob Nystrom for the great resource!).

I have a generally defined Entity class that when a new object is created, data is taken from a SQLite database and then is pushed back into a pointer vector, which is then iterated through, calling update() for each object. All the ints, floats, strings are loaded in fine, but the script() member of Entity is proving an issue. It's not much fun having a bunch of stationary objects laying around my gameworld.

The only solutions I've come up with so far are:

Create a monolithic EntityScript class with member functions encompassing all game AI and then calling the corresponding script when iterating through the Entity vector. (Not ideal)
Create bindings between C++ and a scripting language.

This would seem to get the job done, but it feels like implementing this (given the potential memory overhead) and learning a new language is overkill for a small team (2-3 people) that know the entirety of the existing game engine.

Can you suggest any possible alternatives? My ideal situation would be that to add content to the game, one would simply add a script file to the appropriate directory and append the SQLite database with all the object data. All that is required is to have a variety of integers and floats passed between both the engine and the script file.


texts: In Unity, how do I set up a delay before an action?

texts: I want an object to rotate after a delay. I tried using StartCoroutine, yield and WaitForSeconds, but failed. How can I do it?


texts: How make a laser path prediction line like a “slingshot cowboy” game?

texts: How so I make a laser path prediction line like a “slingshot cowboy” game in cocos2d or box2d and select the target like "slingshot cowboy" game.


texts: Touch input not working well for mobile game made with Unity 2D

texts:
I made a simple game in unity where the user taps their phone screen and the player jumps up. When I test it on my phone (not sure if this matters but it's a Samsung s9+), I tap the screen and usually the tap causes the player to jump up and fall back to the platform properly, but sometimes when I tap the screen nothing happens at all it just stays in place. The game on my phones is also very slightly laggy (although, on my computer it runs smoothly) and I'm not sure how to fix that either or if they're related.

This is the code attached to the player:

 void FixedUpdate()
 {
     Jump();
     Dead();
 }

 void Jump()
 {
     if (Input.touchCount > 0 && isGrounded)
     {
         gameObject.GetComponent<Rigidbody2D>().AddForce(new Vector2(0f, jumpForce * Time.fixedDeltaTime), ForceMode2D.Impulse);
     }
 }

Also, I know that it's the touch input that's the problem, because when I make it so that pressing the up arrow key on the keyboard makes the player jump, it works perfectly fine. If there's some other information about the game you'd need to know to answer my question, let me know. Thanks for your help.


texts: which is the best physics engine for flash as3?

texts: i am a game programmer and i use actionscript to do all my collision checking, boundary checking etc...but recently i noticed there are things called "physics engines" that help me concentrate more on game making rather than physics making. so i would like to know more. i heard there are few engines called "box2dflash" and "APE".


texts: Questions regarding using (CC BY-NC-ND 3.0) and (CC BY-NC 4.0) music for a completely free game (not Freemium)

texts:
I am in the process of developing a small video game for a game-jam on itch.io.
The game-jam requires the developer to first make a github repository, upload all the source code and material (including music, sound effects and artwork) there and provide a link to your game-jam entry on itch.io.
I want to use some music that I found on freemusicarchive.org.
Some of the tracks on the website have (CC BY) licence while majority of them are either CC BY-NC-ND 3.0 or 4.0 (meaning to say that majority of the music tracks are NOT allowed for commercial purposes).
So my question is this:
I do not intend to make any money from my entry and I will make my entry completely free to access it. There will be no freemium or pay-to-unlock-features kind of thing with my game. It will be 100% free. You can go to the URL of my game, which will be hosted on itch.io (zipped HTML) and then anyone can play it.
Can I use music that have non-commercial licences in them (e.g CC BY-NC-ND etc.) for my completely free to play game?
Thanks!


texts: Libgdx Android app: Avoid fullscreen and show titlebar

texts:
I am developing an app using Libgdx and I don't want the app to go fullscreen and want to show the title bar but the app goes to fullscreen and hides title bar despite all efforts.

Here is my style.xml file

<style name="MyStyle" parent="android:Theme.Light"></style>

Here is AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyStyle" >
    <activity
        android:name="com.mygdx.game.android.AndroidLauncher1"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

Here is AndroidLauncher class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
    config.hideStatusBar=false;
    initialize(new MyGdxGame(), config);
    setContentView(R.layout.main_activity);
    tv=(TextView)findViewById(R.id.tv);
    tv1=(TextView)findViewById(R.id.tv1);
    button = (Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (Build.VERSION.SDK_INT < 19) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
            else{
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/*");
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
            }
        }
    });

}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            selectedImagePath = getPath(selectedImageUri);
            Intent act2 = new Intent(this ,AndriodLauncher2.class);
            act2.setData(selectedImageUri);
            startActivity(act2);
        }
    }
}

public String getPath(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}


texts: How do I balance these numbers in a rock-paper-scissors attack system?


texts: UE4: Apply texture on landscape based on angle

texts:
I am creating a material for my landscape. I know that one could for example use the landscapes heightmap as a mask to apply textures at certain heights, but I want to apply textures at certain angles. For example, applying a cliff texture if the angle at that point in the landscape is larger than 45 degrees.

Thanks in advance!


texts: It's possible to add object made by blender to unity terrain ? this object will become a part of it. I can add grass and trees on it.


texts: How to use UpdateSubresource and Map/Unmap?

texts:
From what I understood (from reading various pages) there are 2 ways to update a buffer:

UpdateSubresource() (when buffer is created with DEFAULT usage)
Map(), copy the new data, Unmap() (when buffer is created with DYNAMIC usage)

In the first case do I only call this one function (nothing more)? Because I've seen people say they map the buffer and then update subresource, or maybe I misunderstood them.

Also is there any other way (doubt it :P)? Do I understand things correctly?


texts: How to raycast octree for closest leaf node?

texts:
So I need to raycast a octree for closest leaf node as efficient as possible. I will be doing it on compute shader (hlsl), but I think it doesn't matter because first I need to understand the approach and math behind this process in general.
My struct looks like this:
struct OctreeNode
{
    uint  size; // size of cubic node

    uint posX; // center of node
    uint posY; // center of node
    uint posZ; // center of node

    uint childExists;
    uint isLeaf;
    uint isChild;

    uint parentIndex; //Parent node index in structured buffer
    uint minchildIndex; // Node child min index in structured buffer (+1 is next child, etc)
    uint index; //Index in structured buffer
};

Octree is rather big, so I guess I can't afford to raycast everything and then compare distances. I have been looking into https://stackoverflow.com/questions/6281415/octree-raycasting-raytracing-best-ray-leaf-intersection-without-recursion , but I do not understand the answer (especially HLSL one with hitbox what is unknow thing).
Any hints, code, directions highly appreciated.


texts: Move a sprite in a sine wave along different angles

texts:
I understand this piece of code

Enemy.position.Y = StartPosition.Y + (-(float)Math.Cos(position.X / 100) * 100);

However it only works along the X axis. What I want to be able to do is move it along an arbitrary axis; Set an angle as the x axis.
How would I go about this?


texts: Build / Destroy function design & security checks

texts: I'm working on a browser based strategy game. For the moment I'm working on the build/destroy functions and I have a couple of questions about this. The main question is do you have advice on how I can pass the buildingId and townId to the page where I call the build function? Any advices about the checking I should have in the build / destroy function?


texts: Is there any way to load pieces of a tile-map as and when needed, and not the entire map at once?

texts: I created a tile-based rpg game in java, but it runs really really slow, the reason is the big tile-map that is stored in the buffer. Is there any way to programmatically load pieces of the map when needed and not the entire map at once, so that the buffer will remain small and the game will run fast? Any sort of useful tip would be helpful.


texts:
Lets say I have a 2D character with two colliders: a circle collider that represents the feet, and a box collider that represents the body. Lets say that the character is currently standing on the ground, i.e. only the feet collider is in contact with the ground collider. According to the Unity manual, I will receive an OnCollisionEnter2D message. That message contains a Collision2D object that contains an otherCollider field of type Collider2D. I don't see anything in that object that would tell me which of the two colliders - the body or the feet - initiated the message.

So my question is this: how do you figure out which collider in a compound collider initiated a collision/trigger message?


texts: Matrix in constant buffer on the GPU contains NaNs but not on the CPU

texts:
I've got a shader with the following constant buffer:

cbuffer ShaderParameters
{
    matrix inverseViewProjectionMatrix;
    float4 cameraPosition;
};

When using Visual Studio 2012's graphic debugger I see that the last column of this matrix contains only NaNs, the other values are correct. So somehow my program is passing wrong values to the GPU.

However when I debugged my C++ code I see no NaNs in the matrix that I upload to the GPU. So what is going on? Below are the relevant parts of code

Struct for the constant buffer on the CPU:

struct ShaderParameters
{
    XMMATRIX inverseViewProjectionMatrix;
    XMFLOAT4 cameraPosition;
};

Buffer creation:

D3D11_BUFFER_DESC shaderParametersDesc;
shaderParametersDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
shaderParametersDesc.ByteWidth = sizeof(ShaderParameters);
shaderParametersDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
shaderParametersDesc.MiscFlags = 0;
shaderParametersDesc.StructureByteStride = 0;
device->CreateBuffer(&shaderParametersDesc, NULL, &m_shaderParameters);

Buffer setting (every frame)

D3D11_MAPPED_SUBRESOURCE mappedResource;
ShaderParameters* shaderParameters;
deviceContext->Map(m_shaderParameters, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
shaderParameters = (ShaderParameters*)mappedResource.pData;

XMMATRIX view = camera->GetViewMatrix();
XMMATRIX proj = camera->GetProjectionMatrix();
XMMATRIX mult = XMMatrixMultiply(view, proj);
XMMATRIX invp = XMMatrixInverse(nullptr, mult);

if(XMMatrixIsNaN(invp))
    throw std::exception("invp is NAN");

shaderParameters->inverseViewProjectionMatrix = XMMatrixTranspose(invp);
shaderParameters->cameraPosition = camera->GetPosition();

deviceContext->Unmap(m_shaderParameters, 0);
deviceContext->VSSetConstantBuffers(0, 1, &m_shaderParameters);

Note that the exception is never thrown and if I inspect the matrix manually there are sane values in there (see image)

EDIT: some asked (via twitter) to include some more shader source code as unused values might be seen by the debugger as NaN. So here is the complete vertex shader:

cbuffer ShaderParameters
{
    matrix inverseViewProjectionMatrix;
    float4 cameraPosition;
};

struct VertexInputType
{
    float4 position : POSITION;
    float4 uv       : TEXCOORD0;
};

struct PixelInputType
{
    float4 position         : SV_POSITION;
    float4 direction        : TEXCOORD0;
    float4 cameraPosition   : TEXCOORD1;
};

PixelInputType main(VertexInputType input)
{
        PixelInputType output;

        input.position.w = 1.0f;
        output.position = input.position;

        output.direction = mul(input.position, inverseViewProjectionMatrix) - cameraPosition;
        output.direction.xyz = normalize(output.direction.xyz);

        output.direction.w = 1.0f;

        output.cameraPosition = cameraPosition;

        return output;
}


texts: How to swallow touches on CCMenu while sliding?

texts: I'm creating a sliding menu for my game something like angry birds level selection but I'm having problem with buttons. If I accidentally touch any of the buttons while swiping the level starts to load.


texts: Unity change default settings for standard components

texts: How can I change the default settings for the standard components or is this even possible? E.g. setting the default font-size for a text component so that each new text component I add will have the same font-size?


texts: Alpha blending works when rendering to an FBO, but not when rendering to the screen buffer

texts:
My rendering pipeline goes something like this-

Bind multisampled FBO

Render GameObjects

Render Transparent Objects

Blit multisampled FBO to normal FBO

perform any Post processing

Render a quad with the result

Render GUI

I've found I can render transparent objects in the "Render transparent Objects" function, but alpha blending against the post processing quad doesn't work. Is there any reason why this would be? This draw call is used regardless of whether it is being rendered to the FBO, or to the screen buffer
It is a button in particular I'm trying to render, here is the draw call:

glEnable(GL_BLEND);

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

glFrontFace(GL_CW);

glUseProgram(thisConfig.guiShaders->getProgramID());

//Bind uniforms..... code skipped

glBindVertexArray(VAO);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);

glDrawArrays(GL_QUADS, 0, 4);

glFrontFace(GL_CCW);

Let me know if there is anything I need to provide to help. Again, same shaders are used in both cases, so I don't think the shaders are the problem, but here they are anyway:

#version 330
uniform sampler2D textureImage;

// input packet

in packet{
    vec2 textureCoord;
} inputFragment;

// output packet
layout(location = 0) out vec4 fragmentColour;

void main(void) {

vec3 gamma = vec3(1.0 / 2.2);
vec4 tempFragmentColour = texture2D(textureImage,     inputFragment.textureCoord);
    fragmentColour = vec4(pow(tempFragmentColour.xyz, gamma),     tempFragmentColour.a);
//  fragmentColour = vec4(tempFragmentColour.a);

}

I have tried writing in the alpha values manually in the shaders and I get the same effect.

Working with OpenGL 4.6 on PC with c++


texts: Resolving collisions with float precision errors

texts:
I'm facing a problem when I try to resolve the collision between two units using floats as positions of the units in my game.

I am detecting the collisions using the SweptAABB algorithm and if there is a collision I fix it by using the normalized collision time that the SweptAABB function returns. Something like this:

collisionTime = SweptAABB(unitA, platform)
fixedPosition = (currentPos - previousPos) * collisionTime;

This generally works fine but not always, due of the floats precision errors the fixedPosition can result in a VERY SMALL overlap.
For example: suppose that the fixedPosition for the Y axis should be 12.345234 to avoid the collision but instead of getting that value (after multiplying by the collisonTime) I get something like 12.345239 (a difference of 0.000005) and when eventually the overlap method is executed it will still detecting the overlap:

public boolean overlap(AABB b) {
    Vector2 distance = new Vector2(b.position).substract(position);

    return Math.abs(distance.x) < (extents.x + b.extents.x)
        && Math.abs(distance.y) < (extents.y + b.extents.y);
}

So I decided to start changing the code so that I can get the face of the box that collides and use simple arithmetic addition of the positions instead of multiplication but this also fails for the same reason. For instance, suppose this:

// unitA collides with unitB at this point in the X axis:
float unitB_Face_X = 0.7466669f;
// since position is defined at the center of the unit I move unitA to the right:
float unitA_Fix_X = unitB_Face_X + 2;

But unitA_Fix_X will result in a slightly different value (2.746667) that will eventually be detected as an overlap.

Just a clarification: My game is like Super Mario Bros, a 2D platform. I dont need fine precision, two decimals places (or one) is more than enough for my game world (each unit character has 1f for width and 2f for height).

I think that there must be a correct way to deal with this kind of problem (every 2d platform game out there has solved this problem). I have only think in one solution: Use integers instead of floats for the position of every unit in my game. I cannot avoid floats completly  because of deltaTime (also libgdx uses them for the sprites positions and rendering), but I think I can make the integer conversion at the begining of each frame by doing something like this:

float fPos = unitA.velocity * deltaTime;
int intPosition = (int)(fPos * 1000);

And use the intPosition for detecting and resolving the collisions. After that I will have to convert it back to float for rendering the sprites.

Is this a bad approach? I dont want to shoot my self in the foot.
Thanks in advance.


texts: I have Skinned the character using rig simulator and now wanted to add Bendy controls.. How can I export the skin weights and apply on modified rig?


texts: What's the fastest collision detection (Game Maker)

texts:
I want to build a simulator using Game Maker in which there are many (up to hundreds) of obj_Cell, each has a radius of 10, (they don't have sprites, they just draw a circle with radius 10).

Each step, I want the cells to check around itself for obj_A to see if any obj_A is "touching" it, (has a distance less than 10 from the cell). However, since I have so many obj_Cell and so many obj_A, the most straight forward code (below) will have to be executed tens of thousands of times (number of obj_A * number of obj_Cell)

//In obj_Cell:
(with obj_A)
{
   if distance_to_object(other)<=10
   {
      //do stuff
   }
}

Is there any possible way to make this faster?


texts: Connecting clients with UDP and WebSocket connections

texts:
I'm in the process of making a physics intensive multiplayer game. Naturally I use a UDP to transfer packets regarding rigidbodies between client and an authoritative  server.

However non-essential packets I'd prefer to use a more reliable connection like WebSockets. This would be for things like voice chat, text chat, scoreboard, etc. It also seems the be a nice approach to checking if the client is still connected and if not, stop sending it UDP packets.

I'm actually unable to find use cases of this dual connection approach online and I was wondering how this is typically handled in similar games. Is it very far fetched or unconventional?

Another question would be how far do I take relying on the WebSocket connection? Lets say for managing remaining bullets in a guns magazine, would it be better over UDP or WebSocket?

I feel like WebSockets would be best in this case because if the bullet was successfully spawned and the server needs to remove a bullet from the client's gun's magazine, if that packet doesn't arrive at the client, then they shot a free bullet...

The UDP equivalent for this scenario would be to always send the client's magazine state as packets and the client just updates it's magazine whenever the packets get to them. My concern here is overloading the network traffic data that might not have even changed...


texts: When do you get Mouse.getstate().X or Y as negative?

texts:
I am creating a game in which I use a function:

int x()
        {
            int px = 100;
            int pxend = 128;
            int xx = 0;
            for (int i = 0; i < 6; i++)
            {
                l = Mouse.GetState().X;
                if (l> px && l < pxend)
                {
                    xx = px;
                    break;
                }
                else
                {
                    px += 128;
                    pxend += 128;
                }
            }
            return xx;
        }

and

int y()
        {
            int px = 100;
            int pxend = 128;
            int xx = 0;
            for (int i = 0; i < 4; i++)
            {
                l = Mouse.GetState().X;
                if (l > px && l < pxend)
                {
                    xx = px;
                    break;
                }
                else
                { px += 128;
                pxend += 128;
                }
            }
            return xx;

        }

But when I debug I get value a l as negative even though the debug is initiate after a click on the GameWindow screen. Sometimes it works fine sometime does not. I dont know why does it give me negative value. And when I used them with my Rectangle i get Rectangle.X and Rectangle.Y as 0.


texts:
I'm making a game where at some point the game will create enemies of random types. Each type of enemy available is defined on its own class derived from an enemy superclass. To do this, obviously the different types of enemies should be known. This is what I have thought of:

Just make a list manually. Very simple to do, but I don't like it because I'll be adding more enemy types over time, so any time I add a new class I have to remember to update this (same if I remove an enemy). I would like some kind of auto-updating list.
A completely component based system. There are no different classes for each enemy, but definitions of enemies in some file where all enemy types can be found. I really don't need that level of complexity for my game. I'm still using a component based model to some degree, but each Enemy type gets defined on its own class.
Java Annotation processing. Give each enemy subclass an annotation like @EnemyType("whatever"), then code an annotation processor that writes in a file all available enemy types. Any time a new class is added the file gets updated after compilation.This gives me a feeling of failure even if its a good solution, it's very dependant on Java, so it means I cant think of a general design good for any kind of language. Also I think that this would be too much work for something so simple.

I would like to see comments on these ideas and other possible solutions

Thanks