title: Pseudo 3D curve problem

text:
# Question
Title: Pseudo 3D curve problem
I've converted CodeinComplete's Pseudo 3D road routine to use SDL2 - unfortunately for some reason the curves are incredibly jarring (both entering and leaving it).

I've also converted it to GLBasic, and get the same effect there too (although much less pronounced). I cant think of a reason for it at the moment, as it is more or less directly converted, and the X values are accumulated over the display list.

If anyone can work out why it's happening, I'll be very happy!

Video of the SDL2 problem is here : https://www.youtube.com/watch?v=ij6POR9MkfA Video of the GLBasic problem is here : https://www.youtube.com/watch?v=uzF9Nsl7Ayg

Update : There are three causes unfortunately :

1. cameraDepth was somewhat incorrect and thus produced a slightly skewed display
2. SDL2 polygon routine can only really deal with integers which, again, produces a slightly incorrect display
3. The main problem is that the road is split into 9 sections which seems to affect the calculations as the projection is based on the centre of a segment

The GLBasic code is :

```
TYPE __camera
    x
    y
    z
ENDTYPE

TYPE __pScreen
    scale
    x
    y
    w
ENDTYPE

TYPE __world
    x
    y
    z
ENDTYPE

TYPE __segmentPart
    world AS __world
    camera AS __camera
    screen AS __pScreen
ENDTYPE

TYPE __tile
    colour%
    p1 AS __segmentPart
    p2 AS __segmentPart
ENDTYPE

TYPE __segment
    index%
    curve

    segment[] AS __tile

    colour%
ENDTYPE

TYPE Utility
    PI = 3.14

    FUNCTION accelerate:v,accel,dt
        RETURN v + (accel * dt)
    ENDFUNCTION

    FUNCTION limit:value, minV,maxV
        RETURN MAX(minV,MIN(value,maxV))
    ENDFUNCTION

    FUNCTION easeIn:a,b,percent
        RETURN a + (b-a)*POW(percent,2)
    ENDFUNCTION

    FUNCTION easeOut:a,b,percent
        RETURN a + (b-a)*(1.0-POW(1-percent,2))
    ENDFUNCTION

    FUNCTION easeInOut:a,b,percent
    LOCAL cosV,v

        cosV=(percent*self.PI)*(180.0/self.PI)
        v=a + (b-a)*((-COS(cosV)/2.0) + 0.5)
        RETURN v
    ENDFUNCTION

    FUNCTION percentageRemaining:n,total
        RETURN FMOD(n,total)/total
    ENDFUNCTION

    FUNCTION interpolate:a,b,percent
        RETURN a+(b-a)*percent
    ENDFUNCTION

    FUNCTION project%:p AS __segmentPart,cameraX, cameraY, cameraZ, cameraDepth, swidth, sheight, roadWidth%, tileWidth%, loop%
        p.camera.x=p.world.x - cameraX
        p.camera.y=p.world.y - cameraY
        p.camera.z=p.world.z - cameraZ

        p.screen.scale=cameraDepth/p.camera.z

        p.screen.x=((swidth/2.0)+(p.screen.scale*p.camera.x*swidth/2.0))
        p.screen.y=((sheight/2.0)-(p.screen.scale*p.camera.y*sheight/2.0))
        p.screen.w=(p.screen.scale*roadWidth%*swidth/2.0)
    ENDFUNCTION

ENDTYPE

TYPE Road
    numTiles%
    tileWidth

    width%;height%
    stp
    roadWidth%
    segmentLength%
    rumbleLength%
    lanes%  =   3
    fieldOfView
    cameraHeight
    drawDistance%
    maxSpeed%
    trackLength%
    cameraDepth
    fps
    PI

    segments[] AS __segment
    utils AS Utility

    FUNCTION Initialise%:
        DIM self.segments[0]

        GETSCREENSIZE self.width%,self.height%

        self.PI=3.14
        self.fps = 60;
        self.stp = 1.0 / self.fps;
        self.roadWidth = 1800;                    // actually half the roads width, easier math if the road spans from -roadWidth to +roadWidth
        self.segmentLength = 10;                 // length of a single segment
        self.rumbleLength = 3;
        self.lanes = 3;                          // number of lanes
        self.fieldOfView = 100;                   // angle (degrees) for field of view
        self.cameraHeight = 1000;
        self.drawDistance = 300;
        self.maxSpeed = INTEGER(self.segmentLength / self.stp);
        self.trackLength = 0;
        self.cameraDepth = 1.0 / TAN(self.fieldOfView / 2.0)*self.PI / 180.0;
        self.numTiles = 9;
        self.tileWidth%=self.roadWidth% / self.numTiles%
    ENDFUNCTION

    FUNCTION findSegment AS __segment:z
    LOCAL index%

        index%=INTEGER(z/FMOD(self.segmentLength%,BOUNDS(self.segments[],0)))
        RETURN self.segments[index%]
    ENDFUNCTION

    FUNCTION drawSegment%:position
    LOCAL segment AS __segment
    LOCAL baseSegment AS __segment
    LOCAL basePercentage
    LOCAL x,dx,playerX=0,maxy
    LOCAL segmentIndex%

        baseSegment=self.findSegment(position)
        basePercentage=self.utils.percentageRemaining(position,self.segmentLength)
        x=0.0
        dx=-(baseSegment.curve*basePercentage)
        maxy=self.height%

        FOR n%=0 TO self.drawDistance-1
            segmentIndex%=MOD(baseSegment.index%+n%,BOUNDS(self.segments[],0))
            PRINT "X:"+FORMAT$(4,4,x)+"/"+FORMAT$(4,4,dx),0,0
            PRINT "BP:"+FORMAT$(4,4,basePercentage),0,16
        //  DEBUG "X : "+FORMAT$(4,4,x)+"\n"
        //  DEBUG "DX : "+FORMAT$(4,4,dx)+"\n"
            FOR loop%=0 TO 0
                self.utils.project(self.segments[segmentIndex%].segment[loop%].p1,(playerX*self.tileWidth%)-x,self.cameraHeight,position,self.cameraDepth,self.width,self.height,self.roadWidth,self.tileWidth,loop%)
                self.utils.project(self.segments[segmentIndex%].segment[loop%].p2,(playerX*self.tileWidth%)-x-dx,self.cameraHeight,position,self.cameraDepth,self.width,self.height,self.roadWidth,self.tileWidth,loop%)
            NEXT

            INC x,dx
            INC dx,self.segments[segmentIndex%].curve

            IF self.segments[segmentIndex%].segment[0].p1.camera.z<=self.cameraDepth% OR _
                self.segments[segmentIndex%].segment[0].p2.screen.y>=self.segments[segmentIndex%].segment[0].p1.screen.y OR _
                self.segments[segmentIndex%].segment[0].p2.screen.y>=maxy
                CONTINUE
            ENDIF

            FOR loop%=0 TO 0
                self.renderSegment(self.segments[segmentIndex%].segment[loop%].p1.screen.x - self.segments[segmentIndex%].segment[loop%].p1.screen.w,   _
                                    self.segments[segmentIndex%].segment[loop%].p1.screen.y,    _
                                    self.segments[segmentIndex%].segment[loop%].p1.screen.x + self.segments[segmentIndex%].segment[loop%].p1.screen.w,  _
                                    self.segments[segmentIndex%].segment[loop%].p1.screen.y,    _
                                    self.segments[segmentIndex%].segment[loop%].p2.screen.x + self.segments[segmentIndex%].segment[loop%].p2.screen.w,  _
                                    self.segments[segmentIndex%].segment[loop%].p2.screen.y,    _
                                    self.segments[segmentIndex%].segment[loop%].p2.screen.x - self.segments[segmentIndex%].segment[loop%].p2.screen.w,  _
                                    self.segments[segmentIndex%].segment[loop%].p2.screen.y, _
                                    self.segments[segmentIndex%].segment[loop%].colour%)
            NEXT
        NEXT
    ENDFUNCTION

    FUNCTION renderSegment%:x1,y1,x2,y2,x3,y3,x4,y4,colour%
        STARTPOLY -1
            POLYVECTOR  x1,y1,x2,y2,colour%
            POLYVECTOR  x2,y2,x3,y3,colour%
            POLYVECTOR  x3,y3,x4,y4,colour%
            POLYVECTOR  x4,y4,x1,y1,colour%
        ENDPOLY
    ENDFUNCTION

    FUNCTION lastSlope:segments[] AS __segment
    LOCAL size%

        size=BOUNDS(segments[],0)
        IF size%=0
            RETURN 0.0
        ELSE
            RETURN segments[size%-1].segment[0].p2.world.y
        ENDIF
    ENDFUNCTION

    FUNCTION addSegment%:segments[] AS __segment,curve,y
    LOCAL size%
    LOCAL segment AS __segment
    LOCAL halfTile%
    LOCAL slope

        size%=BOUNDS(self.segments[],0)

        segment.index%=size%
        segment.curve=curve

        halfTile%=9/2

        DIM segment.segment[1]
        FOR n%=0 TO BOUNDS(segment.segment[],0)-1
            segment.segment[n].p1.world.x = 0.0 // (0.0-halfTile%+n)*self.tileWidth
            segment.segment[n].p1.world.y = self.lastSlope(segments[])
            segment.segment[n].p1.world.z = size*self.segmentLength

            segment.segment[n].p2.world.x = 0.0 // (0.0 - halfTile + n)*self.tileWidth
            segment.segment[n].p2.world.y = slope
            segment.segment[n].p2.world.z = (size% + 1)*self.segmentLength

            segment.segment[n].colour=IIF(bAND(n%,1), RGB(255,0,0),RGB(0,255,0))
        NEXT

        DIMPUSH self.segments[],segment
    ENDFUNCTION

    FUNCTION addRoad%:segments[] AS __segment,enter, hold, leave, curve, y
    LOCAL startY,endY,total
    LOCAL n%

        startY=self.lastSlope(segments[])
        endY=startY+(INTEGER(y)*self.segmentLength%)
        total=enter+hold+leave

//      DEBUG "Start Y : "+startY+" endY : "+endY+"\n"
//      KEYWAIT
        FOR n%=0 TO enter-1
            self.addSegment(segments[],self.utils.easeIn(0,curve,n%/enter),self.utils.easeInOut(startY,endY,n%/total))
        NEXT
//      DEBUG "Holding ---\n"
        FOR n%=0 TO hold-1
            self.addSegment(segments[],curve,self.utils.easeInOut(startY,endY,(enter+n%)/total))
        NEXT
//      DEBUG "---\n"

        FOR n%=0 TO leave-1
            self.addSegment(segments[],self.utils.easeInOut(curve,0,n%/leave),self.utils.easeInOut(startY,endY,(enter+hold+n)/total))
        NEXT
    ENDFUNCTION

    FUNCTION addStraight%:segments[] AS __segment,num=25
        self.addRoad(segments[],num,num,num,0,0)
    ENDFUNCTION

    FUNCTION addHill%:segments[] AS __segment,num,height
        self.addRoad(segments[],num,num,num,0,height)
    ENDFUNCTION

    FUNCTION addCurve%:segments[] AS __segment,num, curve,height
        self.addRoad(segments[],num,num,num,curve,height)
    ENDFUNCTION

    FUNCTION addLowRollingHills%:segments[] AS __segment,num,height
        self.addRoad(segments[],num, num, num, 0, height/2)
        self.addRoad(segments[],num, num, num, 0, -height)
        self.addRoad(segments[],num, num, num, 0, height)
        self.addRoad(segments[],num, num, num, 0, 0)
        self.addRoad(segments[],num, num, num, 0, height/2)
        self.addRoad(segments[],num, num, num, 0, 0)
    ENDFUNCTION

    FUNCTION addSCurves%:segments[] AS __segment
//      self.addRoad(ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, -ROAD_CURVE_EASY, ROAD_HILL_NONE)
//      self.addRoad(ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_CURVE_MEDIUM, ROAD_HILL_MEDIUM)
//      self.addRoad(ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_CURVE_EASY, -ROAD_HILL_LOW)
//      self.addRoad(ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, -ROAD_CURVE_EASY, ROAD_HILL_MEDIUM)
//      self.addRoad(ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, ROAD_LENGTH_MEDIUM, -ROAD_CURVE_MEDIUM, -ROAD_HILL_MEDIUM)
    ENDFUNCTION

    FUNCTION addBumps%:
//      self.addRoad(10, 10, 10, 0,  5);
//      self.addRoad(10, 10, 10, 0, -2);
//      self.addRoad(10, 10, 10, 0, -5);
//      self.addRoad(10, 10, 10, 0,  8);
//      self.addRoad(10, 10, 10, 0,  5);
//      self.addRoad(10, 10, 10, 0, -7);
//      self.addRoad(10, 10, 10, 0,  5);
//      self.addRoad(10, 10, 10, 0, -2);
    ENDFUNCTION

    FUNCTION addDownhillToEnd%:num=200
  //    self.addRoad(num, num, num, -ROAD_CURVE_EASY, -lastY()/self.segmentLength);
    ENDFUNCTION

    FUNCTION createTestRoad%:
    LOCAL segment AS __segment

        DIM self.segments[0]

        self.addCurve(self.segments[],12,200,150)
    ENDFUNCTION

ENDTYPE

```

The C SDL2 code (relevent parts that is) :

(DGInt is a float and DGNat is an integer)

```
void Utils::project(struct __segmentPart *p, DGInt cameraX, DGInt cameraY, DGInt cameraZ, DGInt cameraDepth, DGNat width, DGNat height, DGNat roadWidth,DGNat tileWidth,DGNat tileIndex)
{
    p->camera.x = p->world.x - cameraX;
    p->camera.y = p->world.y - cameraY;
    p->camera.z = p->world.z - cameraZ;
    p->screen.scale = cameraDepth / p->camera.z;
    p->screen.x = (width / 2.0) + ((p->screen.scale*p->camera.x*width) / 2.0);
    p->screen.y = (height / 2.0) - ((p->screen.scale*p->camera.y*height) / 2.0);
    p->screen.w = (p->screen.scale*tileWidth*width / 2.0);
}

struct __segment *Road::findSegment(DGInt z)
{
    return (struct __segment *) &segments(FLOOR(z / segmentLength));
}

void Road::render(DGInt position)
{
    struct __segment *baseSegment;
    struct __segment *segment;
    DGInt maxy = height;
    DGNat n;
    DGInt basePercentage;
    DGInt x = 0.0;
    DGInt dx;
    DGInt playerX = 0;

    baseSegment = findSegment(position);
    basePercentage = utils.percentRemaining(position, segmentLength);
    dx = - (baseSegment->curve*basePercentage);

    ALPHAMODE(-1);
    PRINT("Base Per :", 0, 0);
    PRINT(FORMAT_Str(4, 4, basePercentage), 0, 32);
    for (n = 0; n < drawDistance; n++)
    {
        //DGNat sIndex = (baseSegment->index + n) % BOUNDS(segments, 0);

        segment = (struct __segment *) &segments((baseSegment->index + n) % BOUNDS(segments, 0));
        for (DGNat loop = 0; loop < 9; loop++)
        {
            utils.project(&segment->segment[loop].p1, (playerX * roadWidth) - x , cameraHeight, position, cameraDepth, width, height, roadWidth,tileWidth,loop);
            utils.project(&segment->segment[loop].p2, (playerX * roadWidth) - x - dx , cameraHeight, position, cameraDepth, width, height, roadWidth,tileWidth,loop);
        }

        x += dx;
        dx += segment->curve;

        if ((segment->segment[0].p1.camera.z <= cameraDepth) || // behind us
            (segment->segment[0].p2.screen.y>= segment->segment[0].p1.screen.y) ||
            (segment->segment[0].p2.screen.y >= maxy))          // clip by (already rendered) segment
            continue;

        //Render.polygon(ctx, x1 - w1, y1, x1 + w1, y1, x2 + w2, y2, x2 - w2, y2, color.road);
        renderSegment(segment);
        //w1 = segment->p1.screen.x + segment->p1.screen.w;

        maxy=segment->segment[0].p1.screen.y;
    }
}

void Road::renderSegment(struct __segment *segment)
{
    Sint16 x[4], y[4];

    DRAWRECT(0.0, segment->segment[0].p2.screen.y, segment->segment[0].p2.screen.x, segment->segment[0].p1.screen.y - segment->segment[0].p2.screen.y, segment->border[0]);
    for (DGNat loop = 0; loop < 9; loop++)
    {
        x[0] = (Sint16) (segment->segment[loop].p1.screen.x - segment->segment[loop].p1.screen.w);  y[0] = (Sint16)(segment->segment[loop].p1.screen.y);
        x[1] = (Sint16)(segment->segment[loop].p1.screen.x + segment->segment[loop].p1.screen.w);   y[1] = (Sint16)(segment->segment[loop].p1.screen.y);
        x[2] = (Sint16)(segment->segment[loop].p2.screen.x + segment->segment[loop].p2.screen.w);   y[2] = (Sint16)(segment->segment[loop].p2.screen.y);
        x[3] = (Sint16)(segment->segment[loop].p2.screen.x - segment->segment[loop].p2.screen.w);   y[3] = (Sint16)(segment->segment[loop].p2.screen.y);

        filledPolygonRGBA(GETRENDERER(), (const Sint16 *) &x, (const Sint16 *) &y, 4, RGBR(segment->segment[loop].colour),RGBG(segment->segment[loop].colour),RGBB(segment->segment[loop].colour),255);
        //(SDL_Renderer * renderer, const Sint16 * vx,
        //  const Sint16 * vy, int n, Uint8 r, Uint8 g, Uint8 b, Uint8 a);

        //DRAWLINE(x[0], y[0], x[1], y[1], segment->segment[loop].colour);
        //DRAWLINE(x[1], y[1], x[2], y[2], segment->segment[loop].colour);
        //DRAWLINE(x[2], y[2], x[3], y[3], segment->segment[loop].colour);
        //DRAWLINE(x[3], y[3], x[0], y[0], segment->segment[loop].colour);
    }
}

```

# Answer
> 1 votes
The problem was caused by several things : The camera depth calculation was not correct (due to conversion to radians, which wasn't needed), causing a distorted (but looked okay) display, especially of curves. Finally, the actual step values were way too steep (as pixels were being used instead of points).

# Answer
> 0 votes
What is happening is that as you traverse a skewed segment, the camera's center relative to the road changes. That is, by the time you get to the end of that segment, the road is no longer centered. When a new segment is entered the dx value does not line up with the old dx value and the jitter occurs.

So you basically LERP from the current dx to the dx in the next segment to smooth out the curves (as the % is a value from 0 to 1):

`dx = -percentage_of_segment_traversed * ddx`

Jake mentions this in his tutorial here: http://codeincomplete.com/posts/2012/6/24/javascript\_racer\_v2\_curves/ in the "rendering curves" section:

> Finally, in order to avoid jarring transitions when crossing segment boundaries we must ensure dx is initialized with an interpolated value for the current base segments curve.

And the relevant piece of sample code in his Javascript Racer:

```
var baseSegment = findSegment(position);
var basePercent = Util.percentRemaining(position, segmentLength);
var dx = - (baseSegment.curve * basePercent);

```

---
Tags: 2d
---


title: How are sound effects made?

text:
# Question
Title: How are sound effects made?
My friend and I are finishing up our first game right now and I have just discovered that even though he can make some decent music tracks, he has no idea how to make a sound effect. An explosion, for example.

How are sound effects made?

# Answer
Do some research on what a Foley Artist does:

http://en.wikipedia.org/wiki/Foley\_artist
> 6 votes

# Answer
They can be everything. This is one of my favorite things to experiment with. I don't worry about "This could be a --- sound" I only worry that "this sounds interesting" at all times. For example Overgrowth has blood squirts from only slightly modified recordings of them squeezing a pineapple's insides by hand.

My bone cracking sound in my game is from celery and onions being broken and cut. Vegetables and strange gooey substances work great. I've used a VERY modified version of my local TRAX station recording (sounds of a train taking off) close to the ground as a gun boom. It works great too. Experiment it's fun. If you want explosions it would be things like that, things that have lots of changing over time, that isn't very abrupt or necessarily loud. Anything can be altered. Use the train as an explosion. You could just as easily use some old tile from your neighbors alley, or a cardboard box with rocks in it and drop them on concrete.

And yes, this is how it's done professionally too. An example is that a lot of the sounds of Zerg units in Starcraft II are from the sound designers squeezing hand soap in a bucket.
> 30 votes

# Answer
Foley sounds.

There is a video here which is a live recording of some guys from Dark Sector making sound effects for the game. In the clip they use:

* back of hammer on watermelon (splat)
* back of hammer on catelope (thud)
* ripping open watermelon (dismemberment)
* green onions, celery, cabbage (neck snap). Note how the sound they use is the one generated by the weak guy, so his shoulder muscles can barely pull the celery apart, which gives the effect of pulling apart something tough
* sticking fingers inside of a cucumber (squish)
* breaking open an orange (squishy)
* back of hammer inside orange (light thud)
* pulling apart orange pieces (squishy)

Note the tarp floor, which gives a special "scattery" sound when the seeds hit the floor on the first watermelon hit.

An alternative youtube link here
> 7 votes

# Answer
I think the real answer is that most aren't, people just buy and use banks of existing effects.
> 5 votes

# Answer
You might find free sound effects online www.freesound.org has lots of sound effects, but they're under the Creative Commons Sampling Plus 1.0 license meaning you have to attribute the author for each and every one you use.

Alternatively, you could record sounds yourself and mix/edit them in a free program like Audacity.
> 3 votes

# Answer
The websites and programs answered so far are definitely the way to go. Recording your own explosions is no good. Most likely, any level of explosion you create will not sound much like what you're looking for anyway.

Not to mention, programming with a few less fingers would be tough.

Edit: However, as I'm thinking about this, one practical effect that could be pretty well recorded is that of gunshots. There's most likely a shooting range that rents out pistols and, as long as you call beforehand and make sure the range owner is alright with it, you could probably bring in a microphone for, at the very least, a trial run of how the recordings could sound. It's worth noting that, depending on the range, an indoor setup could likely make for some undesired echo if their sound dampening isn't well done. And, of course, have one of the employees supervise if you're not experienced with firearms.
> 2 votes

# Answer
You could try some dynamic sound effects generation where sound parameters would depend on your game action. For example, try Little Endian sound mangling SDKs.
> 1 votes

# Answer
Have fun making your own sounds.

If you are making a retro game I recommend trying out cfxr. It is a random sound generator and the sound effects sound like they would work well in a retro arcade game.
> 0 votes

# Answer
It is possible to create your own sounds with Software, a free software is for example Pure Data, but also any Software Synthesizer with enought variability will do it.

Here are some sources for sources of sounds i found and use

# Sounds

**Free**

**Non free**

**Search machines**
> 0 votes

# Answer
soundbible.com has a lot of free sounds with different licenses for whatever you are using them for.

bfxr.net is a new version of the popular sfxr program. This version has some new features for better sounds like new waveforms and filters.

The people who do these sound effects are called Foley Artists. They do things like throwing pots and pans and squishing fruit for different sound effects in video games and movies. http://en.wikipedia.org/wiki/Foley\_(filmmaking)

If you want to you can try and make your own sound effects like squishing hand soap or boiling water to make lava bubbling sounds. Then you can digitally change the sounds for even more effects! Their are many different options to make cool sounds!
> 0 votes

# Answer
Actually this is a self discipline, called "sound engineering".

There's a guys in a movie industry for example, even whole compamies, which work is to create sound effects for movies, series, video games.

If you're writing a simple game, you can pick some open source sound library, which contains sfx'es for blows, explosions, whatever you need, or to buy a licensed one and use it.
> -1 votes

---
Tags: sound
---


# Question
Title: matrix transformations 2D - place in world-space but keep size in "object/screen-space"
I have a question concerning matrix transformations. I Think I know how it could be done, but Im not sure its the best/correct way to do it.

I want to apply World translations and rotation to an object but the scale should be consistent. See the image for example. The object closest to origo scales according to World-scale, the other object has the same scale but is placed correctly (World scale is taken into consideration when translating). I know I can do this by applying the inverse scale transform in local space Before translating and applying World-transforms. But is there some better way?

# Answer
> 0 votes
The data visualisation terms for this are
geometric zooming (which literally increases size), and
semantic zooming (scaling underlying positions).

Your initial scaling matrix alone would be a geometric zoom. Everything appears in the correct position, but also becomes larger. Your second operation of inverse-scaling relative to the new position essentially converts it into a semantic zoom, for that marker.

You could implement a semantic zoom more efficiently by just multiplying each marker's translation from the origin by the zoom factor. That way, everything is moved by the correct distance, but the markers' rendered graphics don't change size, so there's no need for the second corrective operation.

Both methods should yield mathematically equivalent results, but the latter is a little more performant (because it doesn't require "undoing" work with an inverse), and easier to read.

---

If you do want the markers to be differently sized or rotated, you can of course apply additional transformations once they're translated to their semantic-zoom positions.

---
Tags: 2d, rendering, transformation
---


# Question
Title: How to correctly set window size in Libgdx scene2d.ui dialog
In my libGDX application I am using the `scene2d.ui` classes to render my game's GUI. One of the things I render via these classes is a dialog window with a background image set. I have created the `uiskin.json` file accordingly, and the dialog is shown correctly with the background image.

There is one catch however: The size of the dialog window is exactly set to fit the text elements, but not more. If not much text is shown on the dialog, then the background image is rendered much smaller than it really is.

I can override or hard-code the window size by overriding `getPrefWidth()` and `getPrefHeight()` in my custom `Dialog` class. But that does not feel right.

My question: What is the correct way to set a `scene2d.ui` dialog with a background image to be as large as that background image, regardless of how much text is being shown?

# Answer
> 2 votes
It's easy, you just need to set the width during the insertion of the items on your table.

Example:

```
dialog.getButtonTable().add(btnSound).width(900);

```

# Answer
> 2 votes
Or you can also set directly the dimensions of the background image:

```
dialog.getBackground().setMinWidth(200);
dialog.getBackground().setMinHeight(200);

```

Actually I don't know if this solution has some side effect because it might be that other dialogs use the same background among you game. I think that it's a pity that the Dialog hasn't a inner method that allows to set it's dimensions.

# Answer
> 2 votes
Actually I've found another solution in these days that is the following: You could extend the Dialog class and create your own custom dialog then you override the methods that specify the preferred size of the dialog to the Layout.

```
public class MyDialog extends Dialog {

    @Override
    public float getPrefWidth() {
        return MY_WIDTH;
    }

    @Override
    public float getPrefHeight() {
        return MY_HEIGHT;
    }

}

```

This way you are sure the Dialog will be "forced" to have the dimension defined. A good solution is to create a constructor that accepts a width/height parameters.

---
Tags: libgdx, gui
---


# Question
Title: How do I make voting to kick a "leader" player fair?
My game has many rooms of around 10 people where they compete. It's basically one big guy against the other small 9 people.

However, sometimes the one guy will intentionally 'troll' and make for an unfun game for the other 9 people. These people would like to kick the one guy to replace him with one of the other 9.

If the vote was required to be unanimous (other than the guy being kicked), then him just having one friend in the game would prevent the vote from passing. Likewise, if you did unanimous minus one, then two friends could stop the vote, etc.

There there is the issue with small rooms. If a room has only two or three people, then one guy can trivially kick other people.

Has any research been done for optimal votes required to kick someone from a room depending on how many people are in the room?

# Answer
It sounds like a simple majority vote (no negative-voting) would work.

In a room of 10 (other than the "big guy", who I assume is unable to vote), dethroning them would take 6 players. Of course, if the majority of players are trolls, they could deny the vote, but who wants to stay in a room where the *majority of players are trolls* anyway?

This simply scales down to smaller rooms: In a room of five, you'd need 3 to agree. In a room of two, both would need to agree.
> 5 votes

# Answer
You could implement a "warning system" as well. Something along the lines of:

1) If the majority of the players vote for a player to be kicked, they get a 'warning' that shows up on their screen and vote-to-kick is locked out for 1 minute.

2) If the antagonizing player does not begin to behave within that 1 minute, the other players may vote to immediately kick them with a simple majority vote.

This would give the 'lead' player a chance and give them a 'reality check' of sorts.

\[Editing in my comment as an improvement - I'm still new to SE behaviors.\]

Perhaps a user could accumulate 'warnings' on their account, and they only get kicked if they have 3 or more 'warnings' in the last 30 days? Ex: You can get 1 warning per game, and if you're a frequent offender then instead of a warning you just get the boot. I just try to be wary of 'vote to kick' systems from past experience. Players can be childish at times
> 1 votes

---
Tags: game-design, multiplayer
---


title: Where should I cast new bullets?

text:
# Question
Title: Where should I cast new bullets?
Should I

* Cast new bullets from my Weapon class, which would test a flag when its updated that tells if mouse left is down, which is set by Input class
* Cast new bullets from my Input class, which would call Weapon Cast()

And why?

# Answer
> 1 votes
Your input class should tell your weapon to cast a bullet.

You'll be able to use the same functions when the bullet will need to be fired from an AI entity.

This will help separate concepts: your input class knows that the weapon can fire a bullet, but does not have to know how it's being done.

---
Tags: c++, design-patterns
---


# Question
Title: Unity3D - generating a set of rooms (scenes) and saving them
I'm having a problem wrapping my head around scenario like this.

Say I've got a scene called Room. Now, my game procedurally generates content of each room. Entering a new room to see new content, finishing it and going to the next one isn't much of a problem. However, I'd like to add ability to go back AND to generate a set of rooms (say, 5) along certain path. Now, how exactly can I achieve this?

The latter one, I can store somewhere information about each room whether it should have exits on left/right or top/bottom and just generate as player moves forward using this data. The tricky part is coming back. What would you guys recommend? Serializing the whole scene (will it even work in this case?), picking up and serializing my own information about the randomed scene? Not sure how to approach this.

# Answer
> 1 votes
First, you need a way to create rooms in a deterministic way. A well-established method to do this is generating the procedural content using a random number generator with a fixed seed. When you initialize the rng with the same seed, it will output the same sequence of values resulting in the same room.

The C# `Random` class can be instantiated with a 31 bit seed (it is technically an `Int32`, but negative values are converted to positive ones, so the actual entropy is just 31 bit). That seed should be part the room number and part a "world seed" value which is randomly generated for each playthrough when the player starts a new game but doesn't change afterwards.

Example: Assuming you have a world with no more than 256x256 rooms, you could have the seed for each room be 15 bit world-seed, 8 bit x-coordinate and 8 bit y-coordinate (giving you 32768 unique worlds but each room being unique across all worlds). You would then generate the world seed with the normal rng `world_seed = new Random().Next(32768);`.

To initialize the rng for generating a room, you could then use:

```
Random room_rng = new Random(
         world_seed << 16 +
         x << 8 +
         y
    );

```

Second, you need some way to save the changes the player made to the room to a file when they leave it and reapply them when they re-enter the unloaded room. This is highly application-specific to your game, so you will have to implement your own file format for this. When you need help about how to serialize the state of some specific feature of your game, feel free to ask a new question explaining the problem in detail.

---
Tags: unity, procedural-generation, procedural, serialization
---


# Question
Title: Certain Unicode Characters not displaying when setting text to TextButton in libgdx
Ok I am trying to do a word game much like Hangman Pro but for a different language(specifically amharic) using `libgdx` . And I have got a list of words saved to text file and I have taken care of `BOM` problem when reading the file. Problem arises when setting the individual characters from a random word to a `TextButton`.

Here is a snapshot of the problem:

The part I marked red are the ones missing and it is the same word in both cases. And I know the word is correctly being read because it outputs correctly on `console`

Here is init code and console output

```
public void init(){
        char [] indiv = WordList.randomWord.toCharArray();
        int index = 0;
        Skin skinCanyonBunny = new Skin(Gdx.files.internal(Constants.SKIN_WORDGAME_UI),
                new TextureAtlas(Constants.TEXTURE_ATLAS_UI));
        String name = "textb-dn";
        TextButtonStyle tbs = new TextButtonStyle(skinCanyonBunny.getDrawable("textb-up"),
                skinCanyonBunny.getDrawable("textb-dn"),
                skinCanyonBunny.getDrawable("textb-checked"),
                Assets.instance.assetFonts.defaultNormal);
        for(int i =0;i<Constants.WORD_TABLE_SIZE;i++){
            String tempText = String.valueOf(indiv[(index++)%indiv.length]);
            TextButton temp = new TextButton(tempText, skinLibgdx);
            btnPlayArray.add(temp);
        }

        for(int i = 0;i<Constants.WORD_TABLE_SIZE;i++){
            btnPlayArray.get(i).addListener(new TestInputtListenerOverflow(btnPlayArray.get(i).hashCode()));
        }

    }

```

And a sample of console output. the last one is the random selected word.

```
entry: ቴክኖሎጂ 5
entry: ኢንዱስትሪ 6
entry: ሀይል 3
entry: ወደፊት 4
entry: አቅጣጫዎች 6
entry: ሰው 2
com.tamirat.wordgame.WordGame: ኢንዱስትሪ

```

Can anyone tell me what is happening? If it helps I am using Nyala `ttf` font and converting them to `bitmap` using `Font Forge`. Alternatively I use `BMFont`. Thanks

# Answer
> 0 votes
It is working now using `hiero` runnable `jar`. I had to add every character manually. Not an easy task since there are over 180 distinct characters in the alphabet and resources don't come easy for this particular case. I wish there were less complicated tools for board games like this.Thanks for the help @bornander.

---
Tags: 2d, libgdx, fonts, text
---


title: Trap mouse in SDL

text:
# Question
Title: Trap mouse in SDL
How can I trap the user's mouse inside my game? It's not a fullscreen game, but I want it so that the user cannot drag the mouse to outside the screen.

Do I have to check the coordinates of the mouse and SDL\_WarpCursor to make it say inside the window (manually), or is there an automatic way?

Thank you.

# Answer
While you can implement this using SDL\_WarpCursor(), I've run into problems with that method on some platforms. I've had real problems with some platforms not reliably performing the WarpCursor() action, particularly when I've been calling it every frame.

Also, remember that on many platforms, the cursor is handled at a higher frequency than your app. This is particularly true if you're running below 60fps! So even if the platform is successfully warping the mouse on every frame of your game, the cursor could still get away from your window if it's receiving updates in between your rendered frames.

The correct method for trapping the mouse under SDL is:

```
SDL_WM_GrabInput( SDL_GRAB_ON );

```

This tells SDL that your intention is to actually grab full control of mouse + keyboard (see the documentation), and to therefore keep the mouse inside the window no matter what. From this point on, the mouse will not move outside of the window, regardless of your frame rate, and you should not call SDL\_WarpCursor, except if you really do intend to teleport the cursor somewhere, rather than spamming it continuously.

While in this "grabbing" mode, you will continue to receive mouse motion events as though the mouse was not being constrained inside the window. (So if the cursor is at the right edge of the screen, and the user moves his mouse further right, you'll receive a mouse motion event showing motion to the right, though the cursor position will not change). This is really useful for (for example) turning controls for FPS games, where you only care about relative motion of the cursor, not its absolute position.

**Update for SDL2 -- 9 December, 2013**

This interface has changed for SDL2. If you're using SDL1.2, the answer above is still correct. However, under SDL2 the `SDL_WM_GrabInput(SDL_GrabMode)` function is no longer available. SDL2's new way to capture the mouse is:

```
SDL_SetRelativeMouseMode(SDL_TRUE);

```

Otherwise, this is identical to the earlier function -- in this mode you will continue to receive `SDL_MOUSEMOTION` events as though the mouse wasn't being constrained inside the window.
> 24 votes

# Answer
While Trevor's updated answer does reflect the current state of SDL2, you can also trap the mouse by creating your `SDL_Window` with the `SDL_WINDOW_INPUT_GRABBED` set. Be aware that I've run into some strange issues on Linux (presumably due to some X windowing quirk) where you cannot ever exit the window unless SDL\_QUIT is called (even if another OS event steals the focus away).
> 3 votes

# Answer
For SDL2 there seems to also be the function SDL\_SetWindowGrab if you want to enable and disable it.

```
SDL_SetWindowGrab(SDL_Window* window, SDL_bool grabbed)

```
> 3 votes

# Answer
You can use the SDL Motion Event to detect when the mouse moves. Then, you can call WarpCursor inside that even after firing an event to pipe the relX and relY values. You can also hide your OS cursor and draw a crosshair or something similar in the center of the screen. This ensures that the mouse seems to always be in the middle for the user and you can still receive values for motion and the like.
> 2 votes

---
Tags: sdl, input, mouse
---


# Question
Title: How to remove voxel lights with Minecraft-style algorithm?
I am making a voxel game. I have researched lighting techniques, and the minecraft-style algorithm appears the most efficient. When blocks are placed, they are marked for update. The engine performs a recursive algorithm on them that forms a diamond-shaped pattern like this:

```
01210
12321
01210
00100

```

My question is how you would remove lights using such an algorithm. Suppose your light setup looks like this: (The 2s would be the light sources)

```
01100
12210
01100

```

And you wanted to remove one of the light sources. From what I have seen, it would produce a result like this:

```
01000
10000
01000

```

A diamond-shaped pattern around the light source would be removed. How can I remove a light source without causing this effect?

# Answer
> 3 votes
You can't. That's one of the downsides to MC's lighting model.

What you can do is update the just the cell by setting them to max of the neighbours minus the decay like if there wasn't a light there and mark each of the neighbours as needing an update.

```
01100
12110
01100

```

And then you go over each of the marked cells and update them in the same way, (marking the neighbours of changed cells as you go):

```
01000
12100
01000

```

If a light is in a updating cell then the new light value is either the calculated value or the emitted light whichever is greater.

Then when no more cells have been updated then the update is finished.

Each iteration can be done in a separate game tick to avoid freezing the game. You don't even need to do a full iteration.

The number of iterations can become quite large if the lighting level is very granular. Removing a strength 255 light will result in 128 iterations to remove all of the light. This is related to the count-to-infinity in network routing.

To solve this you can instead reset all light values in the affected radius to 0 (except existing lights to their light value) and mark the edge of the area (and neighbours of existing lights) for lighting updates.

---
Tags: lighting, voxels
---


# Question
Title: What determines the hit detection ordering for graphic elements in Unity (2d game)?
I have a bunch of overlapping buttons spread across several UI Canvases. The default mouse behaviour only registers hover/click events with one of the overlapping buttons, which is ideal for my project. The problem is the order of which button gets activated, is not tied to the Layer it is on or the Sorting Layer the item is on. I cannot seem to control which button is the top button that gets activated.

Using a RaycastAll() function returns the name of all buttons on any given point, and reflects the problem that for some reason, the buttons are arbitrarily ordered.

How do you control the order in which buttons are registered by the mouse?

# Answer
> 0 votes
Okay I found it. Put the canvas the buttons are on, in the same sorting layer and use Order in Layer. Higher values are on top.

---
Tags: unity, sprites, gui
---


# Question
Title: Check if .dds texture is gamma-corrected
How can I check if .dds texture is gamma-corrected? It seems to be gamma-corrected since after manual gamma correction in fragment shader image is too bright. But I wanted to be sure.

# Answer
If the data is only 8bbit per channel, then sRGB is the likely choice but...

If the DDS texture is mip-mapped, *perhaps* you could see if the downsampled pixels indicate if it's in sRGB or linear format, since the filtering process for sRGB *should* be done as sRGB-\>linear, filter/downsample, linear-\>sRGB, which should lead to reasonably different results. EG average of 0xFF and 0x00 in sRGB is around, IIRC, 0xB4 not 0x80.
> 1 votes

---
Tags: opengl, textures, lighting, dds
---


# Question
Title: In JavaScript, should I write a game loop for a turn-based game?
I am using javascript and HTML5 canvas for turn-based games (e.g., checkers, mastermind, minesweeper).

Should I write a fixed-timestep game loop? What are the alternatives?

# Answer
Constantly looping is probably unnecessary for a turn-based game.

If the only time something is going to change is when a player moves, consider using `setTimeout()` or `requestAnimationFrame()`.

Here's an approximate setup:

```
var player = {x: 0, y: 0};

//to be executed whenever the player moves
function animate(xDifference, yDifference){
  var pixelsLeftX = xDifference,
      pixelsLeftY = yDifference,
      finishedMoving = false;

  var xInterval = setInterval(function(){
    pixelsLeftX = xDifference > 0 ? pixelsLeftX - 1 : pixelsLeftX + 1;
    if(pixelsLeftX === 0){
      clearInterval(xInterval);
      if(finishedMoving){
        continue()
      }else{
        finishedMoving = true;
      }
    }
  }, 10),
      yInterval = setInterval(function(){
    pixelsLeftY = yDifference > 0 ? pixelsLeftY - 1 : pixelsLeftY + 1;
    if(pixelsLeftX === 0){
      clearInterval(xInterval);
      if(finishedMoving){
        continue()
      }else{
        finishedMoving = true;
      }
    }
  });
}

function continue(){
  //etc
}

```
> 3 votes

---
Tags: javascript, game-loop, turn-based
---


title: Corona SDK, do I need to pay for it?

text:
# Question
Title: Corona SDK, do I need to pay for it?
I'm a single dev making simple mobile games. I was looking at corona sdk for my next project. I don't understand what the difference between the paid version and the free version is. It seems that the whole SDK is free, so what does the paid version give you that the free version doesnt? I've been reading through the site, but I'm not quite getting it.

I will need to interface with apple's game center etc.. is that not accessible to me without paying?

# Answer
> 1 votes
There were several major changes in Corona pricing model throughout its history. As of now (since March 1, 2015) Corona SDK is completely free for use. The major difference from paid models is no support for Native libraries. However there is no guarantee it won't become paid again or, more generally, if it will be available at all. This is a major drawback of this platform which you must consider. I personally felt it's too risky to invest time into this platform.

---
Tags: lua, corona-sdk
---


# Question
Title: What is the most appropriate path-finding solution for a very large proceduraly generated environment?
I have been reading quite a bit in order to make the following choice: which path-finding solution should one implement in a game where the world proceduraly generated, of really large dimensions?

Here is how I see the main solutions and their pros/cons:

1) grid-based path-finding - this is the only option that would not require any pre-processing, which fits well. However, as the world expands, memory used grows exponentially up to insane levels. This can be handled in terms of processing paths, trough solutions such as the Block A\* or Subgoal A\* algorithms. However, the memory usage is the problem difficult to circumvent;

2) navmesh - this would be lovely to have, due to its precision, fast path calculation and low memory usage. However, it can take an obscene pre-processing time.

3) visibility graph - this option also needs high pre-processing time, although it can be lessened by the use of fast pre-processing algorithms. Then, path calculation is generally fast too. But memory usage can get even more insane than grid-based depending on the configuration of the procedural world.

So, what would be best approach (others not present in this list are also welcome) for such a situation? Are there techniques or tricks that can be used to handle procedural infinite-like worlds?

Suggestions, ideas and references are all welcome.

EDIT:

Just to give more details, one should see the application I am talking about as a very very large office level, where rooms are generated prodecuraly. The algorithm works like the following. First, rooms are placed. Next, walls. Then the doors and later the furniture/obstacles that go in each room. So, the environment can get really huge and with lots of objects, since new rooms are generated once the players approaches the boundary of the already generated area. It means that there will be not large open areas without obstacles.

# Answer
Given that the rooms are procedural built, portals created and then populated, I have a couple of ideas.

A\* works really well on navigation meshes, and works hierarchically as well. I would consider building a pathfinding system that works at two levels - first, the room by room level, and second within each room, from portal to portal. I think you can do this during generation at an affordable rate. You only need to path from room to room once you enter it, so it's very affordable from a memory/cpu cost.

High level A\* can be done by creating a graph of each portal and room - a room is the node, and the 'path' or edge is the portal to another room. The cost of traversal has some options - it can be from the centre point of the room to the centre point of the other room, for example. Or you might want to make specific edges from portal to portal with real distances, which is more useful, I suspect. This let's you do high level pathfinding from room A to room B. Doors can be opened and closed, enabling or disabling specific paths, which is nice for certain types of game. Because it's room/portal based it should be pretty easy and affordable to calculate - just distance calculations and graph book keeping. The great thing about this is it reduces the pathfinding memory costs dramatically in large environments since you are doing only the room-to-room finding.

The harder part will be the low level A\* because it should be polygonal navigation mesh. If each room is square, you can start with a polygon. When you place obstacles, subtract the area occupied from the polygon, making holes in it. When it's all finished you'll want to tesselate it into triangles again, building up the graph. I don't think this is as slow as you think. The difficult part is performing the polygon hole cutting, which requires a good amount of book keeping on that kind of stuff, but it is well documented within half-edge structures, and established computer science graphics books. You can also perform this generation lazily, in a background graph, as you don't actual need the A\* results of this level until someone is in the room - the high level takes care of basic path planning for you. Someone may never even enter the room in a run, because the high level A\* never leads them there.

I know I have glossed over the low level navigation mesh generation, but I think it's one of those things you set your mind to and solve and then it's done. There are a bunch of libraries out there like CGAL (http://www.cgal.org) and others that can do this stuff, but really to get it going fast you might need to write it yourself so you only have the things you need.

Alternatively, you could make each room be a grid, and the obstacles fill up parts of the grid, and then do all the standard grid smoothing algorithms, but I like navmesh data as it is small and fast.

Hope that makes some sense.
> 6 votes

# Answer
I'm going to take a stab and recommend a **hierarchical pathfinding algorithm**, such as **HPA\***. Even though I'm not an expert in AI, I'm fairly confident in this guess because your generator sounds almost identical to the one in a game I'm working on, i.e. I've thought about this problem a bit too.

HPA\* (Hierarchical Path-Finding A\*) is a method of optimising regular A\* by first clustering the map into areas that are inter-connected, then producing a high-level graph of those clusters. When pathfinding, A\* (or any pathfinding algorithm) is run on the high-level graph, then in each of the clusters that form the best high-level path. Apparently it's widely used in RTS games, where lots of units will need to navigate unique paths across a large map in real time, so this should give you an idea of how efficient this method is.

Here's an image from their paper; the left is the clusters with connecting nodes, and the right is the high-level graph:

Fortunately for your generator, it is very suitable for this algorithm, because of the rooms that you place: this gives you half the clustering for free. Your high-level graph is essentially made up of all the doors of your rooms. So what HPA\* is for you is: find the series of rooms/doors I need to go through, and how to navigate every room in that sequence.

Some more neat things about this algorithm:

* A\* is slow because it has to find the complete path before returning any results; with HPA\*, you can find the high-level path plus the path for the first room, so you can follow it immediately and defer the paths for the rest of the rooms later. This makes the algorithm responsive.
* You can cache the pathfinding results between pairs of doors for each room, since paths that traverse but don't start or end in this room are guaranteed to follow one such path.
* You can have multiple levels in this hierarchy, although this is only useful for truly gigantic maps.

Do note that HPA\* is *near*-optimal. You can easily see why by imagining a room with so many obstacles that it takes a long time to get through it. For the same reason, you should watch out if a room has enough obstacles to effectively partition it - don't treat this room as a single cluster in the high-level graph.

For some other possible algorithms, you could try this question on cstheory.SE, which lists a ton of them.
> 7 votes

---
Tags: path-finding, procedural-generation, memory-efficiency, efficiency, navmesh
---


# Question
Title: Building a simple bomberman game with Node.js and Socket.io
I'm building this game mostly because I want to experiment with Node.js and Socket.io, and the game is more like a proof of concept.

To start with, I have a 2D grid system as the game map.

```
_________________________________________.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|
.
|____|____|____|____|____|____|____|____|____|.

```

Each position with values:

```
0: empty
1: wall - can not be destroyed by explosion
2: obstacles - can be destroyed by explosion
3: bomb
4-9: some powerups
10>=: the id of player

```

CLIENT-SIDE

I'm not planning to have any game logic happen on the client side, so the client simply send left, right, up, down and plant a bomb command to my server. There is however, some simple check that happen on the client side - 1. check that there's no wall at the direction the client is moving to; 2. the client didn't plant a bomb in the last 3 seconds.

The client also receives the state of the map as a 2d array and knows how to draw everything using that info.

SERVER-SIDE

Main game logic happen on the server side, which includes updating the position of player, calculating the damage of bomb explosion - destroy stuff in the range, except walls and space behind walls

Questions:

1. When the player is moving, he won't see himself moved until he gets the data back from server that updates his position. So I worry this delay may affect user experience, is it better that I move his position on his browser right away, and only update other players' position using info received from server, that means his own movement is rendered away, while his position info is sent to server.
2. When rendering everything, it's simple to implement that whenever anything on the map move or change, redraw everything with the new data. Is that a waste? Can I only update things that change, for example, a player move right 1 position, nothing else changed on the game map, do I still have to redraw everything? I think I'm going to use Canvas to render.
3. Please feel free to comment or answer if you think there are places I can improve or I simply thought wrong, thanks!

# Answer
> 1 votes
**1.**

You will need client side prediction here. Basically, as you said, your client will send the actions performed on his side to the server and instead of waiting for the server to send his new calculated position, it will `predict` them on his own side. In general, the client and server run the same code for a particular action, so basically for a `MOVE_RIGHT`a client would perform, the same moving logic will be run on both client and server.

When the client receives a new game state from the server (containing the actual position of this particular client on the server), it should set his position to the one in the game state so the client stay in sync with the server.

Lag between client and server can makes things a bit more tricky though. Imagine the situation where there is 150ms of lag between the client and the server. Client send `MOVE_RIGHT` action at `t = 0` and instantly predict the result and move 5 units right (client is at X = 5 after prediction). The action will take 150ms to reach the server (due to lag) but the server keep sending game states regularly (let's say one game state every 20ms). Here is how the timeline looks like on the server:

```
 1. t = 20 => Server send a game state with the client position (X = 0)
 2. t = 40 => A new game state is sent (X = 0)
 3. ... (X = 0)
 4. t = 150 => The action finally reaches the server and is beeing processed (X = 5)
 5. t = 170 => Server send a game state with the updated client position (X = 5)

```

Here now the timeline on the client (keep in mind, 150ms lag between client and server)

```
 1. t = 0 => Send MOVE_RIGHT action and predict the result (X = 5)
 2. t = 170 => A game state is received, client updates his position based on the position in the game state (X = 0)
 3. t = 190 => Same as step 2
 4. ... (X = 0)
 5. t = 300 => Finally a game state is received reflecting the client move (X = 5)

```

I hope you can see the problem now. If the client performs an action at `t = 0`, the server will process it a t = 150 and you will only receives a game state reflecting this action at `t = 300`. So basically, you will move your client 5 unit right at `t = 0` (X = 5), snap it back to X = 0 at `t = 170` and finally move it 5 unit right again at `t = 300`, which is of course unacceptable and will make your game unpleasant to play or even unplayable.

An easy way to overcome this problem is to keep track of unprocessed action on your client. When the client send the `MOVE_RIGHT` action, predict it and then store it with some kind of id. Your server should also send the id of the last action he processed with each game state. So now, when you receive a game state on the client, you can determine which actions are not yet processed on the server and reapply them on the client.

The problem is very well explained in this article: http://www.gabrielgambetta.com/fpm2.html

**2.**

Your server should only include what needs to be updated in the game states it sends. If a player has not moved since the last sent game state, no need to include it. You could also use `delta compression` to reduce the amount of data you send over the network.

About the rendering, i'm not so sure, only render what is visible on screen (i don't know if want to implement scrolling).

Ho, and of course: https://developer.valvesoftware.com/wiki/Source\_Multiplayer\_Networking

---
Tags: multiplayer, html5, html-canvas, node.js, websocket
---


# Question
Title: How do I convert from the global coordinate space to a local space?
Given an entity named `EntityA`, I want to define a local coordinate space, where the position of `EntityA` is the origin, its heading vector is the X axis, and the normal of the heading vector is the Y axis:

Given their global coordinates, how do I find the position of another entity in `EntityA`'s local space?

An example: `EntityA`'s global position is (50,50), and that of `EntityB` is (80,90). What is then the position of `EntityB` in `EntityA`'s local space?

EDIT: Please go easy on the math.

# Answer
> 21 votes
Okay, so Assuming that you know what the World Transformation matrix for that object A is, You just need to construct the inverse of that matrix and you will have what you need.

Suppose the rotation, scaling and translation matrices of object A used to get it to Global Space are **R**, **S** and **T** respectively. You will multiply these together like

**S** * **R** * **T** = **W**

Now, take **W** and find its inverse **W^-1** somehow. The inverse of a matrix is that matrix which does just the opposite. The product of the matrix with its inverse is always the identity matrix.

**W** * **W^-1** = **I**

thus **W^-1** = **I** / **W**;

Now Apply this inverse matrix as the world transformation to the scene and each object will be in the coordinates you wanted.

For matrix multiplication, see This page. For Identity matrix, see this.

Here's another page which gives you the matrices you would need to make **W**.

In the question above, you should take translation in x axis as 50, translation in y axis as 50, no scaling in either axis, and a rotation you haven't specified.

# Answer
> 9 votes
I've done this with trigonometry rather than matrixes in the past (I am a matrix noob). Ashes999's answer is halfway there, get the relative vector, then rotate that by the inverse of EntityA's angle.

```
   relativeX = B.x - A.x
   relativeY = B.y - A.y
   rotatedX = Cos(-Angle) * relativeX - Sin(-Angle) * relativeY
   rotatedY = Cos(-Angle) * relativeY + Sin(-Angle) * relativeX

```

# Answer
> 7 votes
Let me try to give you something somewhere between The Light Spark's answer and Elliot's answer, because from what I read, you're really looking for an algorithm to follow and not just math tossed at you.

Problem Statement: Given that you have a location `A (50, 50)` and a heading (since you didn't provide one, I'll assert it as `y = 2 * x + 25`), find where `B (80, 90)` is relative to `A` and the heading.

What you want to do is actually fairly straightforward. 1) Relocate `A` to the origin of your system. This is simply means that the local-to-`A` values are going to be the global position values minus the global position values of `A`. `A` becomes `(0, 0)` and `B` becomes `(30, 40)`.

1.1) The heading also needs to be moved. This is a actually very easy to do, because the y-intercept in local-to-`A` terms is always 0, and the slope won't change, so we have `y = 2 * x` as the heading.

2) Now we need to align the prior heading to the X axis. So, how do we do this? The easiest way, conceptually to do this is to convert from x, y co-ordinates to a polar co-ordinate system. Polar co-ordinate system involves `R`, the distance to a location, and `phi`, an angle of rotation from the x-axis. `R` is defined as `sqrt(x^2 + y^2)` and `phi` is defined as `atan(y / x)`. Most computer languages these days go ahead and define a `atan2(y, x)` function which does the exact same thing as `atan(y/x)` but does so in such a way that the output tends to be from -180 degrees to 180 degrees rather than 0 degrees to 360 degrees, but either work.

`B` thus becomes `R = sqrt(30^2 + 40^2) = sqrt(2500) = 50`, and `phi = atan2(40, 30) = 53.13` in degrees.

Similarly, the heading now changes. This is a bit tricky to explain, but it because the heading, by definition, always passes through our origin `A`, we don't need to be worried about the `R` component. Headings are always going to be in the form of `phi = C` where `C` is a constant. In this case, `phi = atan(2 * x / x) = atan(2) = 63.435` degrees.

Now, we can rotate the system to move the heading to the X-axis of the local-to-`A` system. Much like when we moved `A` to the origin of the system, all we have to do is subtract the `phi` of the heading from all `phi` values in the system. So the `phi` of `B` becomes `53.13 - 63.435 = -10.305` degrees.

Finally, we have to convert back out of polar co-ordinates into x, y co-ordinates. The formula to do that transformation are `X = R * cos(phi)` and `Y = R * sin(phi)`. For `B` therefore, we get `X = 50 * cos(-10.305) = 49.2` and `Y = 50 * sin(-10.305) = 8.9`, so `B` in local-to-`A` co-ordinates is close to `(49,9)`.

Hopefully that helps, and is light enough on the math for you to follow.

# Answer
> 2 votes
You need to know the pose of Entity A in the global space \\$(x\_1, y\_1, \theta)\\$, where \\$\theta\\$ is the orientation relative to the x axis.

To convert the EntityB location from a global coordinate \\$(x\_2, y\_2)\\$ to a local coordinate \\$(x\_2',y\_2')\\$:

## 1. Using expressions

**Global to Local**

$$ \begin{align} x\_2' &= (x\_2 - x\_1) \cos \theta + (y\_2 - y\_1) \sin \theta \\ y\_2' &= -(x\_2 - x\_1) \sin \theta + (y\_2 - y\_1) \cos \theta \end{align} $$

**Local to Global**

$$ \begin{align} x\_2 &= x\_2' \cos \theta - y\_2' \sin \theta + x\_1 \\ y\_2 &= x\_2' \sin \theta + y\_2' \cos \theta + y\_1 \end{align} $$

## 2. Using matrices

$$ \begin{align} R &= \begin{bmatrix} \cos \theta & - \sin \theta \\ \sin \theta & \cos \theta \end{bmatrix} \\ \vec A &= \begin{pmatrix} x\_1 & y\_1 \end{pmatrix} \\ \vec B\_{global} &= \begin{pmatrix} x\_2 & y\_2 \end{pmatrix} \\ \vec B\_{local} &= \begin{pmatrix} x\_2' & y\_2' \end{pmatrix} \end{align} $$

**Global to Local**

$$ \vec B\_{local} = R^{-1} \times (\vec B\_{global} - \vec A) $$

(where \\$R^{-1}\\$ is the inverse of the matrix R)

**Local to Global**

$$ \vec B\_{global} = R \times \vec B\_{local} + \vec A $$

# Answer
> -2 votes
To put it simply entity B would need a reference to entity A. You'd then need to get the difference between entity's A position and entity B's position.

---
Tags: 2d, mathematics, coordinates
---


# Question
Title: How can I make 2D games like shovel knight?
To make 2D games like shovel knight, do I need specific software? Would this be possible to achieve in Unity or would I have to use something else?

# Answer
> 1 votes
I've never played it but just looked it up...

Assuming you are talking about the following game: http://store.steampowered.com/app/250760/

You could definitely make a game like that in unity, you could also do it with a range of different environments and programming languages. If you are starting out I would recommend Unity with c# from the get go. It's free and has a huge community in case you get stuck on anything. However, others ma have differing opinions on that.

You may or may not realise this but what you have asked is an incredibly broad question with a large amount of potential answers. As this is a community, hopefully others will add to this but to get the list of potential routes started:

Unity with c#, Unity with UnityScript (Javascript), a combination of the previous two, Eclipse with Java, Adobe Flash with Action Script, your own c++ engine, Cocos2D with c++ ...

# Answer
> 1 votes
Any software or library capable of 2D would suffice. Some examples include:

For beginners, Love2D is a good start. It's free, it's simple, you have little technical details to worry about, and the underlying programming language (Lua) is among the easiest languages.

Unity is also a very good start for beginners, as it's relatively easy and does many things for you. It's more powerful than Love2D, but requires some C# knowledge.

MonoGame is also free, though requires Visual Studio (I believe Visual Studio Community/Express work fine for this), and also C# knowledge. It's a little bit more difficult to learn than Love2D, but is a lot more powerful, has better performance, and it's easier to keep your code organized.

Overall if you want to build a game from the ground up, start with Love2D. This could be a very good learning experience. But if you want a bit of a headstart with many libraries, integrated functions and an easier interface, start with Unity instead.

---
Tags: unity
---


title: deferred tiled lighting

text:
# Question
Title: deferred tiled lighting
**EDIT**

I have discovered that it does not seem to be the lighting calculation but the culling code because when i draw the lights without the culling it works perfectly.

I have been attempting to implement tile based deferred light culling using this as a guide. My current issue is that the lights don't seem to be drawing correctly. I have tested that the lights per tile are correct and they are and the light indices for each tile seem to be correct too. When I draw the scene I get allot of the tiles affected by point lights flickering every frame. I also dont think that the point lights are being rendered in there correct positions.

Here is what I am testing at the moment.

I construct the point light array to be sent to the compute shader.

```
for (int y = 32; y < 32; y++) {
    for (int x = 0; x < 32; x++) {
        pointLights[x + y * 32] = new PointLight(new Vector3f(x, y, 0);
    }
}

```

All of theses point lights are sent to the uniform array and the scene is drawn.

As you can see I am using 1024 lights but what I see is only one light affecting my 32 * 32 plane right in the center and when I test what tiles are affected by the light it is correct. These lit tiles also flicker every other frame.

So where did I go wrong Is it in my light culling code, my lighting functions, or something else completely.

Here is my complete compute shader

```
    #version 430

#define MAX_POINT_LIGHTS 1024
#define MAX_LIGHTS_PER_TILE 40
#define WORK_GROUP_SIZE 16

struct Attenuation
{
    float constant;
    float linear;
    float exponent;
};

struct Light
{
    vec3 color;
    float intensity;
};

struct DirectionalLight
{
    Light light;
    vec3 direction;
};

struct PointLight
{
    Light light;
    Attenuation atten;
    vec3 position;
    float radius;
};

vec4 calcLight(Light light, vec3 direction, vec3 normal, vec3 fragPos, vec3 specular, vec3 camPos)
{
    float diffuseFactor = dot(normal, -direction);

    vec4 diffuseColor = vec4(0.0, 0.0, 0.0, 0.0);
    vec4 specularColor = vec4(0.0, 0.0, 0.0, 0.0);

    if (diffuseFactor > 0)
    {
        // might need to be 0.0----------| |
        diffuseColor = vec4(light.color, 1.0) * light.intensity * diffuseFactor;

        vec3 directionToEye = normalize(camPos - fragPos);
        vec3 halfDirection = normalize(directionToEye - direction);

        float specularFactor = dot(halfDirection, normal);
        // maybe not 32?
        specularFactor = pow(specularFactor, 32);

        if (specularFactor > 0)
        {
            // maybe 0.0 again
            specularColor = vec4(light.color, 1.0) * vec4(specular, 1.0) * specularFactor;
        }
    }

    return diffuseColor + specularColor;
}

vec4 calcDirectionalLight(DirectionalLight dirLight, vec3 pos, vec3 normal, vec3 specular, vec3 camPos)
{
    return calcLight(dirLight.light, dirLight.direction, normal, pos, specular, camPos);
}

vec4 calcPointLight(PointLight pointLight, vec3 pos, vec3 normal, vec3 specular, vec3 camPos)
{
    vec3 lightDirection = pos - pointLight.position;
    float distanceToPoint = length(lightDirection);

    lightDirection = normalize(lightDirection);

    vec4 color = calcLight(pointLight.light, lightDirection, normal, pos, specular, camPos);

    //float atten = pointLight.atten.constant + pointLight.atten.linear * distanceToPoint + pointLight.atten.exponent * distanceToPoint * distanceToPoint;
    float atten = 1.0 / (pointLight.atten.constant + pointLight.atten.linear * distanceToPoint + pointLight.atten.exponent * (distanceToPoint * distanceToPoint));

    return color * atten;
}

layout (binding = 1, rgba32f) uniform image2D writeonly finalImage;
layout (binding = 2, rgba32f) uniform readonly image2D geometryPosition;
layout (binding = 3, rgba32f) uniform readonly image2D geometryDiffuse;
layout (binding = 4, rgba32f) uniform readonly image2D geometryNormal;

uniform int numActiveLights;
uniform PointLight pointLights[MAX_POINT_LIGHTS];
uniform Light ambientLight;
uniform DirectionalLight directionalLight;

uniform vec3 cameraPosition;
uniform vec2 resolution;

uniform mat4 projection;
uniform mat4 view;

shared uint minDepth;
shared uint maxDepth;
shared uint pointLightCount;
shared uint pointLightIndex[MAX_POINT_LIGHTS];

layout (local_size_x = WORK_GROUP_SIZE, local_size_y = WORK_GROUP_SIZE) in;

void main()
{
    minDepth = uint(0xFFFFFFFF);
    maxDepth = 0;
    pointLightCount = 0;
    barrier();

    ivec2 pixel = ivec2(gl_GlobalInvocationID.xy);

    vec3 position = imageLoad(geometryPosition, pixel).xyz;
    float d = position.z;
    uint depth = uint(d * uint(0xFFFFFFFF));

    atomicMin(minDepth, depth);
    atomicMax(maxDepth, depth);

    barrier();

    float minDepthZ = float(minDepth / float(0xFFFFFFFF));
    float maxDepthZ = float(maxDepth / float(0xFFFFFFFF));

    vec2 tileScale = vec2(resolution * (1.0 / float(2 * WORK_GROUP_SIZE)));
    vec2 tileBias = tileScale - vec2(gl_WorkGroupID.xy);

    vec4 col1 = vec4(-projection[0][0] * tileScale.x, projection[0][1], tileBias.x, projection[0][3]);
    vec4 col2 = vec4(projection[1][0], -projection[1][1] * tileScale.y, tileBias.y, projection[1][3]);
    vec4 col4 = vec4(projection[3][0], projection[3][1], -1.0, projection[3][3]);

    //vec4 col1 = vec4(-projection[0][0] * tileScale.x, 0.0f, tileBias.x, 0.0f);
    //vec4 col2 = vec4(0.0f, -projection[1][1] * tileScale.y, tileBias.y, 0.0f);
    //vec4 col4 = vec4(0.0, 0.0, 1.0, 0.0);

    vec4 frustumPlanes[6];
    frustumPlanes[0] = col4 + col1;
    frustumPlanes[1] = col4 - col1;
    frustumPlanes[2] = col4 - col2;
    frustumPlanes[3] = col4 + col2;
    frustumPlanes[4] = vec4(0.0, 0.0, -1.0, -minDepthZ);
    frustumPlanes[5] = vec4(0.0, 0.0, -1.0, maxDepth);

    for (int i = 0; i < 4; i++)
    {
        frustumPlanes[i] *= 1.0 / length(frustumPlanes[i].xyz);
    }

    uint threadCount = WORK_GROUP_SIZE * WORK_GROUP_SIZE;
    uint passCount = (numActiveLights + threadCount - 1) / threadCount;

    for (int passIt = 0; passIt < passCount; ++passIt)
    {
        uint lightIndex = passIt * threadCount + gl_LocalInvocationIndex;
        lightIndex = min(lightIndex, numActiveLights);

        PointLight p = pointLights[lightIndex];
        vec4 pos = view * vec4(p.position, 1.0);
        float rad = p.radius;

        if (pointLightCount < MAX_LIGHTS_PER_TILE)
        {
            bool inFrustum = true;
            for (int i = 3; i >= 0 && inFrustum; i--)
            {
                float dist = dot(frustumPlanes[i], pos);
                inFrustum = (-rad <= dist);
            }

            if (inFrustum)
            {
                uint id = atomicAdd(pointLightCount, 1);
                pointLightIndex[id] = lightIndex;
            }
        }
    }

    barrier();

    vec3 normal = imageLoad(geometryNormal, pixel).xyz;
    vec4 diffuse = imageLoad(geometryDiffuse, pixel);
    vec3 specular = vec3(0.1, 0.1, 0.1);

    vec4 color = diffuse;
    color *= vec4((ambientLight.color * ambientLight.intensity), 1.0);
    color += calcDirectionalLight(directionalLight, position, normal, specular, cameraPosition);
    for (int i = 0; i < pointLightCount; i++)
    {
        color += calcPointLight(pointLights[pointLightIndex[i]], position, normal, specular, cameraPosition);
        //color = vec4(1.0f / pointLightCount);
    }

    barrier();

    imageStore(finalImage, pixel, color);
}

```

# Answer
> 1 votes
I had the same problem (flickering lights/visible tile boundaries due to incorrect culling), and the error was in frustum construction code. My 'engine' uses right-handed coordinate system (X - right, Y - forward, Z - up), while Direct3D demos use left-handed (Z-forward, Y-up), and my frustum planes had inverted normals. I simply added the minus sign and lighting is now working properly (no black flickering jaggies):

```
    // this creates the standard Hessian-normal-form plane equation from three points,
    // except it is simplified for the case where the first point is the origin
    inline float4 CreatePlaneEquation( float4 b, float4 c )
    {
        float4 n;
        // normalize(cross( b.xyz-a.xyz, c.xyz-a.xyz )), except we know "a" is the origin
        n.xyz = -normalize(cross( b.xyz, c.xyz ));  //<= NOTE: added minus sign!
        // -(n dot a), except we know "a" is the origin
        n.w = 0;
        return n;
    }

```

And here's my tiled deferred shad code (HLSL Compute Shader). NOTE: AMD's Forward+ demo uses another algorithm to extract frustum planes.

```
// Implementation of tiled deferred shading.

// Input: G-Buffers, depth buffer and list of lights.
// Output: fully composited and lit non-MSAA HDR texture.

// References:
// https://github.com/vonture/DeferredRenderer/blob/master/doc/GDC11_DX11inBF3_Public.pdf

#include "__shader_globals_common.h"
#include "__tiled_shading_common.h"
#include "_transform.h"
#include "_gbuffer.h"
#include "_lighting.h"
#include "_screen_shader.h"
#include "_PS.h"

//-----------------------------------------------------------------------------
// Light culling constants: Parameters for the light culling shader.
//-----------------------------------------------------------------------------

#define MAX_LIGHTS_PER_TILE (1024)

// Tile dimensions determine the tile size for light binning and associated trade-offs.
#define TILE_SIZE_X (32)
#define TILE_SIZE_Y (32)

// number of threads in a thread group (each thread corresponds to one pixel)
#define THREADS_PER_TILE    (TILE_SIZE_X*TILE_SIZE_Y)

//-----------------------------------------------------------------------------------------
// Textures and Buffers
//-----------------------------------------------------------------------------------------

// all potentially visible point lights in the scene
StructuredBuffer< DeferredLight >   b_pointLights;

// output HDR target
RWTexture2D< float4 >   t_litTarget;

//-----------------------------------------------------------------------------------------
//  Group Shared Memory (aka local data share, or LDS)
//-----------------------------------------------------------------------------------------

// Min and Max depth for this tile for depth bounds testing:
groupshared uint gs_TileMinDepthInt;
groupshared uint gs_TileMaxDepthInt;

// Light list for the tile:
groupshared uint gs_TileLightIndices[MAX_LIGHTS_PER_TILE];
groupshared uint gs_TileNumLights;  // number of lights in this tile

//-----------------------------------------------------------------------------------------
//  Helper Functions
//-----------------------------------------------------------------------------------------

// this creates the standard Hessian-normal-form plane equation from three points,
// except it is simplified for the case where the first point is the origin
inline float4 CreatePlaneEquation( float4 b, float4 c )
{
    float4 n;

    // normalize(cross( b.xyz-a.xyz, c.xyz-a.xyz )), except we know "a" is the origin
    // my view space is RIGHT handed, hence, the minus
    n.xyz = -normalize(cross( b.xyz, c.xyz ));

    // -(n dot a), except we know "a" is the origin
    n.w = 0;

    return n;
}

// point-plane distance, simplified for the case where
// the plane passes through the origin (frustum side plane in view space)
inline float GetSignedDistanceFromPlane( float3 p, float4 eqn )
{
    // dot( eqn.xyz, p.xyz ) + eqn.w, except we know eqn.w is zero (see CreatePlaneEquation above).
    return dot( eqn.xyz, p.xyz );
}

void BuildFrustumPlanes(
    in uint2 groupId,   // 'Coordinates' of the thread group (x,y in range [0..TilesX-1, 0..TilesY-1]).
    in float nearClip, in float farClip,
    out float4 frustumPlanes[6] // plane equations for the four sides of the frustum, with the positive half-space outside the frustum
    )
{
    const uint numHorizontalTiles = g_tileCount.x;
    const uint numVerticalTiles = g_tileCount.y;

    // window width evenly divisible by tile width
    const float WW = (float) (TILE_SIZE_X * numHorizontalTiles);//<= NOTE: cast is important!
    // window height evenly divisible by tile height
    const float HH = (float) (TILE_SIZE_Y * numVerticalTiles);  //<= NOTE: must be float!

    // tile rectangle in viewport space
    const uint px_min = TILE_SIZE_X * groupId.x;    // [0 .. ScreenWidth - TILE_SIZE_X]
    const uint py_min = TILE_SIZE_Y * groupId.y;    // [0 .. ScreenHeight - TILE_SIZE_Y]
    const uint px_max = TILE_SIZE_X * (groupId.x + 1);
    const uint py_max = TILE_SIZE_Y * (groupId.y + 1);

    // scale to clip space
    const float px_left     = px_min / WW;
    const float px_right    = px_max / WW;
    const float py_top      = (HH - py_min) / HH;
    const float py_bottom   = (HH - py_max) / HH;

    // four corners of the tile in clip space, clockwise from top-left
    float4 frustumCornersCS[4];
    frustumCornersCS[0] = float4( px_left*2.f-1.f,  py_top*2.f-1.f,     1.f,    1.f );
    frustumCornersCS[1] = float4( px_right*2.f-1.f, py_top*2.f-1.f,     1.f,    1.f );
    frustumCornersCS[2] = float4( px_right*2.f-1.f, py_bottom*2.f-1.f,  1.f,    1.f );
    frustumCornersCS[3] = float4( px_left*2.f-1.f,  py_bottom*2.f-1.f,  1.f,    1.f );

    // four corners of the tile in view space
    float4 frustumCornersVS[4];
    frustumCornersVS[0] = ProjectPoint( g_inverseProjectionMatrix2, frustumCornersCS[0] );
    frustumCornersVS[1] = ProjectPoint( g_inverseProjectionMatrix2, frustumCornersCS[1] );
    frustumCornersVS[2] = ProjectPoint( g_inverseProjectionMatrix2, frustumCornersCS[2] );
    frustumCornersVS[3] = ProjectPoint( g_inverseProjectionMatrix2, frustumCornersCS[3] );

    // create plane equations for the four sides of the frustum,
    // with the positive half-space outside the frustum
    [unroll]
    for( uint i = 0; i < 4; i++ ) {
        frustumPlanes[i] = CreatePlaneEquation( frustumCornersVS[i], frustumCornersVS[(i+1)&3] );
    }

    // Near/far clipping planes in view space
    frustumPlanes[4] = float4( 0.0f,-1.0f, 0.0f, nearClip );
    frustumPlanes[5] = float4( 0.0f,+1.0f, 0.0f, -farClip );
}

// NOTE: expects plane equations for the sides of the frustum, with the positive half-space outside the frustum
inline bool FrustumIntersectsSphere( in float4 frustumPlanes[6], in float3 sphereCenter, in float sphereRadius )
{
    bool intersectsFrustum = true;
    [unroll]
    for( uint i = 0; i < 6 /*&& intersectsFrustum*/; ++i )
    {
        // plane normals point outside the frustum
        float dist = dot( frustumPlanes[i], float4( sphereCenter, 1.0f ) );
        // If it is on totally the positive half space of one plane we can reject it.
        intersectsFrustum = intersectsFrustum && ( dist <= sphereRadius );
    }
    return intersectsFrustum;
}

//-----------------------------------------------------------------------------------------
// Light culling shader
//-----------------------------------------------------------------------------------------

// called with Dispatch( groupsX, groupsY, 1 ) where groupsX = ceil( screen_width/TILE_SIZE_X ), etc.

[numthreads( NUM_THREADS_X, NUM_THREADS_Y, 1 )]
void ComputeShaderTileCS(
    uint3 groupId           : SV_GroupID,       // 'Coordinates' of the thread group.
    uint groupIndex         : SV_GroupIndex,    // The "flattened" index of a compute shader thread within a thread group.
    uint3 groupThreadId     : SV_GroupThreadID, // 'Relative coordinates' of a thread inside a thread group.
    uint3 dispatchThreadId  : SV_DispatchThreadID   // 'Absolute coordinates' of a thread as derived from the Dispatch() call.
    )
{
    // NOTE: This is currently necessary rather than just using SV_GroupIndex to work around a compiler bug on Fermi.
    groupIndex = groupThreadId.y * TILE_SIZE_X + groupThreadId.x;
    // flattened index of this thread within thread group
    const uint localThreadIndex = groupIndex;

    // texel coordinates of this pixel in the [0, textureWidth - 1] x [0, textureHeight - 1] range
    const uint2 globalCoords = dispatchThreadId.xy;

    // Compute screen/clip-space position.
    float2 screenSize;
    DepthTexture.GetDimensions( screenSize.x, screenSize.y );

    // NOTE: Mind Direct3D 11 viewport transform and pixel center!
    const float2 texCoords = (float2(globalCoords) + .5f) / screenSize;

    // here goes ya clip-space position:
    const float2 screenPosition = TexCoordsToClipPos( texCoords );

    float viewPosition_x = screenPosition.x * g_ProjParams2.x;
    float viewPosition_y = screenPosition.y * g_ProjParams2.y;
    float hardwareDepth = DepthTexture.Load( int3( globalCoords.x, globalCoords.y, 0 ) );
    // recover view-space depth
    float3 viewSpacePosition = float3( viewPosition_x, 1, viewPosition_y ) * HardwareDepthToInverseW( hardwareDepth );

    // Work out depth bounds for our samples
    float minZSample = g_DepthClipPlanes.y; // far plane initially
    float maxZSample = g_DepthClipPlanes.x; // near plane initially

    float viewSpaceDepth = viewSpacePosition.y;

    // Avoid shading skybox/background or otherwise invalid pixels
    bool validPixel = viewSpaceDepth >= g_DepthClipPlanes.x && viewSpaceDepth <  g_DepthClipPlanes.y;
    //[flatten] if (validPixel)
    {
        minZSample = min( minZSample, viewSpaceDepth );
        maxZSample = max( maxZSample, viewSpaceDepth );
    }

    // Initialize per-tile variables - shared memory light list and depth bounds.
    if( localThreadIndex == 0 )
    {
        gs_TileNumLights = 0;
        gs_TileMinDepthInt = 0x7F7FFFFF;    // largest normal single precision float (3.4028235e+38)
        gs_TileMaxDepthInt = 0;
    }

    // Block execution of all threads in a group
    // until all group shared accesses have been completed
    // and all threads in the group have reached this call.
    GroupMemoryBarrierWithGroupSync();
    {
        // Calculate min and max depth in the threadgroup/tile.
        // Atomics still aren't that great though, since they effectively serialize the memory access among all threads.
        // To avoid using them, you can use a parallel reduction instead. However a parallel reduction requires more shared memory, so it may not always be a win.

        // Only scatter pixels with actual valid samples in them
        //if (maxZSample >= minZSample)
        {
            // atomics only work on integers, but we can always cast float to int (depth is always positive)
            InterlockedMin( gs_TileMinDepthInt, asuint(minZSample) );
            InterlockedMax( gs_TileMaxDepthInt, asuint(maxZSample) );
        }
    }
    GroupMemoryBarrierWithGroupSync();

    // Calculate the min and max depth for this tile,
    // to form the front and back of the frustum.

    float minTileZ = asfloat( gs_TileMinDepthInt );
    float maxTileZ = asfloat( gs_TileMaxDepthInt );

    // Construct frustum for this tile.

    // NOTE: This is all uniform per-tile (i.e. no need to do it per-thread) but fairly inexpensive
    // We could just precompute the frusta planes for each tile and dump them into a constant buffer...
    // They don't change unless the projection matrix changes since we're doing it in view space.
    // Then we only need to compute the near/far ones here tightened to our actual geometry.
    // The overhead of group synchronization/LDS or global memory lookup is probably as much as this
    // little bit of math anyways, but worth testing.

    // plane equations for the four sides of the frustum, with the positive half-space outside the frustum
    float4 frustumPlanes[6];
    BuildFrustumPlanes( groupId.xy, minTileZ, maxTileZ, frustumPlanes );

    // How many total lights?
    const uint numActiveLights = g_deferredLightCount.x;

    // Cull lights for this tile.

    // Loop over the lights and do a sphere vs. frustum intersection test.
    // Each thread now operates on a sample instead of a pixel.
    // (Detailed explanation here: http://www.gamedev.net/topic/625569-light-culling-in-a-compute-shader/?view=findpost&p=4944777)

    // process THREADS_PER_TILE lights in parallel

    for( uint lightIndex = localThreadIndex; lightIndex < numActiveLights; lightIndex += THREADS_PER_TILE )
    {
        float3  lightCenter = b_pointLights[ lightIndex ].positionAndRadius.xyz;
        float   lightRadius = b_pointLights[ lightIndex ].positionAndRadius.w;

        // test if sphere is intersecting or inside frustum

        if( FrustumIntersectsSphere( frustumPlanes, lightCenter, lightRadius ) )
        {
            // Append light to list:
            // do a thread-safe increment of the list counter
            // and put the index of this light into the list.
            // Compaction might be better if we expect a lot of lights.
            uint writeOffset;
            InterlockedAdd( gs_TileNumLights, 1, writeOffset );
            gs_TileLightIndices[ writeOffset ] = lightIndex;
        }
    }

    // Sync threads
    GroupMemoryBarrierWithGroupSync();

    uint numLightsAffectingTile = gs_TileNumLights;

    // Only process onscreen pixels (tiles can span screen edges)
    //if( all( globalCoords.xy < g_FramebufferDimensions.xy ) )
    {
        SurfaceParameters surface = ReadSurfaceFromGBuffer( globalCoords );

        // RGB accumulated RGB HDR color, A: luminance for screenspace subsurface scattering
        float4 compositedLighting = 0;

        for( uint tileLightIndex = 0; tileLightIndex < numLightsAffectingTile; tileLightIndex++ )
        {
            const uint lightIndex = gs_TileLightIndices[ tileLightIndex ];
            const DeferredLight light = b_pointLights[ lightIndex ];

            compositedLighting.rgb += ComputeLighting( viewSpacePosition, surface, light );
        }

        t_litTarget[globalCoords.xy] = float4( compositedLighting.rgb, 1 );
    }
}

```

---
Tags: opengl, glsl, lighting
---


title: Box2d Coordinate System

text:
# Question
Title: Box2d Coordinate System
In the game I'm trying to code I got to have two bodies. One StaticBody and one DynamicBody. I want to have the DynamicBody on top of the StaticBody. Somehow all I get is this:

Is it possible that the viewports lower, left corner isn't at 0,0? And why can't the DynamicBody get on top of the StaticBody?

# Answer
a box2d rectangle has x and y coordinates with thw center in the center of rectangle... other this, to create a rectangle pay attention to give him halfWidth and halfHeight and not full.

for example, if you want a 2\*2 rectangle in left down corner you have to build it with:

x = x+halfWidth y = y+halfHeight halfHeight =1 halfWidth =1
> -1 votes

---
Tags: android, libgdx, box2d, coordinates
---


# Question
Title: In Scene2D, does Actor.hasActions() no longer exist?
Eclipse does not allow me to do

while (actor.hasActions()){}

saying it's undefined for type actor, but the libgdx API still has it as one of an Actor object functions.

# Answer
According to the source history on `Actor` , the `hasActions` method was added 7 days ago. Get latest and I think it should work for you.
> 2 votes

# Answer
You can instead do:

```
actor.getActions().size != 0

```
> -1 votes

---
Tags: libgdx, scene2d
---


title: Animation reset in libgdx

text:
# Question
Title: Animation reset in libgdx
i have an issue that i hope it's easy to resolve. I'm playing various animations in my libgdx-created game.

For a particular animation, i need that to play in loop mode but only if a particular condition is true. Simple this far.

What i need is to "reset" the animation (i mean restart from sprite n°1) when the condition become true again after the animation stopped. I know that i can simply dispose the actual animation and create another one every time the condition is true, but this seems a complicated way to resolve this..

How do i change the value of the index used by that animation? Is it possible? Do i have to create a class that extends the Animation class from libgdx library?

# Answer
Try only updating the state time of the animation when the condition is true, and then when it goes from false to true and the animation needs to re-start, set the state time to 0 again.

```
float stateTime;

void render() {
    if(condition) {
        stateTime += Gdx.graphics.getDeltaTime();
    }

    frame = animation.getKeyFrame(stateTime, true);
}

void setCondition(boolean v){
    if (v && !condition)
        stateTime=0;

    condition = v;
}

```
> 2 votes

# Answer
if you have an animation you have to give it a time, probably you give it your deltaTime but its wrong. You need a animTime, in your render you will make animTime+=deltaTime. When you want to reset simply set animTime to 0
> 0 votes

---
Tags: libgdx, animation
---


title: Is SFML a game engine?

text:
# Question
Title: Is SFML a game engine?
I am a little confused on the difference between a game engine and an actual game. By making a game, are you making a game engine, or is a game engine a library used to make a game?

# Answer
> 6 votes
Engine simply refers to the underlying software that "drives" your game. You build your game engine on top of SFML. SFML provides a simple way to create visuals, play audio, netcode etc. SFML would become part of that engine.

A game engine can come in a form of a library or with a full fledged editor and own scripting language. But SFML is not a "game" engine. Its main purpose is not just to create games. You can also build other media applications with it. SFML simply provides a layer of software which allows the developer to do things like drawing an image or play a sound. But you can consider it a collection of "engines" for producing visuals, playing audio, etc.

Usually when people speak of a game engine they are talking about a piece of software that's pretty complete on its own. The only thing missing is art(sprites/models/etc) and game logic(gameplay, input, etc ) which results in an actual game.

Even if you're making a small game with sfml, anything you write on top which "runs/drives" your game can be called an "engine". Wouldn't worry too much about it.

Library simply refers to a collection of classes/functions/subroutines/whatever to develop software with.

# Answer
> 1 votes
Actually it would be more accurate to say that a "game engine" is all code common across video games (ie: network, video, audio, etc). This "engine" is then compiled along with the video game being developed, and any additional files such as game assets (like sprites, etc).

By separating common code from game-specific code developers may better work on just the game without having to constantly reinvent the wheel.

---
Tags: sfml
---


# Question
Title: In Unity, how can I cause something to happen on a specific frame of an animation?
I have a GameObject "enemy" with an Animator and several states, like "idle", "walk", and "attack".

I want to activate the "hitbox" when an animation "attack" starts. The problems is that the sword does not fall down immediately: it takes about 2 frames.

Is there a way to know what frame of the animation is currently being run?

# Answer
> 6 votes
If you open the Animation Window (Window-\>Animation) and select your enemy **GameObject**, you can insert events for certain key frames by right clicking beneath the timeline (yellow marked area).

You can specify your own callback for this event, which has to be a function, available on your enemy. This will then be called, whenever this keyframe is being played.

---
Tags: animation, unity
---


# Question
Title: drag and drop a specific image to a specific panel and picture should not drop anywhere else except in that panel
hi guys i'm building a drag and drop in unity and I have panels and images so for example I want the bank image to drop in the panel that has bank text in it and that image shouldn't drop anywhere else please help

# Answer
> 1 votes
Add a variable to check against before you can successfully drop the image. This could be of any number type (int, float, double) any type of string, or even a char. For example, assuming you used a string...

Give the bank panel a variable:

```
public const string panel_code = "bank";

```

Give the bank image the same string:

```
public const string image_code = "bank";

```

In the function that allows you to drop the image, first check:

```
if(image_code == panel_code)
{
    //Handle Image Drop Here
}
else
{
   //Handle (or don't handle) incorrect attempt here
}

```

Don't forget to adjust your private/public appropriately, and if you need it to be more dynamic, you will probably have to remove "const" and assign the string value using a function.

If you would like it to be a more rigid, predefined system with some additional typing benefits (a drop down box to ensure consistency and convenience); try using an enum in place of a string.

Without understanding more about how your code currently works, this is probably the best I can do to help.

Hope it does :)

---
Tags: unity
---


# Question
Title: Transform.LookAt rotates the sprite and collision not triggering
I've applied the below script to a gun object to instantiate bullets to the direction of the mouse position.

The bullet collision is not getting triggered since the bullet has been rotated.

How to solve this.

```
void FixedUpdate()
    {

        mousePosition = Input.mousePosition;
        mousePosition.z = 0.0f;

        //Gun Rotation

        objectPosition = Camera.main.WorldToScreenPoint(transform.position);

        mousePosition.x = mousePosition.x - objectPosition.x;
        mousePosition.y = mousePosition.y - objectPosition.y;

        angle = Mathf.Atan2(mousePosition.y, mousePosition.x) * Mathf.Rad2Deg - 90;

        Vector3 rotationVector = new Vector3(0, 0, angle);
        transform.rotation = Quaternion.Euler(rotationVector);

        //Gun Rotation

        if (Input.GetMouseButtonDown(0))
        {
            GameObject bullet = (GameObject)Instantiate(bulletObject, transform.position, transform.rotation);
            bullet.transform.LookAt(mousePosition);
            bullet.GetComponent<Rigidbody2D>().AddForce(bullet.transform.forward * bulletSpeed);
        }

    }

```

# Answer
> 0 votes
LookAt is a 3D operation. If you change your view to 3D, you'll see that the *face* of the sprite has been rotated in 3D space to face the target:

Since LookAt is defined as changing the forward vector (i.e. the blue arrow in the image) to point at the desired target, this isn't something you're going to be able to use for 2D operations.

Instead, just use the same code you're using to point your gun object in the same direction. `bullet.rotation = Quaternion.Euler(new Vector3(0, 0, angle));`

(If your gun-pointing code isn't working, then that's an entirely different situation altogether.)

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