# Question
Title: Jumping onto higher ground Collider issues
What's the general solution to the following character animation problem (I'm using Unity)?

You have a character with a capsule collider and a jump animation that allows you to jump onto higher ground (such s boxes, etc.). The character shouldn't be able to jump unrealistically high so she goes into a crouched posture while in the air and the collider is scaled accordingly in an animation curve.

However when the character jumps onto the box to land, the character animation (and collider) want to extend back to wards the ground but there is not enough space and either collision detection fails and the character falls into the geometry or the collider starts a collision fight with the box and keeps bumping up and down, keeping the character in an airborne state.

Please see screenshots to get a better idea...

What would be a good way to work around this problem?

# Answer
It seems like you are missing to move the transformation of the player high enough. like on the picture I think the problem is, that you set a jump height according to the animation and not to the player without animation. So jump height looks fine when in crouch position, but when u turn of the animation, you will see, that the player model jumps way to less high.

I think this is your problem. So just fix the jump height and all will be fine.

As a side node, an animation should allways be applied only, when the actual movement is ok.

So in your example, only when the player model jumps correctly to its complete transformation, then apply an animation for the whole duration of the jump.
> 1 votes

---
Tags: unity, collision-detection, animation, mecanim, rigidbody
---


# Question
Title: Why does GameMaker Studio not open from a removable drive?
I downloaded GameMaker Studio 1.4 onto a jump drive so I could use it between two different computers. I downloaded it in a Windows 7 computer, but when I try to use it on a Windows 8 computer, it flashes the updating box, then nothing happens.

I have tried running it in Windows 7 compatibility mode, and I have tried running it as an administrator. Neither works.

# Answer
> 0 votes
Programs are not always made to work that way. What you want is a portable version of that software, but such thing has not being created yet either by the developer or someone else.

Programs that run from an installer in windows usually write to more folders than just the install dir. So that if you only copy the install folder to another pc it will have undefined behavior or other issues because the environment is not prepared for it.

You could just install the program on both computers and call it a day, but is has nothing to do with admin privileges or different windowd versions.

---
Tags: game-maker
---


# Question
Title: What is the genre defined by getting as far as possible along an infinite level called?
I am interested in making a mobile game in the style of an infinite hallway. Like *Jetpack Joyride* where the background moves and you just steer your guy up or down to avoid stuff. You can have a glimpse here on YouTube of what it looks like.

I have never made one before, in fact, I have no idea what that genre is called...

What is this genre called?

# Answer
The genre is a infinite runner. Or an endless side scrolling runner.

The goal of the game is to get as far as possible.

Generally, this kind of game has it's content randomly generated as the player advances. The player advances automatically, while s/he has to perform some other actions to 'survive' as long as possible.

One of the most popular early games of this genre was Canabalt, where the player only had the option to jump at the most appropriate time.

The genre has evolved since then.

---

"How to start making one" is really to broad for this site, but here is the tip of the iceberg:

You would need:

* a 2d platormer game architecture with physics and collision detection
* a live content generation algorithm (as opposed to offline like we see in games like Starbound or Elite: Dangerous). Each run is different.
> 5 votes

---
Tags: terminology
---


title: How to implement AI for fighting game

text:
# Question
Title: How to implement AI for fighting game
I built a 2D fighter yesterday.

The second 'player' does hardly anything. Actually, nothing. To be honest, I have never made a game before that had an opponent like this.

So my question is, how does one start with AI programming for the opponent? Are there any tutorials, any best practices? I want it to be a challenge (for the player, not myself).

# Answer
N-grams are popular here. The basic idea is to keep a list of moves the player has made. You can then, given the last N moves of the player, figure out percentage likelihood of what his next move might be.

Your game should have a database of effective counters and blocks to each move.

For offensive modes in the AI, you can still basic player modeling to determine which attacks the player has had the most trouble blocking or countering, and reuse those.

For AI difficulty, just dumb down the AI at easier levels. The worst AI mode might invert choices (that is, if it knows the player usually blocks punches, it has a higher rather than lower chane to throw a punch). The highest difficulty mode would use the non-handicapped algorithm, and is likely going to beat the crap out of the player.

If you're looking to make the game more fun, I also recommend adding personality to the AI. Some characters might taunt more, some might be more defensive than offensive, etc. players enjoy being able to ascribe human intelligence to AI characters.
> 12 votes

# Answer
Honestly as much as some of the top answers recommend more complex AI, If this is an early attempt at a game and you're not that skilled with code yet, you might try for a more dumb AI

For example a simple system of

wait (0-3 seconds)

Roll d6

pick from 6 actions.

Or something similar depending on how many actions you have
> 3 votes

# Answer
This is how i would go about making ai for a fighting game.

Make lists of moves (depending on char) that are appropriate for different distances away from the player and have him pick a move.if the difficulty is set on hard. Have him pick a hard hitting move. Otherwise pick the move that does less for medium and less for easy. You can also throw in a random factor that picks different ranges from the one that player is actually at depending on difficulty. The amount of decisions should be based on difficulty where he evaluates 3 seconds after each move(easy) 2 seconds(medium) ect. Each time determining his course of action.

summarizing, pick a distance(move set), pick a move and then how long they wait before they do the same thing. In between waiting for the next action they can strafe and dodge by chance. Hope this helps.
> 2 votes

---
Tags: javascript, ai, html5, fighting-game
---


title: Multiple lua scripts using newthread

text:
# Question
Title: Multiple lua scripts using newthread
I'm trying to hook lua-scripts to my entities, where several entities of the same type want to use a separate instance of the same script. Problem is, when I run two or more scripts and use any C-api functionality, I get an access violation after some time. I'm guessing some kind of stack corruption occurs but I'm not sure. The application is single-threaded but uses lua\_newthread for each entity, and I then use lua\_resume on each new thread for when I want the scripts to run. The code looks like this.

Script 1

```
function Update(dt, owner)
   print("Script 1")
   pos = GetPosition(owner)
end

```

Script 2

```
function Update(dt, owner)
   print("Script 2")
end

```

GetPosition()

```
static int GetPosition(lua_State* L)
    {
        Core::Entity entity = lua_tonumber(L, 1);
        Core::TransformationComponent* tc = WGETC<Core::TransformationComponent>(entity);

        lua_newtable(L);

        for (int i = 0; i < 2; i++)
        {
            lua_pushnumber(L, tc->position[i]);
            lua_rawseti(L, -2, i);
        }

        return 1;
    }

```

How I create new lua threads (m\_luaState is the global parent state to which I bind all my functions):

```
lua_State* LuaCore::CreateThread(std::string file)
    {
        lua_State* newState = lua_newthread(m_luaState);

        lua_newtable(newState); //new globals table
        lua_newtable(newState); //metatable

        lua_pushliteral(newState, "__index");
        lua_pushvalue(newState, LUA_GLOBALSINDEX); //original globals
        lua_settable(newState, -3);
        lua_setmetatable(newState, -2);
        lua_replace(newState, LUA_GLOBALSINDEX); //replace newState's globals

        luaL_dofile(newState, file.c_str());

        return newState;
    }

```

How each script is called:

```
            lua_State* ls = GetChildState(stateIndex)
            lua_pushstring(ls, functionName.c_str());
            lua_gettable(ls, LUA_GLOBALSINDEX);

            SimpleLuaCallData* slcd = (SimpleLuaCallData*)inData;

            lua_pushnumber(ls, slcd->dt);
            lua_pushnumber(ls, slcd->ownerID);

            lua_pcall(ls, 2, 0, 0);

            return nullptr;

```

If I remove the call to GetPosition from Script 1, the application runs without issue. Am I missing some kind of required clean-up or garbage collection problems? I'd like to try and avoid creating a new state for each entity, as that seems excessive and sharing globals via the core state is nice. lua\_pcall doesn't produce any results. The application eventually stops running Script 1 and after a few more cycles it gets the access violation on

```
lua_gettable(ls, LUA_GLOBALSINDEX);

```

in the calling function.

# Answer
So turns out the solution was quite simple. When creating my threads I needed to get the reference to that thread, or it would get destroyed by the garbage collector. Why this didn't manifest when running only one script is beyond me, maybe someone can provide a good answer for that? New CreateThread method, for reference.

```
lua_State* LuaCore::CreateThread(std::string file, int& refKey)
    {
        lua_State* newState = lua_newthread(m_luaState);
        refKey = luaL_ref(m_luaState, LUA_REGISTRYINDEX);

        lua_newtable(newState); //new globals table
        lua_newtable(newState); //metatable

        lua_pushliteral(newState, "__index");
        lua_pushvalue(newState, LUA_GLOBALSINDEX); //original globals
        lua_settable(newState, -3);
        lua_setmetatable(newState, -2);
        lua_replace(newState, LUA_GLOBALSINDEX); //replace newState's globals

        luaL_dofile(newState, file.c_str());

        return newState;
    }

```
> 1 votes

---
Tags: entity-system, scripting, lua, entity-component
---


title: How to detect if an object is upright?

text:
# Question
Title: How to detect if an object is upright?
I have a cartoon car and it has a skid sound with the car skids. But when the car flips over the skid sound plays endlessly and its really annoying. I have a basic script that is meant to detect when the car is upright and only play the skid sound with the car is upright. Here is the code:

This script is on the car itself:

```
public bool IsUpright () {
        Vector3 rotationInEuler = transform.rotation.eulerAngles;

        float tiltX = Mathf.Abs(rotationInEuler.x);
        float tiltZ = Mathf.Abs(rotationInEuler.z);

        if(tiltX < uprightThreshold && tiltZ < uprightThreshold){
            return true;
        }else{
            return false;
        }
    }

```

This script is on a skid sound prefab:

```
void Update () {
        if(motor.IsUpright()){
            if(motor.IsMoving()){
                transform.GetComponent<WheelCollider>().GetGroundHit(out tireHit);
                currentFrictionValue = Mathf.Abs(tireHit.sidewaysSlip);

                if(skidAt <= currentFrictionValue && skidWait <= 0){
                    Instantiate(skidSound, tireHit.point, Quaternion.identity);
                    skidWait = 1;
                }
                skidWait -= Time.deltaTime * skidEmission;
            }
        }
    }

```

When the IsUpright bool (first script) is printed to the console it keeps flickering between true and false and it isn't detecting when the car is upright. By the way the uprightThreshold from the first script has a value of 40. I have also check in the inspector and the rotation of the car on both the x and z axis are not constant at 0, it is flickering up and down between about 1 and -1, but unfortunately unity doesn't support having negative rotation values, so rather it goes to 359, which is mucking up the system. Could someone show me how to fix this? Thanks in advance.

# Answer
I would not complicate things much:

```
public bool IsUpright () {
        return transform.up.y > threshold;/*say 0.6 ?*/
}

```

because the `up` vector is normalized and, naturally, points upwards you just need to check its length in Y axis(or the "up" axis if you use different one). It will be 1.0 when perfectly up and -1.0 if perfectly upside down. This simple code will suffice - if you don't require exact angle, of-course(you can still compute the equivalent Y threshold value of angle should you require it).
> 4 votes

---
Tags: physics, unity, audio, car
---


# Question
Title: OnTriggerEnter / OnTriggerStay triggers multiple times and is not been call a second time
I am working on a feature that when the Player pass thru a door, a message will popup on the screen.
I'm having few problems: `Debug.Log` gives me from 2 to 6 logs when I pass thru the collider plane and when I come back to the same collider plane the script it is not been call a second time.
What I'm trying to achive is that `Debug.Log` gives me only one log and every time I pass thru the collider the script runs again. so here is my code:

```
function OnTriggerEnter (other : Collider) { //OnTriggerStay gives the same result
    if (other.tag == "Player") {
    isColliding = true;
  } else {
    isColliding = false;
  }
}
function OnGUI() {
  if (isColliding) {
      Debug.Log(isColliding);
    //Application.ExternalCall('hive.OpenHiveAlert', 'test');
  }
}
function OnTriggerExit() {
    Destroy(this);
}

```

Any help would be appreciated, thanks.

# Answer
> 0 votes
`OnTriggerExit` Did not work in any posible form, what I did in order to trigger my function only once and "reuse it" again is in the folowing code:

```
#pragma strict

var isTrigger = false;

function OnTriggerEnter (other : Collider) {
    if (other.tag == "Player") {
        if (!isTrigger) {
            Application.ExternalCall('hive.OpenHiveAlert', 'test');
            isTrigger = true;

            yield WaitForSeconds (10);
            isTrigger = false;
        }
    }
}

```

It may not be the ideal code, but I can't spend any more time on that... Thank you @Athos and @Jack for your time. :)

# Answer
> 1 votes
That happens because rather than calling Debug.Log once your OnTriggerEnter is called, you are calling it inside the OnGUI. OnTriggerEnter is called only once you enter, which means it does only get called once, whereas OnGUI is called (more than) once per frame, unrelated to any such physic events.

As long as your player is inside the collider (because isColliding becomes true once you enter it), you never reset this. Only once you exit it, the object is destroyed and you no longer see any calls. You will probably have your desired result once you start drawing actual text (because as long as the player is inside the collider, it will draw the GUI).

If you want only one Debug.Log, you should instead place this in the body of your if-statement in your OnTriggerEnter method.

# Answer
> 1 votes
Athos is correct about OnGUI. If you really want to limit it to one Debug.Log message, you can disable the bool in the OnGUI - treating it like a flag that's only true until OnGUI responds the first time. (Though as Athos points out, you'll be fine once you actually start displaying the GUI properly)

Also note that due to the else statement in OnTriggerEnter, if something else were to enter the door trigger, it would disable the isColliding flag which doesn't make a lot of sense to me since the player's collision status doesn't really depend on whether something else enters the doorway

---
Tags: collision-detection, unity
---


# Question
Title: Unity 2D Sprite Bending between Hinge Joints
I've created a tentacle that consists of multiple game objects, each attached to eachother using HingeJoint2D's. Gameplay wise this multiple segmented approach is great because I can use Unity's built-in physics, but it doesn't look very good art wise.

Is it possible to 'bend' 2D sprites, so the tentacle segments look like they're attached to eachother? Or perhaps take a single image and bend it using splines of some sort?

I would prefer to keep using multiple game objects to represent the tentacle.

# Answer
> 2 votes
I'm not familiar with Unity, so some of my suggestion could be irrelevant.

1. You could try and compose a sprite based on the vertices of the GameObjects that you bend. This would help hide the 'chain' that is behind.
In the image bellow, in black is your original "chain". You take some precise location on it and you make out of it a new "continuous chain", drawn in red.
2. Instead of having long segments, you could try to alleviate the issue by using circle shapes. You'd have to reduce the angle of freedom for your joints, but since you'll have more, you'll end up with the same result.
3. The third option I see is instead of using rectangle sprites, try and make 'capsule' sprites: a rectangle with half circle on each end. This would still have "angle-ish" joints, but at least, you won't see the rectangle separations.

In any case, you'll need to tweak your sprites graphics.

---
Tags: unity, 2d, sprites, image
---


# Question
Title: How to use 16/32 square pixel tiles in tilemap on arbitrarily sized canvas in Phaser
My question is about Phaser and Tiled but I'm not quite sure how to ask it so please bear with me.

Do I need to make the size of the canvas or area on which I want to display my tilemap a multiple of the size in pixels of an individual tile in my tileset? Or is there a way of scaling a tilemap to fit a particular screen area?

I'm not really sure how to explain my question better so I will give an example of what I'm talking about. Because I'm using only freely available game art (such as that found on opengameart.org), most tilesets come with tiles sized 16x16 or 32x32 pixels. Does the game area I want to display the tiles in have to be a multiple of 16 or 32, respectively?

Or put another way, if I wanted to have a grid of 32x32 tiles fit inside of a canvas of say, 900x900 dimension, must I have to draw/design my tiles to be of size ~28x~28 pixels?

And if I want to use a tileset with tiles of size 32x32 must I make the canvas a multiple of 32, like 1024x1024 for example?

Thanks for bearing with me and for any help.

# Answer
The usual workflow with tilemaps in Phaser is this:

1. You make a tile map, probably in a map editor like Tiled, and export to a format that Phaser can support, like JSON.
2. Load the tile map in Phaser. You can now draw entire layers of the map in one go - you don't have to worry about individual tiles.
3. You can now figure out how big the tile map is by using methods like `Phaser.Tilemap.widthInPixels()`.
4. You can scale individual layers in the tilemap using `Phaser.TilemapLayer.scale()`. The scaling works just like sprites and groups - you can scale x and y individually, as a decimal, with 1.0 being normal scale.
5. To figure out the right scaling factor, divide the canvas size by the tilemap size. For example, to fit 800 pixels inside a 900 pixel canvas, scale by `900.0/800.0`.

Note that in general, scaling like this will look bad because you're trying to fit non-round numbers. Imagine trying to stretch 28 pixels to fit 32 - either you double 4 out of the 28 original pixels, or you smudge out the whole thing in some manner. Scaling like this is highly unusual for tile maps, so I would advise making your maps fit your canvas, rather than the other way around.
> 3 votes

---
Tags: tilemap, phaser, tiled
---


# Question
Title: How do I check if one square is overlapping another in HTML5 canvas
I have a little program that goes like this:

Whenever somebody presses space, a blue square appears. The blue square shouldn't overlap with any other blue square.

But the function that is checking the overlap is not working! Can somebody please help?

```
window.onload = function() { //Starts the program when the page is loaded.

  var canvas = document.getElementById("paper");
  var background = canvas.getContext("2d");
  var squareDisplay = canvas.getContext("2d");

  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  var xAndYvaluesOfSquares = [];

  //Makes a randint() function.
  function randint(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  function checkForOccupiedAlready(testXPos, testYPos) {
    if (xAndYvaluesOfSquares.length != 0) {
      for (valuePair in xAndYvaluesOfSquares) {
        if (
          ( valuePair[0] + 20 ) < testXPos &&
          ( valuePair[0] - 20 ) > testXPos &&
          ( valuePair[1] + 20 ) < testYPos &&
          ( valuePair[1] - 20 ) > testYPos){ //If in the same area
          return false;
        }
      }
    }
    return true;
  }

  //Makes a new square
  function makeNewsquare() {

    var checkingIfRepeatCords = true;
    //DO loop that checks if there is a repeat.
    do {
      //Makes the square x/y positions
      var squareRandomXPos = randint(50, canvas.width - 50);
      var squareRandomYPos = randint(50, canvas.height - 50);

      //Tests if that area is already occupied
      if (checkForOccupiedAlready(squareRandomXPos, squareRandomYPos) == true) {
        xAndYvaluesOfSquares.push([squareRandomXPos, squareRandomYPos]);
        checkingIfRepeatCords = false;
      }
    }
    while (checkingIfRepeatCords == true);
  }

  function resetBoard() {
    for (i = 0; i < xAndYvaluesOfSquares.length; i++) {
      var XYvalue = xAndYvaluesOfSquares[i];

      squareDisplay.beginPath();
      squareDisplay.fillStyle = "rgb(50, 50, 125)";
      squareDisplay.rect(XYvalue[0], XYvalue[1], 50, 50);
      squareDisplay.fill();

    }
  }

  document.addEventListener("keydown", function (event) {
    if (event.keyCode == 32) { //Space key
      makeNewsquare();
      resetBoard();
    }
  })
}

```

# Answer
You can check whether one rectangle overlaps another rectangle by checking their edges; if we have two rectangles `a` and `b`, and if the two rectangles aren't intersecting, then evaluate the following four statements:

* `a`'s left edge is to the right of `b`'s right edge
* `a`'s top edge is beneath `b`'s bottom edge
* `a`'s right edge is to the left of `b`'s left edge
* `a`'s bottom edge is above `b`'s top edge.

If even one of the above statements is true, then the two rectangles do not overlap. Otherwise, they do overlap.

In pseudocode, you can represent that logic like this:

```
if (a.left >= b.right || a.top >= b.bottom ||
    a.right <= b.left || a.bottom <= b.top)
{
    // no overlap
}
else
{
    // overlap
}

```

**Caveat #1**: In this pseudocode, I'm interpreting two rectangles with opposite edges on the same point as *not* overlapping. If you want those rectangles to count as overlapping, use regular `<` and `>` tests, instead of `<=` and `>=`.

**Caveat #2**: In this pseudocode, I'm assuming that you're using a coordinate system in which positive 'y' extends downward on the screen, such that a rectangle's 'top' will have a lower value than its 'bottom'. If you're using a coordinate system in which positive 'y' extends upward on the screen, you'll need to reverse `<` and `>` comparisons in the pseudocode's top- and bottom-related clauses.
> 3 votes

---
Tags: javascript, html-canvas
---


title: How do splines work?

text:
# Question
Title: How do splines work?
I've been beginning to work with different kinds of splines (e.g. Bezier, Hermite, B-splines) in some of my work with computer graphics and I am trying to get a grasp of how they work (mathematically and programmatically). I know that generally (at least for cubic splines), you will have 4 control points that influence the position of points along an interpolated line. For example, with Bezier curves (as far as I understand), there can be two end points where the line will begin and terminate and two control points that influence the direction of the line.

I've been programming Bezier, Hermite, and B-Splines (in javascript on an html5 canvas) and what I don't understand is how to choose these 4 points in order to see a specific curve rendered on the screen. So far, I have only been able to render at least part of a curve by randomly playing around with different numbers for each point.

This is one of the many questions I have about the inner workings of splines so could someone provide an overview on how they work and how they can be programmed (most of the examples online are more theoretical and rather unspecific)?

# Answer
A coder's guide to spline-based procedural geometry is a video from Unity event Unite 2015.

In the video, the presenter gives visual explanation of how splines can be created and modified. Then, he goes on to give code examples for the same. Very informative.

The video is for Unity3D, but the algorithms presented can be adapted to any platform.
> 5 votes

---
Tags: mathematics, javascript, graphics, linear-algebra, splines
---


# Question
Title: Distance to rect edge from point based on direction
I have a rect that is at position (0,0) at the top left and is 2200x2200 in size.

I am trying to specify the the distance to get to the edge of the rect in specific direction (degrees) from a point within the rect.

So say I am at point 50,50, and want to move 270 degrees until I hit the coordinate of the edge of the rect. What would be the best way to go about this?

Right now I have another function I use to get distance based on direction

```
distance = 2200
direction = 315
toEdge = distance*math.cos(math.radians(direction)), distance*math.sin(math.radians(direction))

```

This will just get a point 2200 units away from direction. I think this is half the step there, but can't get the math right on on how I translate this into getting the distance to the rect edge depending on coordinate.

If anyone could help me out I would be appreciative. Thanks.

# Answer
If I understood what you're asking ,after you get your toEdge point , you need Intersection of a Line and a Rectangle to get intersection point. Then calculte distance from start point to intersection point.
> 1 votes

---
Tags: mathematics, python
---


title: Logging library for (c++) games

text:
# Question
Title: Logging library for (c++) games
I know a lot of logging libraries but didn't test a lot of them. (GoogleLog, Pantheios, the coming boost::log library...)

In games, especially in remote multiplayer and multithreaded games, logging is vital to debugging, even if you remove all logs in the end.

Let's say I'm making a PC game (not console) that needs logs (multiplayer and multithreaded and/or multiprocess) and I have good reasons for looking for a library for logging (like, I don't have time or I'm not confident in my ability to write one correctly for my case).

Assuming that I need :

1. performance
2. ease of use (allow streaming or formating or something like that)
3. reliable (don't leak or crash!)
4. cross-platform (at least Windows, MacOSX, Linux/Ubuntu)

Wich logging library would you recommand?

Currently, I think that boost::log is the most flexible one (you can even log to remotely!), but have not good performance update: is for high performance, but isn't released yet. Pantheios is often cited but I don't have comparison points on performance and usage. I've used my own lib for a long time but I know it don't manage multithreading so it's a big problem, even if it's fast enough. Google Log seems interesting, I just need to test it but if you already have compared those libs and more, your advice might be of good use.

Games are often performance demanding while complex to debug so it would be good to know logging libraries that, in our specific case, have clear advantages.

# Answer
log using socket (any socket wrapper can suffice) + web browser websocket =\> most versatile, unobtrusive logging tool possible, will gain hours of debugging and avoid eye-sore.

* asyncrhonous (speed as it defers all the job on the browser)
* formatted (color, size etc..)
* reliable (sockets...)
* cross-platform (browser)

Now, the bonus:

* dynamic filtering very easily done (using javascript regex if needed)
* with log history, memory and compare (HTML5 spec on the "in-browser" database)
* Easy way to make some graph of any data (using SVG, or canvas or anything) like memory, memory fragmentation, etc...
* easy way to make some 2D graph of any data (kd-tree subdivision ? potential field ? or even just a variable value variation ? etc...)
* allows distant logging (using the browser other computer)
* using html5 in browser storage, you can store log session parameteres (current log filters, etc.. and even notes on each)
* very easy to create bug report or link trac tickets just with a click
* ability to rewind logging easily, with a timeline gui

and many more task outside of logging:

* allows profiler info (graphs...)
* can even serve as console (send command from browser) or even with quick GUI using some HTML or even flash ui
* image diff in the browser (send image using socket, and compare in browser using canvas image pixel capabilities)
* etc...

(nearly all of the above can be done using flash sockets, save the database capabilities)

Now I know it seems a bit long to set up the thing. But it really is a gain of time on long project, with hard debugging situation (such as in games.) It's the most powerful thing I used since debuggers...

Note 1: the only downside =\> double-check side effect when debugging game networking code (impact on socket buffer size, latency, bandwidth, etc...)

Note 2: some broswer deactivated by default websocket due to security reason, check about:config things to be sure it's enabled.
> 7 votes

# Answer
When it comes to performance, I've found templog pretty much unbeaten. It uses expression templates to defer evaluation of logging statements until it's established that the information will be logged at all. Since you can also partly turn off logging (depending on severity, origin, and targeted audience of a log message), some of these logging statement can be eliminated to zero code by the compiler for release builds. (I have actually seen this happen with VC.)

There wasn't much done to the library recently, and others on SO have found the trunk lacking in some regards, but in a company I used to work for we have found the guy quite responsive, and one of my then cow-workers even got commit access and added some code to it, so you might find it worth a shot.

To enumerate your requirements:

> performance

Best I've found. Especially its ability to exclude log messages *at compile-time* and have the compiler completely eliminate those was very appealing.

> ease of use (allow streaming or formating or something like that)

There's the classical horrible compiler error messages of templates-meta stuff when you do something wrong, but when it comes to ease of use, this

```
TEMPLOG_LOG(my_logger,sev_error,aud_support) << "logged in as " << user_name;

```

is hard to beat.
However, you might have to create your own log sinks (that's where the log messages go), as the few pre-packaged ones (stderr, file, Windows logging, etc.) aren't all that sophisticated. Due to performance being a main goal, the intrinsics of the whole thing are somewhat complicated (like log message formatters being quite tangled with log sinks), but we did master that (I remember stepping through it in a debugger helping with that) and once understood it wasn't all that hard to write your own message formatters or log sinks.

> reliable (don't leak or crash!)

We have used it without finding any such severe issues. There's virtually no dynamic memory allocation in there, so it's hard to even imagine it doing something wrong. Of course, we only ever put it to real-world tests in one product.

> cross-platform (at least Windows, MacOSX, Linux/Ubuntu)

When we used it, we used it on Win32, OSX, and several different Linux distributions, Ubuntu among them.

As for multi-threading: We haven't used this, but from what I remember of the lib's architecture it seems you would only need to handle this in log sinks. ICBWT.
> 8 votes

# Answer
You may wish to consider the logog library, at http://www.logog.org , which I think may satisfy your requirements. Caveat: I wrote it.

See also other people's answers at https://stackoverflow.com/questions/696321/best-logging-framework-for-native-c .
> 1 votes

# Answer
You might be interested in Baical tools set:

* Open source and cross platform (Win, Linux, x86/x64) library for logs, traces & telemetry - P7
* Incredibly fast (designed for embedded devices) - 3 million of logs per second to network, 5 millions to file on modern CPU. I don't know any other library for logging which provides such speed and so detailed information for every log message.
* Thread safe
* Every trace message contains:
    + text message
    + level
    + precise time (100ns)
    + source file, function name & line
    + module ID and module name
    + thread ID and thread name
    + processor core index
* Server application to receive and view logs & telemetry
* You may collect, analyze, search, filter logs from multiple sources in real-time
> 0 votes

---
Tags: c++, software-engineering, performance
---


# Question
Title: How do I draw more than just points in 3D?
I'm currently working on a 3D rendering engine in JavaScript. I've successfully rendered a cube and can rotate it. My cube is represented by 3D points in an array (`[x, y, z]`):

```
var cube = [[-20,-20,5],[20,-20,5],[-20,20,5],[20,20,5],
[-20,-20,-5],[20,-20,-5],[-20,20,-5],[20,20,-5]];

```

Now that I can render a basic cube I'd like to try rendering something more complicated to make sure my math works well. It's there a standard 3D object file i can import and use or I have to manually specify the 3D positions of every vertex like I did with the cube?

# Answer
I'm not completely familiar with it, but I think that for *your* convenience, I would take a look into the Wavefront .obj file format.

As I understand, a *lot* of 3d software implement this file format as a convenience to transfer from one 3d app to another.

Since the format is text based, you could 'code' your first shapes at first by hand, and then use a 3d software like Blender to make more complex objects.

You'll have to change the way you "read" your 3d objects, however, but it's for the best :)

Another advantage of using an open file format is that you'll already have a bunch of features right away, without having the burden of thinking how to structure them.

Be aware that different software use different hand-ness and coordinate system convention, so it may differ a bit from your implementation (for instance, a software might think the `y` axis is up, while another, or your own, thinks that `z` axis is up.
> 1 votes

# Answer
Take a look at existing 3d model formats like Wavefront or Collada. They usually contain much more than a list of vertices, but you could write a function that extracts that particular details. Once you can extract vertices I'd look into rendering polygons.
> 1 votes

---
Tags: 3d, javascript
---


# Question
Title: How to render multiple displays in Unity
I have a scene (lest assume, large glass table I want to looking through) and I want to render with 4 displays (each 1920x1080). How can I set up camera for this, I want the "glass cube" to fill entire scene (all four displays).

If I use single perspective camera and I want to see entire scene, I got stretched image near sides - in other words only middle is correct and sides are stretch. If I correct this, than my scene is not filling entire window and is small.

I have tried to create single camera for each "display", but this will cause frustums overlapping and I have part of the image rendered twice (logically). I can use orthographic-camera, there is no overlap, but I have no perspective.

How to solve this problem?

**Edit:** I am using Unity 5

# Answer
You can't.

Sorry.

Well you could. But it would involve a distortion mesh (basically, you render your scene to a texture, and you distort that texture with a mesh, and you display that mesh). And this would imply that your camera never changes position, or that you have a distortion mesh available for each of the camera's possible positions.

Otherwise, well, you've said it, you'll lose the perspective (because you'll use orthographic cameras).

Maybe a work around I could suggest:

Have all your cameras positioned at the same location, but shooting each a FOV of 45°, and each rotated of 45° from the previous one. You'll cover a wide angle of 180°. This way, you won't be shooting twice the same thing. Now the tricky part is to have your scene "wraped" around your cameras: you'll need a table that does a half circle, and if you move objects width-wise in the scene, you'll have to move them radially instead.

In the image, we see a top view of what I suggest; the black lines are the four fields of view, and the red shows the bent (in a half circle) rectangle long table.

This would be the best if you could project onto a curved surface, and better if your could set up your four displays in a 180° fashion.

This, of course, will not *solve* your issue, it could only *alleviate* it.
> 3 votes

---
Tags: rendering, camera, unity
---


# Question
Title: How to make your own 2D AABB collision system in unity?
I can't use the built in unity 2d physics engine for my game, so I tried to make my own using the unity bounds.Intersects, that is working perfectly but my problem is that I don't know how to make the player stop when It collides. Ive tried multiple things like storing the players last position and "teleporting" it back to that position when it collides (That looks choppy). Ive also tried to invert the controls when your colliding (So like W makes the player go down, A makes it go right ect) but that is extremely buggy. How should I do it?

# Answer
> 0 votes
There are multiple ways to approach this. If all your collision shapes are AABBs, you could calculate the velocity, then snap to the nearest edge of the other box e.g. for a box moving right, you would set its x to other.bounds.min.x - box.bounds.extents.x to snap it.

# Answer
> -2 votes
First of all, I don't know why you can't use the built-in physics, but you should consider using it. It's better for performances, and much easier.

if you need to make your own AABB collision system, you have to inform your script that handle moving the player. you could do something like:

```
if(!YourCollisionObject.IsColliding()) {
    Move()
}

```

If there's no collision, your object is free to move, but if there is, your object won't move at all.

---
Tags: unity, collision-detection, aabb
---


title: Testing SFML sf::Touch on ordinary PC

text:
# Question
Title: Testing SFML sf::Touch on ordinary PC
So I’ve created a small app that is designed to be used on smartphones and tablets. Accordingly the app makes use of the sf::Touch class which determines the point on the screen of the device that the finger of the user is touching. This is required because central to the functionality of the app is that it allows the user to swipe across the screen to flick between different images. The end result should be that once a user’s finger (being pressed against the screen) has moved far enough to the left or right periphery of the screen, a swipe function is initiated and the next image moves into view. This appears in the code like so:

```
if (touchInput.isDown(0))
{
    sf::Vector2i currPos;
    currPos = touchInput.getPosition(0);
    if (currPos.x < 540.0)
    {
        leftSwipe(currPos);
    }
    else if (currPos.x > 540.0)
    {
        rightSwipe(currPos);
    }
    oldPos = currPos;
}

```

The problem is that I am testing the application on the PC and when I click the left mouse button down (which I assumed would cause the function touchInput.isDown(0) to return true) it does not appear to update the position of touchInput and was therefore wondering if touchInput should be used on the PC at all and also if it even functions with PC inputs (like a mouse)? or whether for PC testing it would be better to use sf::Mouse instead?

# Answer
> 3 votes
When compiling for a traditional Windows / Mac / Linux desktop setup, no this won't work. I dug through the SFML code and it turns out that the sf::Touch implementation won't really work unless you're on a touch-based device:

From https://github.com/SFML/SFML/blob/master/src/SFML/Window/Win32/InputImpl.cpp

```
bool InputImpl::isTouchDown(unsigned int /*finger*/)
{
    // Not applicable
    return false;
}

```

How you CAN test this is a bit roundabout. You'll need to compile your C++ based game for Android with the Android NDK (native development kit). From there you should be able to run the app on an Android Emulator on your computer or a push the app to a device for testing.

---
Tags: c++, input, sfml, mobile, touch
---


title: LibGdx 2d Free-Form Terrain

text:
# Question
Title: LibGdx 2d Free-Form Terrain
I have a query about how to create a 2d landscape level using libgdx/ box2d (Or possibly with Unity) for Android and iOs. Let me describe the goal and then the specific points I need help with.

What I'm trying to create is something like "Hill Climb Racing" where the player has to drive across a finite 2d free-form landscape, like the one shown here. Different areas may have different properties (friction, texture, restitution, etc) as shown. The player will be able to pinch and zoom out to see all or most of the map and pinch to zoom in to see details..

The level width will vary from game to game but at most it will be about 800 box2d meters wide. Now if I use 32px/m that requires an image 25,600 pixels across and this is where the issues start.. I can't tile it because that might preclude me from making free formed curves which I need to be able to do.

So what I need to know is:

* How can I create a box2d body for the terrain?
* What pixel/meter ratio should I use?
* How many pixels wide should the image be?
* Should I split the image up into sections and how should I chunk the images together?
* What strategies have people used before to achieve this effect?

Hope I have been specific enough and thanks for all the help..

# Answer
> 1 votes
I'm working on a little project that has a similar type of landscape to how you describe.

I use a Box2d chain shape for the physics. The Box2d chain shape just needs to follow the terrain edge, so it's dead simple, and it doesn't have issues with concave shapes and the restrictions Box2d polygons have.

For the graphics, I break down my terrain into triangles (once, at the start of the game), using an ear-clipping algorithm, and render the resulting mesh with OpenGL. You can render the mesh using solid colours, gradients, a single solid stretched texture, tiled textures, or whatever you can come up with via custom shaders and your imagination.

Using the above, you can use much smaller textures to 'fill' the terrain mesh, either via tiling or some other imaginative way. So there's not really any one size fits all, just use whatever you need to piece it all together. You can get away with using very little, if any at all, depending on your desired look.

An alternative that I considered but didn't explore further at the time, may be to break your terrain down into tiles of different type gradients, surfaces, corners, etc, in a way that you can make very flexible and unique looking landscapes but with just a couple of dozen small tiles or so.

As for your world being around 800 Box2d metres in size, I think you may get away with that but it's probably pushing it. I would test that idea out early on to make sure. I know I've read Box2d doesn't like very big dimensions, I'm just not sure offhand what those limits are.

Hope that helps.

---
Tags: libgdx, sprites, box2d, terrain, resolution
---


# Question
Title: When should a game be announced to the public?
I'm not sure if this is where I should ask this as it might be opinion based so I apologize.

I am creating a game and I would like to know at what point in development I should reveal it to the public. An example would be posting on a forum about the language I am using, and having that post announce the game.

I am wondering how close to completion I should have the game before I begin to reveal it.

edit: Lets say that the game is a puzzle game similar to portal in style however without using a portal gun.

# Answer
> 7 votes
As early as possible.

There is no reason to keep your game secret. Creating a public development blog, for example, is a great way to document your thoughts and keep yourself motivated. A modest audience of interested people might give you some valuable feedback, even when all you post is still conceptual.

There is really no reason to be afraid someone might rip off your ideas and beat you to market.

1. The documentation of your progress is proof you had the idea first.
2. Ideas are far less valuable than you think. Everyone has great game ideas (at least they sound good in their heads...). And just like you, they would rather prefer to work on their own ideas, and not those of someone else. The only ideas people rip off are those which are *proven* to be commercially successful, and that proof won't come before you start selling your game.
3. A single idea or good core game mechanic doesn't make a good game. A quality game is one where all the components fit together. When you look at the most successful games, you will notice that very few of them really did anything of matter which was completely new (and with those which did, the idea was often something where nobody else though that one could actually make it work well). What they did better than other games is not just do every single component of the game better than average, but also *fitted them together* well. And this is something you can not "rip off". At least not without actually experiencing the finished product.

But a really aggressive marketing campaign which actually takes considerable energy and resources does only make sense when there is already something playable. Unless your release date is already scheduled, there is no reason yet to push your product into your customers faces.

---
Tags: release
---


# Question
Title: Inherited property in derived class reference only base class
**\[Context\]** I am developing a game in Unity, and wanted to make a Game Manager. Like many examples out there, it uses a Singletron design pattern. But i have several other Managers, all using Singletron pattern, so i decided to make a Singletron base class and make all the managers derive from it. When trying to access the Instance property declared in Base Class within one method in Game Manager derived class, the Instance property refers to the Singletron base class, which is expected.

But it\`s not the behaviour i need. I have tried to look for alternatives, but everytime i found a possible solution, i have to declare the member variables/properties in the derived class, and there would be no need to a Singletron Base Class.

I have also looked for generic alternatives (Singletron \< T \>) but it was not clear how to use these without the need of another script calling it, which would be nonsense since the Game Manager should be the object to manage the game. I could use something like a root game object to creat the managers is instances, but it feels like a ugly and inelegant solution.

The managers are all coded, and this refactor would improve code maintenance, in future.

**\[Code from Singletron Base Class\]**

```
public abstract class Singletron : MonoBehaviour
{
    public static Singletron Instance { get; protected set; }

    protected virtual void Awake ()
    {
        if (Instance == null) {
            Instance = this;
        } else {
            Destroy (gameObject);
        }

        DontDestroyOnLoad (gameObject);
    }
}

```

**\[Pertinent code from Game Manager Derived Class\]**

```
public class GameManager : Singletron
{
    public List<GameObject> gameObjectsList;

    public static void SomeMethod()
    {
        foreach (GameObject go in Instance.gameObjectsList)
        {
            go.DoSomething();
        }
    }
}

```

**\[Question\]** What can i do inside Singletron Base Class to make the Instance.gameObjectList refers the actual class (in example, Game Manager Derived Class) so that i could use the gameObjectsList? Should i cast it to the pertinent manager inside the method (which seens like an inneficient option)?

Thanks in advance!

**\[Edit\]** Looking into design patterns page in wikipedia, i found another design pattern related to singletron. In my case, each manager follows the singletron pattern, but its somewhat equivalent to my singletron base class following a Multiton Pattern

# Answer
> 2 votes
After some research, i found these related posts that helped me out:

But their codes seems to have some overkill features. Cleaning it up a bit, i ended up with this code. I noticed that my difficult with the generic elements was not using the where clause to restrain the derived class.

**\[Code for Singletron Base Class\]**

```
public abstract class Singletron<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance { get; protected set; }

    protected virtual void Awake ()
    {
        if (Instance == null) {
            Instance = this as T;
        } else {
            Destroy (gameObject);
        }

        DontDestroyOnLoad (gameObject);
    }
}

```

**\[Usage in Game Manager Derived Class\]**

```
public class GameManager : Singletron<GameManager>
{
    public List<GameObject> gameObjectsList;

    public static void SomeMethod()
    {
        foreach (GameObject go in Instance.gameObjectsList)
        {
            go.DoSomething();
        }
    }
}

```

I tested it and works. What do ou guys think of it?

---
Tags: unity, c#, inheritance, polymorphism, refactoring
---


# Question
Title: Adding multiple game objects into a prefab
Is it possible for one prefab to contain multiple game objects, preferably in a parent-child relation. I am making a complex enemy that I want to separate into a couple of game objects with separate sprite renderers, scripts and other parameters. This would simplify the code I need to write for each of the elements. I know I can create one (the parent) object, and then instantiate the others in the Awake() or Start() methods, but I'm asking if there is a way to create a prefab that would contain all of the necessary elements (so I can create the entire thing with one Instantiate() call.

Thanks

# Answer
> 6 votes
As already commented, creating a prefab with one or multiple child objects works without any modification. But keep in mind - if you delete one or many child(ren) it will break the instantiated prefab's connection to the prefab. Once the connection is broken, changing the prefab will not apply to the instantiated prefabs.

---
Tags: unity, c#
---


title: How do I wait to execute code?

text:
# Question
Title: How do I wait to execute code?
I'm trying to make a relatively simple elevator (which essentially teleports the player), but I don't want it to instantly teleport them. I want the player to enter the collider, wait 2-3 seconds, and then do it to take make it seem somewhat more natural.

My code thus far:

```
using UnityEngine;
using System.Collections;

public class Teleporter : MonoBehaviour
{
    public GameObject TeleportTo;
    //public Material NewSkybox;

    void TimerInvoke()
    {

    }

    void OnTriggerEnter(Collider other)
    {

        Vector3 displacement = other.transform.position - this.transform.position;

        other.transform.position = TeleportTo.transform.position;
        other.transform.position += displacement;

        //RenderSettings.skybox = NewSkybox;
    }
}

```

Also if possible I'd like to stray away from coroutines. How should I do this?

# Answer
> 5 votes
I usually do that with Coroutines, but since you were very specific that you want to avoid them, maybe in your case you could try something quite simple like:

```
float delay = 0;
bool trigger = false;

public Update()
{
    if (delay > 0) delay -= Time.deltaTime;
    if (delay <= 0 && trigger) TeleportPlayer();
}

void OnTriggerEnter(Collider other)
{
    delay = 3;
    trigger = true;
}

void TeleportPlayer()
{
    Vector3 displacement = other.transform.position - this.transform.position;
    other.transform.position = TeleportTo.transform.position;
    other.transform.position += displacement;
    trigger = false;
}

```

Of course, adjustments can be done depending on how much time you want to wait. Also, consider that deltaTime is not the same every frame, so if you need scientific-level precision for your waiting, some tweaking would probably be required. But I think you got the idea of what the code is doing.

Finally, maybe also of your interest, see this implementation of a WaitUntil function that was created precisely to avoid Coroutines: http://theinstructionlimit.com/a-replacement-for-coroutines

EDIT: although the answer had only the intention of giving a basic idea on how to handle what the OP needed, I decided to include the bool variable "trigger" as a simple way to avoid the code to start the desired action (in this case, the fucntion "TeleporPlayer") when the code is initialized. That way, the life of future learning readers becomes easier.

# Answer
> 4 votes
You can also use Invoke to achieve.

```
void OnTriggerEnter(Collider other)
{
    Invoke("TeleportPlayer", 3f);
}
 void TeleportPlayer()
{

    Vector3 displacement = other.transform.position - this.transform.position;

    other.transform.position = TeleportTo.transform.position;
    other.transform.position += displacement;

    //RenderSettings.skybox = NewSkybox;
}

```

# Answer
> 3 votes
Use Coroutines. You can see `yield return new waitforseconds(3);` in the TeleportPlayer method. That will wait 3 seconds before teleporting the player. Remember though, it only halts execution of the next line within the coroutine. All other methods continue to be executed.

```
 void OnTriggerEnter(Collider other)
        {
           StartCoRoutine("TeleportPlayer");

        }

IEnumerator TeleportPlayer()
{

            Vector3 displacement = other.transform.position - this.transform.position;
      Yield return new waitforseconds(3);

            other.transform.position = TeleportTo.transform.position;
            other.transform.position += displacement;

}

```

# Answer
> 2 votes
Of course, you can do it in code, but my approach is a little more "natural".

On your example - elevator - I will do something as follows:

* When player enters elevator, play animation (fe. closing doors)
* In this animation, at the end I would place code for "teleporting" player.

So you don't need to tweak everything by code, but you would do this in animation, so it's easier and more natural way.

---
Tags: unity, c#
---


# Question
Title: undefined reference to std::__throw_out_of_range_fmt
after some time with oxygine i have decided to start learning SFML, i configured codeblocks to link the header files and .so files, and whenever i try to compile i get this error:

```
||=== Build: Debug in shouldWorkNow (compiler: GNU GCC Compiler) ===|

SFML-2.3.2/lib/libsfml-graphics.so||undefined reference to `std::__throw_out_of_range_fmt(char const*, ...)@GLIBCXX_3.4.20'|

||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

```

the SFML package came from their website, under the gcc 64bit for linux, the files are DEFINITELY linked as i used a hundred tutorials on the Internet and youtube.

(mint 17.2 Rafaela | default gcc from apt-get | sfml 2.3)

# Answer
> 2 votes
it is possible that the SFML package was compiled with another/newer compiler. Try to install the gcc4.9,

```
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt-get update
sudo apt-get install gcc-4.9 g++-4.9

```

---
Tags: c++, sfml
---


# Question
Title: How can I render all objects behind a plane with a specific transparency value?
I have a game where there a multiple floor levels between the player switches. The floor is not present everywhere, so you can look through it. When 'working' (playing, building stuff, etc.) on a specific floor I want to add a transparency value to everything that is NOT on the current floor. Ho can I accomplish that, and what is the best/most efficient way to do that?

# Answer
> 2 votes
Draw the floor (transparent part) after drawing the rest of the objects with transparency blending turned on.

Otherwise you can pass a currentFloor uniform to the fragment shader and a floor attribute to the objects so you can add the extra shade conditionally.

# Answer
> 0 votes
Order of rendering is important.

You need to draw the objects in order, draw objects far away first. Using alpha values ofc, for an example alpha = 0.5.

Think this is called back to fron rendering.

So if you stand at X, floor is |, object are 1,2,4...

X | 1 2 3 4

Then you render 4, 3, 2, 1 and finally the floor |.

---
Tags: rendering, transparency
---


# Question
Title: What is the graphical effect occurring to non-mipmapped distant textures called?
We all know about mip-mapping. It reduces texture quality when a texture is further away.

Without mip-mapping, a texture appears to "flicker", like the top of the mountain here:

Is there any specific name for it?

I want to write a sentence like "I applied mip-mapping to solve the \___ effect", or "This is known as \___, and occurs when mip-mapping is not used".

# Answer
What you're looking for is aliasing. It's little different from aliasing of hard 3d edges drawn on screen. Both come from rendering pixels too strictly, with one color or another. Antialiasing methods like mip-mapping only help blurring the edges so that intermediate colors are rendered. This can be applied to single textures but also to the whole screen.

Note however that mip-mapping is not the only solution to this. You can use other procedural interpolation algorithms too.
> 20 votes

# Answer
Aliasing artifacts/moiré patterns
> 13 votes

# Answer
> Is there any specific name for it?

That *flicker* you are talking about is called in this certain case **moiré effect / pattern**. It's a form of spatial aliasing as already mentioned in other answers. However, aliasing itself can result in a lot more things than just moiré patterns.
> 6 votes

# Answer
I have heard the term "popping and boiling" applied to the aliasing you're showing on that mountain in the background. It is not a mathematical term, but it is descriptive. So aliasing would be what you'd write your paper about if you wanted to invent a different fix for the problem and use it to get money (grants, academic promotion). "Popping and boiling" might be what you'd call it in a demo (for VC money).
> 1 votes

# Answer
I'd just like to add that there's another side-effect of not using mip mapping: Not only will you get the hideous aliasing (see the Nyquist theory for what is going on), you will probably also get a reduction in performance as the texture accesses become incoherent and thrash the memory/cache system of your GPU.
> 0 votes

---
Tags: antialiasing, terminology, mipmaps
---


# Question
Title: In PHP, how do I implement multiplayer "rooms" for a turn-based game?
I'm working on a multiplayer checkers game. I want to let players choose another connected player and invite him to play. I have a working game engine and rendering, but I'm stuck on the multiplayer part.

This is specifically a web-based game.

* How can I know whether a player is connected?
* How can I detect when a player closes the browser, and set them to disconnected?
* When a player sends an invitation to another, how do I let the first player know whether the other accepted?
* How do I connect 2 players on a same game and send their moves to each other?

# Answer
> 1 votes
> How can I know whether a player is connected?

There are several ways, but you could use an AJAX request that pings every 10 seconds. If the user last timestamp was in the last 10+1 seconds, he should still be 'connected'.

> How can I detect when a player closes the browser, and set them to disconnected?

Use the above solution, the user simply times out if there is more than 10 to 30 seconds since last AJAX request.

> When a player sends an invitation to another, how do I let the first player know whether the other accepted?

If you have this properly set in the database, I think this is obvious, you should think a little harder if you know basic php & mysql.

> How do I connect 2 players on a same game and send their moves to each other?

You send AJAX requests to the server, and the server responds to each player, the other player moves. You better use Web Sockets if you want a near real-time interaction

# Answer
> 0 votes
When you want to have a pure ajax solution, the clients need to send updates about their own state to the server in regular intervals in form of `XmlHttpRequest`s. The server then responds to these request with the current state of the game and the other clients.

A disconnect can be detected by noticing that a client doesn't send updates anymore for an extended amount of time.

But notice that WebSockets are usually a far superior solution for games because:

1. both client and server can send messages whenever they want. The server can push events immediately and doesn't need to wait until a client sends a request.
2. the server gets notified when a client disconnects by closing their web browser.

# Answer
> 0 votes
Most modern web based games (and platform too) are based on UDP socket connection, it's like a tunnel with the server, each of them has a socket id, so you can either interact or identify every connection. Using sockets resolves all your troubles, it sends an action when users connects, disconects or emit's any call.

The easiest way to build a sockets app is with nodejs, you can build the sockets infrastructure in node and use your current php services from it.

I developed a morts that uses nodejs to connect clients and manage game rooms, python scripts to manage map objects and c++ "services" to do the hard calculations.

If you wanna stay with pure php you can build your own socket infrastructure, there are good documentation, just google "php socket".

Game rooms relative...In my online game i wrote an object called game that had all the code of a game and an array called Games that stores all the games, so, when two players enteres the lobby it runs something like this:

```
Games.push(new game(GAME_UID,PLAYERS,...));

```

and with an eassy search function you can associate games to its unique GAME\_UID, PLAYER\_ID or whatever.

Good luck ;)

# Answer
> 0 votes
**1.** You could add a table to your database named rooms with a one-to-many relationship and do ajax calls to the database whenever a user enters or leaves a room.

**2.** javascript has these useful event listeners.

```
window.onbeforeunload = function() {
return "Hey, you're leaving the site. Bye!";
//or an ajax call to the database which deletes the user connectivity.
};

```

**3.** To make it more real-time you could add a javascript timer to tell which checks the database for the invited user's response to the invitation.

How do I connect 2 players on a same game and send their moves to each other?

**4.** You could do this with database relations. record players in a table and use the foreign key to join their moves.

This is if you don't have time to be able to learn websockets and other asynchronous web technologies. which allows for better structural design of your game.

---
Tags: javascript, multiplayer, php, turn-based, ajax
---


# Question
Title: What are do's and don'ts on published APK for alpha and beta testing and how to manage it in Google Play for developers?
Before the official public release or publishing the first prototype game, I learned about alpha and beta testing in order to gain feedback and fixes needed to improve or correct the game's system. I have some several questions regarding this feature on development feature on Google Play where game developers can publish games:

* *Is it okay include the actual ad banner display (via AdMob) on game screen during publishing for alpha or beta testing in Google Play developer section?*
* *My alpha version is published but why I can't see the published app on Google Play store? I set it for open alpha testing, with only 1,000-1,500 random users.*
* *After I published for the alpha testing, I tried **this link** download it via different user but it appeared nothing (even the URL to the APK install download) except the main Gmail account I used as my main source for collecting feedback and as a username to gain access to Google Play Developer. How will ensure to other users to download and test the app during open alpha testing version via invite links?*
* *Lastly, whatever the APK version no. for alpha would be the same for beta and official release or not?*

# Answer
> 1 votes
1. As far as I'm aware there's no restriction on whether or not you can show ads in alpha/beta apps - the fact that it's alpha/beta only limits who can download it, and nothing else
2. Only apps that are in production can be found via searching on the Google Play Store - if it's in open alpha/beta then people need to have the testing link (the one in your 3rd point) to be able to download it, and if it's in closed alpha/beta then people have to join the appropriate Google+ community and have the testing link. Seeing as your app is in open alpha, the only way for people to download your app is for you to give them the testing link
3. That link works fine for me, so I'm not sure what the problem is I'm afraid
4. It's fine to have the same version number - just promote the app from alpha/beta to production via the Google Play Developer Console

---
Tags: publishing, google-play, alpha, beta, test-driven-development
---


# Question
Title: In unity 5 export package is not working correctly
I am using unity 5. I Created an objects with layer names. I tried to export a package. After Exporting, i import the package in new project and ran the project its not working. observed that objects layer name is missing for all the objects. i attached the screenshot with this.

Before Export :

After Import the Exported Package :  In layer drop down box no layer name was found. only the default layer name is available. if anyone knows the answer please tell me.

# Answer
> 1 votes
Unless you import the project settings you will have to create the layers in the new project. In some cases it would be nice if the layers names would export/import being recognized as a required resource in the package. Especially if say it was a unity asset package that needed it and someone without knowledge just bought the package.

Now if you copied the whole folder zipped it up and the new user drops the files in including the settings they will get the project settings will overwrite box. and if you ok it the layers will be added along with everything else such as the tags and even the editor windows and all the settings.

---
Tags: unity
---


title: Spawn skateboard under player

text:
# Question
Title: Spawn skateboard under player
I would like to know whys in which one can spawn skateboard under player like we see in subway surfers.

My best two guesses are, 1.Spawnning skateboard and then making it child of player. 2.Changing current child prefab of player with skateboard attached prefab.

With first approach ,its get complicated to know exact character's leg position.

What you think is the best way? if you know any other good way then please mention .

Thanks in advance

# Answer
You can create a new empty game object as a child of the player and align the board up to attach in such a way similar to how you would attach a weapon or anything. Once you got that working you could either instantiate the object on the game object position or simply enable and disable the board when needed.
> 1 votes

---
Tags: unity
---


title: LibGDX Deployment questions

text:
# Question
Title: LibGDX Deployment questions
A few questions from LibGDX newbie:

* How do you deploy a Mac/Windows app? If Mac app, can this be deployed to Mac App Store?
* Do you need to pay monthly (for RoboVM) for iOS development/deployment?

I am using Android Studio. Thanks!

# Answer
> 1 votes
Answering (just) point number 2. RoboVM is free, but if you want the Debugging capabilities you need to shell out some money. Fortunately, right now for indie developers this fee can be null since there's some sort of agreement between libGDX and RoboVM.

You need to get your free RoboVM license, and then apply for the indie "upgrade".

No small letters, is even says: "The license will be automatically renewed every year. You can use it for as many games as you want, no strings attached."

More info here: http://www.badlogicgames.com/wordpress/?p=37621

# Answer
> 0 votes
With libGDX, you can either create a runnable JAR file or a native application file. To get your app on the Mac App Store, you will need to go with the second option. This can most easily be done with a tool called packr. What it does is it packages your JAR file (all the code and assets) with a JRE (Java Runtime Environment) into a standalone .app file that can be run on Mac. For more information on how to create a Windows/Mac app this wiki page should help you.

To deploy apps to the Mac and iOS App Stores, as well as test your apps on physical iOS devices, you will need to pay the yearly Apple Developer fee of 99 USD. This should work with libGDX apps.

RoboVM seems to be free for commercial use with libGDX, so the yearly 99 USD Apple License is the only required fee.

---
Tags: libgdx, ios, macos
---


# Question
Title: Earth and sun - How to make the sun revolve around the earth in the following code?
I want to imitate the planetary system with Earth and Sun drawn as solid spheres on the same window. I have drawn the two: the earth as the bigger sphere and the sun as the smaller sphere.

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

Here is the code so far:

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

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

glFlush();
glutMainLoop();

}

```

# Answer
> 2 votes
Lets approach this from outside the code. You are attempting to have user input make on object revolve around another. This means that we have two objects, the fixed object A, and the revolving object B. For A we draw it at one location and it never changes. For object B we start it at an initial position and update it's position every tick based on user input. Let's start with a simple path of movement and have B move on a circle centered at A. Recall that any point on a circle can be looked at as (r cos(x), 0, r sin(x)) where r is the radius and x is the angle, note that our y axis is 0 because we are rotating about it. So every time the user presses a key you can rotate by changing the current angle that object B is at.

Steps make it a bit easier.

Initialize position of objects A and B. Initialize angle of B to be 0.

User Input If (KeyDown = "A") angle x += 1 // degree, radian : your pick else if (KeyDown = "B") angle x -= 1

At Each Tick Draw B at (r cos(x), 0, r sin(x))

---
Tags: opengl, rotation
---


title: Sound and Unity 5

text:
# Question
Title: Sound and Unity 5
I want to work on sound in games, but I don't have any experience in scripting, only in sound design for film. Some friends that do know scripting are starting to learn in Unity 5, and my part would be working on sound. So my question is do I need to learn the whole C#, as it's used in Unity or can I learn only the part that affects my part of work? Or does this work in this way anyway?

# Answer
> 2 votes
That depends on how you distribute the workload on your team and how much you want to add to the project.

Someone who does nothing except producing audio files and never even touches the unity editor can still add value to the team. Just ask the other team members what sound effects they need, provide them with the files and let them worry about getting the engine to play them. (this is actually the only task described here I, as a programmer, feel completely clueless about and wouldn't even know where to start).

Someone who understands what all the settings in the AudioSource component actually do and what all those filters in the audio mixer are good for could add even more value because that person could then be responsible for using the Unity editor to set up appropriate audio sources for everything. Someone with a background in sound design might be able to make better creative choices in this regard than a layman.

Someone who also knows some scripting can control when and how individual audio clips are played and can use that to take full control of the audio experience of the game while others can concentrate on other aspects.

---
Tags: c#, scripting, unity, sound, sound-effects
---


title: OpenGL not rendering textures

text:
# Question
Title: OpenGL not rendering textures
i'm using OpenGL 2.1 with SDL2.0 and i'm trying to render a texture, using this steps: load the image:

```
    Image* image = new Image();

image->image = SDL_LoadBMP(path.c_str());

if (!image->image)
    throw std::runtime_error(SDL_GetError());

return image;

```

and then generate a texture for it:

```
Texture2D* Texture2D::fromImage(const Image* image){
GLint format;
Texture2D* t2d = new Texture2D();

glGenTextures(1, &t2d->tid);
glBindTexture(GL_TEXTURE_2D, t2d->tid);
t2d->size.setWidth(image->getWidth());
t2d->size.setHeigth(image->getHeight());

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

switch (image->getBPP()){
case 24:
    format = GL_RGB;
    break;
case 32:
    format = GL_RGBA;
    break;
default:
    throw std::runtime_error("Unsurpoted pixel format!");
    break;
}

glTexImage2D(GL_TEXTURE_2D, 0, format, image->getWidth(), image->getHeight(), 0, format, GL_UNSIGNED_BYTE, image->getPixels());

return t2d;
}

```

and then i try to render it:

```
void Painter::drawTexture(Texture2D* texture, const SizeF& size, const PointF& position){
camera.set(camera.getWidth(), camera.getHeight());

texture->bind();//only call glBindTexture(GL_TEXTURE_2D, tid);

glBegin(GL_QUADS);
glColor4f(color.getR(), color.getG(), color.getB(), color.getA());
glTexCoord2f(0.0f, 1.0f);
glVertex2f(position.getX(), position.getY());
glTexCoord2f(1.0f, 1.0f);
glVertex2f(position.getX() + size.getWidth(), position.getY());
glTexCoord2f(1.0f, 0.0f);
glVertex2f(position.getX() + size.getWidth(), position.getY() + size.getHeight());
glTexCoord2f(0.0f, 0.0f);
glVertex2f(position.getX(), position.getY() + size.getHeight());
glEnd();
}

```

but all i got is box with the defined color, i don't understand why, i have already followed this steps before to render a texture, but this time it is not working, i'm not using glEnable(GL\_TEXTURE\_2D) because i read that this is not necessary, but when i do call it i got the error code 1282, but i got no errors on the textures creation, can someone give me some light here? thanks

# Answer
Explicitly enabling texture samplers is not necessary if you're drawing using the programmable shader pipeline (since whether or not you're sampling from textures, and what type of sampling to do across those textures is explicit in the shader code that you're using)

However, based upon your code sample you appear to be rendering using the fixed function pipeline, in which case you do need to explicitly enable (and disable) each texture sampler that you plan to use, to tell the fixed function pipeline what you expect it to do.

So you want to do something like this, in this order:

```
glActiveTexture(GL_TEXTURE0);      // Hey OpenGL, we're about to give commands for texture sampler 0.
glBindTexture(GL_TEXTURE_2D, tid); // when the currently-active sampler samples from a 2D texture, this is the texture to use.
glEnable(GL_TEXTURE_2D);           // the currently-active sampler should actually use the bound 2D texture.
//
// -- draw stuff here
//
glDisable(GL_TEXTURE_2D);          // disable currently-active sampler's 2D sampling again, so it doesn't affect any future draw calls.

```
> 2 votes

---
Tags: opengl, c++, textures, sdl
---


# Question
Title: How to make "Shaky mouse cursor" Before shoot the target Like in a Dart Game?
I develop a shooting game. To make it harder I want to make the reticle shaky/move randomly.

I use Robot class to move random as suggest here.

But I modified it by adding an infinity loop and by surrounding it in a new Thread.

The shaky mouse cursor is running well, but I can't shoot the target because the infinity loop holds mouseClicked(MouseEvent e) to make a response. I'm confused because I've already tried to make a special thread for the random displacement of the mouse cursor but it still makes no response for my mouseClicked(MouseEvent e).

Any idea/solution please?

**UPDATED POST :** i include the code here :

In GPanel.java :

**1. For handle input from mouse hardware (from user when clicked the mouse)**

```
@Override
public void mouseClicked(MouseEvent e) {
     int x = e.getX();
     int y = e.getY();
     System.out.println(ter.getInnerX()+"---------------"+ter.getInnerY());
    System.out.println(x+"=========================="+y);

   if(x>=ter.getInnerX()&&x<=ter.getInnerX()+54)
   {
       System.out.println("masuk");
       if(y>=ter.getInnerY()&&(y<=ter.getInnerY()+95))
       {
           System.out.println("kena");
       }
   }
}

```

**2. Robot class Implemented :**

@Override public void run(){

```
while (true){
    try {
        updateCar();
        checkCollision();
        keylistener();
        Thread.sleep(20);
Robot robot = new Robot();
Random random = new Random();
boolean masuk=true;
int SECONDS=40;
while (true) {
    if(masuk)
    {
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x+1, MouseInfo.getPointerInfo().getLocation().y);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x+1, MouseInfo.getPointerInfo().getLocation().y+1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y+1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x-1, MouseInfo.getPointerInfo().getLocation().y+1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x-1, MouseInfo.getPointerInfo().getLocation().y);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y-1);
        masuk=false;
    }
else
    {
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x-1, MouseInfo.getPointerInfo().getLocation().y);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x-1, MouseInfo.getPointerInfo().getLocation().y-1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y-1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x+1, MouseInfo.getPointerInfo().getLocation().y-1);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x+1, MouseInfo.getPointerInfo().getLocation().y);
        Thread.sleep(SECONDS);
        robot.mouseMove(MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y+1);
        masuk=true;
    }

}
    } catch (Exception e) {
        e.printStackTrace();
    }
    repaint();
}}

```

Number 1 for detect user's input by click the mouse.

Number 2 for implemented Robot.class to make shaky mouse cursor.

Both of number 1 and 2 are in GPanel.java

# Answer
Try Change `mouseClicked` into `mousePressed`. Seems work for me...

Here is the complete code :

```
@Override
public void mousePressed(MouseEvent e) {
     int x = e.getX();
     int y = e.getY();
     System.out.println(ter.getInnerX()+"---------------"+ter.getInnerY());
    System.out.println(x+"=========================="+y);

   if(x>=ter.getInnerX()&&x<=ter.getInnerX()+54)
   {
       System.out.println("masuk");
       if(y>=ter.getInnerY()&&(y<=ter.getInnerY()+95))
       {
           System.out.println("kena");
       }
   }
}

```
> 2 votes

---
Tags: java, algorithm, software-engineering
---


# Question
Title: How to find out the vertices of the polyhedron formed by the overlapping area of two rotated boxes?
What is the most efficient way for finding out the vertices of the polyhedron formed by the overlapping area of two rotated 3D boxes?

If it is still confusing what I mean by "polyhedron formed by...", see the picture below:

Of course, in that picture the boxes are still not rotated\*.

But imagine I rotate both. I would like to identify the vertices that form the inner area of the overlapping.

What is the less expensive way for doing so? (I'm using C#, but can read C++ well).

\*The picture comes from a blog post that teaches how to get the overlapping area of two 3D AABBs: http://blog.meltinglogic.com/2015/04/aabb-overlapping-area/

# Answer
> 3 votes
In the end, here it goes in detail the way I myself figured out to get what I've asked (also inspired by @snake5's comments):

1a) for each of the 12 edges (line-segments) of one box, we test first if it is entirely within the other box. If it is, we already save its both vertices in the final list of vertices that form the desired polyhedron.

1b) if it is not, then we test if such edge pierces (intersects) one or two of all the 6 faces (planes) of the other box (it can't intersect more than two faces). If any intersections exist, we save the intersection point or points (vector3) in the final list of vertices that form the desired polyhedron.

2) then, for these edges (line-segments) which intersected the other box, we take their two vertices and test if they are inside the other box. The ones that are must be also saved in the final list of vertices that form the desired polyhedron.

Although I am not sure whether that's the most efficient way of solving the problem, so far it does not seem too bad performance-wise: the first step, in the unlikely worst case, has to perform 144 line-segment/plane intersection tests and 8 line-segment/plane calculations of intersection points. The second step, in the worst case, has to perform 16 point-within-box test.

In case anyone has any ideas for optimizing that, feel more than welcome to comment that I will update the answer. Or if someone comes up with a better solution, I encourage to put a better answer: I will be glad to uncheck this as the accepted answer. I myself, if this solution proves too heavy, will come back and put a follow up question.

# Answer
> 1 votes
In an intersection, all of the surface planes involved form a new shape defined by these planes.

To find the points, formally there's vertex enumeration. However, I find it easier to just skip all math theory and do 4 nested loops over the planes, intersection of the first two planes gives a straight line/ray, which is checked against the third to obtain a point, which then has to be checked if it's inside the shape (= it's behind every plane).

All generated points that pass the test are the vertices of the polyhedron. In practice though, remember that there has to be some room for numerical errors (merge similar points and allow for some bias when projecting points on plane axes).

There's also another implementation of vertex enumeration that I could find, perhaps it can help: http://library.wolfram.com/infocenter/MathSource/440/

---
Tags: c#, geometry, intersection, computational-geometry
---


# Question
Title: How can I scale up sprites but maintain visual quality?
I am using WebGL. I have an isometric grid which contains tiles. Some have 'tree' sprites on them. If I have my tree sprite loaded from a texture with a fixed resolution, when I zoom into the grid (scale things up), the sprite texture looks poor. How can I render sprites such that quality is maintained when the player zooms in?

Some provisos:

* I can't use vector graphics, as the textures are far too detailed.
* The scaling needs to be smooth.

# Answer
Assuming you are using the DOM (not canvas) for your Isometric grid, these ways may be possible:

* Draw your Images at 10× the highest resolution you display them at, e.g. (1200×1200 for an image being displayed at 120×120).
* Vector (SVG) is another choice, but fine detail is an issue for them, and, somewhat, performance difference also (Rasterising the image everytime you scale it down by a fraction of a pixel).
* Spritesheets of different sizes for one sprite.
* Everything can be relative to the size of the image/sprite, e.g. sprite is 44×44px and the isometric squares are 32×32px so the sprite is larger than the tile (e.g. boss enemies) or the sprite is 22×22px or 16×16px for infantry or player sprites. This can make scaling a lot smoother and easier to work around, everything divisible by 8 (a Byte) or 2 (2 bits) seems to do the trick.
> 2 votes

# Answer
You can't. No processing can add quality or resolution to your textures if it wasn't there from the beginning. If you really need better quality, then you must use bigger assets. Then your question will become: "how to save quality when scaling textures down", and the answer will be - by using mipmaps.

You can cheat by:

* blurring pixels when they become too big (looks better for realistic look),
* never blurring pixels when they become too big (looks better for pixel art)
* for single color images you can use distance maps, which is basically a way of packing flat vector graphics into a texture and displaying them with a fragment shader. In practice, this is only useful for displaying fonts.
> 2 votes

# Answer
If you are doing webgl and can make pixel shaders, check out signed distance textures. They are textures but scale like vector graphics. http://blog.demofox.org/2014/06/30/distance-field-textures/
> 1 votes

# Answer
What you need, at least I guess, is an implementation of **mipmaps** for your 2D trees.

A mipmap are a large frame in which the same object is present in different resolutions. For example, you can have a texture with a 1024x1024 tree image, next to it another one at 512x512, then a 256x256 one and so on... Then your tree object checks for the zoom level the user is currently experiencing (you can easily implement a method for that), and uses the right frame for rendering the tree.

Result is, if you zoom out enough won't need to draw a high-res image, whilst a 128x128 would be enough. On the other hand, if the user zooms in at a 10x level, he expects to see more detail than a 1x zoom view; and he would be bored to see just giant pixels, independently from smoothing filters (bilinear, trilinear...) applied.

So, actually, you draw inside the same box area (smaller or bigger due to zoom level), but:

* Drawing lower-quality images in a small box is faster than drawing a high-quality image inside the same box;
* Drawing high-res images when zooming in resolves the problem you asked for: better quality on zooming.

Also, always remember that downscaling when drawing is slower than upscaling; this is important to decide when a low-res frame should be replaced by a high-res frame (tipically you do this just before the low-res frame would be upscaled, in order to not lose visual quality on a gamer's point of view).

Sources: good old Wikipedia - Mipmap
> 1 votes

---
Tags: textures, javascript, sprites, webgl, scale
---


# Question
Title: Creating force shields: the most efficient way of deforming/reshaping a simpler convex mesh so it envelopes a complex mesh?
So, the best way I can think of how to explain what I need is the following (images used here are just random images found trough google image search).

What I am trying to create **during run-time** is pretty much the same as a force shield that envelopes a robot or a space ship in many different futuristic types of games.

However, considering that these robots or ships have a shape that is unknown in advance, I don't want to just use a sphere-mesh around the ship or just assign a shield-shader directly to the ship mesh like in the pictures below:

I want to end up with a shield that is formed by a mesh that loosely represents the shape of the ship. Something like what can be seen in the pictures below:

However, I don't need those shields to be concave like in that pictures. It can be a convex mesh.

So far, what I've tried was to generate a sphere or a cylinder around the complex mesh (robot/ship), loop trough each vertex and try to approximate to the complex mesh. However, that is severely inefficient and gives non-smooth results.

Would you happen to have any idea, code sample, tutorial links, article references or anything on how can I proceed to get what I want in an efficient manner? The shields do not have to very detailed in terms of polygons. In fact, the less the better.

I am currently using C#, but I can handle C++ as well. Thanks in advance.

# Answer
> 4 votes
Each of your images describes a different algorithm. I would say the top two should not even be in the question. Bottom right is too angular to look good in-game, it looks like luggage in plastic cling-wrap. **Let's focus on bottom left, the best looking approximation of the original mesh.**

I think you want the **3D Minkowski sum** of the original mesh, either (1) by getting a convex hull first and then applying the Minkowski summation algorithm to it, or (2) just do M-sum on its own. For a convex base mesh, the latter will have convex spaces, and inner corners may appear "pinched", see for example the space between the two children's heads at top left:

So you may do wish to do some smoothing after summation, depending on the sort of look you're going for. You'll also notice in the image above that a cubic mesh has been summed against the original mesh, which results in cubic artifacts, while in the image below, different operators are shown. You'll want pointwise or spherewise summation as shown for the dinosaur and bunny:

This technique is common in computational geometry and GIS applications, so you can find implementations in typical comp geom libs like GJK, CGAL etc. You could even download such and use it as proof of concept. I can't guarantee the performance on this will be great, since often those libs are not geared to real-time use. But it gives you a place to get started and you can a write a realtime implementation on your own (may require mesh reduction to get the required speed).

Note that *voxelised Minkowski sum* can yield better performance than traditional, more exhaustive approaches because the vertex count is strictly limited by the number of voxels. Google will help.

# Answer
> 4 votes
**Sliced 2D Convex Hulls** Slice through the mesh (polygon + axis-aligned plane intersection), getting the convex hull of each resultant 2D polygon, e.g. from tip to tail for a ship like that in your image, or from head to toe in a humanoid - as you'd slice a carrot :) These could be equidistant slices or spaced according to some heuristic, but will describe the mesh with a good amount of accuracy albeit leaving out certain convex details. To clarify: You're not actually cutting up the original mesh, instead you're just taking scans through it's geometry, much like a CT scan - slices are frequently used in medical imaging applications. You can then scale each of these slices up, join / triangulate / tesselate them, and cap the mesh at each end with additional vertices.

**EDIT** In slicing down the length, you need to first get a cross section as though you are cutting the ship in left and right halves. Then calculate the 2D convex hull of *that*. The vertices of *that* 2D convex hull can be used to decide where you slice from nose to tail (like ribs). If not done, local maxima like spikes on the ships surface may be missed. The actual tip-to-tail slices may or may not be convex, but I guess skipping the convex hull calculation on these will result in lower cost overall.

This might suit what you're trying to do quite well, given your desire for efficiency - which is easy to tweak based on the number of slices - and your flexibility around concavity / convexity. **EDIT** Since you don't need convexity, this will likely be faster than general purpose quickhull, and a bit easier to conceptualise / configure / debug / control performance. But quickhull might just be more direct.

# Answer
> 2 votes
For a nice artistic look you can voxelize your model in a grid them perform marching cubes. That is you'd end up with a shield with as little or as much detail as you want depending on the grid size. You can also perform a post-processing step on the voxelized grid data to smooth out the mesh before generating the triangles. Or perform a step afterwards to remove unneeded vertices or smooth the mesh (there's probably other algorithms) to get a different look.

# Answer
> 1 votes
One method is to create a mesh by iterating over every vertex of your object and make a vertex normal to the objects surface at that point with an arbitrary magnitude (magnitude of 0 means the shield is the surface). As mentioned this takes time O(cN) where N is the number of points in your original objects mesh.

Now if you want to handle any possible shape or configuration you can attempt to create an easy shape, for example spheres, for each different "part" of the object, then combine the meshes so they do not do not overlap inside the object. If you can efficiently (tree hierarchy) determine the different part of the ship and remove any points in the other mesh this might get where you are trying to go.

---
Tags: geometry, computational-geometry
---


# Question
Title: Finding new position after collision with multiple colliders
What is the most accurate way to find the correct position to where a moving character should be re-positioned as a collision-resolution, after it has collided with multiple colliders?

The figure below illustrates the situation. The rectangles in black are the walls, the rectangle/circle in blue is the moving character and the arrow in read shows the direction of movement, i.e. in this case from right to left. My set up is in 2D and I am using C# in Unity.

# Answer
I encountered a similar problem in a game of mine when defining collision physics for grenades my character throws. I found a solution that could fit your needs.

When an object (e.g. a ball) moves along its trajectory, whether or not affected by gravity, it moves from point A to point B every frame (depending on the framerate you wish, you have to deal with delta timing), giving us a hint about its velocity. If no collision occurs when moving from A to B, we just place our ball in its new position, according to kinematics (first case in the image).

If at least one collision is detected, we find a position C (we don't mind if it's a 2D or 3D model - it works the same) which is the ultimate position along vector AB where our ball doesn't collide with anything else. Though, there's a small distance missing because our ball shall travel AB distance but actually it did AC, that is smaller (second case in the image). Then we calculate two values: the remaining distance (CB = AB - AC, you just apply Phythagoras' theorem when working with *x* and *y* values) and the new direction our ball shall move towards.

If motion from A to B is computed by a script (case 1), iterating it first on AC and then on CB (figure 2) will make the ball still travel AB distance, this time according to collision detection. Having more collision points for the same path shouldn't be a big deal, we just iterate our moving script three, four, five times as we need. You can make an iterative or recursive version of this algorithm.

In my personal project, I use an iterative script which does the following operations in order:

1. If AB \> 0, check collisions between A and B
2. If no collision is detected, move object in position B
3. If collision is detected, find point C and move object in point C
4. Calculate distance CB and *new direction angle* (subscript for this one)
5. Go back to 1 using new distance and new direction angle

Hope that helps.

EDIT: If your object DOES collide with two distinguished object at the same time, get the new direction angle as vector sum of the two hypotetical angles you would compute.
> 1 votes

---
Tags: c#, collision-detection, physics, geometry, collision-resolution
---