# Question
Title: How should I access frame buttons from a controller in an MVC approach?
I'm developing an italian card game using the mvc pattern. I have the class GameFrame that contains the view. The user's card are buttons (JButton objects). I have 3 controllers:

1. GameController: to control the game in general. Contains the game loop.
2. HumanPlayerController: to control the user input
3. ComputerPlayerController: contains the AI of the computer
4. PlayerController: is an interface with the makeTurn() method. It's implemented by HumanP.C. and ComputerP.C.

HumanPlayerController implements ActionListener too. But what is the right way to access to the GameFrame buttons? I need it for understand which card was chosen.

GameFrame and HumanPlayerController are in different packages. Should i make the JButtons public?

# Answer
The way I've done this is by defining an interface to the GUI elements that controllers want access from the view.

```
public interface GameFrameView {
    public JButton getCard();

        // Any other gui elements
}

```

And then my view classes would implement this interface

```
public class GameFrame extends JPanel implements GameFrameView {
    private JButton card;

    // Everything else about this view...

    @Override
    public JButton getCard() {
        return card;
    }
}

```

And then my controller classes would only have reference to the view classes through the interface (in this case, `GameFrameView`), which I normally fulfill via dependency injection. This way, the two are decoupled and you can change either without disrupting the other (as long as the interface doesn't change, or course).

```
public class HumanPlayerController {
    private GameFrameView gameFrameView;

    // Notice that I'm passing in reference by the interface type, not the concrete view type that implements the interface.
    public HumanPlayerController(GameFrameView gameFrameView) {
        this.gameFrameView = gameFrameView;
    }

    public void addCardButtonListener() {
        gameFrameView.getCard().addActionListener(new ActionListener()/*etc*/);
    }
}

```
> 1 votes

# Answer
Edit: My original answer did not really follow MVC, sorry for the confusion. If you look at http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller then you will see that controllers don't listen to models. So for the cases where you don't have a user involved, you either don't use MVC pattern or you replace the user by some Logic Class.

My updated design (pseudocode):

```
GameTable
  List<card> visible
  List<card> deck

  changeDeck(...) { notify_observers(Event.deck_changed) }
  changeCardOnTable(...) { notify_observers(Event.visible_cards_changed) }

GameState
  List<card> selectedCards[num_players]
  boolean gameOverManGameOver;
  int     turn

  startGame(...) { notify_observers(Event.game_started) }
  checkWin(...)  { notify_observers(Event.game_won_or_lost_etc) }
  playerChooseCard(player, card, ...) { notify_observers(Event.player_chose_card) }
  endTurn(...)   { // Do some calculations and some events }

```

AI Manager (you probably don't want to use a controller, because you have no view or user, so essentially you are merging 3 functionalities into one class, it is no longer MVC, but something different.

```
AI Manager
   SomeStrategyClass strategy;

   init(GameTable tableModel, GameState stateModel) {
      observe(tableModel)
      observe(stateModel)
   }

   onPlayerEvent(...) {
      stragegy.think(tableModel, stateModel);
      stateModel.playerChooseCard(strategy.whatToDoNext());
   }

   onInitOrWinEvent(...) {
      // Reset/start/whatever AI should simulate on this event, etc
   }

```

You don't really need a game controller, all the logic on how to play the game, should go inside your models, most likely your state model, inside nextTurn() function. Which leaves you with the remaining View and Controller

```
Player Controller
   GameState stateModel;

   chooseCard(...)         { stateModel.playerChooseCard(...); }
   resetGame(...)          { stateModel.startGame(); }
   doAction(...)           { // do something with one of your models }

Player View
   init(GameTable tableModel, GameState stateModel) {
      observe(tableModel)
      observe(stateModel)
   }
   abstract onCardChangeEvent(...);
   abstract onGameWinOrLoseEvent(...);
   abstract etcEvent(...);

```

Your JFRAME will have a combination of various gui elements, so when you build it it might be something like this.

```
 GUIFrame extends PlayerView
    Button resetButton;
    PlayerController controller;

    // Link button to controller
    init() {
       resetButton.addListener( controller.resetGame() )
       someOtherButton.addListener( controller.doAction() )
    }

    // Implement view methods
    onCardChangeEvent(...) { // redraw gui to show new card layout }
    onGameWinOrLoseEvent(...) { // display some text that the player won or lost }
    etcEvent(...) { // change the GUI to react to change in model state

```

I hope I didn't make the answer more confusing. Cheers.
> 0 votes

---
Tags: java, card-game
---


title: Reflection velocity

text:
# Question
Title: Reflection velocity
I'm trying to get a moving circular object to bounce (elastically) off of an immovable circular object. Am I doing this right? (The results look right, but I hate to trust that alone, and I can't find a tutorial that tackles this problem and includes the nitty gritty math/code to verify what I'm doing). If it is right, is there a faster or more elegant way to do this?

Note that `this` is the moving circle, and `EntPointer` is the immovable circle.

```
        //take vector separating the two centers <x, y>, and then get unit vector of the result:
        MathVector2d unitnormal = MathVector2d(this -> Retxpos() - EntPointer -> Retxpos(), this -> Retypos() - EntPointer -> Retypos()).UnitVector();

         //take tangent <-y, x> of the unitnormal:
        MathVector2d unittangent = MathVector2d(-unitnormal.ycomp, unitnormal.xcomp);

        //the velocity of the moving object in vector form:
        MathVector2d V1 = MathVector2d(this -> Retxvel(), this -> Retyvel());

        //Calculate the normal and tangent vector lengths of the velocity: (the normal changes, the tangent stays the same)
        double LengthNormal = DotProduct(unitnormal, V1);
        double LengthTangent = DotProduct(unittangent, V1);

        MathVector2d VelVecNewNormal = unitnormal.ScalarMultiplication(-LengthNormal); //the negative of what it was before

        MathVector2d VelVecNewTangent = unittangent.ScalarMultiplication(LengthTangent); //this stays the same

        MathVector2d NewVel = VectorAddition(VelVecNewNormal, VelVecNewTangent); //combine them

        xvel = NewVel.xcomp; //and then apply them
        yvel = NewVel.ycomp;

```

Note also that this question is just about velocity, the position code is handled elsewhere (in other words, assume that this code is implemented at the exact moment that the circles begin to overlap).

Thanks in advance for your help and time!

# Answer
> 4 votes
I think the more elegant, and guaranteed correct way to do this is just use the vector reflection equation to reflect the velocity of the circle around the normal of the collision:

```
MathVector2d NewVel = VectorSubtraction(V1, unitNormal.ScalarMultiplication(2.0 * DotProduct(V1, unitNormal))

```

This amounts to 1 dot product, 3 scalar multiplications, and 1 vector subtraction. Before you had 2 dot products, 4 scalar multiplications, and 1 vector addition, and I'm not entirely sure the math is correct in all cases (consider the moving circle with velocity \[1, -1\] bouncing with a normal of \[0, 1\]).

From there, you can add some fanciness such as a coefficient of restitution, which is a figure representing how much of the circle's velocity is lost during the collision.

Also, some of this math changes if the objects have rotational velocity.

---
Tags: physics, vector, geometry
---


# Question
Title: Possible to pass pygame data to memory map block?
I am building a matrix out of addressable pixels and it will be run by a Pi (over the ethernet bus). The matrix will be 75 pixels wide and 20 pixels tall. As a side project, I thought it would be neat to run pong on it. I've seen some python based pong tutorials for Pi, but the problem is that they want to pass the data out to a screen via pygame.display function.

I have access to pass pixel information using a memory map block, so is there anyway to do that with pygame instead of passing it out the video port?

In case anyone is curious, this was the pong tutorial I was looking at: Pong Tutorial

# Answer
Pygame uses a memory map and `pygame.display.flip()` and `pygame.display.update()` are the functions that update the display itself.

You just have to call pygame.display.get\_surface(), to get the screen map as a surface.
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Repelling a rigidbody in the direction an object is rotating
Working in Unity, I have a game object which I rotate each frame, like so:

```
void Update()
{
    transform.Rotate(new Vector3(0, 1, 0) * speed * Time.deltaTime);
}

```

However, I'm running into problems when it comes to applying a force to rigidbodies that collide with this game objects sphere collider. The effect I'm hoping to achieve is that objects which touch the collider are thrown in roughly the same direction as the object is rotating. To do this, I've tried the following:

```
Vector3 force = ((transform.localRotation * Vector3.forward) * 2000) * Time.deltaTime;
collision.gameObject.rigidbody.AddForce(force, ForceMode.Impulse);

```

Unfortunately this doesn't always match the rotation of the object. To debug the issue, I wrote a simple OnDrawGizmos script, which (strangely) appears to draw the line correctly oriented to the rotation.

```
void OnDrawGizmos()
{
    Vector3 pos = transform.position + ((transform.localRotation * Vector3.forward) * 2);
    Debug.DrawLine(transform.position, pos, Color.red);
}

```

You can see the result of the OnDrawGizmos function below:

What am I doing wrong?

# Answer
> 2 votes
The direction of the force applied to a point colliding with your rotating object is the tangent to the sphere, perpendicular to the axis the sphere is rotating on. You should be able to calculate it with the following pseudo-code:

```
vectorToContact = (pointOfContact - centerOfSphere);
directionOfForce = normalize(cross(vectorToContact, axisOfRotation))

```

A small detail to keep in mind is that the axisOfRotation will differ depending on whether the rotation is negative or positive, which in turn depends on whether you're in a right- or left-handed coordinate system; Unity, I believe, is left-handed.

To put that another way, let's say your sphere is rotating along the z-axis, `(0, 0, 1)`. You could either provide `(0, 0, 1)` or `(0, 0, -1)` to the cross product; both are along the z-axis. Which one you provide will depend on the sign of the rotation. If your object is rotating with a positive speed, you'd use the positive z-axis in the cross product.

Lastly, the magnitude of the force would depend on the speed at which your object is rotating, and if you're feeling adventurous, the coefficient of friction of its surface.

---
Tags: unity, rotation, quaternion, rigid-body-dynamics
---


# Question
Title: What are the pros/cons of using a 3d engine for 2d games?
What pros or cons should a beginner be aware of when deciding between a 2d game engine (like Slick2D/Flixel/FlashPunk) and a 3d engine (like Unity) for 2d game development?

I am just getting started in indie game development, though I have dabbled a bit with Game Maker, Flash, and XNA in the past. I've heard a lot of positive things about Unity, and its cross-platform nature makes it appealing, but as I understand, it's a 3d engine at its core.

For a strictly 2d game, are there any compelling reasons to work with a 3d engine like Unity? Or would it just add unneeded complexity to my initial learning experience?

# Answer
> 15 votes
It depends on the game, but for the most part, it will be easier to make a strictly 2d game using an engine that is specifically designed for 2d.

Now for some of the pros and cons (some of these will be related to Unity specifically, some of them are more general)

## Cons

1. 3d engines are usually designed around game objects being 3d models (polygons and textures). While it's certainly possible to make a flat plane and apply a texture to it, you're actively working against the engine when you do that.
2. Additionally, many 3d engines lack the ability to deal with sprite sheets (all frames of animation on one texture), because they expect animation to act on the model (though rigging and other methods), not the texture. Again, there's ways around this, but again, you're actively working against the engine to accomplish this.
3. Added complexity. As mentioned in Josh Petrie's answer, 3d is a huge bit more complex than 2d, mostly in math and scene management. Moving objects and handling 3d space is tough, and if this is one of your first games, it's just going to be all that much harder. The good news: Unity abstracts away some of these issues, though there's going to be some things you still have to handle (and much of the abstraction is, yet again, meant for 3d models, not 2d sprites)
4. Most libraries that Unity comes with or that you can get for it are meant for 3d objects. This includes stuff like lighting, pathfinding, physics, etc. In the meantime, box2d will easily work with Flash, or XNA, or something (well, maybe).

## Pros

1. 3d Acceleration. Graphics cards are a lot better at handling lots of objects in a scene than a CPU, and with Unity you can get that benefit really easily. This lets you display thousands of sprites on the screen, or include particle effects easily, or add in something fun like shaders to support cool effects like warping space and time to your will. Unity has many of these effects built in, which makes it really easy. Note that a lot of 2d engines use OpenGL or DirectX behind the scenes, and in many cases can be hardware accelerated, as well.
2. Support for models. Remember that thing that was a problem earlier? Yeah, it can be a benefit, too. Depending on the game, being able to include rotating spheres or something cool like a 3d object in the background can be a benefit. You can also have a game made out of 3d, but simply forced into a 2d perspective, which can give you the option of rotating the world geometry without having to do tons of extra graphics to handle it.
3. Learning 3d. Let's face it, lots of games are written in 3d, and if you learn how to use Unity, you'll be able to apply many of those skills to the next game which might require 3d. Additionally, a lot of artists coming out of school right now are being taught 3d modelling, so it's "easier" to find a 3d artist than a traditional 2d game artist (whether said artists are any good....)

## Conclusion

There's a lot of cons, there's also a decent amount of pros. It's all going to depend on the sort of game you want to make, it's up to you to decide if it's worth it. Flash is still an extremely viable option, so there's nothing wrong with going with a 2d engine if that's what fits your game better.

# Answer
> 7 votes
One big drawback *is* the extra complexity -- 3D engines don't always have the same level of first-class support for 2D graphics as dedicated 2D engines would. This means that it's either a lot of extra work to deal with composing and managing a 2D scene, and/or you're still having to deal with the complexity of the 3D math and transformation pipeline. Especially if you're not entirely familiar with the fundamentals of 3D graphics theory, you can find yourself lost and confused when your images don't show up and if you are not careful, you can stumble on to a "solution" that makes your images appear but isn't necessarily correct (and will thus bite you later on).

But beyond the human aspect, as long as the 3D engine has the tools you need to build your 2D game, it's not a *bad* idea to use one. They are far more prevalent these days and tend to be developed more aggressively, so that's a plus. Additionally there are probably still a handful of 2D-focused engines or frameworks out there that aren't using D3D or OpenGL behind the scenes, and thus may not be getting the benefits of modern GPUs.

In this related question you can see a lot of discussion about what might make 3D more difficult (you will only have to deal with a subset of that were you to only use the 3D engine for a 2D game though).

# Answer
> 2 votes
Pro: More effort is spent by video card manufacturers optimizing their 3D drivers. You're not stuck in 2D for special FX or fluorishes. You don't have to simulate over-and-under yourself. Switching viewpoints doesn't require a complete re-do of all your art. I'll argue that 3D scales better visually.

Con: Asset pipelines will probably have to be adapted to your engine. Some operations that are simple in 2D are more complex in 3D. Libraries will probably have extra functionality that you'll never use.

# Answer
> 0 votes
Just learn Unity if you can. Unity works REALLY well with Blender 3D which is open source and free. There are a ton of good online tutorials on how to model and animate 2D in Blender with planes. Also there are a TON of models you can download online usually for free or cheap that you can use as starting points.

This of course is assuming that you aren't adept to creating your own Game Engine. My favorite 2D game right now is Super Meat Boy which was designed in Flash and the programming end was done custom... making a game engine that suited that games particular needs. This is the best way to approach a project like that because it gives you a lot of freedom. That said it takes a lot of work to go that route.

---
Tags: 2d, 3d
---


# Question
Title: Bounding Box Collision Glitching Problem (Pygame)
So far the "Bounding Box" method is the only one that I know. It's efficient enough to deal with simple games. Nevertheless, the game I'm developing is not that simple anymore and for that reason, I've made a simplified example of the problem. (It's worth noticing that I don't have rotating sprites on my game or anything like that. After showing the code, I'll explain better).

**Here's the whole code:**

```
from pygame import *

DONE = False
screen = display.set_mode((1024,768))
class Thing():
    def __init__(self,x,y,w,h,s,c):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
        self.s = s
        self.sur = Surface((64,48))
        draw.rect(self.sur,c,(self.x,self.y,w,h),1)
        self.sur.fill(c)
    def draw(self):
        screen.blit(self.sur,(self.x,self.y))
    def move(self,x):
        if key.get_pressed()[K_w] or key.get_pressed()[K_UP]:
            if x == 1:
                self.y -= self.s
            else:
                self.y += self.s
        if key.get_pressed()[K_s] or key.get_pressed()[K_DOWN]:
            if x == 1:
                self.y += self.s
            else:
                self.y -= self.s
        if key.get_pressed()[K_a] or key.get_pressed()[K_LEFT]:
            if x == 1:
                self.x -= self.s
            else:
                self.x += self.s
        if key.get_pressed()[K_d] or key.get_pressed()[K_RIGHT]:
            if x == 1:
                self.x += self.s
            else:
                self.x -= self.s
    def warp(self):
        if self.y < -48:
             self.y = 768
        if self.y > 768 + 48:
             self.y = 0
        if self.x < -64:
             self.x = 1024 + 64
        if self.x > 1024 + 64:
             self.x = -64
r1 = Thing(0,0,64,48,1,(0,255,0))
r2 = Thing(6*64,6*48,64,48,1,(255,0,0))
while not DONE:
    screen.fill((0,0,0))
    r2.draw()
    r1.draw()
    # If not intersecting, then moves, else, it moves in the opposite direction.
    if not ((((r1.x + r1.w) > (r2.x - r1.s)) and (r1.x < ((r2.x + r2.w) + r1.s))) and (((r1.y + r1.h) > (r2.y - r1.s)) and (r1.y < ((r2.y + r2.h) + r1.s)))):
        r1.move(1)
    else:
        r1.move(0)
    r1.warp()
    if key.get_pressed()[K_ESCAPE]:
        DONE = True
    for ev in event.get():
        if ev.type == QUIT:
            DONE = True
    display.update()
quit()

```

**The problem:**

In my actual game, the grid is fixed and each tile has 64 by 48 pixels. I know how to deal with collision perfectly if I moved by that size. Nevertheless, obviously, the player moves really fast.

In the example, the collision is detected pretty well (Just as I see in many examples throughout the internet). The problem is that if I put the player to move WHEN IS NOT intersecting, then, when it touches the obstacle, it does not move anymore. Giving that problem, I began switching the directions, but then, when it touches and I press the opposite key, it "glitches through". My actual game has many walls, and the player will touch them many times, and I can't afford letting the player go through them.

**The code-problem illustrated:**

When the player goes towards the wall (Fine).

When the player goes towards the wall and press the opposite direction. (It glitches through).

Here is the logic I've designed before implementing it:

I don't know any other method, and I really just want to have walls fixed in a grid, but move by 1 or 2 or 3 pixels (Slowly) and have perfect collision without glitching-possibilities. What do you suggest?

# Answer
> 1 votes
It is probably because you are hitting right on the border and are not checking for that.

```
# if collision move opposite else move forward
if  ((((r1.x + r1.w) >= (r2.x - r1.s)) && (r1.x <= ((r2.x + r2.w) + r1.s))) && (((r1.y + r1.h) >= (r2.y - r1.s)) && (r1.y <= ((r2.y + r2.h) + r1.s)))):
    r1.move(0)
else:
    r1.move(1)

```

Also I think there are a couple of errors in your `warp()`. I think it should read:

```
def warp(self):
    if self.y < -48:
         self.y = 768
    if self.y > 768 + 48:
         self.y = 0
    if self.x < -64:
         self.x = 1024    <----- here
    if self.x > 1024 + 64:
         self.x = 0     <------ and here

```

---
Tags: collision-detection, python, pygame, grid
---


# Question
Title: How do I rotate a sprite with ccbezierTo in cocos2d-x?
In cocos2d-x, I move a sprite with `ccbezierTo` like this:

```
// use for ccbezierTo
bezier.controlPoint_1 = ccp(m_fish->getPositionX() + 200, visibleSize.height/2 + 300);
bezier.controlPoint_2 = ccp(m_fish->getPositionX() + 400, visibleSize.height/2 - 300);
bezier.endPosition = ccp(m_fish->getPositionX() + 600,visibleSize.height/2);

bezier1.controlPoint_1 = ccp(m_fish->getPositionX() + 800, visibleSize.height/2 + 300);
bezier1.controlPoint_2 = ccp(m_fish->getPositionX() + 1000, visibleSize.height/2 - 300);
bezier1.endPosition = ccp(m_fish->getPositionX() + 1200,visibleSize.height/2);

bezierForward = CCBezierTo::create(6, bezier);
nextBezier = CCBezierTo::create (6,bezier1);

m_fish->runAction(CCSequence::create( bezierForward, nextBezier, NULL));

```

How can I make my sprite rotate while moving it with `CCBezierTo`?

# Answer
i found a solution on this site. Use this very useful code:

```
 CGPoint oldpos = [[self target] position];
    [super update:time];
    CGPoint newpos = [[self target] position];
    float angle = atan2(-newpos.y + oldpos.y, newpos.x - oldpos.x) * 180 / M_PI;
    angle += 90; // my sprites start pointing up
    [[self target] setRotation:angle];

```

and sprite can rotate when move with ccbezierTo.
> 0 votes

---
Tags: cocos2d, cocos2d-x, transformation
---


title: spinning a 2d Cube

text:
# Question
Title: spinning a 2d Cube
I know that a cube is actually a 3d shape , but i have some other problem over here.

I have been doing 2D Game dev using libgdx but have never touched 3D rendering. Now what I want in my 2D game is that instead of coins I make my player collect magical cubes. But those cubes need to be spinning on one Diagonal, same can be seen in popular game Vector.

Here is a screenshot.

Can someone explaing the mathematics of such an animation

# Answer
There is no need to create an actual 3D object within your game to achieve that.

Simply make an animation of a cube rotating and render that. It's simple! LibGDX has a short tutorial written about it.
> 3 votes

---
Tags: 2d, 3d, rendering
---


# Question
Title: How can I convert an image from raw data in Android without any munging?
I have raw image data (may be .png, .jpg, ...) and I want it converted in Android without changing its pixel depth (bpp). In particular, when I load a grayscale (8 bpp) image that I want to use as alpha (`glTexImage(`) with `GL_ALPHA`), it converts it to 16 bpp (presumably `5_6_5`).

While I do have a plan B (actually, I'm probably on plan 'E' by now, this is really becoming annoying) I would really like to discover an easy way to do this using what is readily available in the API.

So far, I'm using `BitmapFactory.decodeByteArray()`.

While I'm at it. I'm doing this from a native environment via JNI (passing the buffer in from C, and a new buffer back to C from Java). Any portable solution in C/C++ would be preferable, but I don't want to introduce anything that might break in future versions of Android, etc.

# Answer
> 2 votes
Note that since JPEG images use a Y or YUV colourspace they do not really have a pixel depth and thus there is no "right" depth for them. That said, you are correct in expecting a 8bpp grayscale image when decoding a monochrome JPEG.

I don't know of an available API to achieve what you are trying to do in an automatic way. However, you can ask for a specific depth using the `BitmapFactory` preferred options:

```
 BitmapFactory.Options opts = new BitmapFactory.Options();
 // This option is suitable for monochrome JPEGs:
 opts.inPreferredConfig = Bitmap.Config.ALPHA_8;
 // This option is suitable for 32-bit PNGs:
 opts.inPreferredConfig = Bitmap.Config.RGB_8888;

 bitmap = BitmapFactory.decodeByteArray(data, 0, len, opts);

```

This is still a hint for the decoder and does not guarantee that you will always get what you expect. I have additional suggestions:

* embed your own versions of libPNG and/or libJPEG. I suggest trying libjpeg-turbo which allows to fine-tune the available colourspaces even more.
* instead of using PNG or JPEG as your interchange format, use one or several texture compression formats suitable for your target devices; there are readily available tools to convert PNGs to ETC1, which is part of the OpenGL ES standard. Maybe add a layer of `gzip` on top of that.
* do not hesitate to experiment and try **generic compression methods**: store your image just as you would upload it to the video card, and compress it using `libgz` or `libbzip2`. I have images that get significantly smaller using bzip2 on an uncompressed version than when crushing with pngcrush. That may be an acceptable tradeoff.

Hope this helps!

# Answer
> 0 votes
To convert raw to image, the best Java API is *ImageIO*.

Documentation: ImageIO @ Java API

It may help you.

---
Tags: android, opengl-es, textures
---


# Question
Title: difference between cocos2d-x vs cocos2d-js
I'm just moving towards native apps... A friend of mine told me to start with cocos2d, I'm good in javascript. While searching google for cocos2d, and within cocos2d-x.org I found

1. cocos2d-x
2. cocos2d-JSB
3. cocos2d-html5
4. cocos2d-Javascript

I know what cocos2d-x is for.. and what cocos2d-html5 is for.. but what is cocos2d-JSB and cocos2d-Javascript.. Can somebody please tell me.. what exactly these 2 things are.. My questions are:

1. Can we develop 100% pure native apps/games in cocos2d-JSB and or cocos2d-javascript.
2. I also know cocos2d-JSB is javascript bindings.. but what does that exactly mean?..
3. Last but not least question.. what is cocos2d-Javascript for?.. does that work alone or we need cocos2d-html5 to make it previewable in iOS/Android/WindowsPhone...

Please give me Details.. because i'm so confused... I want to develop native apps for iOS/Android and WindowsPhone.

Thank you

# Answer
> 4 votes
It's quite simple actually: cocos2d javascript is the join up of cocos2d-x's JSB and cocos2d html5. It's just a name given to that mix up.

JSB is a set of Javascript native function overwrites that, when interpreted by the necessary scripts, are converted to their native correspondents. And these native functions are interpreted by the compiler, resulting in an application.

My suggestion is that you program your games in cocos2d html5 AND use cocos2d-x JSB to do the heavy lifting for you. But I'll already warn you, there will be small code modifications and to create an IPA, you will need to compile using Xcode, what means you will need a Mac.

So, answering in order:

1. Yes, you can. Because of JSB.
2. It is a set of scripts made to convert your JS code into it's native equivalent;
3. It's the join up of cocos2d-html5 with JSB, it is what makes the true cross-platform possible. You don't need to actually use html5, but i strongly recommend. Using it will let you debug in browser before trying to deploy

Maybe these links will be useful to you:

1. http://www.raywenderlich.com/32970/how-to-make-a-cross-platform-game-with-cocos2d-javascript-tutorial-getting-started
2. http://www.raywenderlich.com/33028/how-to-make-a-cross-platform-game-with-cocos2d-javascript-tutorial-the-platforms

Good Luck!

---
Tags: android, ios, cocos2d, cocos2d-x, cocos2d-x-js
---


title: How to optimize collision detection

text:
# Question
Title: How to optimize collision detection
I am developing a 2D Java Game with LibGDX. This is what it kinda looks like (simplified):

The big black circle is the player, which you can move by tilting the smartphone. The red circles and blue rectangles are enemies, which will move from the right of the screen to the left. The player has to avoid crashing into them.

Right now I am checking in the Game Loop every enemy against the player, whether they collide or not. This seems kinda inefficient to me, but I don't know how to improve it.

I have tried the Quadtree approach, but it did not really work. The player could easily glitch through enemies and the collision was not detected. Unfortunately, I have destroyed the Quadtree implementation. I used this tutorial/blog as my Quadtree implementation.

# Answer
> 5 votes
Andon's answer is really good. Here's another way to approach it. Which includes his method and mine.

Sorting.

For there to be a collision your black dot has to be within a range both in the x and y axis. Both. So you could have an algorithm that puts each of your red and blue dots in an xZone and a yZone. Let's say you're using coordinates of -200 to +200 on x and y. If your objects are 20 pixels wide, they have to be within so many pixels of each other in order to collide. So make your zones the size of that range. Then you know that you only have to check within 3 zones horizontally and 3 zones vertically. That's basically what And on said - although his was velocity based and mine is just zone based.

Then I add to that: sort the objects. Give each zone a number. In my example below: `zoneNum = xZone * 20 + yZone.` It will be different for you depending on how many zones tall and wide you decide you need. Also figuring out the xZone and yZone is a formula based on your coordinate scale and the number of zones you decide to have.

The black dot is in zone 62. Therefore you only need to check dots that are in zones 41-43, 61-63, and 81-83. When the black dot moves, create a `checkFirstZone` and a `checkLastZone`.

Then sort the array of red and blue objects by zoneNum. Or sort each category individually if they're in different arrays. You only have to do this when they move. If they don't move in your game it's only once. As you sort them though create a `checkFirstBlueIndex`.

When checking collisions, start at checkFirstBlueIndex and check until you're past the last zone, skipping zones that aren't needed to be checked.

```
int x=checkFirstBlueIndex
do while done==false
    if blue[x].zoneNum > checkLastZone or x>numberOfBlues then done=true;
    checkBlueCollisionForIndex(x);
    x++;
 end do loop

```

The above would check all indexes from zone 41 to 83. Which is still 48 more zones than you need to check. So based on how much speed increase you need, you could also limit it to only check those 9 zones. Math. There are simple formulas for knowing if a zone needs to be checked or not.

You could add that part to your checkBlueCollisionForIndex() function - first check if it's in a hot zone, but you'd have to test the speed on that.

One other way would be to check the 3 zones in each of the 3 lines. So you could have a `zoneLineEnd` which you'd set to 'checkFirstZone' plus 3. When you pass that skip to the next line. Something like this:

```
zoneLineEnd = checkFirstZone + 3;
x = checkFirstBlueIndex;
do while done==false;
    if blue[x].zoneNum > zoneLineEnd then done=true;
    checkBlueCollisionForIndex(x);
    x++;
end do loop
// then skip ahead until the next line start
do while blue[x].zoneNum < zoneLineEnd+18 or x>numberOfBlues
   x++;
end do loop
zoneLineEnd+=3;
// then repeat the check for the 3 zones on that line.
// then repeat the skip again and the next check.

```

When your black dot moves zones you do have to reset `checkFirstZone, checkLastZone'. And skip ahead to find 'checkFirstBlueIndex`. Add something like this before the above pseudo code.

```
if blackDotMoved {
    done=false;
    x=0;
    do while done==false
        if blue[x].zoneNum==checkFirstZone
            checkFirstBlueIndex = x;
            done=true;
        end if
    end do
end if

```

Of course when you're on the edge of the screen the zone math might wrap around and check collisions on the other side of the screen. This might not be a big deal since your collision detection will already handle that. You probably don't need to worry about checking 3 extra zones. At some level it's faster to check them than to check to see if you need to check them.

In the end though, you have to check and weigh if sorting and checking zones takes less time than just checking each dot. With a handful of dots like this, sorting probably takes longer. But with 500 dots sorting and skipping will be a big help.

In my game my ship only moves forward and my terrain is presorted by xUnit. So no matter how long my terrain is I only have to check collisions on a small set at a time. I split the world into zones and my startZoneIndex moves forward as the ship moves forward. And I only check collisions for the 3 zones ahead of that.

*** UPDATE ***

I just noticed that you said your enemies only move left to right. In that case you might want to make your zones go left to right instead of top to bottom. Then your sorting could work better. To make things faster I might only do xZones and then you're just checking 3 zones, but more objects since the zones are the full height. It always depends on the details of your game. But maybe once a colored dot has moved beyond the black dot you never have to check it again. Unless the black dot can zip over there. Depends on your game.

# Answer
> 5 votes
The easiest thing to do would be to cluster these points into a 2D grid (my brain is already hardwired to do that when I see colored squares and circles).

Determine the largest number of grid lines your player can cross in each dimension given its current velocity and then throw out any enemies that are not within +/- n-many grid lines of the player. You can do all of that with a few integer comparisons and reserve complicated tests involving floating-point arithmetic, euclidean distance, etc. for points that actually need to be tested.

Imagine drawing a bunch of evenly spaced grid lines (horizontal and vertical) through the diagram you already showed. Whenever an enemy moves, have it place itself into the appropriate grid cell; this is trivial, just divide its x,y coordinate by the distance between each grid line and throw out the fractional part. There are more sophisticated data structures you can use to further accelerate this process (*e.g.* kD trees, quadtrees, etc.), but what it boils down to in the end is partitioning (clustering) the enemies into groups for broad-phase rejection.

# Answer
> 2 votes
I was in a very similar situation not long ago and what I did was to stick to your original approach. It's far easier, but you know your needs and situation better. You do have to check collisions between the player and each obstacle, but to improve the performance you can implement a broad phase check before the actual collision check. First, you find the distance between the enemy and the character. If it's "close enough" (up to you to define what that means") then perform a collision check. Otherwise, carry on to the next enemy.

Also, you said in the comments that you set your enemies to `null` once they're out of the "game field". I assume you then create a new instance of an enemy when you need a new one. That's definitely going to waste a lot of time and could temporarily freeze your application during garbage collection. But you already received a suggestion to use an object pool instead. That's also what I ended up using. :)

---
Tags: java, collision-detection, libgdx
---


# Question
Title: How to remove seams from a tile map in 3D?
I am using my OpenGL custom engine to render a tilemap made with Tiled, using a well spread tileset from the web. There is nothing fancy going on. I load the TMX file from Tiled and generate vertex arrays and index arrays to render the tilemap. I am rendering this tilemap as a wall in my 3D world, meaning that I move around with a fly camera in my 3D world and at Z=0 there is a plane showing me my tiles. Everything is working correctly but I get ugly seems between the tiles.

I've tried orthographic and perspective cameras and with either I found particular sets of parameters for the projection and view matrices where the artifacts did not show, but otherwise they are there 99% of the time in multiple patterns, depending on the zoom and camera parameters like field of view.

Here's a screenshot of the artifact being shown: https://i.stack.imgur.com/5y3kr.png Here's the tileset I am using (which Tiled also uses and renders correctly): https://i.stack.imgur.com/SD48p.png

My tileset has no mipmaps and is set to GL\_NEAREST and GL\_CLAMP\_TO\_EDGE values. I've looked around many articles in the internet and nothing helped.

I tried uv correction so the uv fall at half of the texel, rather than the end of the texel to prevent interpolating with the neighbour value(which is transparency). I tried debugging with my geometry and I verified that with no texture and a random color in each tile, I don't seem to see any seams. All vertices have integer coordinates, i.e, the first tile is a quad from (0,0) to (1,1) and so on. Tried adding a little offset both to the UV and to the vertices to see if the gaps cease to exist. Disabled multisampling too. Nothing fixed it so far.

Thanks.

# Answer
I'm sorry but I solved it myself. I was dumb enough to perform the texel correction wrong the first time, and now I came back to it and did it properly, everything started working properly with no visible artifacts.

Feel free to delete my question; Either way, here's the solution for the correct UV's:

```
vec2 texel_correction(1.f / tilesetWidth , 1.f / tilesetHeight);

topLeftU = float(tileLeft) / tilesetWidth + texel_correction.x;
topLeftV = float(tileTop) / tilesetHeight + texel_correction.y;
bottomRightU = float(tileLeft + tileWidth) / tilesetWidth - texel_correction.x;
bottomRightV = float(tileTop  + tileHeight) / tilesetHeight - texel_correction.y;

```
> 2 votes

---
Tags: opengl, tilemap, seams
---


# Question
Title: Slick UnicodeFont displays in different location depending on the screen size?
I am using the Slick2D library to draw text. The text draws perfectly, however it is in the wrong location!

I could easily draw it in the correct location, however the problem is that the "correct location" is very different depending on the size of the screen - And my game needs to be able to have the screen size changed.

Here is the render method for the text:

```
 public static void render() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glUseProgram(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glMatrixMode(GL_PROJECTION);
    glLoadMatrix(orthographicProjectionMatrix);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();
    glDisable(GL_LIGHTING);
    font.drawString(0, 0, "OMG ITS TEXT!", Color.green);
    glEnable(GL_LIGHTING);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glLoadMatrix(perspectiveProjectionMatrix);
    glMatrixMode(GL_MODELVIEW);
}

```

So, how can I set the text to be in the middle of the screen irrespective of screen size?

Thanks!

# Answer
> 1 votes
Ok so I haven't used slick2d for a long time but basically you need to find the screens width and height and then divide them by 2 like so...

Paste these at the top of the class in the public variable section

```
int width;
int height;

```

Paste these in the method that has the "GameContainer" reference

```
width = container.getWidth() / 2;
height = container.getHeight() / 2;

```

If you don't have a GameContainer reference then try this

```
width = Display.getWidth()/2;
height = Display.getHeight()/2;

```

These return the centre of the screen... Next you want to use those variables for the drawing of you string like so...

Replace

```
font.drawString(0, 0, "OMG ITS TEXT", Color.green);

```

With

```
font.drawString(width, height, "OMG ITS TEXT", Color.green);

```

Now it should display the words in the centre of your screen... I can't remember where the anchor point for text is but you may have to find the width of the text and divide that by 2 then subtract it from the "width" variable to have perfectly centred text...

Like I said, I haven't used slick for a long long time and I am on my phone so I didn't get a chance to test it...

I hope this clears it up for you

---
Tags: java, lwjgl
---


title: 2D Tile Collision free movement

text:
# Question
Title: 2D Tile Collision free movement
I'm coding a 3D game for a project using OpenGL and I'm trying to do tile collision on a surface.

The surface plane is split into a grid of 64x64 pixels and I can simply check if the (x,y) tile is empty or not.

Besides having a grid for collision, there's still free movement inside a tile.

For each entity, in the end of the update function I simply increase the position by the velocity:

```
pos.x += v.x;
pos.y += v.y;

```

I already have a collision grid created but my collide function is not great, i'm not sure how to handle it. I can check if the collision occurs but the way I handle is terrible.

```
int leftTile = repelBox.x / grid->cellSize;
int topTile = repelBox.y / grid->cellSize;
int rightTile = (repelBox.x + repelBox.w) / grid->cellSize;
int bottomTile = (repelBox.y + repelBox.h) / grid->cellSize;

for (int y = topTile; y <= bottomTile; ++y)
{
    for (int x = leftTile; x <= rightTile; ++x)
    {

        if (grid->getCell(x, y) == BLOCKED){
            Rect colBox = grid->getCellRectXY(x, y);
            Rect xAxis = Rect(pos.x - 20 / 2.0f, pos.y - 20 / 4.0f, 20, 10);
            Rect yAxis = Rect(pos.x - 20 / 4.0f, pos.y - 20 / 2.0f, 10, 20);

            if (colBox.Intersects(xAxis))
                v.x *= -1;

            if (colBox.Intersects(yAxis))
                v.y *= -1;

        }
    }
}

```

If instead of reversing the direction I set it to false then when the entity tries to get away from the wall it's still intersecting the tile and gets stuck on that position.

EDIT: I've worked with Flashpunk and it has a great function for movement and collision called **moveBy**. Are there any simplified implementations out there so I can check them out?

# **EDIT2: I've figured out a solution, you can check the answer below**

# Answer
## **I solved it for now.**

You can use that code in your programs to check for grid collision and allowing free movement inside a tile. I already have a grid created with tile info already there. Here's the code:

```
XY vertical = XY(0, 1);
XY horizontal = XY(1, 0);
XY diagonal = XY(1, 1);

void Entity::moveBy(float x, float y){
vec2f direccao = vec2f((x > 0) ? 1 : -1, (y > 0) ? 1 : -1); // direction vector

Rect newBoundingBox = Rect(pos.x + x - 20 / 2.0f, pos.y + y - 20 / 2.0f, 20, 20); // new bounding box for future position (future position = x + velocity.x

XY playerCell = XY((int)(pos.x / grid->cellSize), (int)(pos.y / grid->cellSize)); // get the cell the player is in giving the world pos. Eg: 38, 20

XY vert = direccao * vertical; // multiply direction vector with vertical vector = (dir.x * vert.x, dir.y * vert.y)
XY hori = direccao * horizontal; // multiply direction vector with horizontal vector = (dir.x * hori.x, dir.y * hori.y)

//this will get the cell in the vertical axis that the entity can collide
vert = vert + playerCell; // vert = (vert.x + playerCell.x, vert.y + playerCell.y)
hori = hori + playerCell; //repeat previous operation for horizontal axis

// if blocked vertical -> y
if (grid->getCell(vert.x, vert.y) == BLOCKED){
    Rect col = grid->getCellRectXY(vert.x, vert.y);
    if (!col.Intersects(newBoundingBox))  // simple AABB collision detection
        pos.y += y;

}
else
    pos.y += y;

// if blocked horizontal -> x
if (grid->getCell(hori.x, hori.y) == BLOCKED){
    Rect col = grid->getCellRectXY(hori.x, hori.y);
    if (!col.Intersects(newBoundingBox))
        pos.x += x;
}
else
    pos.x += x;

// not doing diagonal collision check for now

}

```
> 0 votes

# Answer
There are two ways you can perform collision detection:

1. Check in advance whether there's a collision, then move
2. First move, then check whether we're in collision and correct our position

I'm not sure which way you're doing it, but given the fact you've said the entity is still intersecting the tile, I'm assuming it's the latter.

If so, try correcting the entity's position so that it doesn't intersect anymore. E.g. snap the entity to tile's borders, when it will try to cross it.

OpenGL does not have collision detection functionality. You could try using something more high-level like Ogre3D or low(er)-level like SDL. They should make your life a bit easier.
> 1 votes

---
Tags: collision-detection, grid, tiles
---


title: Issue with multiplayer interpolation

text:
# Question
Title: Issue with multiplayer interpolation
In a fast-paced multiplayer game I'm working on, there is an issue with the interpolation algorithm. This interpolation is for a moving object not controlled by the local computer.

The server sends packets with the object's position at a fixed rate. (red markers) The interpolation algorithm is attempting (and failing) to create a smooth path between the red markers.

The results of this interpolation are shown by green and black markers. Green is the local position at the exact time a packet is received, and black is the local position at every frame.

**Green:** Local position when a packet is received (edited for clarity)

**Red:** Position received from packet (goal)

**Blue:** Line from local position to goal when packet is received

**Black:** Local position every frame

On a network with a realistic amount of lag and packet loss, this is the result:

The local position (green&black lines) seems to oscillate around the goals (red lines) instead of moving between them smoothly.

This is how it looks on a perfect network with the object moving right to left. (0 ping, 0 packet loss, etc.)

The code works like this:

1. Every x ms, receive a packet with a Vector3 position
2. Set the `goal` to that position
3. Set the `positionAtLastPacket` to the current local position
4. Every frame, lerp from `positionAtLastPacket` to `goal`, attempting to reach the goal approximately when the next packet should arrive.
5. If the next packet takes longer than expected, interpolation continues past the goal and becomes extrapolation.

I believe what is happening is the extrapolation overshoots a bit to far. Over several packets, this issue compounds, causing the oscillation.

```
    // local transform position when the last packet arrived. Will lerp from here to the goal
    private Vector3 positionAtLastPacket;

    // location received from last packet
    private Vector3 goal;

    // time since the last packet arrived
    private float currentTime;

    // estimated time to reach goal (also the expected time of the next packet)
    private float timeToReachGoal;

    private void PacketReceived(Vector3 position, float timeBetweenPackets)
    {
        positionAtLastPacket = transform.position;

        goal = position;

        timeToReachGoal = timeBetweenPackets;
        currentTime = 0;

        Debug.DrawRay(transform.position, Vector3.up, Color.cyan, 5); // current local position
        Debug.DrawLine(transform.position, goal, Color.blue, 5); // path to goal
        Debug.DrawRay(goal, Vector3.up, Color.red, 5); // received goal position
    }

    private void FrameUpdate()
    {
        currentTime += Time.deltaTime;

        float delta = currentTime/timeToReachGoal;
        transform.position = FreeLerp(positionAtLastPacket, goal, currentTime / timeToReachGoal);

        // current local position
        Debug.DrawRay(transform.position, Vector3.up * 0.5f, Color.black, 5);
    }

    /// <summary>
    /// Lerp without being locked to 0-1
    /// </summary>
    Vector3 FreeLerp(Vector3 from, Vector3 to, float t)
    {
        return from + (to - from) * t;
    }

```

Any idea about what's going on?

# Answer
Welp, it turns out my router was messed up, causing the game to fall back on TCP without warning. Everything is working fine now, I'm just stupid.

I should have realized something was wrong when the packets started coming in like this:

There were many other things causing the game to fall back on TCP. Some of them are specific to TNet (my framework) but I'll list them off just in case:

* The Unity Web player doesn't support UDP at all for security reasons.
* Using a VPN to connect back to a server on your local network (in an attempt to test with high ping) will often cause UDP to fail. I don't know why exactly, so it might be specific to my VPN.
* Mixing up the ports for a TNet server, or connecting on the wrong ports. It's a bit confusing to get right, so here is the *correct* way: (using example port numbers)

Create:

```
TNServerInstance.Start(TCP_PORT, UDP_PORT, null, BROADCAST_PORT);

```

Discovery on LAN:

(set your lobby port to BROADCAST\_PORT)

Connect:

```
TNManager.Connect(xxx.xxx.xxx.xxx, TCP_PORT);

```

---

Overall, I highly recommend getting a VPS to host your server for testing, which would have made fixing this problem much easier to discover and find. Digital Ocean has served me well, and it only costs $5/month for more badnwidth and power than I would ever need.
> 0 votes

---
Tags: unity, multiplayer, interpolation
---


# Question
Title: Phone crash when try to use vibration on Android
Im developing an app that when you click a button the phone has to vibrate, the issue is that the phone just chashes. Saing that I need permitions to vibrate. I've already set this permition in the build.setting (android manifiest).

Here is the code

build.settings:

```
settings =
{
orientation = {
    default = "portrait",
    supported = { "portrait", }
},

iphone =
{
    plist=
    {
        CoronaUseIOS7LandscapeOnlyWorkaround = true,
        CoronaUseIOS7IPadPhotoPickerLandscapeOnlyWorkaround = true,
        CoronaUseIOS6LandscapeOnlyWorkaround = true,
        CoronaUseIOS6IPadPhotoPickerLandscapeOnlyWorkaround = true,
        UIApplicationExitsOnSuspend = false,
        UIPrerenderedIcon = true,
        UIStatusBarHidden = false,
        CFBundleIconFile = "Icon.png",
        CFBundleIconFiles =
        {
            "Icon.png",
            "Icon@2x.png",
            "Icon-60.png",
            "Icon-60@2x.png",
            "Icon-72.png",
            "Icon-72@2x.png",
            "Icon-76.png",
            "Icon-76@2x.png",
            "Icon-Small.png",
            "Icon-Small@2x.png",
            "Icon-Small-40.png",
            "Icon-Small-40@2x.png",
            "Icon-Small-50.png",
            "Icon-Small-50@2x.png",
        },
    },
},
android =
{
    permissions =
    {
        { name = ".permission.C2D_MESSAGE", protectionLevel = "signature" },
    },
    usesPermissions =
    {
        "android.permission.INTERNET",
        "android.permission.VIBRATE",
    },
},
}

```

the file that uses the vibration is:

```
local onButtonEvent = function (event )

        system.vibrate()
end

```

I read all post in Corona page without success. Can I see the android manifest to see if the permissions are there. I've read that is a Corona issue not sure.

# Answer
It worked with the following build.settings:

```
settings =
{
orientation = {
    default = "portrait",
    supported = { "portrait", }
},

iphone =
{
    plist=
    {
        CoronaUseIOS7LandscapeOnlyWorkaround = true,
        CoronaUseIOS7IPadPhotoPickerLandscapeOnlyWorkaround = true,
        CoronaUseIOS6LandscapeOnlyWorkaround = true,
        CoronaUseIOS6IPadPhotoPickerLandscapeOnlyWorkaround = true,
        UIApplicationExitsOnSuspend = false,
        UIPrerenderedIcon = true,
        UIStatusBarHidden = false,
        CFBundleIconFile = "Icon.png",
        CFBundleIconFiles =
        {
            "Icon.png",
            "Icon@2x.png",
            "Icon-60.png",
            "Icon-60@2x.png",
            "Icon-72.png",
            "Icon-72@2x.png",
            "Icon-76.png",
            "Icon-76@2x.png",
            "Icon-Small.png",
            "Icon-Small@2x.png",
            "Icon-Small-40.png",
            "Icon-Small-40@2x.png",
            "Icon-Small-50.png",
            "Icon-Small-50@2x.png",
        },
    },
},
android =
{
    permissions =
    {
        { name = ".permission.C2D_MESSAGE", protectionLevel = "signature" },
    },
    usesPermissions =
    {
        "android.permission.INTERNET",
        "android.permission.VIBRATE",
    },
},
}

```
> 1 votes

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


# Question
Title: Generate 2D Triangular Mesh from Vertices on a Map
Given a map of vertices `{(x1,y1), (x2,y2), ... (xn,yn)}`, how can I generate a 2D triangular mesh covering all vertices, and where the area of all triangles completely covers the map?

The triangular areas may fully enclose other triangular areas, but no two triangles may intersect.

# Answer
First you need to create a polygon from the points. One way to do that is start with the point with the smallest x (since that has to be part of the final polygon). Let's call that point A. Then you need to find the next point of the polygon. Since the polygon has to contain all the other points you can pick one (B) and test if all the other points are to the right of that line. If you find a point to the left you set that to B instead. In the following picture the blue line is the edge we're testing and the green is the point we're testing against:

The line from A-B is then the first edge of the polygon. After that you do the same thing with B as A. Repeat this until the next point in the polygon should be the first point, i.e. you've closed it. In the example above you'll get this:

The next step is to triangulate it. There are many algorithms for this, but if you want to do it yourself I'd recommend ear clipping since your polygon won't contain any holes.
> 2 votes

---
Tags: algorithm, maps, mesh
---


# Question
Title: How to make other semantics behave like SV_Position?
I'm having a lot of trouble with shadow mapping, and I believe I've found the problem. When passing vectors from the vertex shader to the pixel shader, does the hardware automatically change any of the values based on the semantic?

I've compiled a barebones pair of shaders which should illustrate the problem.

Vertex shader :

```
struct Vertex {
    float3 position : POSITION;
};

struct Pixel {
    float4 position : SV_Position;
    float4 light_position : POSITION;
};

cbuffer Matrices {
    matrix projection;
};

Pixel RenderVertexShader(Vertex input) {
    Pixel output;
    output.position = mul(float4(input.position, 1.0f), projection);
    output.light_position = output.position;
    // We simply pass the same vector in screenspace through different semantics.
    return output;
}

```

And a simple pixel shader to go along with it:

```
struct Pixel {
    float4 position : SV_Position;
    float4 light_position : POSITION;
};

float4 RenderPixelShader(Pixel input) : SV_Target {
    // At this point, (input.position.z / input.position.w) is a normal depth value.
    // However, (input.light_position.z / input.light_position.w) is 0.999f or similar.
    // If the primitive is touching the near plane, it very quickly goes to 0.

    return (0.0f).rrrr;
}

```

How is it possible to make the hardware treat light\_position in the same way which position is being treated between the vertex and pixel shaders?

This differrence is almost exclusive to the Z component, as the X and Y values of light\_position are behaving as expected.

EDIT: Aha! `(input.position.z)` without dividing by W is the same as `(input.light_position.z / input.light_position.w)`. Not sure why this is.

EDIT 2: Dividing (output.light\_position) by (output.light\_position.w) in the vertex shader causes really odd behavior, where (input.light\_position.z / input.light\_position.w) will be either 0 or 1 based on the camera's position and angle.

EDIT 3: Moving the projection multiplication into the pixel shader doesn't seem to make any difference. This means that the hardware is doing something to the SV\_Position semantic which is critical to make it work.

EDIT 4: (input.light\_position.z / input.light\_position.w) IS behaving like depth, it's just that the precision seems to have decreased unbelievably. Only does it approach 0 once it's primitive literally intersects the near plane.

# Answer
> 0 votes
Turns out, the depth values were correct the whole time. I was looking at a bad image for reference, where objects would get darker as they got further away from you. Of course, this is completely incorrect.

---
Tags: hlsl, directx11, shadow-mapping, interpolation
---


title: Driver inversion

text:
# Question
Title: Driver inversion
I have a GUI game, which is driven by user every time it clicks the mouse. Every time user clicks a square on a board, the board state is updated (we re-compute the score, the player to make next move and legal movements it can make) and repainted. Both mouse click, state recomputation and painting are handled in the GUI thread. Now, suppose that I want to train AI to play without GUI. That is, game engine should consume next move by simply calling AI's `makeMove` function in one thread. This would allow to play millions of games per second automatically. GUI may just screenshot some arbitrary states time after time. How do you switch to this strategy?

# Answer
The Philip's proposal to separate design into game/view/controller seems plausible. He however proposes muliple threads, which seems an overkill. I have discovered that using secondary loops permits to avoid unnecessary multithreading (I see no useful jobs those threads could do -- I am discussing a linear flow of control).

We design a game model, and start a game from our main thread

```
void play() {
    initializeSquaresAndPlayers()
    while (true) {
        foreach(player) if wins(player) {
            updateStatus(player + " wins", true)
            break
        }
        updateStatus(status(), false);
        Point square = move(); // request user choice
        if (square == null) {
            updateStatus("current game terminated", true);
            return;
        }
        go(square); // update game state
    }
}

```

`Game.play` loops requesting user move until somebody wins or game is terminated by `null` response (that is useful if user wants to restart the game). The Controller/Viewer must implement two methods

```
abstract Point move();
abstract void updateStatus(Stirng status, boolean gameOver);

```

They are strightforward in case of console game (I used random square for `move` and printed status into console, ignoring gameOver). The gui is more complex. At first, you start the game.play loop by (that is my applet)

```
public void init () {
    createControls();
    restart();
}

// restart is called every time user presses "New Game" button
private void restart() {
    setControlsEnabled(true);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            game.play();
        }
    });
}

```

The `game.play` call is deferred until later for the Applet's main method, `init()`, could have chance to finish.

Here is implementation of two-phase move (and presentation of status, by the way)

```
class GuiGame extends Game {
    Point move() {
            secondaryLoop =
                    Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
            secondaryLoop.enter(); // will block until loop.exit
            return response; // in Applet.move
}
    @Override
    void updateStatus(String status, boolean gameOver) {
        statusLabel.setText(status);
        canvas.setEnabled(!gameOver);
    }
}

class MyApplet extends Applet {

    void move(Point square) { // complete the move
        response = square;
        secondaryLoop.exit();
    }

    void init() { ...

```

You see that `Game.move()` is starts blocking until `response` is initialized (by Applet.move(response), which is called by user click). The clicks are handeled by control listeners, created in Applet.init()

```
public void mousePressed(MouseEvent arg0) {
    if (arg0.getSource()== newGame) {
        move(null); // terminate current game
        restart();
    }

    if (canvas.isEnabled() && arg0.getSource() == canvas) {
        move(new Point(canvas.getWidth(), canvas.getHeight()));
    }

}

```

You see that by clicking, we can either restart the game or respond. In either case we send response to the game engine, its play loop, by `move(response)` method that memorizes the response so that return below loop.enter could see.

The net effect is that we can have a console-style game engine, which initializes the game model and drives the game by a loop, which requests player's next `move` every iteration. Console applications compute the response immediately. GUI is blocking while pumping GUI message loop until human clicks a choice. Threads/synchronization are unnecessary indeed for such linear control flow. Thank you Java1.7 for streamlining the implementation using secondary message loop.
> 0 votes

# Answer
You should try to refactor your game to separate the **Model** (the abstract state of the game) from its **View** (the graphical representation of the game-state) and its **Controllers** (anything which can interact with the game). This architecture is usually referred to as the Model - View - Controller Pattern.

Currently, your view would be the graphical user interface, which parses the model and visualizes its state to the user. An additonal view of the AI wouldn't need a graphical representation. It would just parse the model directly.

Your current controller is also the graphical user interface. When you have a naive implementation, it might manipulate the model directly. This isn't a clear separation of concerns. In order to modify the game-state, it should call methods on the model. The methods of the model shouldn't refer to the GUI (as in `skipButtonPressed()`) but rather to the intention the real/virtual player wants to perform (`skipTurn()`).

This would enable you to replace the GUI-controller with an AI-controller which also calls methods directly on the model when it wants to do something. The model itself shouldn't know (or care) whether the method-call comes from a GUI, from an AI, a network interface or whatever.
> 3 votes

---
Tags: java, architecture
---


title: How to manage Areas/Levels in an RPG?

text:
# Question
Title: How to manage Areas/Levels in an RPG?
I'm working on an RPG and I'm trying to figure out how to manage the different levels/areas in the game. Currently I create a new state (source file) for every area, defining its unique aspects. My concern is that as the game grows the number of class files will become unmanageable with all the towns, houses, shops, dungeons, etc. that I need to keep track of.

I would also prefer to separate my levels from the source code because non-programmer members of the team will be creating levels, and I would like the engine to be as free from game specific code as possible.

I'm thinking of creating a class that provides all the functions that will be the same between all the levels/areas with a unique member variable that can be used to look up level specifics from data. This way I only need to define level/area once in the code, but can create multiple instances each with its own unique aspects provided by data.

Is this a good way to go about solving the issue? Is there a better way to handle a growing number of levels?

# Answer
Having just one generic "Map" class and have each instance of this class load its layout, objects, scripts etc. from an external file is the usual way to do it.

Usually a WYSIWYG map editor is used to create and edit these map files. This map editor can be integrated into your game or be a stand-alone program. In the latter case you can often safe lots of work by using an existing map editor and just implement its file format in your game engine.

For 2d games, I prefer Tiled.
> 3 votes

# Answer
Don't go with a class for each area! Make you area have certain parameters! Unless its something really specific - when I mean specific is that really changes the concept of area and you can't fit it anywhere.

Then, you should make a event system for you game (you will thank me later) this will make creating different area lore and dynamic actions a lot easier in the long run!

-By Event System I mean, something that interpretes simple commands that can be chained to create complex actions (move, turn,jump, change something in the map , etc) this will make creating dynamic areas extremely easy!

Source : I have worked in many 2D RpGS in the past, and trust this saves a lot of time in the long run.

Think before you act. Planning will bring you a long way.
> 2 votes

---
Tags: rpg, data, game-state
---


# Question
Title: How would I go about updating my electronic circuit simulator's 'electricity'?
I have made an application which allows the user to place down wires, power sources, and inverters on a virtual circuit board. All connections between tiles are automatic, as shown here:

As you can see in the last image, the updating of power throughout this grid is not yet functioning. I think I understand how to do this updating conceptually, but getting it to work in my program is appearing to be much more difficult than I first imagined. My source code can be found here.

Getting tiles to pass on power to their neighbors is quite easy, but the tricky part is getting wires to "unpower" after the removal of a power source. The size of the grid is just 18x18, so efficiency really isn't a factor, for those wondering.

If you have any tips as to how to I might approach this task, please let me know.

# Answer
> 6 votes
The simple solution would be to just discard and recalculate the power distribution in the whole grid whenever you make a change. Considering that your grid is only 18x18, it shouldn't be too computationally intensive to do so.

Inverters might be problematic, though. What do you want to happen when the player connects the output of an inverter to its input? This would lead to a paradoxical situation. In a real-life circuit, the inverter might either oscillate (switch between on- and off as fast as it can) or just short-circuit and break.

When you want to go for the oscillating solution, you should go for a tick-based simulation where a fixed number of updates is calculated each second. In such a simulation, an inverter would not directly forward the state of its input. It would instead be modeled as an object which blocks power-flow, but which is also an independent power-source, just with the difference that the player can not switch it off- and on directly. The update-function which is executed in regular intervals would then look like this in pseudo-code:

```
 for each source
      if source is inverter
         if input wire is in "on"
             set source to "off"
         else
             set source to "on"

 for each wire
     set wire to "off"

 for each source
     if source is "on"
         flood-fill wires starting from output-wire and set all found wires to "on"

```

note that evaluation of the inverter-state and evaluation of the wire-state are two separate steps. That way you will not run into any infinite loops during the update.

When you instead want to go for a "breaking" solution, you would recursively flood-fill from all sources. The status of each wire would start out as "undefined". When you start flood-filling from a souce, you fill with the value "on". When you pass through an inverter, you toggle from "on" to "off" or vice versa and continue flood-filling with the new value. When you ever encounter an "off" wire while flooding with "on" or an "on" wire while flooding with "off", you found a paradoxon in the players circuit, revert the last move and tell the player they can't do that.

# Answer
> 1 votes
This sounds strange, and high-level, but I would consider modelling electricity through cellular automata.

Practically, this means modelling electricity as a state (on/off) for each cell, and codifying a set of rules that tell you which states are on or off.

The rules might go something like:

* For every cell that's a power source, set the state to "on"
* Notify every adjacent cell that's connected that we're on
* For each cell which receives notification:
    + Set your state to on
    + Recursively notify all connected neighbours

All you need to worry about is tracking which cells are connected to. The added benefit is if you put a delay before notifying neighbours (eg. 0.25ms), you can "see" the electricity "flowing" from start to finish.

Unplugging would mean turning off the power source, which should work in a similar way, except with setting stuff to "off" instead of "on." Inverters wouldn't be hard to model either.

---
Tags: java, 2d, tilemap, graph
---


# Question
Title: Set a 2d camera's position so that a building is under the players feet
My issue is this: i am making a scrolling game in XNA, and the camera updates based on the players velocity, but the player never actually moves, he is always in the center of the screen. When he hits the top of the building though i want him to always be on top and sink through the texture in a way like this:

what i am doing to make this happen is i am just setting his velocity to 0, so its not moving, but the more velocity he hits a building with the more he sinks through it.

I also tried setting the buildings position to the plays Bounding Box's bottom, and this achieved the look i wanted but this also resulted in the other buildings rising in the air, because the velocity was still moving (even if i set it to 0).

if it was not a scrolling game, this would be not a problem, because you just set the players position to the top of the building, but because the player never actually moves, i actually need to move the camera to the point where the building is under the players feet without the other buildings rising. (Take note this is note a real camera, it is just a class that moves the objects in the world based on the players velocity). All questions are welcome.

# Answer
The way I see it, you are just stopping the movement the instant a collision is detected, which apparently causes the problem you just mentioned.

Why don't you try also relocating the player's Y coordinate when a downwards collision is detected, so that it is just a few pixels in the ground? This way you still detect collision, but keep the player at a fixed height in relation to the ground he's colliding with.

Now, regarding the camera, just a suggestion. Since you're using XNA, there is a nifty way of making a camera without even having to create a Camera class, but without having to reposition every single object in the screen either. Just store a Vector2 with the Camera's position, and when you start your spritebatch, pass a Translation Matrix as parameter, containing the X and Y info from your cameraPosition Vector2.

```
    Vector2 cameraPosition = new Vector2(500, 1000);
    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, Matrix.CreateTranslation(new Vector3(cameraPosition.X, cameraPosition.Y, 0)));

```

Using a Translation Matrix to work the camera helps in a lot of ways, as you can just keep your objects in their real positions, which should make your life easier overall. You should be careful not to keep drawing what's outside the camera for perfomance issues, though.
> 1 votes

# Answer
One way might be is to add a set of "offset" properties to your player class or allow the ability to offset what the "center position" is.

Move the camera until he is about to sink in, and then change his center position instead of the camera's position. You can then draw the character sunken in without moving the camera around him. Then we he needs to get out of the hole, you can adjust the offset until it is back to the "real center" and then start to move the camera again.

You can see an example here at the one minute mark or anytime a character gets near the edge of the map. http://www.youtube.com/watch?v=7mMJio2MO6w&feature=player\_embedded
> 0 votes

---
Tags: xna, c#, xna-4.0
---


title: Unity3D : Pause Menu - Android

text:
# Question
Title: Unity3D : Pause Menu - Android
I am making a 2D game for Android. Almost completed the game but now I need a pause game option. I added a pause icon on the top right side of the screen. The icon is a GUI texture. What I did so far :

I made a script which will bring up some buttons (which is not working) and attached it to the `GUITexture`.This is the script :

```
#pragma strict

function OnMouseDown() {
   Debug.Log("*Pause Menu Opens*");
   Time.timeScale = 0;

   if (GUI.Button(Rect(10,10,100,50),"Restart"));
      Application.LoadLevel(Application.loadedLevel);

   if (GUI.Button(Rect(10,60,100,50),"MainMenu"));
      Application.LoadLevel("MainMenu");
}

```

Now the problem stands at the part where the buttons won't show up and the game freezes at the first frame. Please if you can help I would be really thankful.

`Edit #1` : I just noticed that when I click "Pause" the game freezes and it takes me to the `MainMenu`. That's because I added the `GUIButton` which takes you to the main menu. I think the whole script structure is wrong. I also forgot to mention that I am new to scripting/unity.

Thank you.

# Answer
The problem here is that you're trying to access the GUI functions from outside the OnGUI function. You'll want to set some sort of variable indicating that the game is paused in the input event handler, and then alter the game's behaviour in the OnGUI function, like this:

```
function OnMouseDown(){
    this.paused = !this.paused;
}

function OnGUI(){
    if(this.paused){
        if (GUI.Button(Rect(10,10,100,50),"Restart")){
            // do something
        }
        // Insert the rest of the pause menu logic
    }
}

```
> 0 votes

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


# Question
Title: C++ property system interface for game editors (reflection system)
I have designed an reusable game engine for an project, and their functionality is like this:

Is a completely scripted game engine instead of the usual scripting languages as Lua or Python, this uses Runtime-Compiled C++, and an modified version of Cistron (an component-based programming framework).to be compatible with Runtime-Compiled C++ and so on.

Using the typical GameObject and Component classes of the Component-based design pattern, is serializable via JSON, BSON or Binary useful for selecting which objects will be loaded the next time.

**The main problem**: We want to use our custom GameObjects and their components properties in our level editor, before used hardcoded functions to access GameObject base class virtual functions from the derived ones, if do you want to modify an property specifically from that class you need inside into the code, this situation happens too with the derived classes of Component class, in little projects there's no problem but for larger projects becomes tedious, lengthy and error-prone.

I've researched a lot to find a solution without luck, i tried with the Ogitor's property system (since our engine is Ogre-based) but we find it inappropiate for the component-based design and it's limited only for the Ogre classes and can lead to performance overhead, and we tried some code we find in the Internet we tested it and worked a little but we considered the macro and lambda abuse too horrible take a look (some code omitted):

```
   IWE_IMPLEMENT_PROP_BEGIN(CBaseEntity)
     IWE_PROP_LEVEL_BEGIN("Editor");
       IWE_PROP_INT_S("Id", "Internal id", m_nEntID, [](int n) {}, true);
            IWE_PROP_LEVEL_END();
            IWE_PROP_LEVEL_BEGIN("Entity");
              IWE_PROP_STRING_S("Mesh", "Mesh used for this entity",
         m_pModelName, [pInst](const std::string& sModelName) {
           pInst->m_stackMemUndoType.push(ENT_MEM_MESH); pInst->m_stackMemUndoStr.push(pInst->getModelName());
           pInst->setModel(sModelName, false); pInst->saveState();
         }, false);
       IWE_PROP_VECTOR3_S("Position", m_vecPosition,
  [pInst](float fX, float fY, float fZ) {
    pInst->m_stackMemUndoType.push(ENT_MEM_POSITION); pInst->m_stackMemUndoVec3.push(pInst->getPosition()); pInst->saveState();
    pInst->m_vecPosition.Get()[0] = fX; pInst->m_vecPosition.Get()[1] = fY; pInst->m_vecPosition.Get()[2] = fZ;
    pInst->setPosition(pInst->m_vecPosition);
  }, false);
       IWE_PROP_QUATERNION_S("Orientation (Quat)", m_quatOrientation,
  [pInst](float fW, float fX, float fY, float fZ) {
    pInst->m_stackMemUndoType.push(ENT_MEM_ROTATE); pInst->m_stackMemUndoQuat.push(pInst->getOrientation()); pInst->saveState();
    pInst->m_quatOrientation.Get()[0] = fW; pInst->m_quatOrientation.Get()[1] = fX; pInst->m_quatOrientation.Get()[2] = fY; pInst->m_quatOrientation.Get()[3] = fZ;
    pInst->setOrientation(pInst->m_quatOrientation);
  }, false);

     IWE_PROP_LEVEL_END();
    IWE_IMPLEMENT_PROP_END()

```

We are finding an simplified way to this, without leading confusing the programmers, (will be released to the public) i find ways to achieve this but they are only available for the common scripting as Lua or editors using C#. also too portable, we can write "wrappers" for different GUI toolkits as Qt or GTK, also i'm thinking to using Boost.Wave to get additional macro functionality without creating my own compiler.

The properties designed to use in the editor they are removed in the game since the save file contains their data and loads it using an simple 'load' function to reduce unnecessary code bloat may will be useful if some GameObject property wants to be hidden instead.

In summary, there's a way to implement an reflection(property) system for a level editor based in properties from derived classes?

Also we can use C++11 and Boost (restricted only to Wave and PropertyTree)

# Answer
> 8 votes
This is an incredibly complicated problem. I had an old series on blog about it but (a) I no longer recommend that approach and (b) old posts on my blog can't be read easily due to a snafu with a plugin and me not having time to fix it all.

The gist of what you need to do on the "simple" end is to keep a table of `IProperty` objects which are specialized to the type of property you're binding. Accepting a very limited set of property types will help.

It's not trivial to do. You need to be comfortable with advanced C++ including writing templates, partial specializations, pointers to members, and so on.

```
// common parts of a property; probably needs a name and description for editor reflection
class IProperty {
public:
  virtual void ReadFromString(void* object, const string& value) = 0;
  virtual void WriteToString(const void* object, string& out) = 0;
};

// handle simple types like int, float, etc. supported by lexical_cast
template <typename ObjectT, PropertyT>
class ScalarProperty : public IProperty {
  using PointerT = ObjectT::*PropertyT;
  PointerT _pointer;
public:
  ScalarProperty(PointerT pointer) : _pointer(pointer) {}
  virtual void ReadFromString(void* object, const string& value) override {
    ObjectT* typed = static_cast<ObjectT*>(object);
    typed->*_pointer = lexical_cast<PropertyT>(value);
  }
  virtual void WriteToString(const void* object, string& out) override {
    ObjectT* typed = static_cast<ObjectT*>(object);
    out = to_string(typed->*_pointer);
  }
};

// call make_property(&MyObjecet::m_property) to bind a particular int property
template <typename ObjectT>
unique_ptr<IProperty>make_property(ObjectT::*int pointer) {
  return make_scoped<ScalarProperty<ObjectT, int>>(pointer);
}
// do this for float, etc. you can use SFINAE, a macro, or so on to get all the versions you need

```

That covers the harder part. The rest is making a class that encapsulates a type and pushing all the `IProperty` handles into it. You can use macros to wrap this up, a custom registration function, etc.

Another popular approach that many engines use is to use a special preprocessor to generated reflection data. You can just prefix a class's member with `editable` or use a macro next to the declaration like `REFLECT("name", flags)`. This has the requirement that you have a tool capable of the subset of C++ found in declarations so that it can generate the necessary code. There are also tools like clReflect but this sadly hasn't been updated in some time.

Overall, this is just a massive pain in the butt. The ISO committee is currently investigating ways of adding compile-time reflection to C++ which will make building these kinds of systems much easier. In the meantime, though, pain and suffering.

A simpler option I've seen but never tried myself is to have a method called `Reflect` that uses the visitor pattern:

```
class IReflector {
public:
  virtual void Reflect(int& value, const char* name, const char* description) = 0;
  virtual void Reflect(Vector3d& value, const char* name, const char* description) = 0;
  virtual void Reflect(string& value, const char* name, const char* description) = 0;
};

class MyComponent {
  int foo;
  Vector3d bar;
  string name;

public:
  virtual void Reflect(IReflector& refl) {
    refl->Reflect(foo, "Foo", "The foo");
    refl->Reflect(bar, "Bar", "Bar is the place");
    refl->Reflect(name, "Name", "My name");
  }
};

```

You can then write different derived versions of `IReflector` that read in values, write out values, or even just ignore the value itself and collect the type/name/description to build up a UI table. You can generalize a little further to support use of this system without needing an instance of the object in question, keep registration of types/factories, etc., but that will get you moving.

# Answer
> 4 votes
The best way I've seen is to make use of some custom introspection. As Sean pointed out, this is pretty difficult to do on your own since it's not a direct standard C++ feature in any way. So if you're up for implementing something more advanced then read on.

---

I actually implemented this (not the editor, just generic properties) in an open source project. The project isn't finished, but the property part is. Here's the link. You can see that this makes heavy use a generic function wrapper to call member functions.

This lets you write code like:

```
Class object;
Property p = Property( &Class::gettor, &Class::settor );
p.Bind( object );
Type value = p.Get( );
p.Set( value );

```

The overall idea is to use templates to extract type information out of a function or member function for all the parameters, and the this pointer type. From here you can create a way to call functions in a generic manner, and enumerate type information during run-time. You can see what type the property is representing, and getting/setting the property (from an interface standpoint) is trivial. The editor can enumerate type information at run-time and detect whether it's dealing with an integer, a string, or something else and generate necessary user input windows/editor grids to modify the proper.

Storing type information is about registering information about the basic C++ types (like int, float, c-strings, etc.), and then representing more complex data by combinations of the fundamental types. In implementation this would look like making a simple `TypeInfo` struct to store information about a type (any information you want, for an editor you'd want name, size, etc.):

```
struct TypeInfo
{
    const char* name;
    u32 size;
}

```

A property could consist of a gettor/settor combo. Each gettor/settor would be a nice wrapper for a function (C-function or class/struct method), along with an array of `TypeInfo` structs to represent the type of each parameter. Another `TypeInfo` could be used to give details about the `this` pointer if a class/struct method is being used.

Run-time assertions can also be made to ensure type safety!

A simpler approach would be to instead of using a generic function wrapper, to use `void *`'s to access the memory of your objects directly. This can be made type-safe, and would be easier to implement. The idea here is to add a new type of introspection struct:

```
struct Member
{
  const char* memberName;
  u32 offset;
}

```

The `TypeInfo` struct can carry an array of `Member` struct, where each `Member` struct describes where in memory this member exists relative to the host object, and the name of the member in code. Both of these bits of data are needed to modify the value and represent it within an editor.

In all the best online resource I know for this stuff is my own source code. Like Sean (the other answer here) I do have some older articles on this topic, but they aren't the best and are old now. The introspection stuff is all in here.

---

There is another style of implementation that is even more difficult to achieve explained in a talk by Sergiy Migdalksiy from Valve. Instead of registering type information at run-time and funneling it through generic code, it reads C++ code and generates new C++ as a pre-compilation step. This can be used to automatically generate new property functions in whatever specific interface you desire.

---
Tags: c++, map-editor, world-editor, code-reflection
---


# Question
Title: How can I make an object's hitbox rotate with its texture?
In XNA, when you have a rectangular sprite that doesnt rotate, it's easy to get its four corners to make a hitbox. However, when you do a rotation, the points get moved and I assume there is some kind of math that I can use to aquire them.

I am using the four points to draw a rectangle that visually represents the hitboxes.

# Answer
> 0 votes
So after some research into Matrices with the head tutor of IT I understand how to rotate each of the points, its a bit buggy still but it will rotate on the spot in time with the sprite as well as move with it in straight lines.

Heres some XNA relevant pseudo code that explains it

```
        Matrix move = Matrix.CreateTranslation(new Vector3((currentPosition - previousPosition), 0));
        Matrix rotate = Matrix.CreateRotationZ(currentAngleInRadiens - previousAngleInRadiens);

        forEachPoint
        {
            if (pointHasMoved)
            {
                //Move the point to a center position(this is for rotating the point around a relevant position)
                //Move the point back to its original position
                point = Vector2.Transform(point - centerPoint, rotate) + centerPoint;
                // Translate the point
                point = Vector2.Transform(point, move);
            }
        }

```

# Answer
> 1 votes
You could do so that you have a rotation matrix with a translation. From there you can take a point and transform it into it´s cordinate system. then it becomes like a regular hitbox collision.

Wiki has a good article on how this works in the depth : WIKI

The same approach works for a "pixel" collision method to, just remember to transform the collision point rather than the object it´s colliding with. Lazy foo has a AWESOME article on how to do pixel collision. It should be fairly easy to transform that code into any language. Lazy foo

---
Tags: xna, 2d, xna-4.0, physics
---


title: How do I create a camera?

text:
# Question
Title: How do I create a camera?
I am trying to create a generic camera class for a game engine, which works for different types of cameras (Orbital, GDoF, FPS), but I have no idea how to go about it.

I have read about quaternions and matrices, but I do not understand how to implement it. Particularly, it seems you need "Up", "Forward" and "Right" vectors, a Quaternion for rotations, and View and Projection matrices.

For example, an FPS camera only rotates around the World Y and the Right Axis of the camera; the 6DoF rotates always around its own axis, and the orbital is just translating for a set distance and making it look always at a fixed target point.

The concepts are there; implementing this is not trivial for me.

SharpDX seems to have has already Matrices and Quaternions implemented, but I don't know how to use them to create a camera.

Can anyone point me on what am I missing, what I got wrong?

I would really enjoy if you could give a tutorial, some piece of code, or just plain explanation of the concepts.

# Answer
Ok, I'll give it a shot...

Your camera will need much of the same functionality as your regular entities in the game. Specifically, it will need to have both a position and orientation in your game world.

A simple 3D vector can be used to store the world position whilst a unit quaternion can be used to represent its rotation from some reference direction. I should stress here that only unit quaternions can be used to represent rotations. This is to say that the norm/magnitude/length of the quaternion should be equal to 1.0.

The unit quaternion represents a rotation from some reference vector - usually the "forward" vector (0, 0, 1). OpenGL uses a right-handed coordinate system where the z-axis points out of the screen. So unless you have a good reason for using something different, I would choose (0, 0, 1) to be your reference "forward" vector. Together, the quaternion rotation and forward vector represent an orientation.

This is really all that you need for the positioning and orientation of a camera. A suitable maths library should provide the functions necessary for manipulating the camera's rotation quaternion. For example, Unity provides the Quaternion.LookRotation function. With a similar function you can orient your camera to point in a given direction:

```
Vector3 direction = new Vector3(1.0, 0.0, 0.0); // Right
camera.rotation = Quaternion.LookRotation(direction);

```

To rotate the camera by some given unit quaternion `q`, you can simply multiply this by the camera's unit quaternion rotation on the left:

```
camera.rotation = q * camera.rotation;

```

Note that you don't need to normalise the result since the Hamilton product of two unit quaternions is itself a unit quaternion. Suitable 3D maths libraries will provide a constructor or static factory function for creating unit quaternions from Euler angles or from an angle about a given axis (angle-axis).

When rendering you will need to supply OpenGL or DirectX with a view matrix. This is in fact the **inverse of the camera's transformation matrix**. Now, if you are using a quaternion for the camera's rotation, you will need to convert this quaternion to a rotation matrix, `R`. You will also need to convert the camera's position into a translation matrix, `T`. Multiply these two matrices together in order to find the camera's transformation matrix. Matrix multiplication is not commutative; the order of multiplication matters and which order you choose depends on the kind of behavior you want.

Finally, your camera will need a projection matrix. You can think of this as the lens of the camera. You will probably want to use a perspective projection for a FPS game. For other games you may or may not want to use an orthographic projection. There is plenty of information available on finding/calculating these matrices so I won't elaborate.

That's all you really need. I should mention that you can use matrices instead of quaternions to represent the camera's rotation. This is generally more of a personal preference than a performance or memory efficiency consideration.

You can take a look at the small 3D maths library I am currently working on if you are interested in the mathematics side; such as how to calculate a "look at" quaternion.
> 3 votes

---
Tags: camera, matrix, quaternion, sharpdx
---


# Question
Title: Electronic circuit simulator four-way flood-filling issues
I've made an electronic circuit board simulator which has simply 3 types of tiles: wires, power sources, and inverters. Wires connect to anything they touch, other than the sides of inverters; inverters have one input side and one output side; and finally power tiles connect in a similar manner as wires. In the case of an infinite loop, caused by the output of the inverter feeding into its input, I want inverters to oscillate (quickly turn on/off).

I've attempted to implement a FloodFill algorithm to spread the power throughout the grid, but seem to have gotten something wrong, as only the tiles above the power source get powered (as seen below)

I've attempted to debug the program, but have had no luck thus far. My code concerning the updating of power can be seen here.

# Answer
> 2 votes
Your flood-fill algorithm seems to works correctly, but you are overwriting the results.

You have a loop in which you update every single tile. When it is a wire, you switch it off. When you reach a power-source, you flood-fill from it.

What happens in your code is:

1. the board gets iterated in a loop from up to down switching off all wires
2. the loop reaches the source in the middle of the board
3. a flood-fill is performed from the source and all wires on the board get switched on
4. the loop continues updating and switches off all not yet processed wires which were just switched on during the flood-fill

To fix this code you need two separate loops. First a loop over all wires to reset their state to off and then, when the board is properly cleared, a second loop to flood-fill from the power sources.

---
Tags: java, 2d, tilemap, graph
---


# Question
Title: How to get scripted programs governing game entities run in parallel with a game loop?
I recently discovered Crobot which is (briefly) a game where each player codes a virtual robot in a pseudo-C language. Each robot is then put in an arena where it fights against other robots.

A robots' source code has this shape :

```
/* Beginning file robot.r */
main()
{
    while (1)
    {
        /* Do whatever you want */
        ...
        move();
        ...
        fire();
    }
}
/* End file robot.r */

```

You can see that :

1. The code is totally independent from any library/include
2. Some predefined functions are available (**move**, **fire**, etc…)
3. The program has its own game loop, and consequently is not called every frame

My question is: How to achieve a similar result using scripted languages in collaboration with a C/C++ main program ?

I found a possible approach using Python, multi-threading and shared memory, although I am not sure yet that it is possible this way. TCP/IP seems a bit too complicated for this kind of application.

# Answer
> 0 votes
A way to implement it is to use Python, threads and TCP/IP. What you need is :

1. A main application managing the game itself
2. A python thread for each bot
3. A python script to connect a bot to the main application (sending/receiving messages)

What you do ***not*** need (in this particular case) is :

1. Embed Python in the main application or vice versa
2. Mutex, semaphore or any other stuff preventing the memory to get corrupted (thanks to TCP/IP)

I can suggest the following design which worked for me :

Using this design, I came up with a very simple interface for the bots and a fairly playable game. A bot looks like :

```
# Beginning of file name_of_bot.py
def main(bot):
    while True:
        bot.move()
        ...
        scanResult = bot.scan()
        ...
        bot.rotate(15)
        ...
# End of file name_of_bot.py

```

...where you can do anything you want since it is a Python script (provided that you keep the main function's signature as it is) !

**Update**: For those interested, here is the link to the actual game on GitHub.

---
Tags: c
---


title: FBX 3ds max export, bad vertices

text:
# Question
Title: FBX 3ds max export, bad vertices
I need to import model in OpenGL via Fbx SdK, and for testing purposes I created a simple box centered in the (0, 0, 0), length 3, in 3ds max. Here's the image:

But when i exported it, and imported in the OpenGL it wasn't in the center. Then I exported it in ASCII format, and opened the file in Notepad, and really Z coordinates were 0, and 3. When I converted model to editable mesh and checked every vertex in 3ds max it had expected (+-1.5, +-1.5, +-1.5) coordinates. Can anyone help me with this one? I'm really stuck. I tried to change whole bunch of parameters in 3ds max export, but every time it changes Z koordinate.

# Answer
> 1 votes
By the look of the gizmo attached to your cube in the image, your cube appears to have its local origin in the center of the bottom face which gives the vertices on the bottom face a local z value of 0 and the vertices on the top face a local z value of 3.

So to make the cube appear centered in the world origin, there is a matrix (transform) that when applied (and 3ds is applying it in your image), scoots all the vertices down for rendering 1.5 and makes it appear as if the vertices were at 1.5 & -1.5.

In the fbx export file, you get both the original vertices and that transform. Most likely, you drew just the original vertices without applying the transform to them.

To solve it, grab the transform while parsing the fbx and apply it to the vertices or go back to 3ds and reset the transform to change the local origin from the bottom face to the center of the cube and re-export.

---
Tags: 3dsmax, fbx
---