texts:
I am developing a 3D game in DarkBASIC Professional, and I have a theoretical problem with the combination of skydomes and fog in general. My question is not specific to a programming language, so I am not refering to code.

What I want to achive

The player can see a night sky with stars
The sky should rotate slowly
Trees will block the light of the stars
Trees will be dark when far away and colorful when player is near (normal shader work).
A tree at the horizont should not "pop up" randomly when it enters the skydome. It should slowly fade, as the player comes near.

Techniques I use

Instead of a skybox, I have choosen a skydome with a night-sky-texture. This texture scrolls.
DarkBASIC has a "fog" feature. If enabled, I can choose a fog color and a fog distance. Things like trees will slowly fade and vanish into this fog color and will be completely faded when they reach the fog distance.
I am using black colored "fog" for the night scene, so that the trees far away will vanish in the dark night.
DarkBASIC's "fog" and "ambient light" features automatically shade the trees, so that far away trees are dark, and trees close to the camera, colorful.
The skydome will always enclosure the camera. It will automatically move when the camera moves.
(Note: Since the landscape is very big, I couldn't choose a giant skydome that covers the whole level, because the rendering of the texture on a giant skydome requires too much rendering time (at least for DarkBASIC's engine).)

I have tried several things now, and I am don't know what to do to fulfill all requirements.

Version 1

What I did:

I am using black fog with a fog distance of 1000.

Pro:

Trees are perfectly faded horizontally and vertically and no tree "pops up" at the horizont

Contra:

There is no skydome, so the sky is just 100% black, without any stars.

Version 2

What I did:

I am using a sky sphere with diameter 300
I am using black fog with fog distance 1000

Pro:

Since I am using the fog feature, trees will slowly fade to black when the camera diverges from them.
The sky can be seen completely (also at the horizont) because the sky sphere is smaller than the fog distance

Contra:

The trees are taller than 300, and therefore poke through the skydome! So I only see half trees...
(Note: I cannot increase the value "300", because otherwise the skydome will be shaded too much by the fog, which would result in a extremely low star light.)
Since the skydome is smaller than the fog distance, trees will "pop up" at the sky, once they come close (and pass the skydome)

Version 3

What I did:

I set black fog with a distance of 1000
The skydome is an ellipsis with height 300 and width 1200.

Pro:

The sky can be seen when the camera looks up (because the skydome does not exceed the fog distance)
Trees at the horizont are faded and do not "pop up"

Contra:

The trees are taller than 300, and therefore poke through the skydome! So I only see half trees...
(Note: I cannot increase the value "300", because otherwise the skydome will be shaded too much by the fog, which would result in a extremely low star light.)
The sky at the horizont is black and no stars can be seen. (But this is not a big deal in my opinion, since there will be always things at the horizont which block star light)

What I actually need

I think I need something like an "elliptic fog". A fog that will shade objects at the horizont stronger than objects above the player (sky). But such a thing does not exist in DarkBASIC.

So I am trying to find out a good solution using the standard techniques fog, ambient light and skydomes to achive my goal. Do you have a solution for me?


texts: How to get all child with same tag from CCLayer?

texts: Actually i am working with cocos2d Game. I am using CCLayer for particular scene. now there are so many buttons means CCMenuitems are available. I want to disable that all menuitems having same tags.


texts: Getting Started with 2d Game Dev (C++): DirectX or OpenGL?

texts:
So, i'm a student looking to get my foot in the door of game development and im looking to do something 2D, maybe a tetris/space invaders/something-with-a-little-mouse-interaction clone.

I pointed my searches in the direction of C++ and 2d and was eventually lead to DirectX/OpenGL

Now as i understand it, all these packages will do for me is draw stuff on a screen. And thats all i really care about at this point. Sound isn't necessary. Input can be handled with stdlib probably.

So, for a beginner trying to create a basic game in C++, would you recommend DirectX or OpenGL? Why? What are some key feature differences between the two? Which is more usable?


texts: Setting object O2 to have the same geometric relation to P2 as O1 has to P1

texts:
I'm trying to place Object O2 with the same relation to P2 that O1 has to P1, like shown in the picture below.

This is a problem that I'm facing trying to implement portals in Unreal Engine 4, where:

O1 is the player camera
P1 is a portal
O2 is a second camera, used to render the scene from the perspective of the other portal
P2 is the portal linked to P1

// Get the player position in relation to this portal and project it in relation to the linked portal
FMatrix NewCameraWorldMatrix = LinkedPortal->GetTransform().ToMatrixWithScale() * GetTransform().ToMatrixWithScale().Inverse() * PlayerCamera->GetComponentTransform().ToMatrixWithScale();
FTransform NewCameraWorldTransform = FTransform(NewCameraWorldMatrix);
PortalCameraAnchor->SetWorldLocationAndRotation(NewCameraWorldTransform.GetTranslation(), NewCameraWorldTransform.GetRotation());

However, the above code is not solving the problem I presented and I can't figure out why.
Any ideas on what may be the issue?
Note: I've wrapped the PortalCamera with an Anchor since the PortalCamera must have a specific relative orientation at all times and using SetWorldLocationAndRotation directly on it would mess up its rotation.
Note: I have these logs (one per portal) which might be useful:
LogTemp: Warning: ---------------------------------------------------------------------------------------
LogTemp: Warning: GetTransform().ToMatrixWithScale().Inverse(): [-1 2.38419e-07 0 -0] [-2.38419e-07 -1 0 0] [0 -0 1 -0] [-1410 1570 -420 1]
LogTemp: Warning: LinkedPortal->GetTransform().ToMatrixWithScale(): [1 0 0 0] [0 1 0 0] [0 0 1 0] [820 -1410 420.238 1]
LogTemp: Warning: PlayerCamera->GetComponentTransform().ToMatrixWithScale(): [0.572059 -0.791792 0.214041 0] [0.810578 0.585631 0 0] [-0.125349 0.173497 0.976825 0] [-372.749 -65.9088 332.374 1]
LogTemp: Warning: NewCameraWorldMatrix: [-0.572059 0.791793 -0.214042 0] [-0.810578 -0.585631 -5.10315e-08 0] [-0.125349 0.173497 0.976825 0] [767.052 3445.01 -144.706 1]
LogTemp: Warning: NewCameraWorldTransform.GetTranslation(): X=767.052 Y=3445.011 Z=-144.706
LogTemp: Warning: NewCameraWorldTransform.GetRotation(): X=-0.095848404 Y=0.048997864 Z=0.885227978 W=0.452530354
LogTemp: Warning: ---------------------------------------------------------------------------------------
LogTemp: Warning: GetTransform().ToMatrixWithScale().Inverse(): [1 -0 0 -0] [-0 1 -0 0] [0 -0 1 -0] [-820 1410 -420.238 1]
LogTemp: Warning: LinkedPortal->GetTransform().ToMatrixWithScale(): [-1 -2.38419e-07 0 0] [2.38419e-07 -1 0 0] [0 0 1 0] [-1410 1570 420 1]
LogTemp: Warning: PlayerCamera->GetComponentTransform().ToMatrixWithScale(): [0.572059 -0.791792 0.214041 0] [0.810578 0.585631 0 0] [-0.125349 0.173497 0.976825 0] [-372.749 -65.9088 332.374 1]
LogTemp: Warning: NewCameraWorldMatrix: [-0.572059 0.791792 -0.214041 0] [-0.810577 -0.585631 5.10314e-08 0] [-0.125349 0.173497 0.976825 0] [767.11 3444.93 -145.171 1]
LogTemp: Warning: NewCameraWorldTransform.GetTranslation(): X=767.110 Y=3444.927 Z=-145.171
LogTemp: Warning: NewCameraWorldTransform.GetRotation(): X=-0.095848396 Y=0.048997886 Z=0.885228097 W=0.452530175
LogTemp: Warning: ---------------------------------------------------------------------------------------


texts:
Debugging my code I faced some unexpected behavior.

I called an RPC using uLink.NetworkView on the server passing some parameter including a GameObject tagged as Player.

Inside that RPC I make a call to GameObject.FindObjectsWithTag("Player")

What I refer to by saying "unexpected" is that that function returns all the gameobjects in hierarchy INCLUDING the gameobject passed as parameter to the RPC call.

I noticed that inside the editor it appears in hierarchy the gameobject passed to the RPC but without all the components BUT the transform.

My question is to know exactly how the scope is working, I seem to understand that the scope of the FindObjectsWithTags seems to include RPC parameters but without the most informations.

Any clue about this?


texts: Why does Unity's Application.Quit() take so long?

texts:
When a user clicks a button in my game, I call Unity's native Application.Quit() to close my game. The call is directly on the button press, with no coroutines or intermediate processes that sit between the press and the call.
In a standalone build of my game, after the button press, it takes around 2 seconds for the window to close. Ideally, I'd like the window to close near immediately, as it does in other Unity games I've played.
Why might Application.Quit() take so long to close the window, and how can I speed it up so that the window closes immediately?
For what it's worth, I am running Windows 10 on a Razer Blade 15 w/ 10th gen core i7. The game is a simple platformer w/ no networking or external integrations.


texts: How to determine whether the direction of rotating a 2D vector to another one is counter-clockwise or clockwise using the cross product?

texts:
Vec2 a, b; // some random vector
Vec2 cross = a.Cross(b);
RelativeDirection(a,b,cross); // return true if the direction of
                              // rotating a to b is counter-clockwise

How do I implement the function RelativeDirection()?

I got some suedo code from the textbook:

if a.Cross(b) > 0 then ... else ...

but the cross product is a vector right? how do you compare it with an integer?


texts: theoretical solution for "drawing" with mask

texts:
So am trying to create a make-up game and i need to have a basic drawing solution,
and so far i have made a good progress with the help of the DepthMask solution
My approach was like this :
suppose we want to edit the eyelash color (texture)

1-in the beginning there is an eyelash object at a layer named old
2-after choosing the new color that we will draw with, a new game object is created under the first eyelash, which mean it's invisible for the moment
3-then when we start drawing, we are actually creating little circles above the old eye lash, these circles contain the depthMask shader which effect the old eyeLash and give the impression that we are drawing with the new color

So far, everything is going great, my problem is that i cannot use this approach to use a 3rd color, suppose the player want to create an eyelash with mixed color, how can i do that with the previous solution ? or is it impossible to do ?

EDIT: I already thought about adding new layers with each new color, and it works, but since unity is limited to 31 layers, this solution can never be a good one.

I really hope someone can answer this, and if you know a better way to do it then please don't hesitate to tell me.

EDIT2:
After a couple of hours, i've reached a pretty cool result, and i think that this can be the good way to reach my goal, this script allow to replace a specific pixel in a material texture with another chosen texture (target texture must be in the same size, and readable)

// the texture that i will paint with
public Texture2D targetTexture ;
//temporary texture
Texture2D tmpTexture;

void Start ()
{
        //setting temp texture width and height
        tmpTexture = new Texture2D (targetTexture.width, targetTexture.height);

        for (int y =0; y<tmpTexture.height; y++) {
                for (int x = 0; x<tmpTexture.width; x++) {
                        //filling the temporary texture with the target texture
                        tmpTexture.SetPixel (x, y, targetTexture.GetPixel (x, y));
                }
        }
        //Apply
        tmpTexture.Apply ();
        //change the object main texture
        renderer.material.mainTexture = tmpTexture;

}

Now i think that the problem will only be, "how to know which pixel i should replace based on mouse position over the object ?"

Thank you very much and have a great day.


texts: How do I maintain the world pitch, roll or yaw of child objects?

texts:
I've got an application where I'm trying to display an object in 3D, with information provided by real-world accelerometers and inclinometers - sensors that pick up the angle of the equipment, relative to ground. The trouble comes when I want to show this 'world pitch' or 'world roll' on an object that is a child of another. I'd think that there is a trivial solution to the problem, but for the life of me, I can't figure out what it is.

Let's say I've got a robot arm with several pieces - "LowerArm", "Elbow", "UpperArm" and "Hand". "Hand" is the child of the "UpperArm", and "UpperArm" is the child of "Elbow". I'd like to place "Hand" at 0 degree pitch, relative to world-space, no matter how I move the parent objects. If I grab my "LowerArm", and rotate it 90 degrees, the hand should still lay 'flat', relative to the ground; in local coordinate space, it should moved 90 degrees, to compensate.

I want it to remain attached; so it should continue to follow the other parts, in terms of roll and yaw. If I twist the arm, the hand twists with everything else - it just maintains that 0 degree world pitch. Observe the yellow object, in the below example:

How can I do this? I would have thought that there was some kind of trick, with matrices or quaternions, that could resolve it; but I've had no luck, so far. It's hard to figure out what the new 'forward' vector should be.


texts:
I'm creating a JavaScript game, and I'm getting stuck. When the player obtains X amount of gold, a middle column appears (you've unlocked the shop, yay!), and when you obtain more gold than an item costs, it will appear (except special conditions where it requires more than just gold of course).

Right now, I'm stuck on the base foundation of the system, and I would like to hear some suggestions before I move on.

function _shop() {
    this.items = [
        {
            effect : function() { engine.player.revive(true); },
            "price" : 100,
            "name" : "Heal"
        }
    ];
}

The shop holds an array of item objects, some will be holdable, some will be instant use (currently working on instant use).

Now, here's how the item is called:

in my elements.js file --

addShopItem : function(gold) {
    console.log(engine.shop.items.length);
    for (var i = 0; i < engine.shop.items.length; i++) {
        if (engine.shop.items[i]["price"] <= gold) {
            document.getElementById("items").innerHTML += "<br />"+engine.shop.items[i].name;
        }
    }
},

Which is called by going raiding (irrelevant, won't post that code, it's going to change to the engine's trigger function with flags based on the item object.

Now my question is:

Is this a good way to handle an dynamic shop system?
What's the best way to link this to a player object? (My initial guess is an object inventory inside the parent?


texts:
Background
I was able to convert simple statemachines like this...

Into a BT looking like this (Notation describtion)...
root
  sequence  #After another
    playAnimation name:idle
    sequence
      walks? # Breaks current sequence if false
      playAnimation name:walk
    sequence
      runs?
      playAnimation name:run

Goal
But how do we convert more complex multi-layered animation states into a behaviour tree ? How would such a BT look like ? The difficult parts here are transistions between the different states, something i couldnt solve in an BT.

Question
Is it possible to convert every statemachine into a behaviour tree ?
What does the theory says and how does it look like in practice ?


texts:
In XNA I am using a spritebatch to render a board. I have created a camera class which can provide me a view and projection matrix. Currently I am supplying the view matrix to my sprite batch when I call begin.

I can get the view matrix to correctly move everything around and do some zooming in and out. My problem is that I want to zoom in on a specific point (for now the center of the screen) but currently zooming just zooms in on the coordinate 0,0.

Here is how I am constructing the view matrix;

        _ViewMatrix =
            Matrix.CreateTranslation(
                new Vector3(
                    (-_Position.X + _Width * _Zoom / 2),
                    (-_Position.Y + _Height * _Zoom / 2),
                    0) ) *
            Matrix.CreateScale(new Vector3(_Zoom, _Zoom, 1));

How could this be altered to make it scale correctly relative to the given point. Later I will probably want to zoom to the mouse position, but if someone has a simple example I'm sure I can work out how to adapt it.


texts:
I have a crate setup (in pic below) with a rigid body component, box collider and 3 circle colliders(they allow me to push the crate most of the time without getting stuck on the floor textures which are normal box colliders) As you can see in the pic there are collisions detected between the crate and floor even though they are not physically touching.

How can i make the collisions more precise as my crate gets snagged on the floor textures when there is minuscule difference between the floor box colliders?


texts: How do I implement flat shading in GLSL?

texts:
I'm working with GLSL and trying to implement flat shading on a 3D model (rather than smooth shading). To illustrate what I mean, here are two screenshots of cubes in Blender. Here's one with flat shading.

And here's the same cube with smooth shading.

I understand the theory behind this kind of shading. Each face on the cube (six total) has a normal facing away from the surface. Each vertex (eight total) has a normal computed by summing together face normals, then normalizing to unit length. This results in each vertex normal pointing directly away from the center of the cube.

Smooth shading can be implemented in basically two ways. In the first, color is computed per-vertex (using light direction and normal), then fragment color is interpolated among all vertices. In the second, normals themselves are interpolated, then color is computed per-fragment (using the same lighting calculations).

Here are my current GLSL shaders to implement the first option (there's no specular lighting yet, but it gets the idea across with ambient and diffuse). Vertex shader first.

in vec3 vPosition;
in vec3 vNormal;

out vec4 fColor;

uniform mat4 mvp;
uniform vec3 aColor;
uniform vec3 lDirection;
uniform vec3 lColor;

void main()
{
    gl_Position = mvp * vec4(vPosition, 1);

    vec4 ambient = vec4(aColor, 1);
    vec4 diffuse = vec4(max(dot(lDirection, -vNormal), 0) * lColor, 1);

    fColor = ambient + diffuse;
}

Then fragment.

in vec4 fColor;

void main()
{
    gl_FragColor = fColor;
}

So that works fine for smoothed shading, with fragment values interpolated among vertices. I'll also point out that I'm using buffers and index arrays for rendering.

For flat shading, each fragment on a face should instead use the same normal (such that every pixel on the surface has the same final color after lighting calculations). The problem is that I can't pass data to shaders per-face, but only per-vertex. Given this, I can think of three solutions.

Pass four vertices per face, with each vertex storing the face normal. This would still technically be smooth shading, but done in such a way that every interpolated pixel will use the same color (making if effectively flat). This approach seems wrong because it would basically ruin my vertex buffer, since I'd have to pass 24 vertices (four per face) despite the cube only containing eight unique vertices.
Use GLSL's flat mode (there's a flat keyword in GLSL). Using this approach, each fragment would only pull from a single "provoking vertex" rather than interpolating from all vertices on the face. This feels wrong because that I wouldn't actually be using the correct face normal. I also haven't been able to figure out the proper syntax for this style anyway. For the record, I'm aware of glShadeModel, but it's apparently deprecated.
Average vertex normals per fragment rather than interpolating them. To me, this feels like exactly the correct solution, since every pixel on a face would use the same normal, with that normal computed by summing and normalizing vertex normals (similar to how vertex normals are computed from face normals to begin with).

From those options, #3 clearly feels like the correct solution, but I haven't had any luck in figuring out how. So that's my question.

How can I tell the fragment shader to use a normal averaged among all vertices, rather than interpolated?


texts:
I am trying to save a username for game in preferences (first time user enters the game, registration screen shows up, and after that whenever user enters the game, username is automatically synchronized).

i tried the following

// in create() method of game class
   userPreferences = Gdx.app.getPreferences("userPrefs");

then, in my registration stage

        enter.addListener(new ClickListener() {
            @Override
            public void clicked(InputEvent event, float x, float y) {
                super.clicked(event, x, y);
                user.username = usernameField.getText();
                PanBallGame.getGameInstance().userPreferences.putString("username", user.username);
                user.requestPath = "/addUser";
                new RequestObserver(user);
            }
        });

but this doesn't save the username in preferences.
Can anyone explain how to get this work ? Thank you .


texts: LIBGDX: Translate grid drawn with ShapeRenderer with an OrthographicCamera

texts:
I am trying to draw a grid for my "world" that may or may not extend beyond the screen. What I would like to do right now is draw the entire world (which is relatively small) and then use the orthographic camera to translate the view to where the player is inside the "world." Currently I'm just trying to translate the "world" by 100 on the x and y axis to test. What am I doing wrong? Can I use the Shaperenderer with the OrthographicCamera?

public class WorldRenderer implements Disposable{

    private static WorldRenderer worldRenderer;
    private Color gridLineColor = Color.LIGHT_GRAY;
    private OrthographicCamera camera;

    private int worldX;
    private int worldY;

    public WorldRenderer(WorldController worldController) {

        init();

    }

    public void init() {

        worldRenderer = this;
        camera = new OrthographicCamera();

        worldX = 0;
        worldY = 0;

    }

    public void render() {

        //Set the background color to white.
        Gdx.gl.glClearColor(255, 255, 255, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        renderBackground();

    }

    public void renderBackground() {

        ShapeRenderer renderer = new ShapeRenderer();

        //Draw vertical lines.
        for(int i=0;i<=Constants.WORLD_WIDTH * Constants.GRID_WIDTH;i+=Constants.GRID_WIDTH) {

            renderer.begin(ShapeType.Line);
            renderer.setColor(gridLineColor);
            renderer.line(i, 0, i, Constants.WINDOW_HEIGHT);
            renderer.end();

        }

        //Draw horizontal lines.
        for(int i=0;i<=Constants.WORLD_HEIGHT *          Constants.GRID_HEIGHT;i+=Constants.GRID_HEIGHT) {

            renderer.begin(ShapeType.Line);
            renderer.setColor(gridLineColor);
            renderer.line(0, i, Constants.WINDOW_WIDTH, i);
            renderer.end();

        }

        camera.translate(100, 100);

    }

}


texts: Best way to allow a user to Control Body in Box2D

texts:
I am working on a simple game and I am deciding how I should let users interact with the world. I really have 2 options,

1.) When the user moves an object I apply a force to the body

2.) With each move iteration I "move" the body by setting position.

Which is "better" or am I looking at this wrong entirely and should I be doing something different?

Also, does it matter if I want to keep the object stationary when it is hit by another body (I am assuming this means I will need to use static body which leads me back to #2)?

Thanks


texts: Can an iOS application have an explicit quit button?

texts:
I've heard a rumor that you cannot have an explicit quit button on your app when it goes to the Apple App Store, can anyone verify this? It seems that most applications do not have one, and there is no explicit quit. How to developers handle quitting in general on iOS applications?

Note: I am using Unity, C#, and Xcode to develop my game for the iPad.


texts: Appropriate data structures for large item database

texts: I'm currently building an RPG Game and as such I intend to have a lot of items. In my current system I have a database of items stored in a JSON file which I read and then store the items in a generic List<>. My question is as the numbers of items grow should I be looking into using a better data structure to store my database? As I wonder if i'll be able to search the list in an appropriate time when there's potentially thousands of items.


texts: Is there any scroll algorithm for OpenGL ES?

texts:
I was working on J2ME games in the past, when draw a large backgroud, I always use the Carmack 2d scroll algorithm, keep a image buffer a little larger than device screen, draw the changed small tiles to this buffer, then draw the buffer to device screen. This can reduce the number of times to call drawImage().

Now we need to prepare for opengles 2D games for iphone and android. I am new about opengl, but i have try to read some engine code and keep learning opengl. There isn't much problem about 2d graphic system, except the tile buffer, there is no image buffer any more, so what size of the tile should i use? The screen size maybe 800*480, if i keep the 32*32 tile, i need to draw about 400 tiles per frame, will this be ok?


texts: Function is not showing up in the OnClick editor

texts:
I'm just a beginner and I am currently having problems with the OnClick editor. I already drag and dropped my script to an empty gameobject and dragged that game object to the OnClick editor but still my function of "Pause" won't show up even if I already have it set to public. Please help

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

public class uiManager : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }
    public void Pause() {

        if (Time.timeScale == 1) {
            Time.timeScale == 0;
        }
        else if (Time.timeScale == 0) {
            Time.timeScale == 1;
        }
    }
}


texts: Facebook Game Development - Where can I save my data?

texts: I'd like to develop a small Facebook game with some graphics involved (not that many). Within that game, the users will be able to buy/sell certain items and I wonder WHERE I can save those items/virtual money...? Does Facebook offer me a database I can use?


texts:
Whilst looking into game-oriented applications of programming patterns I discovered a question on this site which suggests that a 'set of states' is superior to a 'stack of states' but does not clarify how a 'set of states' would be applied.

A stack of states is simple enough to comprehend - the state on the top is the active state.

But what exactly is a set of states? A set as I understand it is merely a collection of unique objects (i.e. there are no duplicates). Presumably all the states in the set are currently active. But sets are unordered, so how does one maintain order in an unordered collection? An ordered set could be used, but that then brings the question of why use a sorted set and not a list - what benefit does the uniqueness bring?
I'm just not sure I can imagine how such a thing would be implemented or what benefits it would bring. (Presumably the former issue is causing the latter).

So what exactly is a 'set of states'? (In the context of game design/programming).


texts: How do I scale a motion capture animation?

texts:
I used motion capture in my room using the Kinect. As I don't have much space I make compressed running moves, i.e. I put my legs up and down while not moving far forward.

How can I stretch the animation, so me walking 1 meters amounts to the skeleton walking 3 meters or similar while not exaggerating movements to the left/right?


texts: Json Libgdx serialize / de-serialize a Object Map of Object Maps

texts:
Any one have any ideas on how I can serialize / de-serialize an

ObjectMap<Enum, ObjectMap<String, Object>>();

(Object is usually a String Integer or Vector2 ) using libgdx's built in json classes?. On de-serialize the inner ObjectMap, is always null even though the values are written to the json file.


texts:
Right now I have the graphical and input portions of a console for my game (command parsing hasn't been implemented yet). I was wondering how you would go about making changes to properties in game objects. For example, if I typed in the console:

skeletonMonster maxHP 20

That would change all of the existing in-game skeletons' max hit points to 20. After you parse this information what are some ways to change the value? How can I change the that member variable without directly accessing it (by making it public/global)?

I'd like to implement this so I don't have to change variables in the code and recompile every time while playtesting.


texts: What is an optimum failure rate that will keep people coming back to my game?

texts:
I'm guessing some research has been done into this but I can't find much information. The question might be a bit too vague in itself as it depends on so many other factors.

I'm developing a puzzle game that I want to be challenging, but not so challenging that users don't bother coming back to try again if they fail. I'm assuming the shorter the game length to more willing a user will be to try again.

For example, if a level takes an hour with a 95% failure rate, I suspect that many users wouldn't bother trying again after a couple of failures. But if a game takes 30 seconds then they'll probably keep trying again until they succeed.

I'm wondering if anyone has, or can point me in the direction of information that offers guidance on this aspect of game development.


texts: What are the responsibilities of a game engine, and which of these things need to especially be efficient?

texts:
Possible Duplicate:
  What should a game engine do?

What are the usual responsibilities of a game engine, and which of these things especially need to be efficient (performance-wise)?

Can I get a break-down of the purposes that a game engine is used to serve, and how it differs from a game itself? I'm a newb, so some intuitive things may need to be explained.... Thanks! :)


texts:
I've got a program that prints OBJ files in the format

# x y z r g b format opens with MeshLab only (http://meshlab.sourceforge.net/)
v xVal yVal zVal rVal gVal bVal
v xVal yVal zVal rVal gVal bVal
v xVal yVal zVal rVal gVal bVal
v xVal yVal zVal rVal gVal bVal
.....

And I'd like to start including "quality" data as well.  I'm having a hard time finding an example that shows the correct way to format an OBJ file with quality data, does anyone have one they can share with me?

Thank you


texts: How do I create the playing field for my game?

texts:
I want to create a game with playfield as shown in the video in OpenGL

www.youtube.com/user/stanfordcs248

I have fair knowledge of OpenGL and I know this playfield can be rendered using several different cubes but that takes a lot of effort. Also it takes away the power of easily modifying the field. One idea that was suggested to me to solve this problem was to use an XML file describing almost every component of the game. Like the floor, walls , moving floors, moving obstacles etc. That way i can easily change the playfield when I want. But this approach also seems tedious. Also I couldn't figure out the structure of the XML that would make my life quite easy. So is there any better way to create or store information about the playfield than suggested above?

Note : Blender is also an option. But please provide a tutorial if you are suggesting the Blender way.


texts: How to detect two different mice at the same time, and record their separate movements?

texts:
I would like to use two computer mice simultaneously, and to record data their separate movements on windows. I have successfully used TeamPlayer to create two cursors, but the software that I am using to record the movement data records only one output - the sum of the two cursors. How am I to use both computer mice at once, and record their separate outputs?
I have looked at the thread Is it possible to detect two different mice at the same time, and have their movements recorded seperately?, but this is quite old now and most of the solutions offered are now unavailable.


texts:
Edit: My goal is to have it function like this:

Ball hits 1st Quarter = rebounds higher (aka Y++)
Ball hits 2nd Quarter = rebounds higher (using random value)
Ball hits 3rd Quarter = rebounds lower (using random value)
Ball hits 4th Quarter = rebounds lower (aka Y--)

I'm currently using Rectangle Collision for my collision detection, and it's worked. Now I wish to expand it.

Instead of it simply detecting whether or not the paddle/ball intersect, I want to make it so that it can determine what section of the paddle gets hit. I wanted it in 4 parts, with each having a different reaction to impact.

My first thought is to base it on the Ball's Y position compared to the Paddle's Y position. But since I want it in 4 parts, I don't know how to do that.

So it's essentially be

if (ball.Y > Paddle.Y)
{
PaddleSection1 == true;
}

Except modified so that instead of being top half/bottom half, it's 1st Quarter, etc.


texts:
Let's say that I have a cannon on the bottom of the screen that shoots balls to the click direction. I also have some collisions algorithms and here comes the problem. I am trying to implement an OnHold method that shoots continously and it works, but I think that I need to make shooting on another Thread. I've implemented this in two ways:
 1. I was checking the delay and if it passed I shot
 2. I was checking previous ball y position and when it floated away I shot

The problem comes here that when I hold the button for some time, for example. 5 balls are okay (they're near each other - not colliding) and then comes a ball that is late O.o

I don't know how to implement a new Thread within these MotionEvents. If is there someone who can point me (if should I make in on Threads or something) a solution - I would be grateful :)

  @Override
public boolean onTouchEvent(MotionEvent event) {
    // TODO Auto-generated method stub

    touched_x = event.getX();
    touched_y = event.getY();
    int i = 100;

    int action = event.getAction();
    if (action == MotionEvent.ACTION_DOWN) {
        startShootTime = new Date().getTime();
        running = true;
    } else if (action == MotionEvent.ACTION_MOVE ) {
        shootTime = new Date().getTime();
        // movement: cancel the touch press
        running = true;
        touched_x = event.getX();
        touched_y = event.getY();
       // && game.gameLoop.current_time - shootTime > 400 &&
              //  game.gameLoop.current_time - startShootTime > 100
        //  while(actionUpflag) {
        int size = game.gameLoop.balls.size();
        if(size == 0){
            game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));
        }else if(size > 0 && game.gameLoop.balls.get(size-1).image_center_y < metrics.heightPixels - game.gameLoop.ball_bmp_width-50)
        game.gameLoop.balls.add(new Ball(metrics.widthPixels, metrics.heightPixels, touched_x, touched_y, game.gameLoop.ball_bmp_width, metrics.heightPixels-game.gameLoop.ball_bmp_width/2));

        invalidate(); // request draw

    } else if (action == MotionEvent.ACTION_UP) {
        running = false;
    }

    return true;
}


texts: Emulate border color texture address mode efficiently

texts:
In WinRT the border color texture address mode is not supported.

The best I came up with in emulating the border address mode, is doing this in my pixel shader:

float4 tcol = tex.Sample(texSampler, texCoord);

if(texCoord.x < 0 || texCoord.y < 0 || texCoord.x > 1 || texCoord.y > 1)
  tcol = borderColor;

But as only ps_4_0_level_9_1 is supported as minimum requirement in WinRT, this conditional in the pixel shader is quite inefficient.

How would I emulate border texture addressing mode efficiently?


texts: Do I need a backend engineer for my studio right now?

texts:
I am working on a mobile game that requires a well thought-out backend, because it spans across the healthcare/data science space and we need to be compliant in terms of security/regulations in how we approach this. Think something like Fitbit.

My team is nearly finished with the client-side game aspect; but I am wondering whether I need to take on a short-term contract/part-time backend engineer to create our entire backend infrastructure OR someone who would work on this full-time with our team.

Here is what we would need to do:

Setup our entire backend infrastructure and plug this into Unity
This would require knowing how to handle (transmit/receive) data securely, and also perform computation with that data in the cloud
Set-up an API where other developers can query our data
Set-up our dev ops infrastructure (Docker, Jenkins) for the future

The kicker here is that we are not yet live and are just in a testing phase. I don't want this to be 2-3 weeks of work, with no users for 3 more months while we're working on other aspects of the project, with the dude having nothing to do.

Does this sound like a lot of work? Or could it easily take up a devs time for a month or two? Would a short contract be advisable here, or would it be better to hire someone FT and have them grow with us.


texts: With a Texture Atlas that has 128x128 tiles, how can I use that in Unity3D?

texts:
So I've got a working texture atlas that has tiles fitting 128x128. However, I can't quite figure out how to use them. I know it's probably got something to do with

    TileRenderer.material.SetTextureScale("_MainTex", new Vector2(0.25f, 0.25f));
    TileRenderer.material.SetTextureOffset("_MainTex", new Vector2(0 * 0.25f,0));

but I'm not sure where to take it from there. Can anyone offer some advice? The size of the image is 1024x128 if that helps, which I think it might.


texts: How to improve collision detection memory usage?

texts:
I am making an action platform 2D game, something like Megaman.
I am using XNA to make it.

I already made player physics, collisions, bullets, enemies and AIs, map editor, scrolling X Y camera (about 75% of game is finished ).
As I progressed I noticed that my game would be more interesting to play if bullets would be destroyed on collision with regular(stationary) map blocks, only problem is that if I use my collision detection (each bullet with each block) sometimes it begins to lag(btw if my bullet exits the screen player can see it is removed from bullet list)

So how to improve my collision detection so that memory usage would be so high? :)
( on a map 300x300 blocks for example don't think that  bigger map should be made);

            int block = 0;
            int bulet= 0;
            bool destroy_bullet = false;

            while (bulet < bullets.Count)
            {
                while (block <  blocks.Count)
                {
                    if (bullets[bulet].P_Bul_rec.Intersects( blocks[block].rect))
                    {//bullets and block are Lists that holds objects of bullet and block classes
                        //P_Bul_rec just  bullet rectangle

                        destroy_bullet = true;
                    }
                    block++;
                }
                if (destroy_bullet)
                { bullets.RemoveAt(bulet); destroy_bullet = false; }
                else { bulet++; }
                block = 0;
            }


texts: Skeleton bone in incorrect spot in-game yet, blender rig, skeleton mesh and physics asset are all correct and behave properly

texts:
I've made a custom character and rigged it in blender. Then exported/imported into ue4. It behaves properly in the PHAT and the skeleton mesh looks fine and it all behaves properly in the simulations.
In the BP and in-game the physics all behave fine except 1 single bone rises above the rest and appears to "flip" the root bone for unknown reasons. Almost like all the sudden the root does a 180 and then one specific bone attached rises as a result, not sure if it rises and that flips the root or the root is flipping for some unknown reason.
What I don't understand is why everything is fine until it is in-game/bp. Maybe I'm misunderstanding how physics work with skeleton mesh?

I've been banging my head on the wall trying to figure out phat, skeletons and how physics work in ue4 for about a month now and there is basically 0 docs/tutorials on this. As much as I love being stuck on this problem forever if anyone has an idea on what is going wrong that'd be great.


texts: How do collision meshes work in games like Zelda on the N64?

texts:
I was recently reading about the technology of Ocarina of Time/Majoras Mask and discovered that world collision is done using a single triangle mesh (vertices, normals, etc) for an entire area. There are also no signs of preprocessed spatial partitioning methods in that data structure.

What algorithms exist for performing character collision on a similar arbitrary triangle mesh fast enough to run on a platform like the N64?

Quake is a contemporary game with a similar feature that came to mind. I understand Quake brush collision works by subdividing an AABB with planes. If a point is in the AABB and behind all the planes there is a collision. However, this method only works using a bunch of individual convex objects to make up a collision scene.

Zelda data structure details Here:

http://wiki.spinout182.com/w/Zelda_64:_Collision_Format
http://zeldaspeedruns.com/oot/generalknowledge/zelda-64-engine

EDIT - I don't need to know the real method used by the real game, Zelda is an example. I am looking for a method of achieving a similar effect under similar hardware constraints.


texts: Is the TCP protocol good enough for real-time multiplayer games?

texts:
Back in the day, TCP connections over dialup/ISDN/slow broadband resulted in choppy, laggy games because a single dropped packet resulted in a resync. That meant a lot of game developers had to implement their own reliability layer on top of UDP, or they used UDP for messages that could be dropped or received out of order, and used a parallel TCP connection for information that must be reliable.

Given the average user has faster network connections now, can a real time game such as an FPS give good performance over a TCP connection?


texts:
I tried a few different codes but none of them work on my android device...I retrieve the data with this command " GameManager.Instance.gemsToSave"

The code:

     public static GameManager Instance { get; private set; }

     public float highscoreToSave;
     public int coinsToSave;
     public int gemsToSave;

     private void Awake()
     {
         if (Instance == null)
         {
             Instance = this;
             DontDestroyOnLoad(gameObject);
         }
         else if(Instance != this)
         {
             Destroy(gameObject);
         }
     }
     private void OnEnable()
     {
         Load();
     }
     private void OnDisable()
     {
         Save();
     }
     public void Save()
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(Application.persistentDataPath + "/playerInfo.dat");
         PlayerData data = new PlayerData();
         data.highScore = highscoreToSave;
         data.coins = coinsToSave;
         data.gems = gemsToSave;

         bf.Serialize(file, data);
         file.Close();
     }
     public void Load()
     {
         if(File.Exists(Application.persistentDataPath + "/playerInfo.dat"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/playerInfo.dat", FileMode.Open);
             PlayerData data = (PlayerData)bf.Deserialize(file);
             file.Close();
             highscoreToSave = data.highScore;
             coinsToSave = data.coins;
             gemsToSave = data.gems;
         }
     }
    }

[Serializable]
class PlayerData {

public float highScore;
public int coins;
public int gems;

}

Thanks!


texts: Animation rotates model but I don't see how

texts:
I have 2 animations.
In the following animation preview, the same model is being used.
As you can see in the animator, there is no significant rotation difference.
However, one animation rotates the model 90 degrees to the left.
I have inspected all the rotation values in the animation tab. I just don't see any difference.
What causes this signifant rotation difference?
Thank you!


texts:
I am loading a texture and using glGenerateMipmap() on it to achieve some level of mipmaping.

I get different result on nVidia gt 555m, and on Intel HD 3000.

The texture rendered by nVidia is not with Anisotropic filtering, and that rendered by intel HD 3k is.
How to manually adjust this feature for different GPU?

Also the tiling of the texture is much more apparent on nVidia!!

In the description of glGenerateMipmap() it is specified that the way glGenerateMipmap works is different for different implementations of OpenGL.

Is this something to do with glHint() GL_FASTEST , GL_NICEST , and GL_DONT_CARE?
Or am I better of mipmaping the texture myself?


texts: Scalability/Performance of physics-based character animation

texts:
I am asking this question because I am currently at the point where I have to think about how the characters in the game that I am making will be animated and I want to check if my desired approach will apply well.

As the title suggests I am very interested in physics-based skeletal animation and in addition to that I would like to use neural networks to closely connect the AI of a character and its movements.

Things like this have already been done and it should be pretty easy to find resources on how to implement such a system into a 3D rendering engine.

What I am asking is how well can I expect this to work with the game that I am picturing? The game is going to be a top-down shooter (looking very much like Redie) in an open world, which will mean that the animations will have to be able to adapt to any kind of terrain. An important mechanic in the game is an FOV system, which makes the player act like an absolute light, only illuminating areas that the character can directly look at (just like in Teleglitch, but 3D). This is a reason why I want to use volumetric shadows and it should allow for some culling opportunities.

However, during the game, the screen may be filled with swarms of characters, thinking, moving and colliding each individually.

To avoid some work and to be easier on the FPS, I have set my goals for the graphical quality to 'minimal', which means I will only use low polygon meshes (similar to the ones used in Redie or this video) and most objects will be solid coloured.

What I would like to put a lot of focus on is accurate lighting/shadowing (volumetric shadows), accurate physics and dynamic character animation, which should all be computed for hundreds of individual entities at a high frame rate.

Is it a good idea to use physics based skeleton animation for this many (easily 500) characters? Also taking into account all the computation time saved by low poly meshes(and hitboxes) and all the time still to be spent on calculating many lightsources and volumetric shadows?

I am programming in C++ and I am using OpenGL for rendering.


texts: AI for a mixed Turn Based + Real Time battle system - Something "Gambit like" the right approach?

texts:
This is maybe a question that's been asked 100 times 1,000 different ways. I apologize for that :)
I'm in the process of building the AI for a game I'm working on. The game is a turn based one, in the vein of Final Fantasy but also has a set of things that happen in real time (reactions). I've experimented with FSM, HFSMs, and Behavior Trees. None of them felt "right" to me and all felt either too limiting or too generic / big.
The idea I'm toying with now is something like a "Rules engine" that could be likened to the Gambit system from Final Fantasy 12. I would have a set of predefined personalities. Each of these personalities would have a set of conditions it would check on each event (Turn start, time to react, etc). These conditions would be priority ordered, and the first one that returns true would be the action I take. These conditions can also point to a "choice" action, which is just an action that will make a choice based on some Utility function. Sort of a mix of FSM/HFSM and a Utility Function approach.
So, a "gambit" with the personality of "Healer" may look something like this:

(ON) Ally HP = 0% -> Choose "Relife" spell
(ON) Ally HP < 50% -> Choose Heal spell
(ON) Self HP < 65% -> Choose Heal spell
(ON) Ally Debuff -> Choose Debuff Removal spell
(ON) Ally Lost Buff -> Choose Buff spell

Likewise, a "gambit" with the personality of "Agressor" may look like this:

(ON) Foe HP < 10% -> Choose Attack skill
(ON) Foe any -> Choose target -> Choose Attack skill
(ON) Self Lost Buff -> Choose Buff spell
(ON) Foe HP = 0% -> Taunt the player

What I like about this approach is it makes sense in my head. It also would be extremely easy to build an "AI Editor" with an approach like this. What I'm worried about is.. would it be too limiting? Would it maybe get too complicated?
Does anyone have any experience with AIs in Turn Based games that could maybe provide me some insight into this approach.. or suggest a different approach?
Many thanks in advance!!!


texts: Detect collision with static collider only

texts: Is this possible to detect collision with static colliders only I check it is not working. I dont want to use rigidbody or character controller with my box collider.


texts: What are some good tools for prototyping map layout and design?

texts:
I'm curious as to what the best method for sketching out and prototyping a map is, and if there are any tools available to facilitate this.

Pen and paper is probably a good place to start, but I would like to know if there are any worthwhile tools to look into, something akin to a UI mock up tool like Balsamiq


texts: Imported FBX animations (exported from Blender) have different, messier keyframes than in .blend file?

texts:
I imported an a character to Unity 2019.2.8 that I made in Blender 8.0, which was exported from that program in .FBX format. The animations play back the same (perceptually, but the keyframes are very messy and out of place by comparison.

What can be causing this? The animations in Blender and Unity are the same length (I checked) so what happened to the keys? How can I re-import these animations so that the keys match?

EXAMPLE:
(this all happens in Blender 8.1)

In Blender, have a rigged and animated character ready:

These animations (this animation in particular, "Battle_Punch") was recorded with the Frame Rate set to 60fps. That may not be true for all of them (hope not) but it is for this one.

Prior to export, I select all the objects in under the Luigi collection. I do that by right-clicking the Armature object in the Collections panel and selecting "Select Hierarchy".

Then I use the following FBX export settings:

Of particular note should be the options to export only what is selected.
I set the normals to "face" because once-upon-a-time, that worked well for me when the default did not.

Here are my FBX IMPORT settings inside Unity:

Model:

Rig:

Animation (only change is Import Constraints-YES and Anim. Compression-NONE):

(I'm sure the Materials settings are unimportant for this)

Here are they keyframes I get with Anim. Compression set to NONE:

...and here is what I get with the default setting (Reduced Keyframes). This result is the same as if I select OPTIMAL:

You can compare this to the keyframes in the first image and see that this outcome resembles shotgun fire better than it resembles my keyframes.

Now, an observation: Tinkering with the translation/rotation/scale error settings under Reduced Keyframes in the Animations import settings will give me more keyframes, but I can't confirm this is more consistent with what I started with because it will insert a keyframe for every position, not just where the original keyframes were.

How do I get keyframes ONLY where my original keyframes were?


texts: Creating new games on Android and/or iPhone

texts:
I have a succesfull Facebook poker game that is running very nicely. I was asked if I can port my game to other platforms - mainly mobile devices (phones as well as tablets, would tablets need a separate version)?

I am currently a PHP programmer (and game designer) and I simply don't have the time to learn Android or other languages - so I have decided to pay third parties to port the game for me (if possible).

Which programming language is needed for the following four devices - Android phone, iPhone, iPad and tablets?
Can they all run off a central SQL database?  If no then I don't think I'm interested.
Do any of these run Flash?
Have I covered all my main bases here?

For example is programming for an Android phone that much different from programming for an Andorid tablet? They will have slightly different graphics (because the tablet has a greater screen area might as well use it) but does either version need to be developed separately, from scratch?

Same goes for iPhone/iPad, do they really need to be programmed separately if the only difference is the graphics?


texts: OUYA Developer Kit throws various errors on start

texts:
I followed these instructions for Mac OS X using an existing IDE (shell + text editor) instead of the Eclipse ADT thingy. I activated “Use Host GPU”, and installed Intel HAXM.
Installing the ouya-framework.apk and ouya-launcher.apk appears to go well. But when I start up my AVD there’s a dialog box saying “Unfortunately, the OUYA Launcher has stopped.”, I still get the choice of starting up the OUYA Launcher. When I do so there’s another dialog box saying “Can’t play this video”. I skip the controller settings, and then there’s a JOIN A WIRELESS NETWORK screen which I can’t get past.

This is the ODK 1.0.2, and I tried it using both Mac OS X 10.8.3 and 10.7.5.


texts:
I use the standard approach to billboarding within Unity that is OK, but not ideal:

transform.LookAt(camera)

The problem is that this introduces distortion toward the edges of the viewport, especially as the field of view angle grows larger. This is unlike the perfect billboarding you'd see in eg. Doom when seeing an enemy from any angle and irrespective of where they are located in screen space.

Obviously, there are ways to blit an image directly to the viewport, centred around a single vertex, but I'm not hot on shaders.

Does anyone have any samples of this approach (GLSL if possible), or any suggestions as to why it isn't typically done this way (vs. the aforementioned quad transformation method)?

EDIT: I was confused, thanks Nathan for the heads up. Of course, Causing the quads to look at the camera does not cause them to be parallel to the view plane -- which is what I need.


texts: How to set off Cinemachine camera shake during an explosion

texts:
How do I set up camera shake during an explosion with Cinemachine?
This is the first time that I've messed with the impulse listener on cinemachine and so far, I can only get the camera to shake when the an object makes a collision with the object that the 'Cinemachine Collision Impulse Source' component is attached to(in my case, a Grenade).
I want to set it up so that the camera will only shake at the moment the grenade explodes(Because my Grenade script has a countdown timer before it explodes, it does not just explode upon collision).


texts: How can I determine if a cube is adjacent to another cube, and optimize its buffers if so?

texts:
I'm trying to optimize the rendering of a collection of cubes, (based on an answer I was given to another question I asked). I understand the logic behind occlusion culling, but I'm having trouble with the code.

When I create a cube, I want to determine if that cube is touching another existing cube, and if so I don't want to generate the redundant data in my vertex or index buffers.

I'm planning on making a method that I call from my cube constructor so that everytime I create a cube, these checks are made, and neither occluded face is ever drawn.

How would I go about this?


texts: Mapping 3D object coordinates to 2D screen coordinates with perspective projection

texts:
Sort of following on from where this person was in their topic:
Matrix for 2D perspective

What I have at the moment is a transformation matrix that's defined as follows:
http://pastebin.com/GM6BhP0R
-- The field projMat is just a 4x4 matrix.

I have an array of 3D points that I'm trying to map to the canvas and I'm doing that by first multiplying each vertex (3D point) by a view matrix, which I've just set to the identity matrix for the time being, although if I can get this set up that will be responsible for creating a camera with I suppose.

Lastly I take this newly transformed 3D point and I multiply it by the projection matrix as defined in the code sample above. I was hoping that this would give me the screen coordinates for the points, however there appears to be no depth to the points (e.g. points with a higher Z coordinate should start to taper in, while closer points shouldn't), so objects further away from the camera appear smaller.
As I said though, after the transformations it appears to render the points in the same position irrespective of its Z coordinate. Here's how I'm rendering the points (in Java just in case you want to know):

for(int i = 0; i < vertices.length; i++) {
    Vector3f transPos = Matrix4f.multiply(projMat, Matrix4f.multiply(viewMat, vertices[i]));
    screen.drawPoint((int) transPos.getX(), (int) transPos.getY(), 0xffffffff);
}

As you can see here the inner multiplication just multiplies the vextex (point) with the view matrix, which is set to the identity, then the 3D vector that's produced by that is then multiplied by the projection matrix, which should set it to a perspective view.

If you can see where I've gone wrong I'd appreciate any help.


texts: Is this a viable architecture for lag compensation?

texts:
In some games/engines (such as Source), the server compensates for latency by applying player inputs in the past. Whenever the server receives a player's input for a frame, it rewinds the game to the frame that input was intended for, applies the player input, then simulates the game again up to the current time. The server needs to do several times as much game-logic computation as the clients, as each frame can be simulated many times - so it seems like this would not scale well to many clients or processing-intensive games.

However, we can turn this around. If the client input for a particular frame always arrives before the server simulates that frame, then the server never needs to rewind - it only ever simulates each frame once.

In order for a player's input to reach the server before the frame that the player entered it on, the client needs to run in advance of the server. If a particular client has a latency of 250 ms, then it must simulate tick 51388 at least 250ms before the server simulates tick 51388.

Therefore, the client must be predicting the game state several ticks in advance. Every time the client receives an update from the server, the client rewinds the game, applies the update, and fast-forwards up to the current time.

If n is the number of clients, then the clients each do O(n) extra work per tick to support lag compensation, instead of the server doing O(n^(2)) extra work per tick (assuming the game state size scales as O(n)).

I don't know of any games that actually do this. What are the problems with this approach?


texts: Earth and sun - How to make the sun revolve around the earth in the following code?

texts:
I want to imitate the planetary system with Earth and Sun drawn as solid spheres on the same window. I have drawn the two: the earth as the bigger sphere and the sun as the smaller sphere.

Now I want the earth to revolve around the sun when I press key A and when I press key B the earth must rotate around its axes. How do I achieve this? Thanks.

Here is the code so far:

 #include <GL/glut.h>
 void init(void){
 glClearColor(0.0,0.0,0.0,0.0);
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 }
 void display(void){
 glClearColor(0.05,0.05,0.5,0.0);
 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 glColor3f(0.03,0.05,0.09);
 glutSolidSphere(0.5,30,30);//Earth
 glMatrixMode(GL_MODELVIEW);
 glLoadIdentity();
 glTranslatef(.7,.7,.7);
 glColor3f(1.0,1.0,1.0);
 glutSolidSphere(0.2,50,50);//Sun
 glLoadIdentity();
 glFlush();

 }
int main(int argc, char **argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE);
glutInitWindowPosition(10,10);
glutInitWindowSize(400,400);
init();
glutCreateWindow("Planets");
glutDisplayFunc(display);

glFlush();
glutMainLoop();

}


texts: What format is this 3D model in or how can I change my rendering code to accept obj files?

texts:
I have a file in my project that defines 2 numbers and 4 arrays:

#define NUM_TEAPOT_OBJECT_VERTEX 824
#define NUM_TEAPOT_OBJECT_INDEX 1024 * 3

static const float teapotVertices[NUM_TEAPOT_OBJECT_VERTEX * 3] =
{
    // ...
};

static const float teapotTexCoords[NUM_TEAPOT_OBJECT_VERTEX * 2] =
{
    // ...
};

static const float teapotNormals[NUM_TEAPOT_OBJECT_VERTEX * 3] =
{
    // ...
};

static const unsigned short teapotIndices[NUM_TEAPOT_OBJECT_INDEX] =
{
    // ...
};

These, together with a texture as jpeg, define a teapot 3D model.

How can I generate these arrays from a 3D model? Our 3D models are in .obj (and a .jpeg for texture).

I use these arrays in the following code:

Vuforia::Matrix44F modelViewMatrix = Vuforia::Tool::convertPose2GLMatrix(result->getPose());
// OpenGL 2
Vuforia::Matrix44F modelViewProjection;

VuforiaApplicationUtils::translatePoseMatrix(0.0f, 0.0f, kObjectScale, &modelViewMatrix.data[0]);
VuforiaApplicationUtils::scalePoseMatrix(kObjectScale, kObjectScale, kObjectScale, &modelViewMatrix.data[0]);
VuforiaApplicationUtils::multiplyMatrix(&projectionMatrix.data[0], &modelViewMatrix.data[0], &modelViewProjection.data[0]);

glUseProgram(shaderProgramID);

glVertexAttribPointer(vertexHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotVertices);
glVertexAttribPointer(normalHandle, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotNormals);
glVertexAttribPointer(textureCoordHandle, 2, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)teapotTexCoords);

glEnableVertexAttribArray(vertexHandle);
glEnableVertexAttribArray(normalHandle);
glEnableVertexAttribArray(textureCoordHandle);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, augmentationTexture[0].textureID);
glUniformMatrix4fv(mvpMatrixHandle, 1, GL_FALSE, (const GLfloat*)&modelViewProjection.data[0]);
glUniform1i(texSampler2DHandle, 0 /*GL_TEXTURE0*/);
glDrawElements(GL_TRIANGLES, NUM_TEAPOT_OBJECT_INDEX, GL_UNSIGNED_SHORT, (const GLvoid*)teapotIndices);

glDisableVertexAttribArray(vertexHandle);
glDisableVertexAttribArray(normalHandle);
glDisableVertexAttribArray(textureCoordHandle);

If you know how I can adapt this code to load standard 3D models, such as .obj files, please help.


texts: glReadPixels performance not improving with PBO

texts:
I'm currently using glReadPixels to read from the depth buffer to calculate where on the map the player is pointing, for the purpose of placing objects on the ground. I do this after rendering the heightmap, but before rendering all other objects, so I don't get a skewed result.
float depth;
glReadPixels( mouseX, windowHeight - mouseY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth );

This works fine, but as expected causes my frame time to go up from 15ms to 25ms.
I then tried wrapping the glReadPixels call within a PBO and using the value a frame or two later when it becomes available.
// Within data struct
GLuint pbo;
GLsync readSync;
float depth;

// Within init
glGenBuffers( 1, &pbo );

// ...

// Within render loop
if ( readSync != 0 ) {
    GLenum syncStatus = glClientWaitSync( readSync, 0, 0 );
    if ( syncStatus == GL_ALREADY_SIGNALED || syncStatus == GL_CONDITION_SATISFIED ) {
        glGetBufferSubData( GL_PIXEL_PACK_BUFFER, 0, 4, &depth );
        readSync = 0;
    }
}
if ( readSync == 0 ) {
    glBindBuffer( GL_PIXEL_PACK_BUFFER, pbo );
    glBufferData( GL_PIXEL_PACK_BUFFER, 4, 0, GL_STREAM_READ );
    glReadPixels( mouseX, windowHeight - mouseY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, 0 );
    readSync = glFenceSync( GL_SYNC_GPU_COMMANDS_COMPLETE, 0 );
}

While this does work, I'm not seeing any performance improvement compared to the non-PBO method. I've read that some drivers can be fussy about reading from the depth buffer, but I get equal results when reading from the front buffer as well.
Am I missing something here?


texts: How to get projectile direction vector in a 2d grid?

texts:
I am having trouble figuring out how to trace the path of my projectiles in an Asteroids clone. Currently the ship is locked to the center of the screen and can be rotated a full 360 degrees. I know the angle the ship is pointing at any given time, but I am not sure how to calculate the vector that the projectile should use for its trajectory. I know that I can find the correct vector by subtracting the end point from the start point.. but the issue is that I do not know the end point. Theoretically.. the end point is whenever the projectile touches the edge of the screen or some object. This is the current game code: https://jsfiddle.net/m6sxrk8w/
 just using a hardcoded movement vector of {x:-1, y:-1}. Can anyone give some advice on how to dynamically determine the true vector given the current direction of the ship? There must be some simple math I am missing here...


texts: 2DRaycast is shooting slightly in wrong directions

texts:
I wanted just a simple 2DRaycast, which points from my character to my mousePointer. So I found the following code in the Internet, most people seem to use it like that. So I tried it, but it isn't working for me like it is supposed to do, check the screenshot below. The direction is kinda weird, so I tried some variants of the variables and tried with Normalize, which didn't solve the problem.

    Vector2 test = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
    Vector3 test1 = (Camera.main.ScreenToWorldPoint (Input.mousePosition));
    //test.Normalize ();
    RaycastHit2D hit = Physics2D.Raycast (transform.position, test);
    Debug.DrawRay (transform.position, test, Color.red);

I tested both variables, test and test1, same things happen, even with Normalize and without it. The following Screenshot shows, what happens (The red thing is the mouse pointer).

Edit:

Solution:

    Vector2 test = new Vector2 (Camera.main.ScreenToWorldPoint (Input.mousePosition).x, Camera.main.ScreenToWorldPoint (Input.mousePosition).y);
    Vector3 test1 = (Camera.main.ScreenToWorldPoint (Input.mousePosition));
    //test.Normalize ();
    RaycastHit2D hit = Physics2D.Raycast (transform.position, test1 - transform.position);
    Debug.DrawRay (transform.position, test1 - transform.position, Color.red);

I use now the second variable, because we need the Vector3 here, because we substract with Transform.position which is a Vector3.


texts: Algorithm for querying linearly through a non-linear list of questions

texts:
For a multiplayers trivia game, I need to supply my users with a new quizz in a desired subject (Science, Maths, Litt. and such) at the start of every game.

I've generated about 5K quizzes for each subject and filled my database with them. So my 'Quizzes' database looks like this:

|ID   |Subject     |Question
+-----+------------+----------------------------------
|  23 |Science     | What's water?
|  42 |Maths       | What's 2+2?
|  99 |Litt.       | Who wrote "Pride and Prejudice"?
| 123 |Litt.       | Who wrote "On The Road"?
| 146 |Maths       | What's 2*2?
| 599 |Science     | You know what's cool?
|1042 |Maths       | What's the Fibonacci Sequence?
|1056 |Maths       | What's 42?
And so on... (Much more detailed/complex but I'll keep the exemple simple)

As you can see, due to technical constraints (MongoDB), my IDs are not linear but I can use them as an increasing suite.

So far, my algorithm to ensure two users get a new quizz when they play together is the following:

// Take the last played quizzes by P1 and P2
var q_one = player_one.getLastPlayedQuizz('Maths');
var q_two = player_two.getLastPlayedQuizz('Maths');

// If both of them never played in the subject, return first quizz in the list
if ((q_one == NULL) && (q_two == NULL))
  return QuizzDB.findOne({subject: 'Maths'});

// If one of them never played, play the next quizz for the other player
// This quizz is found by asking for the first quizz in the desired subject where
// the ID is greater than the last played quizz's ID (if the last played quizz ID
// is 42, this will return 146 following the above example database)
if (q_one == NULL)
   return QuizzDB.findOne({subject: 'Maths', ID > q_two});
if (q_two == NULL)
   return QuizzDB.findOne({subject: 'Maths', ID > q_one});

// And if both of them have a lastPlayedQuizz, we return the next quizz for the
// player whose lastPlayedQuizz got the higher ID
if (q_one > q_two)
   return QuizzDB.findOne({subject: 'Maths', ID > q_one});
else
   return QuizzDB.findOne({subject: 'Maths', ID > q_two});

Now here comes the real problem:

Once I get to the end of my database (let's say, P1's last played quizz in 'Maths' is 1056, P2's is 146 and P3 is 1042), following my algorithm, P1's ID is the highest so I ask for the next question in 'Maths' where ID is superior to 1056. There is nothing, so I roll back to the beginning of my quizz list (with a random skipper to avoid having the first question always show up). P1 and P2's last played will then be 42 and they will start fresh from the beginning of the list. However, if P1 (42) plays against P3 (1042), the resulting ID will be 1056...which P1 already played two games ago.

Basically, players who just "rolled back" to the beginning of the list will be brought back to the end of the list by players who still haven't rolled back. The rollback WILL happen in the end, but it'll take time and there'll be a "bottleneck" at the beginning and at the end.

Thus my question: What would be the best algorith to avoid this bottleneck and ensure players don't get stuck endlessly on the same quizzes?

Also bear in mind that I've got some technical constraints:

I can't get a random question in a subject (ie: no "QuizzDB.findOne({subject: 'Maths'}).skip(random());"). It's cool to skip on one to twenty records, but the MongoDB documentation warns against skipping too many documents.
I would like to avoid building an array of every quizz played by each player and find the next non-played in the database with a $nin.

Thanks for your help


texts: How can I ensure free graphics are suitable for use in a game?

texts:
We want to program a small minigame where we need a lot of icons for all kind of things (like in "Alchemy"). We looked through some free vector graphics pages, like http://www.freepik.com/, but they all state some vague instructions where and where-not to use the images.

For example this site writes

For both personal and commercial projects and to modify it.

but on the other hand:

Include FreePik Contents in an online or offline database or file.

Which sounds contradictionary, you need to store it in a file to modify it.

How can we get sure, that images that we use from such sites are really free to use on attribution and we don't get any problems later?

How should the licences look like, so we can be sure to get no problems later,if we use free icons from there?


texts: How to override onSetContentView while Using Ratio Resolution policy in Andengine Base game activity

texts:
I am developing (Learning to build :)  ) a game with  andengine GLES2.
I am using base game acitvity , and i overrides the setContent view to place my admob ad.Every thing works fine except the resolution policy . Ratio Resolution policy is the one I am using along with CAMERA_WIDTH = 800; and CAMERA_HEIGHT = 480;

The issue is whenever overided onsetContentView scene is not get aligned to center ,margins displayed only on bottom not on both top and bottom, Same will cause when horizontally align the margin will be displayed only at right side, not on both sides. how can i correct this. I am giving my code below

@Override
protected void onSetContentView() {

    System.out.println("Content setting");
    this.mRenderSurfaceView = new RenderSurfaceView(this);

    final LayoutParams layoutParams = new LayoutParams(
            android.view.ViewGroup.LayoutParams.MATCH_PARENT,
            android.view.ViewGroup.LayoutParams.MATCH_PARENT);

    layoutParams.gravity = Gravity.LEFT ;

    final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams = new FrameLayout.LayoutParams(
            layoutParams);

    adView = new AdView(this, AdSize.BANNER, "xxxxxxxxxxxxx");

    final FrameLayout.LayoutParams adViewLayoutParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.WRAP_CONTENT,
            FrameLayout.LayoutParams.WRAP_CONTENT, Gravity.LEFT
                    );

    final FrameLayout frameLayout = new FrameLayout(this);
    final FrameLayout.LayoutParams frameLayoutLayoutParams = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.FILL_PARENT,
            FrameLayout.LayoutParams.FILL_PARENT,Gravity.CENTER);

    frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
    frameLayout.addView(adView, adViewLayoutParams);

    this.setContentView(frameLayout, frameLayoutLayoutParams);
    this.mRenderSurfaceView.setRenderer(this.mEngine, this);

}

here is the image what i get you can see the white margin below the scene if you select the image ( its not get into attention due to stack overflow also had white background )

any suggestions will be very help full to me

How Can i solve this Isuue Please help me

Thanks to all,


texts:
Is it possible to calculate the exact camera bounds? By this I mean the white lines that represent the camera area e.g the lines in the picture:

I'm using Camera.main.screenToWolrdCoordinates to convert screen coordinates to world coordinates because I want to position the player exactly on that white line that the camera represents:

But when I calculate the boundaries using Camera.main.screenToWolrdCoordinates I get this:

The players legs are outside of that lower camera bound on y axis, it will also happen on x axis when I strict the players movement by using the value that I got from Camera.main.screenToWolrdCoordinates , I also have bouncing balls in my game that I want to strict by the same boundaries. So my question is how can I calculate camera bounds exactly by this I mean again these white lines that represent the camera view, I hope that my question is clear enought. Just to make it more clear, when I calculate the bounds using Camera.main.screenToWolrdCoordinates I just assign the Y value that I got from that calculation to the Y position of the player.


texts: How can I move the camera to create a parallax effect?

texts:
Right now I am making an application which can be described as model viewer for iPad Pro. The client wants to have an orbiting camera around the object and in addition he wants to have a parallax effect similar to iPhone 3D wallpapers which will is based of of tilt of the tablet.

My problem right now is that I am not really sure how to calculate the parallax effect and how to rotate the camera (or model) to create the 3D effect. Can you give me an idea how to do this ?

Thank you


texts: flicker when drawing 4 models for the first time

texts:
i have some models that i only draw at a certain moment in the game (after some seconds since the game has started). The problem is that in that first second when i start to draw the models, i see a flicker (in the sence that everything besides those models, dissapears, the background gets purple). The flicker only lasts for that frame, and then everything seems to run the way it should.

UPDATE
I see now that regardless of the moment i draw the models, the first frame has always the flickering aspect

What could this be about? i'll share my draw method:

int temp = 0;
foreach (MeshObject meshObj in ShapeList)
{
    foreach (BasicEffect effect in meshObj.mesh.Effects)
    {
        #region color elements

        int i = int.Parse(meshObj.mesh.Name.ElementAt(1) + "");
        int j = int.Parse(meshObj.mesh.Name.ElementAt(2) + "");
        int getShapeColor = shapeColorList.ElementAt(i * 4 + j);
        if (getShapeColor == (int)Constants.shapeColor.yellow)
            effect.DiffuseColor = yellow;
        else if (getShapeColor == (int)Constants.shapeColor.red)
            effect.DiffuseColor = red;
        else if (getShapeColor == (int)Constants.shapeColor.green)
            effect.DiffuseColor = green;
        else if (getShapeColor == (int)Constants.shapeColor.blue)
            effect.DiffuseColor = blue;

        #endregion

        #region lighting

        effect.LightingEnabled = true;
        effect.AmbientLightColor = new Vector3(0.25f, 0.25f, 0.25f);

        effect.DirectionalLight0.Enabled = true;
        effect.DirectionalLight0.Direction = new Vector3(-0.3f, -0.3f, -0.9f);
        effect.DirectionalLight0.SpecularColor = new Vector3(.7f, .7f, .7f);

        Vector3 v = Vector3.Normalize(new Vector3(-100, 0, -100));
        effect.DirectionalLight1.Enabled = true;
        effect.DirectionalLight1.Direction = v;
        effect.DirectionalLight1.SpecularColor = new Vector3(0.6f, 0.6f, .6f);

        #endregion

        effect.Projection = camera.projectionMatrix;
        effect.View = camera.viewMatrix;
        if (meshObj.isSetInPlace == true)
        {
            effect.World = transforms[meshObj.mesh.ParentBone.Index] * gameobject.orientation; // draw in original cube-placed position
            meshObj.mesh.Draw();
        }
        else
        {
            effect.World = meshObj.Orientation; // draw inSetInPlace position
            meshObj.mesh.Draw();
        }
    }
    temp++;
}


texts: Andengine Rotate Wheel with fast acceleration

texts:
I have a Wheel sprite and i am rotating it using Physics RevoluteJointDef. Its rotating.
But problem is how i can make wheel to start moving fast. It took the speed after sometime like real.

// Create body for green rectangle (Static)
    final Body greenBody = PhysicsFactory.createBoxBody(pw, greenRectangle, BodyType.StaticBody, PhysicsFactory.createFixtureDef(0, 0, 0));

    // Create body for red rectangle (Dynamic, for our arm)
    final Body redBody = PhysicsFactory.createBoxBody(pw, wheel, BodyType.DynamicBody, PhysicsFactory.createFixtureDef(1, 0.5f, 0.1f));
    pw.registerPhysicsConnector(new PhysicsConnector(wheel, redBody, true, true));

    // Create revolute joint, connecting those two bodies
    final RevoluteJointDef revoluteJointDef = new RevoluteJointDef();
    revoluteJointDef.initialize(greenBody, redBody, greenBody.getWorldCenter());
    revoluteJointDef.localAnchorA.set(0,0);
    revoluteJointDef.localAnchorB.set(0,0);

    revoluteJointDef.enableMotor = true;
    revoluteJointDef.motorSpeed = 100;
    revoluteJointDef.maxMotorTorque = 1000;

    pw.createJoint(revoluteJointDef);

    registerUpdateHandler(pw);


texts: How can I create a lightning attack similar to Agahnim's in Legend of Zelda: Link to the Past?

texts:
I'm currently trying to recreate this attack, and I'm unsure of how it works.

It seems like the boss creates 4 lightning bolts which move downward at 45 degree/diagonal angles, changing direction every so often.

I'm building my game in Zelda Classic. I'd preferably like to know how to do this in C++, although I am fine with Java or anything C++/C-like.


texts: How to bind std::map to Lua with LuaBind

texts:
Is this possible in lua to achieve?

player.scripts["movement"].properties["stat"] = "stand"
print (player.scripts["movement"].properties["stat"])

I've done getter method in c++ with this approach:

luabind::object FakeScript::getProp()
{
    luabind::object obj = luabind::newtable(L);

    for(auto i = this->properties.begin(); i != this->properties.end(); i++)
    {
        obj[i->first] = i->second;
    }

    return obj;
}

But I'm stuck with setter. The first line in lua code which I'm trying to set value "stand" for key "stat" is not going to work and it keep redirecting me to the getter method. Setter method only works when I drop ["stat"] from properties.

I can do something like this for setter in my script:

player.scripts["movement"].properties = {stat = "stand"}

But this isn't what I want because I have to go through my real keys in c++ to determine which key is placed in setter argument table value.

This is my map in class:

std::map<std::string, std::string> properties;


texts:
I am working with DirectX (C#/C++).
I am wondering is it possible to do not triangulate meshes and what the difference between cases (in loading and rendering code)? If so, how to do this? I know DrawIndexed requires primitive_topology to be set - which value should I use then?
I always used triangulated mesh before with no problems but it is interesting..


texts: OpenGL : Suggestion on handling collision detection and vertex data?

texts:
I was thinking  how to do collision detection in my OpenGL application and came to conclusion that I should keep two copies of my geometry data.

1)First copy : Only for OpenGL rendering purposes.This can be saved as VBO,Vertex Indices.(saved in GPU?)

2)Second copy :I save in client side(in a class ,say 3DEntity) which I perform all tests including bounding-box collision test,ray casting,

So, after I load a mesh data (say from an OBJ file), first I prepare the "first copy" and then using "vertex indices" I prepare the "second copy".
(For example: If my mesh is a simple cube ,my "first copy" will have 8 vertices,and use Vertex Indices to render it properly.But my "second copy" will have total 36 vertices.Because  I have to do ray-casting on triangles)

I keep a transformation matrix inside the "3DEntity" to keep states like Position,Rotation..etc of my "3d Entity".
So in psuedo code;

class 3DEntity {
 Vertex[] verticesForPhysics;
 Matrix tranformationMatrix;
}

I keep the "verticesForPhysics" values fixed.(Means, its always in  model coordinate system).So When I want to move,rotate my entity I simply change "transformationMatrix".

When doing tests like collision detection , I make a temporary copy of vertices again,by multiplying  "verticesForPhysics" by "transformationMatrix" giving the vertices in World coordinates.

Vertex[] verticesForPhysicsInWorld=transformationMatrix * verticesForPhysics;

Now I do my tests using these "verticesForPhysicsInWorld".

Is this the correct way of handling this ? How do other OpenGL game engines handle this ?
I am worried about data redundancy by keeping two copies and making another temporary copy for collision detection tests


texts:
I'm quite new to programming games and I'm currently working on a group project in university on creating one. In the game we've got a set of squares (cities, other entities) which are placed on the real plane. We'd like to start the game with a few squares in the center of the map and, as time goes, randomly place new ones around them, growing the whole network like that. I couldn't figure out how to elegantly do this and I found a lot of map generation algorithms, but they're mostly for surfaces and similar things, whereas my problem is more discrete. Any ideas?
I've added a picture in response to a comment - so our game might start off with the three red squares and as time goes we might add additional three squares (greens), after a while we can add two more squares again and so on.


texts: how to solve slow framerate (how to solve situation when user uses computer much slower then minimum requirement)

texts:
We have some minimum requirements set for the game, however, it's possible to play the game on much slower computers and we argue in the team how to approach the situation when the hardware is too slow to run the game the way it's meant to run.

We generally have three ideas:

run benchmark in the beginning and if the computer won't pass it inform the player he can't play, he should update drivers etc,
under certain framerate pause the game and ask the player to disable thing running in background or update drivers etc.

(1. and 2. can be combined)

under certain framerate slow the game down - so let's say the game should run on 60 FPS and between 60 and 20 the speed will be normal and if it goes lower than 20 fps it will progressively slow down so the player sees the same amount of frames as it'd run at 20FPS

In our case, the game looks pretty bad when we simulate 10 FPS and less and it isn't nice under 20.

Is there any common approach to this?


texts: What are some great papers/publications relating to game programming?

texts: What are some of your favorite papers and publications that closely relate to game programming? I'm particularly looking for examples that are well-written and illustrated, and/or have had a profound influence on the industry. (Here's one example: in this GDC talk, Bungie's David Aldridge mentions that a paper called "The TRIBES Engine Networking Model" was the starting point for Halo's network code.)


texts: VSCode doesn't open the specified Unity script

texts: I have downloaded Visual Studio Code to edit Unity scripts. When I double click on a script in Unity, VSCode opens but it doesn't open the script, only an empty file called Unity appears. Anyone knows how to solve this?


texts:
I've been looking for similar questions here and on google, but none have worked for me yet.
I have a game, where I have a 2d array of square tiles (they're objects with accessible x and y pixel coords, side length in pixels, and whether are they see-through).

In there, there are enemies and the player. They can move independently from the grid (as in, pardon the example, Minecraft), and I have got access to their coords. What I want is a function that will tell me if a given enemy can see the player or not (just returning bool).
Can you help me?

EDIT: I used Bresenham. If anyone there is from Poland, a great description of Bresanham's jest tutaj :http://edu.i-lo.tarnow.pl/inf/utils/002_roz/2008_06.php :)


texts: How to move sprite mimicking mouse/touch position on some part of the screen?

texts:
I am having a difficulty and I am been doing it wrong, I think. I want to move sprite relatively to touch. Just like when you are playing space shooter like 1943. I just learning some math and try to mimic those control by myself but I have no luck doing so far.

I have snippet of code, its far from perfect, I was able to move the sprite relatively but keeps jumping off when I first touch and moved.

Here is what I got so far:

When the touch move:

void Trooper::onTouchMoved(cocos2d::Touch * touch, cocos2d::Event * event)
{
    mPreviousTouchPosition = mTouchMovePosition;
    mTouchMovePosition = touch->getLocation();

    cocos2d::Vec2 delta = utility::Object::getPosition() + (mTouchMovePosition - mPreviousTouchPosition);
    delta = utility::Object::getContainingScene()->convertToNodeSpace(delta);

    utility::Object::setPositionTo(delta);

    CCLOG("Coordinates when moved : %f , %f" , delta.x , delta.y);
}

Here is the data I logged and the first line for coordinates when moved seem anomalous to me:

Coordinates on touch : 633.746338 , 395.874329
Coordinates when moved : 883.746338 , 644.876404
Coordinates when moved : 882.747925 , 644.876404
Coordinates when moved : 880.752136 , 642.879517
Coordinates when moved : 878.755249 , 641.881104
Coordinates when moved : 876.758423 , 640.882690
Coordinates when moved : 874.761536 , 637.887939

I shouldn't be seeing this kind of huge number when my actual sprite is on 250 , 250. The difference of previous touch position and the current touch position should be added to the sprite position. I wanted to achieve relativeness regardless I touch and move. The sprite should mimic that. Did I missed something or anything wrong with my math?

Thank you!


texts: Techniques to mitigate microstuttering when the FPS is above 60fps and vsync is off

texts:
The problem with first person shooters is that your input is important, and coupling it with VSync ruins it.
The following frames per second data when rendering with OpenGL shows:

60-100 fps: annoying jitter
140 fps: minor jitter, but certainly noticeable
200 fps: very minor small jitter sometimes
260 fps: either generally fine or very very small
300+ fps: perfectly fine

The problem is other games I play that use similar rendering algorithms only stutter in the range of 60-100fps, whereas my range is 60-250fps (albeit it gets better when you get into the 200 range but you can still notice it if paying attention).
At first I thought my game loop may have been wrong, but after going through it in great detail it is working just fine (and vsync works perfectly smooth with it too, if it was broken this would be an issue the update rate and the vsync monitor refresh rate are not divisible by each other).
60 - 100 fps is 62.5 - 10ms
100 - 250 fps is 10 - 4ms
Not being able to go above 4ms would be pretty constraining!
Because I'm using C# (note: I have zero GC, it doesn't run), I don't know if this means I'm somehow running into higher variability with the VM than I would when I did stuff in C++. I don't know if being in the 4-10ms range means that sometimes it will spike.
Now I did profile this, and this is what I've seen:

Ignoring the green line, the blue line is the uncapped version and orange is vsync. Since the vsync line has massive variability but seems to render fine, whereas the blue one has spikes but are all generally below the vsync line (and definitely not greater than the spikes from vsync), I don't understand whether I'm actually seeing those blue spikes and it's because of some kind of intermediate frame tear or not. It doesn't look like a frame tear to me, it just looks like a frame is lost and I lurch forward a bit more than normal like I was lagging online.
So the question is... what can I do to diagnose this issue? Or is this normal?
I was thinking of rendering to a framebuffer and just drawing that every 1/60 seconds in an attempt to smooth things out and emulate vsync but this comes with it's own drawbacks. Problem is... my back is against the wall and I'm worried I'll be doing potentially stupid and wasteful stuff.
EDIT 1: Ticker code that does what I do
(int, double) timerFunc()
{
    long currentTime = GetCurrentTime();

    accumulation += currentTime - lastTimeSeen;
    lastTimeSeen = currentTime;

    // If it returns 1.27, then we have to run 1 tick, and interpolate at t = 0.27
    double tickFraction = accumulation / timePerGametick;

    int ticksToRun = floor(tickFraction);
    double fraction = tickFraction - ticksToRun;

    if (ticksToRun > 0)
        accumulation -= (ticksToRun * timePerGametick);

    return (ticksToRun, fraction);
}

EDIT 2: Game loop and basic logic (uses timerFunc data from above)
void update(int ticksToRun) {
    for i in ticksToRun {
        foreach plane in planes that should move {
            plane.Tick();
        }

        foreach entity in entities {
            entity.Tick();
        }
    }
}

// interpolation will be in [0.0, 1.0)
void render(double interpolation) {
    foreach plane in planes {
        planeDelta = (plane.current - plane.prev);
        planeInterpolated = plane.prev + (planeDelta * interpolation);
        render(planeInterpolated);
    }

    foreach entity in entities {
        entityDelta = (entity.current - entity.prev);
        entityInterpolated = entity.prev + (entityDelta * interpolation);
        render(entityInterpolated);
    }

    swapBuffers();
}

void gameLoop() {
    while (true) {
        (int ticksToRun, double fraction) = timerFunc();

        pollInput();

        if (ticksToRun > 0)
            update(ticksToRun);

        render(fraction);
    }
}


texts: Issue with implemented Minesweeper algorithm

texts:
So I'm attempting to learn Python by way of Minesweeper.  I've got experience with SDL, so I figured playing around with PyGame sounded like a fun way to learn the syntax of the language.

Anywho, I'm having an issue in uncovering adjacent open squares as you would in a normal game of Minesweeper.  I click on a cell with 0 neighboring mines, and attempt to scan the top, left, right, and bottom to see if those also have 0 neighboring mines, and I do this recursively.

Here is the error that I receive:

RuntimeError: maximum recursion depth exceeded in cmp

And here is my algorithm:

#open up blank mines
def open_blank_cells(mines, cr, cc):
  #top
  if (cr > 0):
    t_mine = mines[cr-1][cc]
    t_mine.switch_state(3)
    if (t_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr-1, cc)

  #right
  if (cc < 9):
    r_mine = mines[cr][cc+1]
    r_mine.switch_state(3)
    if (r_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr, cc+1)

  #bottom
  if (cr < 9):
    r_mine = mines[cr+1][cc]
    r_mine.switch_state(3)
    if (r_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr+1, cc)

  #left
  if (cc > 0):
    l_mine = mines[cr][cc-1]
    l_mine.switch_state(3)
    if (l_mine.neighbor_mines == 0):
      open_blank_cells(mines, cr, cc-1)

  return

where mines is my 2D array of cells, cr is the index of the current row (first array index), and cc is the index of the current column (second array index).

I thought that my algorithm was decently solid (but please tell me if I'm wrong there!!!), so I turned to the Internet and found that the default Python recursion limit of 1000 could be to blame.  However, when I bump it higher with the call to sys.setrecursionlimit the game either exhibits the same behavior, or simply crashes as the system kills it.

When I comment out 2 of the 4 recursive checks in the function, it will open up blank cells without any problem.  3 or more however breaks the algorithm.

Edit

As requested....

Calculation of neighbor_mines

# if not a mine, figure out how many surround it
  for i in xrange(10):
    for j in xrange(10):
      if (mines[i][j].is_mine == False):
        #check top 3
        if (i > 0):
          if (j > 0):
            if (mines[i-1][j-1].is_mine == True):
              mines[i][j].neighbor_mines += 1

          if (mines[i-1][j].is_mine == True):
            mines[i][j].neighbor_mines += 1

          if (j < 9):
            if (mines[i-1][j+1].is_mine == True):
              mines[i][j].neighbor_mines += 1

        #check left and right
        if (j > 0):
          if (mines[i][j-1].is_mine == True):
            mines[i][j].neighbor_mines += 1

        if (j < 9):
          if (mines[i][j+1].is_mine == True):
            mines[i][j].neighbor_mines += 1

        #check bottom 3
        if (i < 9):
          if (j > 0):
            if (mines[i+1][j-1].is_mine == True):
              mines[i][j].neighbor_mines += 1

          if (mines[i+1][j].is_mine == True):
            mines[i][j].neighbor_mines += 1

          if (j < 9):
            if (mines[i+1][j+1].is_mine == True):
              mines[i][j].neighbor_mines += 1

Switch_state

 def switch_state(self, newstate):
    self.state = newstate

    #marked as mine
    if (newstate == 1):
      nf = "sq_mine_marked.png"
    elif (newstate == 2):
      nf = "sq_mine_question.png"
    elif (newstate == 3):
      nf = "sq_mine_open.png"
    elif (newstate == 4):
      nf = "sq_mine_mine.png"
    else:
      nf = "sq_mine.png"

    oldrect = self.rect #save old rect as load_image overwrites it
    self.image, self.rect = load_image(nf, (255,0,255))
    self.rect = oldrect


texts: Understanding use of dot product in speed boost pad

texts:
I am trying to understand the dot product. I have found a website that gives you intuition about this topic and one of the examples involves a speed boost pad:

Imagine the red vector is your speed (x and y direction), and the blue vector is the orientation of the boost pad (x and y direction). Larger numbers are more power.
How much boost will you get? For the analogy, imagine the pad multiplies your speed:

If you come in going 0, you'll get nothing [if you are just dropped onto the pad, there's no boost]

If you cross the pad perpendicularly, you'll get 0 [just like the banana obliteration, it will give you 0x boost in the perpendicular direction]

But, if we have some overlap, our x-speed will get an x-boost, and our y-speed gets a y-boost:
\$\text{Total} = speed_x \cdot boost_x + speed_y \cdot boost_y\$
Neat, eh? Another way to see it: your incoming speed is \$\|a\|\$, and the max boost is \$\|b\|\$. The percentage of boost you actually get (based on how you're lined up) is \$\cos(θ)\$
, for a total of \$\|a\| \|b\|\cos(θ)\$.

Let's say we have an object moving with a speed v of <3,3> at an angle of 45 degrees and a boost pad p of <10,0>. I am looking to see the increase of vector v when it hits the pad.
I have calculated the dot product obtaining a value of 30. My questions are:

how does this value modify the speed vector?

And what does this value actually represent? The new total length of v? Does it modify only the x coordinate of v?

And how do I add it over the initial vector? What would be the new speed vector after the interaction with the boost pad?

If we are to normalize the vectors and calculate the dot product, we get a value of around 0.70(cos 45). How is this value to be used on the current speed vector v<3,3>? And what does this percentage represent?

Also, I imagine that the new value for the vector would be just for the frame where it hits the pad, thus to make use of the boost a timer should be added before the speed comes back to normal.