# Question
Title: How can I tell how much of a "scratch card" has been revealed?
I have developed scratch card effect.I am now working on reward system, so my question is how will I go on and implement logic which will let me know that the object behind scratch card is now visible??

# Answer
I agree with Superdoggy's answer, but I believe there is a better way to go about this. If you know the area of the scratch card collision box you are wanting to reveal, you could go about it by: Get the Total Pixel amount of the object(width\*height). When the mouse is pressed: check the pixels around the mouse in a radius of your choice, and if it is within the area of the object, and the pixel is currently opaque, set to transparent and ++ a 'revealed pixel' counter. To check how much of the scratch card is currently visible, just divide 'Revealed Pixels' by 'Total Pixels.'

Unfortunately I don't know how to program in Unity, so here's some pseudo code!

```
    Initializer:
      set object = {x1, y1, x2, y2}
      set revelead_pixels = 0
      set radius = (number greater than 0)
      set bool object_pixels[object.x2 - object.x1][object.y2 - object.y1] = 1
      set percent_visible = (percentage of object to be visible before coninuing, 0 to 1)

    On mouse press:
      --mouse.x and mouse.y are coordinates of mouse

      FOR x, radius * 2 DO

        FOR y, radius * 2 DO

          --only run if x and y are within circle around mouse
          IF ((x - radius) * (y - radius) > radius) THEN
            continue
          ENDIF

          --if mouse + 'for variables' is within object
          IF ((x + mouse.x >= object.x1) AND (x + mouse.x < object.x2) AND (y + mouse.y >= object.y1) AND (y + mouse.y < object.y2)) THEN

            --if the current pixel is set to 1 (or opaque)
            IF (object_pixels[x + mouse.x - object.x1][y + mouse.y - object.y1] == 1) THEN
              object_pixels[x + mouse.x][y + mouse.y] = 0
              revealed_pixels += 1
            ENDIF

          ENDIF

        ENDFOR

      ENDFOR

      IF revealed_pixels >= ((object.x2 - object.x1) * (object.y2 - object.y1)) / percent_visible THEN
        --This statement runs if over preferred amount of pixels are visible
      END

```
> 4 votes

# Answer
I would add up all of the alpha values of the scratch card pixels that are overlapping the object pixels. Then if "A" \< some value you can assume that the user has cleared enough pixels that they can see the object.

You can find a really good tutorial on per-pixel collision detection in C# here: Linkylink. It's made for C# with XNA, but the concept isn't too hard to adapt to C# with Unity, I would assume. Simply just modify the code a bit to count alpha values of colliding pixels instead of just checking for collision.

Hope this helps!
> 2 votes

---
Tags: unity
---


title: How do I integrate drag over distance?

text:
# Question
Title: How do I integrate drag over distance?
In my game I want to model kind-of-accurate bullet physics. I have the following drag equation (in C#):

```
float drag = 0.235f * density * velocity*velocity * Mathf.PI * sizeMM*sizeMM/4000000;

```

In non-code terms, this is the same as the drag equation:

```
drag = 0.5 x [density] x [speed]^2 x [area] x [drag coefficient (0.45)]

```

Where density is the density of the material (air being 1.225kg/m^3), velocity is the velocity in m/s, and sizeMM is the diameter of the spherical projectile in mm. 0.235 was obtained by the 1/2 in the drag equation and 0.45 from the drag coefficient for spherical objects, and 4mil was the result of squaring 2000 (2 for halving diameter, 1000 for converting to metres).

The drag value appears to be appropriate, for a 11.43mm radius bullet travelling at 251m/s through air, I get a drag value of 1.860946 (presumably in m/s). What I need to be able to do is integrate that over a set distance D to obtain the result velocity as it impacts the target, and I already know that distance value.

I'm open to all potential answers to the problem, provided no loops are used. I need the resulting math to be as fast as possible, due to the possibility of it being used upwards of 20 times per second in multi-person combat.

I need the resulting math to always use the provided input variables. Density could change based on the material (i.e. flesh, kevlar, wood), sizeMM will change based on the type of ammo, and velocity will obviously change.

Approximations are preferred if accurate. If you can give an equation that is within 0.1% of the always-exact one and runs twice as fast, I'd prefer that.

# Answer
Only in exceptional circumstances will players notice or care about the accuracy of your physics simulation. Most games fake calculations like these, which has several advantages; fake calculations are easier to code, computationally less expensive and most importantly, they allow the behaviour of the game to be tweaked in favour of fun rather than realism. If playtesting reveals physically accurate bullet drag is less appealing than some other model, faking it becomes a deliberate design choice.

If you still believe realistic drag is an important feature for your game, here's a bit of physics. The drag equation can be solved analytically, though if you should want to involve other forces on the bullet, you require numerical integration. Combining the drag equation with Newton's second law of motion, we get: *m v'(t) = -½ v(t)² ρ A Cd*, the solution of which is: *v(t)=2 m / (ρ A Cd t + 2 m v(0)-1)*.

This gives us the bullet's speed as a function of time, not of distance, but we can integrate *v(t)* over time to get the distance travelled *x(t)*, then invert that to get the travel time as a function of distance: *t(x) = 2 m(eρ A Cd x / (2 m)-1) / ( ρ A Cd v(0) )*. The many symbols in this formula obscures its relatively simple exponential nature, which becomes apparent if we simplify *v(t(x))*, the speed the bullet has when it reaches *x*: *v(x) = v(0) e-(ρ A Cd/ (2 m)) x*.

The plot below shows the bullet velocity against distance with the parameters you supplied (air density: 1.225 *kg/m3*; bullet radius: 11.43 *mm*; initial speed: 251 *m/s*; drag coefficient: 0.45; mass: 10 *g*).

The equation works reasonably well for bullets of different sizes, shapes and masses, but not for different materials. Wood, kevlar and flesh are not fluids and the drag equation does not apply. Newton's approximation of impact depth may be of some use, but its accuracy is limited, especially for materials like kevlar, which are designed to outperform this approximation.
> 4 votes

# Answer
You don't need to integrate for this.

What you have calculated above is the amount of energy that's scrubbed off per second.

1. Decide what Muzzle Velocity you will have.
2. Calculate the Starting Energy of the round in Newtons based on the Mass and Muzzle Velocity.
3. Calculate your Time to Target using the Velocity and Distance to Target.
4. Multiply Time to Target by your Drag Coefficient to get the Total Energy Lost to the round over its flight.
5. Subtract the Total Energy Lost from the Starting Energy to get the Impact Energy at the Target.

The math for this can be done as one line if you build the equation for it.
> 0 votes

---
Tags: c#, unity, physics, integration
---


# Question
Title: Box2D No Gravity when moving against wall
I use Box2D in my current project and I have a problem with the gravity..

You can see my problem here: https://www.youtube.com/watch?v=2\_kv9LkKwN4&feature=youtu.be

when i jump normal everything is fine, but when I press against a wall while I jump the body doesn't fall down after I release the move key in the direction of the wall the body falls down.

This is my move code:

```
public void moveByLinear(float x, float y) {
    linearMovement.set(x, y);

    body.setLinearVelocity(linearMovement);
}

```

and

```
moveByLinear(movespeed, getBody().getLinearVelocity().y);

```

movespeed is 8

# Answer
## What's Happening

This is completely accurate physical behaviour, which can be explained using a free-body diagram and a little high school physics1:

The mass of the block is `m` and `g` is the gravitational constant. `Fa` is the applied force. To understand why the block is not moving, we can write out the force balances in the `x` and `y` directions.

## `x`-Momentum

I will assume that the block is not accelerating in this direction, as in the video.

## `y`-Momentum

For the time being I will assume nothing about the acceleration in the `y` direction, so the parameter `ay` remains in the equation.

## Friction Force

The friction force, being a reactive force, is bound by a set of rules, depending on a number of factors. The first rule is that the magnitude of the force is limited by the inequality:

where the greek letter `mu` (I pronounce it like the name of pokemon #151) is the coefficient of friction and `Fn` is the normal force. The right hand side of this equation is an upper-limit on the friction force.

Friction only resists relative motion between the surfaces in contact. When these surfaces are not moving relative to one another, the friction force vector opposes the sum of any other forces acting along the contact surface.

On the other hand, when there *is* relative motion at the surface the friction force opposes the direction of motion.

Given the inequality, there are two possible cases for the motion of the block. In both cases I will assume the block starts from rest.

## Case 1 (current situation)

In this case, the friction force will oppose the only other force acting along the contact surface (the gravity force) so that the acceleration is zero.

## Case 2 (what you want)

In this case the surface responds with the largest possible friction force, `Ff,max`, which is not enough to prevent the block from accelerating downward:

## Recommended Solution

If you want the block to fall, the easiest way to do so is to set the friction of the fixturedefs of the fixtures in contact to 0. This should guarantee that the maximum friction force is 0, because `mu` is zero.

1Note that what I presented is not entirely accurate, but simplified for present understanding. In real life there is a non-uniform distributed load across the contact surface such that the moment of the friction force is balanced by a greater reaction force at the lower part of the contact surface. In box2d this is approximated by splitting the normal force into just two (un-equal) point forces which counteract the torque from the friction force at the two vertices in contact.
> 3 votes

---
Tags: 2d, libgdx, box2d, platformer
---


# Question
Title: Managing cross-platform targets/compatibility with Monogame
I recently started using Monogame for the first time because of it's cross platform compatibilities and heavily active development. The first thing I did is installing the whole framework using their provided installer, but as soon as I wanted to make my first Monogame project, I noticed the following:

Although being cross-platform, there is no real 'Monogame' library. The framework ships with multiple assemblies for several platforms, each with their own dependencies. This is reflected both in the Visual Studio project templates as well as for the nugets they provide.

Now I'm wondering: Is there a straightforward way to just develop with the Monogame framework 'itself' in the first place, and then deciding on platform etc. later by using build targets and conditional compilation? Or do I just have to reference every assembly and it will work out of the box? What's your approach when developing with Monogame for different platforms? Making a .NET project for every target platform?

Their documentation unfortunately doesn't describe the different platform assemblies. They are just there, ready to be used with the infomation that Monogame IS cross-platform compatible.

# Answer
Monogame game is cross-platform compatible, but not in the sense that you just magically click and it will work. In most cases, you are going to need to tweak individual builds, in order to get them to function properly in each environment.

If you consider supporting iOS or Android, you are going to have to look into the xamarin dependencies as well, which are not even part of the Monogame framework at all.

Fortunately, most of the code will just work. It is a matter of getting the builds to compile and work as intended on each environment. There will almost always be at least some minor issues, you will need to compile and try it for each supported environment.
> 1 votes

# Answer
In Monogame, the source code of your game is the *only thing* that is identical for every platform. Of course you would have to change how you handle inputs for every platform (for example windows doesn't have touch) and how you calculate the screen size (mobile doesn't have multi-monitor setups). If you chose to use the `#IF __ANDROID__` and `#IF WINDOWS` keywords in your code and inside your visual studio project, then you will basically have a common source code folder and you will be able to copy paste it between projects to bring them up to date.

Typically, the best way of developing games is to first develop it for windows Desktop and then when you are finished developing your game, spend a couple of minutes making an Android (or any other) project and setting it up. This is because Desktop projects compile so much faster.

There is no reason to worry about multi-platform until the moment you are ready to deploy your game. Note that you will need a 25$ license from Xamarin to compile your game for Android/iOS. That license lasts for 1 month, but you actually only need it just for the few seconds that it takes to compile (if you are not planning on adding content to your game and having to re-compile at least). The free trial version of Xamarin only produces `.apk` (and the equivalent for iOS) which last for 24-hours.

As for the dependencies, here is how my project looks like when I build from Monogame's source code. Windows DirectX (on the left) and Android (on the right). Its pretty straight forward. `Monogame.Framework.Windows.dll` and `SharpDX.dll(s)` for windows. And `Monogame.Framework.Android.dll` and `OpenTK.dll` for Android. You would be able to compile these 2 projects without having anything Monogame related installed. Because I reference the dlls such as `SharpDX.dll` locally (I have placed them in a SharpDX/ folder inside my Monogame.Framework.Windows library-project).
> 3 votes

---
Tags: xna, c#, monogame, .net, visual-studio
---


# Question
Title: Game Controller that is constantly changing
I'm writing a game where the main character is a ghost, and therefor can possess just about everything. The problem is, I'm not sure how to efficiently & effectively handle the changing actions of the player.

My idea was to have the game controller have a pointer to the current Entity, and a map of keys to actions. Every entity that is possess-able will have a component called OnPossess, which will just be a wrapper around a function pointer to some global function for that type of entity. When that entity gets "possessed", the OnPossess function is called and the controllers key-to-action map is updated.

Something like this:

```
class Controller
{
    public:
    Entity* controlled_entity_;

    std::map<char, std::function<void(Entity*)> > action_map_;
    void OnInput(char input);
};

struct Component : public OnPossess
{
    std::function<void(Controller*)> OnPossess;
}

namespace Character_A
{
    void OnPossess(Controller* controller) {
        controller.action_map_ = Character_A_Map;
    }

    std::map<char, std::function<void(Entity*)> > Character_A_Map = { std::make_pair('l',MoveLeft),
                                                                        std::make_pair('r', MoveRight)
                                                                    };

    void MoveLeft(Entity* entity) {
        //Move left stuff
    }

    void MoveRight(Entity* entity) {
        //Move right stuff
    }
}   //End namespace Character_A

```

However, I feel as though this is not the way to go. Having every type of entities available actions sitting out in a global namespace with a function pointer map pointing to those functions just doesn't feel right. I had also thought about having a component that held the map of actions, with the actions just being lambdas, but then I have a bunch of copies of the same map lying around in memory.

Would there be any alternative solutions?

# Answer
> 0 votes
Your ghost will possess different Entities and use their actions. But will you ever change the actions of these Entities while the program runs?

If not, you could create a map for each "class" of entities and have the controller point to the current map to use. Say you have an enemy that's a Spider, so all spiders use the same actions' map. You could use a Factory,

```
class Factory {
public:
    Factory();
    virtual ~Factory();

    virtual Entity* createEntity() = 0;

protected:
    void addAction( char key, std::function< void( Entity* )> action );
    std::map<char, std::function<void(Entity*)> > *getActionMap();

private:
    std::map<char, std::function<void(Entity*)> > _actions;
}

```

And each factory would have its own map of actions.

```
SpiderFactory::SpiderFactory() {
    addAction( 'l', []( Entity *e ) { /*...*/ } ); // Move Left
    addAction( 'r', []( Entity *e ) { /*...*/ } ); // Move Right
}

Entity *SpiderFactory::createEntity() {
    return //Entity with pointer to the action map
}

```

If you don't like to define your functions as lambdas, you could use an anonymous namespace in the SpiderFactory.cpp file, or define them as static methods (I think that would work too)

```
namespace {
    void MoveLeft( Entity *e ) {
        //...
    }
}

```

Well that's quite a big suggestion. I'm hoping it will at least give you an idea for what you want to achieve. This will make it so there'so only 1 map per "class" of entities, if you don't need to change the actions at any point.

---
Tags: c++, input
---


# Question
Title: entity component - get object from entity system without knowing it's ID
Ive been building a game using a Entity Component system, but im having a bit of an issue finding a specific object in my entity system without knowing the Entity's Id.

My game is organized in Layers, with each layer owning its own set of systems, such as Entity System, Render System, Collision etc.

Right now, the game has two layers. The Game layer, which encapsulates all game objects and their data, and a Hud layer, which houses all the UI controls. (Pause, restart etc).

What I want to be able to do is, once a specific thing happens in the game layer, such as an enemy dying, I want to be able to communicate to the Hud layer to tell a button to appear or disable itself etc. The problem is, I have no way of finding that button because I have no Id to query for the button in the Hud layers entity system and the reference to the button gets lost after I create the button when the game starts up.

Ive looked into implementing a message queue type of thing, or using some sort of publish/subscribe pattern, but still the issue is how I can communicate that change to an object who's Id I dont know.

One solution I thought about is giving all UI Elements unique names. That way whenever I need to do a change in the UI, I can query the Hud Layer Entity System for an entity with that name, and get its reference back. But then that entirely ruins an entity having a unique Id, because it now relies on using a name for identification.

Is there any way I can get around this?

# Answer
I think the Observer Pattern may fit here. Instead of sending a message to your button, let your button observe some component.
> 3 votes

# Answer
The game layer probably shouldn't know about the HUD layer. The HUD layer should maybe listen to events from the game layer.

Your example is a bit vague, so let's say there is a button above each enemy that should have the lifetime of the enemy. You could make a button system that checks that the corresponding enemy(a component of the button) is still alive.
> 1 votes

---
Tags: xna, c#, architecture, entity-system, entity
---


# Question
Title: How can I grab the script component of a collided object without knowing what script it is?
CalculateDamage() is an animation event called at a point during the character's animation in my 2D game. The commented out code is before I realized that not all of my pirates will be of class MeleePirateUnit, so I'm trying to do things more generically here. My order of inheritance is like so:

MonoBehaviour \> Unit \> MeleePirateUnit, RangedPirateUnit.

So sometimes, the collidedobj is a MeleePirateUnit, sometimes it's a RangedPirateUnit, etc etc. How do I set pirateUnit to the correct type of the script component of my gameObject? I thought just getting component of type monobehaviour would work since RangedPirateUnit and MeleePirateUnit both derive from monobehaviour but I'm getting an error of

Assets/Scripts/Combat Scene/RangedPirateUnit.cs(72,56): error CS1061: Type `UnityEngine.MonoBehaviour' does not contain a definition for`health' and no extension method `health' of type`UnityEngine.MonoBehaviour' could be found (are you missing a using directive or an assembly reference?)

```
public void CalculateDamage(){
        if (!isDestroyed){
            var pirateUnit = collidedObj.GetComponent<MonoBehaviour>();
            //MeleePirateUnit pirateUnit = collidedObj.GetComponent<MeleePirateUnit>();
            pirateUnit.health = pirateUnit.health - (damage - pirateUnit.defence);
            if (pirateUnit.health<=0){
                Destroy(pirateUnit.gameObject);
                isDestroyed = true;
                didAttack = false;
            }
        }
    }

```

# Answer
Assuming your Unit class has the `health` var, try:

```
Unit pirateUnit = collidedObj.GetComponent<Unit>();

```
> 2 votes

---
Tags: unity
---


# Question
Title: Cannot add key in matinee for static meshes (UE4)
My problem is the following: I was trying to make a sliding door based on a video tutorial, I had the static mesh, which was the door itself, and I added a Matinee for that door, so I went 'Add New Empty Group -\> Add Movement Track', so I had the door with a movement track, but when I tried to add a key, I couldn't. This was the error message: "Nothing to keyframe, or selected object can't be keyframed on this type of track." And I only get this message when I try to add keys in the movement track of a static mesh. When it's a camera, everything is fine. Any idea why this is happening, and how I can solve this? Thanks for your help

# Answer
> 2 votes
To animate a Static Mesh in Matinee, you need to change it to Movable. This can be done by selecting the mesh, and under the Details panel, changing the Mobility option from Static to Movable. Then you are able to keyframe it on a movement track.

Cheers, MAK777

---
Tags: unreal-4, unreal
---


# Question
Title: Implementing The Command Pattern - Undo And Entity References
I am trying to implement a replay/undo system for a turn based strategy game I am currently working on. A sample move could go as follows:

```
1. A players select a pawn and gives it an attack command.
2. The attacked unit dies.
3. The dead unit is removed from the map and the controlling player.
4. The controlling player takes some damage.
5. The attacking unit gains a survivor strength power up for the remainder of the game.

```

The rest of the game plays similarly to a Fire Emblem type game, but the point is a single command like attacking yields multiple effects to various game entities.

Eventually I want to make the game networked, but for now everything is local play.

After doing some research, I came across several resources discussing the command pattern and feel it is the solution to my replay and undo system. I ended up using an interface similar to https://gamedev.stackexchange.com/a/37684/41499 but I am confused on some of the implementation details.

1. Do I make commands to update each component of my game separately (i.e. AtkUnitCmd, RmvUnitFromMapCmd, RmvUnitFromPlayerCmd, InflictPlayerDmgCmd, etc.) or should my AtkUnitCmd handle all updates of entity state internally?
2. How do I handle dead units? I can store a reference to the dead unit, but this would likely need to change when networking is implemented as the object itself would not be transmitted over the network correct?
3. Each command has some animation involved for example when a unit moves an animation needs to play. I may choose to skip the animations while other times leave them on. Do I bake the animations into the commands themselves or should I separate the animation code and call it somehow when the command is played?

Any thoughts?

# Answer
Broadly speaking there are three approaches to rewinding game state (with various flavours in between): **reversing/undoing** actions, **replaying** actions from an earlier, fixed state, or **storing all states** and just picking the right one on demand. The first is more flexible but in the worst case you need to double your work, creating reverse versions of all your commands, plus you need to keep around "dead" state so you can undo into them (reviving dead entities, keeping all their properties around so you can resurrect them, v.s never really removing them, just toggling an "alive" flag). The latter two are much easier, but if you have complex, real-time, long-running states it can be very expensive to replay or store everything.

Judging from your genre though (TBS), I'm inclined to guess that the replaying or even full storage approach will be fine. After all, chess is a turn-based game but entire games can be stored in a few dozen characters, describing the moves.

Given that the replay and store approaches don't require reverse commands, your first two questions are irrelevant for them, which may save you a ton of trouble. Note that you should consider hybrid approaches too, which offer excellent compromises. Braid, IIRC, used a hybrid of stored states every short while plus replaying commands forward, and could store almost an hour of real-time gameplay.

> 1. Do I make commands to update each component of my game separately (i.e. AtkUnitCmd, RmvUnitFromMapCmd, RmvUnitFromPlayerCmd, InflictPlayerDmgCmd, etc.) or should my AtkUnitCmd handle all updates of entity state internally?

Whatever's most convenient, but you'll find that more atomic commands are better simply because of code reuse - surely `AtkUnitCmd` isn't the only command capable of inflicting damage?

> 2. How do I handle dead units? I can store a reference to the dead unit, but this would likely need to change when networking is implemented as the object itself would not be transmitted over the network correct?

It would be easiest to keep around the dead units and flip an `alive` flag to revive them. But you raise an interesting question: how to maintain references over the network? Most network-ready game engines should have this solved for you and offer some kind of "universal entity reference", but if you are rolling your own, my suggestion is to use a portable, container-agnostic unique identifier. Yes, if you assume your clients are running the same binary then you can get away with more specific references like memory offsets or indices, but using unique identifiers will save you trouble down the road, when switching containers or dealing with non-determinism. For most people, all it takes is one hours-long debugging session over invalid references for this investment to pay off.

> 3. Each command has some animation involved for example when a unit moves an animation needs to play. I may choose to skip the animations while other times leave them on. Do I bake the animations into the commands themselves or should I separate the animation code and call it somehow when the command is played?

Separating rendering from game logic is the best thing to do. Consider MVC and related patterns.
> 3 votes

---
Tags: networking, design-patterns, turn-based-strategy
---


# Question
Title: Problematic cameraposition (Eye = (0,0,0), at=(0,-2,0) and up = (0,1,0))?
I am taking a course in computergraphics and we talk a lot about OpenGL and the math you need to do everything OpenGL does "by hand". A Question which was asked in an old exam (I am preparing at the moment) was:

Why is the following Cameraposition considered problematic? eye = (0,0,0), at=(0,-2,0) and up = (0,1,0)

Is it because the eye-at = (0,2,0) and therefore the cross product of up x (eye-at) = (0,0,0) and that means, that no real transformation matrix can be constructed?

I found a post where someone asked a similiar question ( https://gamedev.stackexchange.com/a/45328/50476 ), but the explanation is somehow strange for me, because he says that he wants to calculate the cross product of the eye vector and the up vector. But there is no need for that, if you want to be able to calculate the transformation matrix?

# Answer
Well, that is the mathematical reason why it's problematic, but I'd prefer an analytical explanation.

A `LookAt(pos, look, up)` transform (you call it "cameraposition") is meant to represent a camera located at `pos`, pointing at `look`. However, with just `pos` and `look`, there are an infinite amount of possibilities for your camera, as you rotate it through the axis between `pos` and `look`.

Enter `up`. `up` is meant to disambiguate between the infinite cameras that can be placed at `pos` and pointing at `look`, by setting a vector to point up. In principle you need a vector orthogonal to the axis between `pos` and `look`, but in practice, any vector that you can use to disambiguate, and choose a rotation for your camera is acceptable.

If `pos = (0, 0, 0)`, `look = (0, -2, 0)` and `up = (0, 1, 0)`, You are placing the camera in the origin of the world and looking straight down. Now you need a vector to choose the rotation of that camera. Almost any vector would do, but `(0, 1, 0)` happens to be one of those that doesn't work. The vector is pointing straight up, is parallel to the axis between `pos` and `look`, and cannot be used to choose a rotation for the camera.

Any other vector where `x != 0` or `z != 0` would work though.
> 2 votes

# Answer
> Is it because the eye-at = (0,2,0) and therefore the cross product of up x (eye-at) = (0,0,0) and that means, that no real transformation matrix can be constructed?

Exactly, the actual values in the resulting matrix is just the coordinates of the view direction (`at-eye`), up and right vectors next to each other;

```
result = [[right.x up.x view.x]
          [right.y up.y view.y]
          [right.z up.z view.z]]

```

They have to be orthogonal to each other so that's why the cross products need to happen. Some libraries provide a arbitrary `up` should the user supplied one be invalid.
> 0 votes

---
Tags: mathematics, camera, matrix
---


# Question
Title: Bullet Physic: Stack transformations on body after adding
How can I stack multiple transformations on a body? I mean... Rotate, translate and then rotate again?

If I understood, a transformation on a rigid body can be made like this:

```
    btTransform transform;

    transform.setOrigin( ... );
    transform.setRotation( ... );
    someRigidBody->setWorldTransform(transform);

```

But, this way I am forced to calculate the final rotation ( when is more natural stack the operations. So it can rotate on its own axis, translate and then rotate on a new axis )

Thank you

# Answer
As stated in the comment to your question, btTransform is a matrix. You can do the matrix operations as you see fit, without using the set\* methods.

Once you're satisfied, just use the matrix as you're doing now.
> 0 votes

---
Tags: transformation, bullet-physics, rigid-body-dynamics
---


title: How to define default graphic setting?

text:
# Question
Title: How to define default graphic setting?
Currently I'm developing a PC game using Unity

Usually on PC games we found graphic/video settings due to varying hardware installed and limitation. Just as in the title, how does a game set its default graphic setting? What parameters do I need to take into account for defining my default graphic setting? Or does the game detect installed hardware capability and programatically enable/disable graphic effects?

AFAIK, most of the time when I tried to play some AAA games with minimum system requirement after installation, the game would be laggy because of some effects like ambient occlusion, high quality texture, and stuff are enabled. So I'm sure the default setting is not the lowest/worst graphic setting available.

# Answer
> 2 votes
Here is a way to view this:

Generally, games are sold with a "minimum requirements" and a "recommended requirement". This is decided by you, the developer. This means you should try your game on both of these systems, and the game should run without lagging or bugging or glitching on these setups (with the appropriate settings).

What if you found set of machine specs that would fit in between these 2, which could be what the average joe would have? You could define this machine as your default machine, on which the default settings would make the game run ok.

Now, if you have a lot of money and time, you could try and implement a way to gather the capabilities of the client machine, and match the default settings with that; or interface with the NVidia and ATI APIs to ask them to configure your game the proper way.

---
Tags: graphic-effects, settings
---


# Question
Title: Can't play animation from script in unity
I'm making a 2D sidescrolling game in Unity, and when the player shoots an obstacle, I want the obstacle animation to play and then destroy itself. I got it to destroy itself, but the animation won't play. Any suggestions?

```
    public class obstacleAnim : MonoBehaviour {

    protected Animation obsanim;

    // Use this for initialization
    void Start () {
        obsanim = GetComponent<Animation> ();
    }

    void OnCollisionEnter2D(Collision2D col)
    {
        if (col.gameObject.tag == "circle")
        {
            obsanim.Play ("circobs");
            Destroy (gameObject, 1.0f);
        }
    }
}

```

thank you for any help!

# Answer
I tested your script and it works as expected. The problem is most likely the animation itself. You should enable autoplay from the Animation component and see if your animation works without the script. Also make sure there are no errors in the console. Click the error counter in case you have accidentally hidden them.
> 2 votes

# Answer
Did you try not to Destroy the object at the moment when you play the animation? wait until the animation is finished.

i hope it helps!
> -2 votes

---
Tags: c#, unity, 2d, animation
---


# Question
Title: Unity3D - How to make partially selected EditorGUI.Toggle?
I have nested group of toggles created with EditorGUILayout.ToggleLeft().

I want to change state of the parent toggle to partial check if child toggles have mixed states, like here:

But EditorGUILayout.ToggleLeft value is a boolean value, so how can I do that?

# Answer
Need to use EditorGUI.showMixedValue
> 1 votes

---
Tags: unity
---


title: Unity and Linux

text:
# Question
Title: Unity and Linux
Is it slow to run unity with wine? And are there any plans for unity coming to the Linux platform. Since i now that it can create a build for Linux i wish it was coming for Linux as well.

# Answer
I dealt with this issue and found out that at the moment Unity3d is not coming on Linux. I'm using Ubuntu Trusty Tar, running unity 5.02 with Wine under PlayOnLinux. It works perfectly.

I will quote you some instruction which can be easily found on youtube

> I used simple PlayOnLinux installation! Downloaded the Editor file for Windows from the Unity site(I took 64-bit). Than I went in Play On Linux, went to tools \> Manage Wine versions and installed Wine 1.7.40 for both x64 and x86. Than I pressed install. On bottom left selected the install non-listed program. Than I created new virtual drive called Unity3D, selected the installation bits accorting to the Editor downloaded(I took 64-bit). After that completed all installation and made shortcut for Unity.exe. In here I downloaded quick icon, but now I have set the original icon for it(RC shortcut(.desktop file) and select icon(press on icon and choose one from your computer). It runs for me. After that I selected the Unity icon in Play On Linux, pressed configure, on the top selected section with additional packages, installed the Microsoft Core Fonts so I can see text in Unity editor. I also installed Standard Assets from the Unity site like this:Download the .exe Open Play On Linux Install- Non-Listed program Update existing virtual drive- Unity 3D Select Wine 1.7.40 Select the Standard Assets file Install Done, it is installed, don't make any shortcuts here, leave it as it is, run the Unity and enjoy;)
> 2 votes

---
Tags: unity, linux
---


# Question
Title: How do I make an AI that stays at a distance from the player act correctly when cornered?
I am working on a few different AIs for a tile-based game. I'm trying to figure out one where that tries to keep a certain distance from the player. So if distance becomes small, move away.

The whole game is in a pretty small are so it can't just forever move away. The movement is 4 directional.

How do I make the AI keep going at a distance, and once caught in a corner or close to a side of the room, to ignore the rule and just try to go around the player to the other side of the room?

# Answer
There is an algorithm that adds this in automatically. Instead of merely moving away from the player, each AI will target the closest tile that is "out of range" of the player, I'll use 4 tiles. In the case that the AI is running from the player in an open area, it will choose to just run. In the case of a corridor, the AI "knows" it would be risky to slip by a player and instead chooses to keep progressing the other direction. Finally, in the case of a cornering we are left with the closest tile "out of range" to the player being *behind the player*.

*the safe tiles (white) are behind the player*
> 3 votes

---
Tags: c#, unity, ai, tiles
---


title: Kart Racing Attack AI

text:
# Question
Title: Kart Racing Attack AI
I am developing a kart racing game. In it, the players fight with each other while racing.

There were several ways I tried to add attack AI to the enemies and the player.

1. When the user clicks on the attack function, it throws raycasts in the certain area; if enemy is found then the user gets presented with the weapon and auto attacks occurred.

Later I moved on from this code for two reasons, first very dirty and highly unoptimised and second it's only able to calculate limited distances (not for missile weapons which are long range); a new approach needed to be implemented.

2. After thinking and researching I tried Physics.Overlap; this did solve my optimization problem with short range weapons but still the problem of long range persists.
3. Thinking around more I came up with other ways to implement long range attack, i.e., by spawning one collider just a little behind the player and it will go foreword until a certain distance and if the enemy gets found it will inform the player and the weapon will be spawned and attacked.

Though that third approach looks good so far, the problem arises when the game gets high pace as the collider sometimes do not catch the other players or get too slow to catch the other players and result of that buggy attack look.

So I would like to know: **is there any other way to implement long range attacks considering it is a kart racing game?**

Any help will be appreciated

# Answer
As discussed in the comments above, you may be over-engineering this. If you have ~12 characters who could possibly be attack targets, iterating over all 12 and checking the distance (or squared distance if you want to be extra frugal and avoid a square root) should take a negligible amount of time. In typical situations you'll spend more time waiting to get the character's position vector from memory than it takes to do this check.

Just make sure you have a pre-populated list of racers, rather than calling a slow Find()-type routine every time. These methods search through every object in your scene, and get slower the more content you have. You'll probably want such a list for keeping track of rankings during the race anyway, so this shouldn't add any extra overhead.

Your other checks, like figuring out if the racer is in a direction you can shoot, and whether there are any occluding obstacles in the way, can then be run for only those racers who are within your maximum range.
> 2 votes

---
Tags: c#, unity, ai, logic
---


# Question
Title: C# 2D Enemy Follow Y Axis Only While Rotating to Look At Player (Unity)
I have a 2D game where the player can move up and down on the y axis, I need the enemy to rotate to look at my player (which I have working, but probably isn't the best method) while also moving up and down with the player.

I have both of those things working, but not fully, right now whenever I move up and down, the rotation happening seems to cause the enemy to move backwards more and more with each up and down movement.

I need it to remain stationary on the x and z axis's.

Also, if anyone knows how I could make it so the enemy always wants to be slightly above the player on the y axis, that'd be awesome. Meaning, instead of locking onto the player dead straight, maybe the enemy can be up slightly by perhaps 20%.

This is the code I'm working with:

```
public float moveSpeed = 3.0f;
public Transform target;

private Transform myTransform;

// Use this for initialization
void Start () {
  myTransform = transform;
}

// Update is called once per frame
void Update () {
  Quaternion rotation = Quaternion.LookRotation(
    target.transform.position - transform.position,
    transform.TransformDirection(Vector3.up));
  transform.rotation = new Quaternion(0, 0, rotation.z, rotation.w);

  if (target.transform.position.y < myTransform.position.y)  {

    myTransform.position -= myTransform.up * moveSpeed * Time.deltaTime;
  }
  else if (target.transform.position.y > myTransform.position.y) {

    myTransform.position += myTransform.up * moveSpeed * Time.deltaTime;
  }
}

```

# Answer
```
float YOffset = 0f;

void Update()
{
    myTransform.LookAt(target);
    float targetPosY = target.transform.position.y + YOffset;
    if(myTransform.position.y != targetPosY)
    {
        float MoveAmount = moveSpeed * Time.delta;
        if(Mathf.Abs(myTransform.position.y - targetPosY) < MoveAmount)
            myTransform.position = Vector3.up * MoveAmount;
        else
        {
            if (targetPosY < myTransform.position.y)
            {
                myTransform.position -= Vector3.up * MoveAmount;
            }
            else if (targetPosY > myTransform.position.y)
            {
                myTransform.position += Vector3.up * MoveAmount;
            }
        }
    }

```

}

1.) Consider using Transform.LookAt to simplify the rotation.

2.) In your movement code, myTransform.Up represents the Up vector of the transform in local spcae, so if your model is tipped off center then Up will no longer point Up in world space. Use Vector3.Up as MistaGiggles suggests.

3.) You can make your enemy hover above the player by adding an Offset amount for the Y axis like the sample code above.

Additional way to rotate your enemy based on your comment:

1.) Get the normalized vector from enemy to player and assign it to Transform.Right, which would be your X axis. Unity takes care of updating the Transform's rotation internally when you set Up/Right/Forward manually.

```
    Vector2 lookDir = (target.transform.position - myTransform.position);
    myTransform.right = lookDir;
    if ((target.transform.position.y + YOffset) < myTransform.position.y)
    {
        float MovementAmount = moveSpeed * Time.deltaTime;
        if((myTransform.position.y - MovementAmount) < (target.transform.position.y + YOffset))
        {
            myTransform.position = new Vector3(myTransform.position.x,target.transform.position.y + YOffset, myTransform.position.z);
        }
        else
            myTransform.position -= Vector3.up * moveSpeed * Time.deltaTime;
    }
    else if ((target.transform.position.y + YOffset) > myTransform.position.y)
    {
        float MovementAmount = moveSpeed * Time.deltaTime;
        if((myTransform.position.y + MovementAmount) > (target.transform.position.y + YOffset))
        {
            myTransform.position = new Vector3(myTransform.position.x,target.transform.position.y + YOffset, myTransform.position.z);
        }
        else
            myTransform.position += Vector3.up * moveSpeed * Time.deltaTime;
    }

```
> 2 votes

# Answer
First of all, why have a private member "myTransform" and then mix usage of "transform" and "myTransform"? It is more readable to just use "transform".

I have a feeling that the problem arises from using "myTransform.up" vs "Vector3.up" combined with your rotation code. I think the combination of the quaternion calculations and the local up vector is resulting in an accumulated offset in the axis you want to remain unchanged.

Have a look at this for calculating the rotation (you may need to offset the result).

Alternatively make use of Euler angles, as you are only working with one axis of rotation (where you have no benefit of using quaternions over euler angles).

As for moving backwards, if you are working in the global y-axis, use "Vector3.up" (which is global up) vs "myTransform.up" which is the up direction of your object after rotation is taken into account (and so will change direction depending on where it is looking).
> 0 votes

---
Tags: c#, unity, 2d
---


# Question
Title: Using Smaller Textures in Unity on Older/Smaller devices
In Unity, when you have MipMapping selected, will this cause the full size texture to always be brought into memory? I have a game which runs on high end mobile devices with ultra-high resolution textures, but I have complaints of it crashing on smaller/old devices. Will this fix it, or is there a more fitting way to address this problem?

# Answer
> 1 votes
If you're just looking to make your game compatible with some older devices consider using Quality Settings . Go to Edit-\>Project Settings-\>Quality Settings to set up each level and instruct Unity to use full size textures/half size etc.... Then add a Menu Scene that will load first allowing the User to select the settings he wants for his devices.

# Answer
> 0 votes
Only enabling mipmaps will not solve your problem. Mipmaps are generated by the hardware at runtime in order to avoid using large scale textures that are on objects that are far away from the camera and do not need that level of detail at that point. It is advisable to create smaller textures.

# Answer
> 0 votes
When utilising standard texturing with mipmapping you not only are loading the entire texture in memory but also an extra 1/3 (one third) of the total texture memory for the mipmaps. Read the How It Works section in the wikipedia page.

I don't think Unity releases info about the low level implementation of their texturing system, so we should assume they use standard texturing and the above holds true.

That said, it is common practice to have multi-resolution textures for different devices. This not only reduces RAM usage but also disk storage, which is also very limited on older hardware.

# Answer
> 0 votes
Mipmaps won't help you. Instead, you need to load different assets based on something like iPhoneGeneration. And even then, you would need to make sure your assets are in Resources and not actually part of the scene, because everything in a scene is loaded immediately when that scene loads. In other words, swapping a texture in a scene wouldn't prevent that texture from loading in the first place.

---
Tags: unity, textures, mobile
---


# Question
Title: How can I keep the clicked point under the mouse when rotating? (GLM)
I have a spherical mesh of radius 1, centered at (0,0,0) in world coordinates. I want to rotate the sphere so that the clicked point remains under the mouse at all times. However, I cannot find an algorithm that does this. The clicked point always drifts away from the mouse. My current algorithm does the following:

Cast a ray to a sphere of radius 1. Find intersection point in world coordinates (Pa).

After the mouse is moved, cast another ray and find a new intersection point. (Pb) since both those 3D points are on a sphere of radius one, centered at the origin, they should have length = 1 but just in case I normalize them both.

Find the rotation axis by doing Pa x Pb. Normalize the resulting axis

```
axis = glm::cross(Pa,Pb);
axis = glm::normalize(axis);

```

Find the angle by doing arccosine on the dot product

```
float angle = glm::acos(glm::dot(Pa,Pb));

```

Build a rotation matrix from the axis and angle

```
mat4 rotation = glm::rotate(glm::degrees(angle),axis); <-- This was the mistake glm::degrees is not needed

```

Multiply the existing model matrix by that calculated matrix:

```
modelMatrix = rotation*modelMatrix;

```

The rotations are correct but the clicked point does not stay under the mouse (I am checking by drawing a black square point on the sphere texture when the drag starts). If I click and drag to the right, the initially clicked point drifts to the left (lags).

# Answer
> 1 votes
I found the culprit.

glm::degrees(angle)

I had copy pasted that line from some guy off the internet who was for some reason converting the angle to degrees. There is absolutely no need for this conversion.

According to a user on reddit: One warning about this method, your model matrix will degrade over time using this kind of technique (repeatedly multiplying with a new matrix), causing the rendered model to scale or skew. You may want to develop a function to "fix" the matrix, using a technique like converting to another format (quaternion or Euler angles) and then back to a matrix, or more directly by extracting matrix basis vectors, orthonormalizing them, and sticking the values back into the matrix.

---
Tags: rotation, matrix, mouse, sphere
---


title: Libgdx Statebased game not working

text:
# Question
Title: Libgdx Statebased game not working
I'm using Libgdx and I wanted to change the default application to a Game with multiple screens. I get an odd nullpointer that has to do with the engine. I'll show you my little setup code. Here I have the desktoplauncher:

```
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.x = 2000;
        config.width = 640;
        config.height = 480;

        new Core().create();
    }
}

```

The core extending Game

```
public class Core extends Game {

    Play game;

    @Override
    public void create() {
        game = new Play(this);

        setScreen(game);
    }

}

```

and the Play class implementing screen:

```
public class Play implements Screen{

    Core game;

    public Play(Core game) {
        this.game = game;
    }

    public void show() {

    }

    public void render(float delta) {
        System.out.println("efsse");
    }

    public void resize(int width, int height) {

    }

    public void pause() {

    }

    public void resume() {

    }

    public void hide() {

    }

    public void dispose() {

    }

}

```

It's been a bit since I've used libgdx, but tutorials showed that this is the correct format. Yet I get the exception: Exception in thread "main" java.lang.NullPointerException at com.badlogic.gdx.Game.setScreen(Game.java:62) at com.test.game.Core.create(Core.java:15) at com.test.game.desktop.DesktopLauncher.main(DesktopLauncher.java:13)

**UPDATE** looking at old code, the desktop launcher setup goes as following:

```
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();

        new LwjglApplication(new Core(), config);

        config.x = 2000;
        config.width = 640;
        config.height = 480;
    }
}

```

# Answer
In your `DesktopLauncher` it's not enough to just new up a `LwjglApplicationConfiguration`, you have to pass that along with your `Game` instance to the constructor of a `LwjglApplication`. Try changing your `main` method to this;

```
public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.x = 2000;
        config.width = 640;
        config.height = 480;

        new LwjglApplication(new Core(), config);
    }
}

```

The `LwjglApplication` is responsible to creating a lot of things that **libGDX** depends on, so that needs to be initialized.
> 2 votes

---
Tags: java, libgdx
---


title: Pathfinding with inertia

text:
# Question
Title: Pathfinding with inertia
I'm currently working for pathfinding for a game where units are moving, but they have inertia. Most typical pathfinding algorithms (A\*, Djikastra, etc.) are simply designed to minimize the length of the path.

However, these techniques do not apply, as far as I know, to instances where the unit has inertia. If the unit has inertia, then there is a significant difference in the cost to leave a tile in a particular direction based on the direction you want to go.

For example, the cost of leaving a tile proceeding North is significantly higher if you entered the tile from the East than if you entered from the South. (In the former example, you would have to slow down to halt you East-West velocity, while in the latter, you could go straight through.)

The fact that the system has inertia means that in order to make a turn, you may have to slow down well in advance of making the turn. My best thought to date is that you calculate the additional time it would take to slow down, and then add it to the heuristic cost of moving. However, this would seem to imply that you could never add a tile to the closed list, as entering from another direction could fundamentally change the cost of moving.

In addition, the concept of using a grid is an abstraction anyway, because both position and velocity are floating-point concepts. Is there some algorithm that could handle pathfinding on an open plane with inertia better than A\*, or what modifications could I make to a pre-existing algorithm to make it suitable to this kind of motion?

# Answer
> 2 votes
The only new constraint that inertia lays onto path-finding is continuity, which means no sudden breaks in velocity. Start by generating an A\* path, but with a big twist. The reason A\* by itself is not appropriate is because it violates continuity, so lets make a new one.

A\* chooses the best path as the shortest path, but with inertia the shortest path is no longer the fastest path. The fastest path is going to be the one that gives **the shortest path without breaking continuity**.

Normal A\* allows each iteration to "jump" to an adjacent tile starting with the lowest cost. Instead of allowing only adjacent tiles, we will allow any tile that is within our range of motion for the next turn. This means the only tiles we can choose next are the tiles that would require us to change momentum an amount the object physically can.

TLDR: We shift the choices of A\* by our momentum and add *that* to our momentum.

# Answer
> 2 votes
Pathfinding algorithms like A\* can deal with inertia (or any other dimension you can throw at it) just fine. The key is to treat them as an additional dimension, and create a higher-dimensional search graph to search in.

To keep things simple, let's suppose we have only two speeds: **slow** and **fast**, and this path:

```
A --(sharp turn)-- B ----------- C --(ravine)-- D

```

To execute the sharp turn `AB`, we need to be slow; to jump the ravine, we need to be fast, and we can only change speeds on paths. Here's the resulting search graph:

```
(fast): A       B ----> C -----> D
                  \   ^
                    X
                  /   v
(slow): A ----> B ----> C        D

```

So you can see, the only path from A to D in this case is by `A` to `B` slow, `B` to `C` speeding up to fast, and `C` to `D` fast.

Path cost is also easy: it depends on the speed. So if we arbitrarily decide that the cost of fast-fast is 1, fast-slow or slow-fast as 2, and slow-slow as 3, the cost of `A->D` is 3 + 2 + 1 = 6.

The problem as you may have guessed, is that A\* operates on **graphs**, and not on continuous ranges. That is, you *need* to come up with discrete speeds like I did with slow/fast, and each additional speed level will *multiply* the size of your search graph. The more physically demanding your game, the more speed levels you'll need, and the more costly pathfinding will be, and at worst it will be too expensive for games. If it is, then you have some other options:

* Make your AI cheat so it can fudge some paths, for example being able to make a turn even if it's going slightly too fast. This means you can get away with less speed levels in your A\* search graph
* Similar to racing games, pre-calculate ideal path curves, and your AI simply navigates to the best node on that curve and continues along it

---
Tags: algorithm, physics, path-finding, motion
---


# Question
Title: How can I stop Substance's runtime texture caching?
Procedural textures with the Substance Engine seem to update very quickly if you turn off caching, modify one exposed variable at a time, modify it frequently, and even then only after you've attempted to modify it 2 or 3 times.

However, I want basically the opposite. For example, units have a "blood" variable that generates blood differently on them as they take damage, as well as a "battle wear" variable that generates scratches and dents, but doesn't revert when they heal.

So to force a variable not to cache, I have to set it to some dummy value, then back to normal, then call `RebuildTexturesImmediately`.

How can I tell Substance not to cache a variable at runtime, so I can change it once and have the texture regenerate quickly?

# Answer
> 1 votes
Try using CacheProceduralProperty to specify at runtime what properties you want to cache and which ones you don't.

---
Tags: unity, textures, performance, procedural-generation, substance-engine
---


# Question
Title: UPS and FPS - What should I limit and why?
I'm currently writing a game using C++ and SDL2 and there's one thing that I'm wondering about - does it make sense to limit my frames per second (FPS) and/or my updates per second (UPS)?

I get the idea that if you limit the UPS, you essentially control the speed of the game - if the player moves 1px per update and you always update it 30 times per second, he'll move at a speed of 30px/s and you'll probably also relieve the CPU since the amount of calculations per second decreases. If you limit the FPS, the amount of drawcalls per second decreases, therefore you relieve your GPU. I hope I understood all of that correctly, if not, feel free to correct me.

My question is - what am I supposed to limit in my game? FPS? UPS? Both? Neither? Is there another, better approach to this? How is this done in most games and why?

Answers are greatly appreciated!

# Answer
Yes, it does make sense.

As you said it will make less load on the system, which is good for thermals, and other applications.

However.... Your games logic should NOT depend on the updates per second. Therefore I recommebd you to take a look at deltatime, which will make your game independent of the updates per second.

I recommend you to take a look at this question. It explains pretty well how to calculate and use it. How to get and use delta time

Hope it helped!
> 10 votes

# Answer
The best answer is: **It depends**.

## You don't have to limit neither one

**Updates**: If your updates are not bound to an upper limit, then game logic should be dependent on a *delta time* amount, to avoid running the game faster or slower depending on the machine where it is run. This is a very common approach used by many games, but it is not the only one.

**Rendering**: If rendering is not bound to an upper limit, the framebuffer might be presented in an incomplete or erroneous state, causing tearing artifacts. This is why many games employ *Vertical Synchronization* (v-sync)

## You might limit both

**Updates**: Some games make use of *fixed timesteps* for some or all of its gameplay systems. This approach works just as you've described. The number of Updates Per Second is limited to an upper bound to ensure things don't move too fast on a top notch machine. This removes the need for delta timing. Some applications are better with fixed timesteps, some with delta timing. Choosing which approach will depend entirely on what exactly you are trying to achieve. The online book GameProgrammingPatterns has a chapter dedicated to game loops that touches on both architectures.

**Rendering**: Frames Per Second should be set to an upper limit to avoid the afore mentioned tearing problem, however, your application **should not** attempt to do that manually with some CPU lock. Instead, enable v-sync and let the underlaying hardware synchronize with the refresh rate of the monitor. By doing that, your game will be forward compatible with future monitors which might operate on a much higher frequency then the currently commonplace 60Hz. It is also worth noting that many gamers, in particular those into benchmarking, still prefer to run without v-sync to allow the highest possible frame rate. So it is sensible to allow enabling or disabling the feature during runtime.

## What you shouldn't limit

If your game uses a polling-based approach to user input, e.g.: calls a `getInput()` of sorts to update controller states during the update step, then this is better if not limited. Or if limited, then set to a very high upper bound. The more often you query user input and act on it, the more responsive and smooth the game will "feel". The so called 60Hz games that we hear about nowadays are not updating AI and all world states at that rate, some are not even rendering that fast, but they query controller input at least 60 times per second and update the player avatar accordingly. Granted that this is only really relevant to fast paced action games.
> 6 votes

# Answer
There are two posts you may want to take a look at:

Fix your Timestep

Interpolated physics rendering

I find the discussions on the posts really invaluable, but in my opinion it makes the most sense when there is an important amount of physics simulation in the game. In summary, the idea is that simulation should have a fixed time step (otherwise the physics could explode at some point where the delta is too big), whereas rendering should be given freedom to run at the maximum rate possible. In order to synchronize both (the simulation and the rendering), the render state is interpolated by a factor that depends on how far the simulation is from the following update (remember that simulation is fixed).

Hope it helps.
> 1 votes

---
Tags: game-loop, logic, sdl2
---


# Question
Title: LIBGdx - Kryonet with an InetSocketAdresse
I'm trying to implement Kryonet in my game and i'm facing some trouble. Using the source from the code i develop my server like that :

```
try {
        this.server = new Server();
        ServerManager.registerClasses(this.server);
        this.server.addListener(new Listener() {

            public void received(Connection connection, Object object) {
                if(object instanceof PositionMessage) {
                    System.out.println("[SERVER] Message from ID : " + connection.getID() + " - " + ((PositionMessage)object).message);
                }
            }

        });
    this.server.bind(port);
    this.server.start();
    System.out.println("Server started on port " + port);
    ServerManager.isLaunched = true;
} catch (IOException e) {
    e.printStackTrace();
    ServerManager.isLaunched = false;
}

```

And that's how my client is coded :

```
this.client = new Client();
ServerManager.registerClasses(this.client);
client.start();
client.addListener(new Listener() {

    public void connected (Connection connection) {
        System.out.println("Send");
        PositionMessage pm = new PositionMessage();
        pm.message = "Hi, i'm connected";
        client.sendTCP(pm);
    }

    public void received (Connection connection, Object object) {

    }
});
new Thread("Connect") {
    public void run () {
        try {
            System.out.println("Connecting on " + ipServer + " au port " + port);
            client.connect(5000, ipServer, port);
            System.out.println("I am connected");
            isConnected = true;
        } catch (IOException ex) {
            ex.printStackTrace();
            System.out.println("The server doesn't exist");
            isConnected = false;
        }
    }
}.start();

```

It works perfectly, the client can connect and the message is send and receive by the server. But with that code, the problem is that the server is only local and can't be access from the outside (or it is and i'm just bad at it...) so to bypass that i'm not using only a port to create the server, but a InetSocketAdress passing my ip adress. So i replaced the bind in the server code by this :

```
this.server.bind(socketAdresse, socketAdresse);

```

With socketAdresse =

```
ServerManager.socketAdresse = new InetSocketAddress(ipServer, port);

```

The server is created (at least it seems created, i can't find a way to find if the server is launched, but i have no exception catched. Now for example, if i create a server with my local ip (the same way i was doing without the InetSocketAddress) and the port 2302, the client never connect to the server and i have literally no message. It just tell me that on the client side that the connection was succesfull but the server never receive any information, + when i do a check on the client if it connected, it says "false".

So my problem is that when i don't use a InetSocketAdress, the client can connect fine on my local ip, but i want to be able to host on the web so i use an inetsocketadress but the problem is that a client can't connect to my server and it doesn't give me an error.

Thanks for the help !

# Answer
You don't have to provide the host address in your server code on Kryonet. Your computer network has its own IP address which is used by Kryonet when you start the server.

So on client code, when you start the client you put in the IP address (127.0.0.1) in case where both client and server are on same network.

In the case when server and client are on different networks, you need to get the external IP of the computer(network) on which your game server is hosted. Lets say for example your server is hosted on computer(network) with IP 'xxx.x.x.x'. In your client code you will have `client.connect(xxx.x.x.x, PORT_SERVER_LISTENING_ON)`.

All you have to do on server is `server.bind(TIMEOUT, TCP_PORT, UDP_PORT_IF_YOU_USING)`.

Also if you want to host the server on your computer, you need to do port forwarding.
> 1 votes

# Answer
I am not 100% sure that this will solve your problem but it seems that you forgot to register the `PositionMessage` class. Be sure to register it in the same order on the client and the server and also, do not register the server and client classes.
> 1 votes

---
Tags: java, libgdx, networking
---


title: Unity5 imported models show no texture

text:
# Question
Title: Unity5 imported models show no texture
I've got a problem with Unity materials. I'm a beginner- so I used Wings3d for creating 3d models.

But there's a little Problem. Both objects on the picture below have the same material(a Standart Material with 0 smoothness, 0 metallic and only a only an Albedo picture)-but obviously the right one has no texture( and that's the problem).

First I ignored it and used a custom shader ("Custom/WorldCoord Diffuse) which I found in a package for fixing it. Poorly this shader doesn't support Normal or Height maps and strangely slows down my game extremly (my scene with only Standart shaders ~80 FPS | my scene with this strange shader~7 FPS).

I don't know how to write my own shaders and I don't know blender, and I don't have much time to fix this.

# Answer
> 3 votes
It looks like the Wings3D object doesn't have texture coordinates. There is a texture applied, it's just not applied correctly. Without texture coordinates, it'll just stretch a single pixel of the texture over the entire object.

---
Tags: textures, models, materials, unity
---


# Question
Title: How to i create a Particle system in unity5?
how to i create Particle system in unity 5 like a fire, smoke and other types of particles by using unity 5.

# Answer
Take a look at the built in Unity particle system. Additionally, there's a number of Unity beginner tutorials (which I think would be great for you), including one for the particle system.

You can get started very quickly by creating a particle emitter via the Unity Editor topbar menu:

> GameObject -\> Create Other -\> Particle system

This will place a particle generator in your scene. From there you can use the Inspector to change the values of the `Particle System` script attached to the object you just created. Tweak the values and see what the results are live in the editor.

Creating different effects is really up to you. Only you know what you want them to look like. You just need to learn the options available to you and create the effects you want from there.
> 3 votes

---
Tags: unity, particles
---


title: Smooth rotation Unity3d

text:
# Question
Title: Smooth rotation Unity3d
I have an animation and I modified some rotations of some bones in the animation at a certain frame. What I want to do is how to make the animation in the next couple of frames interpolate smoothly so that the changes I made looks smooth? Like for example, if I have an animation of a game object, and in frame number 100 it rotated 90 degree in the x-direction. So now frame 100 has a modified rotation angle of the object, but frame 101 has the original animation. I want to smooth the rotation so that the transition of the obect from the modified frame back to the original animation looks smooth.

# Answer
> 1 votes
I did not understand completely what you wanted to do but I can give you some tips on frame perfect animation.

If you use a controller (in the script sense) for your animation, you can manually select what each frame does. ie;

```
int frame = 0;
void Update(){ //runs once per frame
    frame++;
    if(frame % 2 == 0)
        //even frames code
    else
        //odd frame code

}

```

Other usefull tips you can use are

```
ticks += Time.deltaTime; //says how much time has elapsed since the last frame
Math.lerp(a,b,ticks);    //you can use this to smooth out animations in the update

```

best of luck

---
Tags: unity, unityscript
---


title: Java: Problems with Tile Collisions

text:
# Question
Title: Java: Problems with Tile Collisions
I have created a tiled map using a BufferedImage (img) from a PNG. From that, I would like to detect the player's (peter) collisions with individual tiles on the map. However, my code will not run and the console gives me: *Exception in thread "main" java.lang.StackOverflowError*

I am doing this accross to seperate classes: Peter and Map

In my **Peter** class, I have created collision boxes (left, right, up, down) for my player. I would like to make it so that collision of different sides of the player will be able to be detected.

```
public Rectangle getBoundsL() {
    return new Rectangle(x, y+4, 4, HEIGHT-8);
}
public Rectangle getBoundsR() {
    return new Rectangle(x+WIDTH-4, y+4, 4, HEIGHT-8);
}
public Rectangle getBoundsU(){
    return new Rectangle(x+4, y, WIDTH-8, 4);
}
public Rectangle getBoundsD(){
    return new Rectangle(x+4, y+HEIGHT-4, WIDTH-8, 4);
}

```

In my my **Map** class, I go through a nested for loop that examines the colour of the BufferedImage's pixels in order to draw the Rectangles that represents the boundaries of my walls.

My *checkCollision* methods are supposed to return a boolean value when one of the player's collisions boxes intersect with the boxes of any of the wall tiles (in this case, the player's left box).

```
Peter peter = new Peter();

public boolean checkCollisionL(){
    for(int y = 0; y < mapHeight; y++){
        for(int x = 0; x < mapWidth; x++){
            if((img.getRGB(x,y) == 0xff000000) &&
            peter.getBoundsL().intersects(new Rectangle(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE))){
                return true;
            }
        }
    }
    return false;
}

```

However my game is unable to run, and the console instead gives me the following error:

```
    Exception in thread "main" java.lang.StackOverflowError
    at peterslostworld.Peter.<init>(Peter.java:12)
    at peterslostworld.Map.<init>(Map.java:25)
    at peterslostworld.Peter.<init>(Peter.java:12)
    at peterslostworld.Map.<init>(Map.java:25)
    at peterslostworld.Peter.<init>(Peter.java:12)
    at peterslostworld.Map.<init>(Map.java:25)
etc, etc....

```

It would appear (to me at least) that the it takes issue with referencing the **Peter** class in the **Map** class. However, I do not know how to fix this issue.

EDIT: As requested, here are the (incomplete) classes involved in the game:

```
 package peterslostworld;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class PetersLostWorld extends JPanel {

    Peter pete = new Peter(this);
    Map map = new Map();

    public PetersLostWorld() {
        addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyReleased(KeyEvent e) {
                pete.keyReleased(e);
            }

            @Override
            public void keyPressed(KeyEvent e) {
                pete.keyPressed(e);
            }
        });
        setFocusable(true);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        map.paint(g2);
        pete.paint(g2);

    }

    public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame("Peter's Lost World");
        PetersLostWorld game = new PetersLostWorld();
        frame.add(game);
        frame.setSize(800, 600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        while (true) {
            game.repaint();
            Thread.sleep(10);
        }
    }
}

package peterslostworld;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;

public class Peter {
    private static final int WIDTH = 32;
    private static final int HEIGHT = 32;

    Map map = new Map();

    boolean right = false;
    boolean left = false;
    boolean up = false;
    boolean down = false;

    int x = 40;
    int y = 40;
    int pSpeed = 5;

    private PetersLostWorld game;

    public Peter(PetersLostWorld game) {
        this.game = game;
    }

    Peter() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_A){
            left = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_D){
            right = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_W){
            up = true;
        }
        if (e.getKeyCode() == KeyEvent.VK_S){
            down = true;
        }
    }

    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_A){
            left = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_D){
            right = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_W){
            up = false;
        }
        if (e.getKeyCode() == KeyEvent.VK_S){
            down = false;
        }
    }

    public void paint(Graphics2D g2) {

        g2.setColor(Color.red);

        g2.fillRect(x, y, WIDTH, HEIGHT);
        if(left){
            x-=pSpeed;
        }
        if(right){
            x+=pSpeed;
        }
        if(up){
            y-=pSpeed;
        }
        if(down){
            y+=pSpeed;
        }

        g2.setColor(Color.blue);
        g2.draw(getBoundsL());
        g2.draw(getBoundsR());
        g2.draw(getBoundsU());
        g2.draw(getBoundsD());
    }

    public Rectangle getBoundsL() {
        return new Rectangle(x, y+4, 4, HEIGHT-8);
    }
    public Rectangle getBoundsR() {
        return new Rectangle(x+WIDTH-4, y+4, 4, HEIGHT-8);
    }
    public Rectangle getBoundsU(){
        return new Rectangle(x+4, y, WIDTH-8, 4);
    }
    public Rectangle getBoundsD(){
        return new Rectangle(x+4, y+HEIGHT-4, WIDTH-8, 4);
    }
}

package peterslostworld;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Map {
    String path = "C:\\Users\\Owner\\Documents\\Eclispe\\Game03\\src\\game03\\maze.png";
    public int mapHeight = 0;
    public int mapWidth = 0;
    BufferedImage img;

    public Rectangle[] mapTiles = new Rectangle[mapWidth*mapHeight];

    public boolean collideLeft = false;
    public boolean collideRight = false;
    public boolean collideUp = false;
    public boolean collideDown = false;

    public static int TILESIZE = 32;

    Peter peter = new Peter();

    public Map(){
        try{
            BufferedImage image = ImageIO.read(new File(path));
            img = image;
            mapHeight = image.getHeight();
            mapWidth = image.getWidth();

        }
        catch (IOException e){
        }
    }

    public boolean checkCollisionL(){
        for(int y = 0; y < mapHeight; y++){
            for(int x = 0; x < mapWidth; x++){
                if((img.getRGB(x,y) == 0xff000000) &&
                peter.getBoundsL().intersects(new Rectangle(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE))){
                    return true;
                }
            }
        }
        return false;
    }
    public boolean checkCollisionR(){
        for(int y = 0; y < mapHeight; y++){
            for(int x = 0; x < mapWidth; x++){
                if((img.getRGB(x,y) == 0xff000000) &&
                peter.getBoundsR().intersects(new Rectangle(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE))){
                    return true;
                }
            }
        }
        return false;
    }
    public boolean checkCollisionU(){
        for(int y = 0; y < mapHeight; y++){
            for(int x = 0; x < mapWidth; x++){
                if((img.getRGB(x,y) == 0xff000000) &&
                peter.getBoundsU().intersects(new Rectangle(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE))){
                    return true;
                }
            }
        }
        return false;
    }
    public boolean checkCollisionD(){
        for(int y = 0; y < mapHeight; y++){
            for(int x = 0; x < mapWidth; x++){
                if((img.getRGB(x,y) == 0xff000000) &&
                peter.getBoundsD().intersects(new Rectangle(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE))){
                    return true;
                }
            }
        }
        return false;
    }

    public void paint(Graphics2D g2){
        for(int y = 0; y < mapHeight; y++){
            for(int x = 0; x < mapWidth; x++){
                if(img.getRGB(x,y) == 0xff000000){
                    g2.fillRect(x*TILESIZE, y*TILESIZE, TILESIZE, TILESIZE);
                }
            }
        }
    }
}

```

# Answer
> 1 votes
In your Map class, you are instanciating a Peter object on creation on line 25:

```
Peter peter = new Peter();

```

In your Peter class, you are instanciating a Map object on creation on line 12:

```
Map map = new Map();

```

So, when you create on of the two objects, it will start creating an infinite amount of maps and Peters (probably not what you want).

This is a basic problem of cross-reference that can be solved by deleting one of the two lines specified at the top of my answer.

**EDIT**

Having looked your code more carefully, I can see that you do not need to instanciate a Map object in your Peter class nor do you need a handle to any map object, so you can delete this line at line 12:

```
Map map = new Map();

```

---
Tags: java, collision-detection, game-design, tiles
---


title: Unknown length of primitive array

text:
# Question
Title: Unknown length of primitive array
For my Voxel like game I need to generate terrain meshes from an array of ids. Because of that I have no idea how big the final vertex array will be.

Currently I'm doing like this: generate mesh and save to arrayList, then in a few lines of code I convert the arrayList to a primitive array. This is working fine, but it's just really SLOW.

So now my question is is there a way I can use a primitive array, without knowing it's final size? If not is there a fast way I can take an array with a lot of empty elements, and then shrink it?

*Edit:* Heres how I convert it:

```
List <Float> vertices = new ArrayList <Float> ();

//Generating mesh

float[] doneVertices = new float[vertices.size()];
for(int i = 0; i < vertices.size(); i++) doneVertices[i] = vertices.get(i);

```

# Answer
> 2 votes
To get decent performance, you should define your own private class `FloatArray` which contains a `float[] values;` (lowercase *f* !) and an integer `count` which keeps track of the "logical" size. When there are no elements, set `values` to a new array of 16 items and `count` to zero.

Then when you need to add elements, check whether `count` is greater than or equal to the current length of the array. If so, create a new array which is twice as big, copy all the existing elements to it, and replace `values` with a reference to the new array. Once `values.length` is greater than `count`, store the array element and increment `count`.

Note that `values` may end up being up to twice as big as the largest number of elements that are actually needed, but that's generally not likely to be a problem. Further, on average no array element is going to end up getting copied more than twice. If one were to grow the array by a smaller amount each time, one would need to create more arrays and copy elements more times; the cost of doing that could likely exceed the cost of allocating a larger array than needed.

In any case, avoid using type `Float` (uppercase *F*) whenever possible, since converting a `float` to a `Float` is rather expensive. Using your own private type that stores values of `float` in a `float[]` will be *much* more efficient.

# Answer
> 1 votes
You cannot use a standard array without knowing its size. You must use an ArrayList. But that is not where your lag is coming from. You have an issue with your algorithm. If you share your code, we can help you beat it into submission.

I suggest just starting and finishing with an ArrayList. If you are creating a new ArrayList and adding the objects one at a time every frame, that could explain it.

UPDATE:

Change your code to:

```
List <Float> vertices = new ArrayList <Float> ();

//Generating mesh

Float[] doneVertices = vertices.toArray(new Float[0]); // Notice the capitalized Float.

```

But I doubt this is going to fix everything. You should check for other areas you can improve performance as well.

---
Tags: java, lwjgl
---


# Question
Title: Error drawing two VAO, each one using different shader programs (vertex + fragment shader) in OpenGL Core 4.3 / GLSL 430
I am trying to draw over a GL\_TRIANGLE\_FAN one texture to render video frames, using shaderProgram1, and render above it some points (GL\_POINTS) using shaderProgram2.

By this way: (OpenGL Core 4.3)

```
void GLViewer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(handleShaderProg1);

    glUniform...(); //Set Uniforms for shaderProg1... <-- FIXED

    glBindTexture(GL_TEXTURE_2D, textureHandle); //Bind texture
    glBindVertexArray(vaoHandle1); //Bind VAO
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    glBindVertexArray(0); //Unbind VAO
    glBindTexture(GL_TEXTURE_2D, 0); //Unbind texture (used in shaderProg1)

    glUseProgram(handleShaderProg2);

    glUniform...(); //Set Uniforms for shaderProg2... <-- FIXED

    glBindVertexArray(vaoHandle2);  //Bind VAO
    glDrawArrays(GL_POINTS, 0, 25);
    glBindVertexArray(0);  //Unbind VAO
}

```

But only the points defined in vbo2 are rendered over the black glClearColor. Without using the shaderProgram2, all are rendered, texture and the points above it.

Is mandatory to use a FBO and two pass deferred rendering? If not, what could be the problem?

---

**SOLVED** : After an OpenGL debugging, I discovered a newbie bug...

In my case, I needed to pass the uniforms to the shader every time the current shader program will be changed to another shader program. I was thinking that the uniform variables will keep alive after another call to glUseProgram. I was wrong...

# Answer
After you are done with the first VAO call `glUseProgram(0);`. Same applies for the second VAO.

```
void GLViewer::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(handleShaderProg1);
    glBindTexture(GL_TEXTURE_2D, textureHandle); //Bind texture
    glBindVertexArray(vaoHandle1); //Bind VAO
    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
    glBindVertexArray(0); //Unbind VAO
    glBindTexture(GL_TEXTURE_2D, 0); //Unbind texture (used in shaderProg1)

    glUseProgram(0);

    glUseProgram(handleShaderProg2);
    glBindVertexArray(vaoHandle2);  //Bind VAO
    glDrawArrays(GL_POINTS, 0, 25);
    glBindVertexArray(0);  //Unbind VAO

    glUseProgram(0);
}

```
> -1 votes

---
Tags: opengl, glsl
---


# Question
Title: Accessing the child sprites of a sprite sheet in unity?
I have a spritesheet set up with the individual sprite regions named in unity. I haven't been able to find out how to access these sprites by name?

# Answer
> 6 votes
If you load your sprite sheet in programmatically:

```
private Sprite[] Sprites;

....

Sprites = Resources.LoadAll<Sprite>("SHEET NAME");

```

The Sprite object has a name property, which you can then use to retrieve a specific sprite by name:

```
public Sprite GetSpriteByName(string name)
{
    for (int i = 0; i < Sprites.length; i++)
    {
        if (Sprites[i].name == name)
            return Sprites[i];
    }
}

```

**EDIT (alternative method)**

You could store it in a Dictionary collection instead, which would provide you with a quicker lookup:

```
private void LoadDictionary() {
    Sprite[] SpritesData = Resources.LoadAll<Sprite>("SHEET NAME");
    Sprites = new Dictionary<string, Sprite>();

    for (int i = 0; i < SpritesData.Length; i++)
    {
        Sprites.Add(SpritesData[i].name, SpritesData[i]);
    }
}

public Sprite GetSpriteByName(string name) {
    if (Sprites.ContainsKey(name))
        return Sprites[name];
    else
        return null;
}

```

---
Tags: unity, 2d
---


# Question
Title: What is the best way to send/receive data about user coordinates and other properties?
For example If I have 2 users, and each of them have an object, and that object has: x coordinates, y coordinates, angle, state, and other properties...

I use java

let'say the game changes at 30 frames per second, so each frame something happens, I should send A JSON object through sockets to my server, but the more data we have the bigger the JSON gets, I wonder if there is a way to optimize this sending of data and receiving, cause FPS games send much data, and does not lag, how the games LIKE Dota 2, Counter-Strike etc...send the data? do they use JSON to send the position, angle and other things to notify the server?

thanks

# Answer
**JSON**

Philipp makes a good point about JSON. It is human readable and makes debugging network code easy. If you have no experience in programming network code, this would be the way to go. Yes, there is a lot of overhead by using JSON, but for small to medium data transfers, it should be more than enough. And like Alexandre Vaillancourt said, you can always compress data before sending it.

**Faster and smaller**

But if you want to optimize your network code to send the less data as possible for your game to use the less bandwidth (and be fast), then I would suggest using frames.

Let's say you want to send all the information you mentionned:

```
x: int
y: int
angle: float
state: int

```

This is a player information packet. We need 16 bytes of data in the frame. For the server to be able to read that frame, we will need a header. Let's use 1 byte and say the player information packet is the frame with the id 1. You would then have a frame that looks like this:

```
Bytes  Information
    0 1 (For player information packet)
  1-4 X position (as an int)
  5-8 Y position (as an int)
 9-12 Angle (as a float)
13-16 State (as an int)

```

Wrap this in a UDP or TCP packet and send it. The server, when receiving it, would then read the first byte of data to extract the identifier, see that it's a player information packet, and know exactly how to read the remaining data.

**About big games like Dota 2 and CS:GO**

Don't even bother with this. They use highly sophisticated networking algorythms that are in almost no way applicable to small games people like you and I make. Keeping it simple is the key, because if you ever need to debug your packets (and trust me, you will, and a lot), you cannot call a team of 10 people specialized in network programming like Valve would do.
> 1 votes

---
Tags: java, android, coordinates, angles, socket
---


# Question
Title: Multithreaded or Thread pooled server for real time multiplayer games?
So if the Thread pool handles 10 players out of 100 per second, this could make a delay that will be no good for real-time games, so as I see it that MultiThreaded will be better, thus it will handle all the 100 players at the same time, but I wonder if there are other options for this?

# Answer
> -1 votes
When you make an online game where multiple connections to clients will be made, you want to read from them as fast and soon as possible. Inducing lag on the server side is a bad idea, especially for packets that need to be treated fast.

The best way to handle these connections is to have one thread running for each client. Most networking engines will block when reading or waiting for data, so that is why you need to thread all reading done from the sockets (assuming you use sockets) or any other connection type.

To write data to the clients, however, you can use a single thread, or reuse the threads you have set up for reading if you want. Flushing data out on a connection is blocking in most of the cases, but it will not block for a long time, so you can afford to run it on the main thread. Do send big data chuncks (like files) on a seperate thread like you would do when reading the said file.

In summary:

**Thread Pool**

* Will induce lag for receiving packets, and will sometimes even miss some.
* Is, however, more performant than having one thread per client.
* In the end, Thread Pools are a *greedy optimization* that has too much downside for the advantages it gives.

**One thread per client**

* Will not miss any packet, and can be bound to events better.
* This is the safe way to go, and probably the best in all cases.

# Answer
> 0 votes
Thread handling is always a pain and the source of countless obscure and irreproducible bugs.

I would recommend you to leave the thread management of the receiver threads to the operating system and use Non-Blocking IO with Selectors and SocketChannels. This allows you to handle hundreds or even thousands of sockets with a single thread.

A common NIO handler is a loop which always gives you a set of channels which are ready to perform a specific operation. On most common operating systems it interfaces directly with low-level functionalities of the operating system which means that it is much more efficient at this than your own implementation with one socket per client could ever be.

In my last project I had one thread with NIO to handle the network IO, but that thread was just receiving the network messages, parse them, and then dispatch them to event queues of other threads (one for each active map chunk) which did the heavy lifting regarding calculating game mechanics.

---
Tags: java, multiplayer, multithreading
---


# Question
Title: How to stop an ImageView being dragged before the user stops dragging
I am making a maze game using Android Studio. I have a GridLayout on the bottom layer of the layout, each cell contains a custom LinearLayout. Some of these LinearLayouts have a special boolean property isWall. If isWall = true I put a different image in the LinearLayout.

The "start" cell of the grid contains a child ImageView of a ball. I want the user to be able to drag the ball through the maze and drop it on any non-wall LinearLayout. I don't want the ImageView to be dragged across any cell containing a LinearLayout where isWall = true. I know how to get the DragListener to return false after the user drags the ImageView across a "wall" and drops it on the other side, and I basically have the ball return to the cell it was in before that drag.

How to I make the ImageView itself stop mid-drag, thus forcing the user to stay inside the maze walls?

# Answer
As it turns out, you can't interrupt a touch gesture within the normal scope of how Android operates. It might be possible if you do serious hacking on the source code, way deep down in the Choreography class and some of the core classes, which is NOT advisable, but even then it may not work.

What you (or I; weird answering my own question) most likely need to do is use a SurfaceView instead of the GridLayout. When you override `onTouchEvent()` get the X and Y coordinates of the TouchEvent (`event.getX(), event.getY()`) and see if those points fall within the bounding Rectangle of any of the original tiles or maze path areas (`Rect.contains(x, y)`). As long as the touch events are happening in the "acceptable" areas of the game board, continue to redraw the Ball object centered at the (x,y) point of the TouchEvent. As soon as you detect that the TouchEvent has occurred outside of the "acceptable" areas, either stop redrawing the Ball or set a flag on the object to indicate where the last acceptable (x,y) points were, redraw the Ball there, and flag it as "immovable" until the next TouchGesture starts.
> 1 votes

---
Tags: android
---


# Question
Title: How to draw a sprite without black transparency key?
I would like some help with the following. At the moment when I draw the sprite I want it to be *full* black with no transparency, i.e. 255 alpha channel. But what I get is *half* transparency. How can I fix this ?

Here is my code:

```
bool Black_ImageToTexture(int texWidth, int texHeight, LPDIRECT3DTEXTURE9 pTexture,
    int xPos, int yPos)
{
    D3DLOCKED_RECT lockedRect;
    // Lock the texture
    HRESULT hResult = pTexture->LockRect(0, &lockedRect, NULL, 0);

    if (FAILED(hResult)) {
        // Failed to lock the texture for whatever reason, cannot continue
        return true;
    }

    // Cast the image data to a BYTE pointer so we can easily step over the pitch
    BYTE *pBits = (BYTE*) lockedRect.pBits;

    // For each row:
    for (UINT y = 0; y < texHeight; ++y) {
        // Get a pointer to the start of this row of texels,
        // and then advance to next row
        DWORD *pPixel = (DWORD*)pBits;
        pBits += lockedRect.Pitch;

        // Process this row (Swap R and B channels)
        for (UINT x = 0; x < texWidth; ++x) {
            (*pPixel) = 0xFF000000;
            pPixel++; // Next pixel
        }
    }

    pTexture - > UnlockRect(0);
    return true;
}

```

Finally, render it:

```
d3dspt->Draw(test_texture, NULL, &center, NULL, D3DCOLOR_ARGB(255, 255, 255, 255));

if(FAILED( D3DXCreateTexture(g_pd3dDevice_0, 1680, 1050,
    D3DX_SKIP_DDS_MIP_LEVELS(32,D3DX_DEFAULT), D3DUSAGE_DYNAMIC, D3DFMT_UNKNOWN,
    D3DPOOL_DEFAULT, &test_texture)))
{
    handle_error_code(123238);
    return E_FAIL;
}
else  {
    Black_ImageToTexture(1680, 1050, test_texture, 0, 0);
}

```

# Answer
> 0 votes
`D3DX_SKIP_DDS_MIP_LEVELS(32, D3DX_DEFAULT)`, `32` should have been `1` instead .

---
Tags: directx9
---


title: 2d camera shaking back and forth

text:
# Question
Title: 2d camera shaking back and forth
I'm trying to create a smooth moving 2d camera but the camera is shaking back and forth 1 pixel.

Player camera rectangle:

```
public Rectangle recCamPosition(Global global)
{
  return new Rectangle((int)Position.X, (int)Position.Y , 320, 240);
}

```

Camera rectangle:

```
public Rectangle recCamera(Global global)
{
  return new Rectangle((int)_pos.X / global.zoom, (int)_pos.Y / global.zoom, 320, 240);
}

```

The move method:

```
public void physic(Vector2 position, Player player, GameTime time, Global global)
{
  if(player.recCamPosition(global).X!=recCamera(global).X)
  {
    _pos.X+=(player.Position.X-160-recCamera(global).X)/16;
  }
}

```

# Answer
Try this (assuming \_pos is Vector):

```
return new Rectangle((int)(_pos.X / global.zoom), (int)(_pos.Y / global.zoom), 320, 240);

```

Because:

```
(int)0.5f / 1 == 0 / 1 == 0
1 / 2 == 0
(float)1 / 2 == 0.5f

```
> 1 votes

# Answer
I think you should try the Vector2.Lerp() method. It basically interpolates two Vector2 values, and it's great for camera movement. What you've got is fine - but this might just be a bit better. To use it you could simply have the position and size of the camera rectangle as two Vector2s and lerp them. Here's an example.

```
Vector2 CurrentPosition;
Vector2 CurrentSize;

//Speed should be a value from 0.0f to 1.0f
public Rectangle UpdateCamera(Vector2 TargetPosition, Vector2 TargetSize, float Speed)
{
    CurrentPosition = Vector2.Lerp(CurrentPosition, TargetPosition, Speed);
    CurrentSize = Vector2.Lerp(CurrentSize, TargetSize, Speed);
    return new Rectangle((int)(CurrentPosition.X), (int)(CurrentPosition.Y), (int)(CurrentSize.X), (int)(CurrentSize.Y));
}

```
> 1 votes

# Answer
Okay i fix the shake but i need to use ints and dont shake for pixel per pixel movement

The solution of this was here`Matrix.CreateTranslation((int)-_pos.X,(int)-_pos.Y, 0)*` and change by this

```
   Matrix.CreateTranslation(-_pos.X,-_pos.Y, 0)*

```
> 0 votes

---
Tags: xna
---