# Question
Title: Accelerometer to move player left and right
Please take a look on my code and help me to find problem.

I used this tutorial: COCOS2D\_ACCELEROMETER\_MOVEMENT This works only sometime….some time not move..How can I resolve this problem? Here is my sample: DOWNLOAD Thanks for reading this…what's wrong with my code ? Is there any other way?

Here is my code:

```
#define kHeroMovementAction 1
#define kPlayerSpeed 500
- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
    // use the running scene to grab the appropriate game layer by it's tag

    // grab the player sprite from that layer using it's tag
    CCSprite *playerSprite = mPlayer;
    float destX, destY;
    BOOL shouldMove = NO;

    float currentX = playerSprite.position.x;
    float currentY = playerSprite.position.y;

    if(acceleration.x > 0.25) {  // tilting the device upwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.x < -0.25) {  // tilting the device downwards
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else

        if(acceleration.y < -0.25) {  // tilting the device to the right
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else if (acceleration.y > 0.25) {  // tilting the device to the left
        destX = currentX - (acceleration.y * kPlayerSpeed);
        destY = currentY + (acceleration.x * kPlayerSpeed);
        shouldMove = YES;
    } else {
        destX = currentX;
        destY = currentY;
    }

    if(shouldMove)
    {
        CGSize wins = [[CCDirector sharedDirector] winSize];
        // ensure we aren't moving out of bounds
        if(destX < 30 || destX > wins.width - 30 || destY < 30 || destY > wins.height - 100) {
            // do nothing
        } else {
            CCAction *action = [CCMoveTo actionWithDuration:0.5f position: CGPointMake(destX, playerSprite.position.y)];
            [playerSprite stopActionByTag:kHeroMovementAction];
            [action setTag:kHeroMovementAction];
            [playerSprite runAction:action];
        }
    } else {
        // should stop
        [playerSprite stopActionByTag:kHeroMovementAction];
    }

}

```

# Answer
That method of moving a player left and right is a little bit complicated and can be done in a much much nicer way using a simpler class design.

Create a player class and declare `cgpoint vel` and `pos`. You will also want a CCSprite in the header file of this class:

```
@interface player : CCLayer
{
    CCSprite *spriteName;
    CGPoint vel;
    CGPoint pos;
}

@end

```

In the class set `self.isAcelerometerEnabled = TRUE;` in the init method.

Then in the player class you want:

```
-(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    float deceleration = 0.1f, sensitivity = 8.0f, maxVelocity = 150;

    // adjust velocity based on current accelerometer acceleration
    vel.x = vel.x * deceleration + acceleration.x * sensitivity;

    //limit the maximum velocity of the player sprite, in both directions (positive & negative values)
    vel.x = fmaxf(fminf(vel.x, maxVelocity), -maxVelocity);
}

```

In your update method for the player class you want:

```
-(void) update:(ccTime)delta
{
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    float imageWidthHalved = [boat texture].contentSize.width * 0.25f;
    float leftBorderLimit = imageWidthHalved + 45;
    float rightBorderLimit = screenSize.width - imageWidthHalved - 45;

    pos = spriteName.position;
    pos.x += vel.x;

    if (pos.x < leftBorderLimit)
    {
        pos.x = leftBorderLimit;
        vel = CGPointZero;
    }
    else if (pos.x > rightBorderLimit)
    {
        pos.x = rightBorderLimit;
        vel = CGPointZero;
    }

    spriteName.position = pos;
}

```

Then in your main world class init just call (assuming you have declared a player object in your header file and called it player):

```
player = [player node];
[self addChild:player z:2];

```

Hopefully this will be enough code to get you started, assuming you know how to create classes in cocos2d. Also in your player class dont forget to call:

```
[self scheduleUpdate];

```

In the init method in your player class.
> 8 votes

---
Tags: iphone, cocos2d-iphone, cocos2d
---


# Question
Title: How to implement object velocity as a vector
I'm working on a Breakout game, and want to change the ball's movement code from how I currently do it, to something based on vectors (as I feel learning and implementing movement based on vectors will help me in the long run).

Currently I am doing something like this (Pseudocode):

```
if(ball.Y < HEIGHT)
    ball.Y += 1; // I actually save a direction as well,
                 //and multiply this by the direction (1 or -1)
else
    ball.Y -= 1;

if(ball.X < WIDTH)
    ball.X += 1;
else
    ball.X -=1;

```

Anyway, you get the gist of it. My current code is actually much more verbose, but handles collisions well. Basically I am just using screen coordinates, and I find that this is probably not the best way to be doing this.

How would you implement a more correct, extensible (to other projects), way to move objects?

EDIT: I am not looking to use a 2D Vector library; more-so I am looking for an explanation of how vectors are used for movement in games, and how I can implement them myself.

# Answer
To explicitly answer your question: vectors can be used to translate objects the same way as you're currently doing it. They just wrap things up nicely, and let you write less code.

For instance, what you're likely asking for is a way to dynamically move an object based on a facing vector, as opposed to a rotation.

Lets assume we have the following class:

```
function vec2(x, y)
{
   this.x = x;
   this.y = y;
}

vec2.prototype.translate = function (translateBy)
{
   this.x += translateBy.x;
   this.y += translateBy.y;
}

vec2.prototype.multiplyByScalar = function (scalar)
{
   this.x *= scalar;
   this.y *= scalar;
}

```

We can move an object with position vector `v1` along a facing vector `v2` by `moveSpeed` like so:

```
v1.translate(v2.multiplyByScalar(moveSpeed));

```

If `v1` is `vec2(1, 1)`, `v2` is `vec2(1, 0)`, and `moveSpeed` is `2`, then after that line of code `v1` will be `vec2(3, 1)`. You'll notice that the facing vector is a unit vector: the sum of its components add to one. This means that you'll be able to use it, and your object will only ever translate `moveSpeed` units in total.

There are plenty of other cool things you can do with vectors, especially once you have collision code that returns you the vector where the collision happened. In breakout, this would allow you to set a facing vector equal to the normal of the collision vector, providing an easy way to bounce off of any surface, regardless of its rotation.

I'd recommend that you read a book or extensive article on vectors. Also, this code is JavaScript, as my Java is unreliable and rusty.
> 4 votes

# Answer
In short (and as has been mentioned by others), 2D Vectors are functionally just wrappers around a pair of values representing position, motion, or whatever in 2D space.

It sounds like you're just looking for resources to better understand them. It's hard to know what your expertise level is, so here's a link dump based on things that, from a quick glance or my past experience, I'm guessing may be useful for you:

Hope these help.
> 4 votes

# Answer
I've done something similar by using 2 standard 2D vector classes (by standard 2D vector classes, I mean classes which represent an x and a y coordinate). The first vector, v1, represented the position of the ball at that moment in time, while the second, v2, represented the velocity vector. That vector represented the distance and direction traveled between two timesteps in the game, giving the following calculation for a new position (ignoring collisions, etc):

```
v1 = v1 + v2;
//do stuff here
//assign new v2 here

```

Hope this helps!
> 1 votes

# Answer
I strongly recommend that you read a book about the topic. I recommend "3D Math Primer for Graphics and Game Development, Second Edition." by Fletcher Dunn and Ian Parberry. You can also checkout the book's webpage http://gamemath.com/ which includes powerpoint presentations of all the chapters (under Download).
> 1 votes

# Answer
I'm going with pseudocode but I hope you will understand me.

First there is position:

```
struct position { x = 0; y = 0};

```

So every object in our world has such struct. There is also another struct:

```
struct velocity {x = 100; y = 50};

```

This means that our object is moving 100 pixels to the right and 50 pixels up each second (or any arbitary amount of time); That is a diagonal movement. If we want to reverse the ball (for example it goes to right, and we want it to go left, we just reverse the sign of x variable)

In our update function we change the position based on velocity * time;

For that we need the time passed since last time we called our function (delta) to ensure that we keep updating the loop independently of frames per second.

```
- (void) update(deltaTime)
{
struct tempPosition = ball.position;

// we get our ball position into temporary struct

tempPosition.x += velocity.x * deltaTime
//delta time is usually fraction of second,
//so our ball will move the same amount of pixels per second, no matter how often or not
//often we call our update function. So in case that half a second passed our ball
//will move for 50 pixels, and in case 0.1 seconds passed it will move only 10 pixels.

tempPosition.y += velocity.y *deltaTime;

ball.position = tempPosition;
// If your language permits for structs multiplication or assigning
// structs directly, you can shorten the method to something like

// ball.position += velocity * deltaTime;

}

```

You should run this update method for every object on screen, for example by looping an array of all objects. Just add every object when you create it to that array and then do a for loop. Or if you are on pure C, make separate functions to update ball and paddle and run them in your main loop.

I hope that helped, if you have more questions just ask.

By the way, for collision detection it works same way, you just reverse the sign of variable in struct like this:

```
ball.velocity.x = - ball.velocity.x;

```
> 1 votes

# Answer
I'd use verlet integration:

```
class Vector {
    Vector(Vector vec);//Copy constructor
    Vector(float x, float y);
    float x;
    float y;
    /* and some addition and subtraction methods */
};
class Verlet {
    Verlet(float x, float y, float deltax, float deltay){
        current = new Vector(x, y);
        previous = new Vector(x - deltax, y - deltay)
    }
    Vector current;
    Vector previous;
    void step(){
        Vector delta = current - previous;
        previous = new Vector(current);
        current = current + delta;
    }

};

```

This makes really easy to implement collisions and all that. Also adding gravity or dampening is simple as pie.
> 0 votes

---
Tags: 2d, java, vector, movement
---


# Question
Title: Publishing a game -- any way to target both WP7 and Win8 Store?
I'm at a dilemma which seems should soon become an important issue for a lot of developers.

If I build a game in XNA, I won't be able to publish it on the Windows 8 Store, as it would be a classic application -- and classic applications can't be sold on the store.

If I build a game in Metro DirectX, I would be able to sell it on the Store, but porting it to Windows Phone would involve porting it to Reach XNA, which in fact would likely involve more effort even than porting to OS X or Android -- both of which support C++. Of all the WinRT API that is supported on C++/JS/.NET, DirectX can only be programmed from C++. It's also unlikely that Microsoft will update Windows 7 or Vista to support the new DirectX features, although that would make the Metro DirectX the first new version of DirectX to stop supporting the immediate predecessor OS.

If I build a game in Pre-Win8 DirectX 9/10/11, I won't be able to sell it on the Windows Store or Windows Phone, but I could sell it on something like Steam. It would also involve the most amount of manual plumbing. In fact, DirectWrite, despite being part of DirectX 11, doesn't talk to Direct3D.

I'm getting really tired of all these restrictions -- artificial and otherwise -- and I'm coming to a point where I'm considering switching to a platform with a less fragmented API, like Android or Mac/iOS.

As far as bringing a game into market goes, excluding the actual market share of any platforms that I might consider, what other factors would help me in making a decision?

Just a few years ago this question was a lot easier to answer: if you were primarily concerned with Windows platforms, all you had to answer was whether you wanted DirectX, XNA, or something like SlimDX. If you made the wrong decision, no biggie -- all you really would have lost is XBox and the fairly small Windows Phone market.

# Answer
This is not a direct answer to your question, but some advice.

You want to hit every market you can. Especially as s mall indie/hobbyist developer, every single potential customer matters. Developing for a single platform (even a popular one) is a very unwise decision in today's world of 6+ highly popular gaming platforms. At the very least, you want to be able to hit PC, iOS, and Android (Windows Phone is a very small market compared to those three). Hitting XBL would also be nice, but it is not an easy thing to do as a hobbyist unless you use XNA (but don't do that). Note that those three primary platforms all have widely different low-level APIs and so trying to pick a single platform API is going to land you nowhere.

I've been led to believe that XNA is unlikely to ever receive another major update again, and it may be a legacy API at this point. If you're starting development on a longer term project, you might be better off picking a platform API that is receiving regular updates. I would avoid XNA unless Microsoft recommits to the API.

While Metro's new API is not usable on the current Windows Phone, it will likely be available on the next version of the WP OS. Again depending on the length of the project, it may not make sense to worry about WP7 limitations. Metro of course will still not be found on any other devices (well, maybe the next XBox), and porting to iOS, Android, OS X, Linux, or the other consoles is going to require changes to use various APIs.

Your game should ideally not be dependent on any of these platform technologies. The vast majority of your game logic should not even be aware of whether the graphics API in use is raw D3D, XNA, OpenGL, or so on. Your game logic should not be dependent on any particular low-level OS routines. Your game should be relatively straight forward to port to any of the major OSes, including PC, iOS, Android, consoles, and so on.

Coding an engine that can handle this takes a bit of thought and understanding, but it's not *hard*, strictly speaking. Write a thin wrapper around the low-level platform-specific APIs, and then porting largely becomes a matter of rewriting those wrappers and nothing else. The biggest issue to deal with aside from that is just testing the different input schemes (touch vs mouse/keyboard vs controller) and varying screen resolutions. I dare say that so long as you target at least two fairly different platforms from day one (say, PC and iOS) you'll have little problem adding more, and if you have any specific questions about the APIs or porting then you already know a fantastic place to ask them and get answers.

You can also consider targeting HTML5, depending on what kind of game you're going to build. For 2D games, the platform support for HTML5 is pretty wide at this point, and most people with a browser will be able to play your game. Especially if you use one of the higher level toolkits like PlayN. You can also do 3D HTML5 games with WebGL, though the platform support for that is still relatively limited (all the PC browsers except IE handle it, but none of the released mobile browsers do last time I checked).

You can also just use an existing highly portable game engine, like Unity3D.
> 4 votes

# Answer
If you really want to use XNA as your framework of choice to build your game, you should have a look at MonoGame. Support for 3D is quite new to the framework and probably not ideal, however it would let you write in C# and reuse the vast majority of your code for both platforms (WP7 Marketplace and Windows 8 store). Game are already being submitted to the Windows 8 store using MonoGame!

Saying that, I believe Windows Phone 8 is set to support C/C++ and Directx (not sure on limitations).
> 1 votes

# Answer
Without XNA there will be no games on WP8 and W8 and without games nobody will buy them. So it is better to wait for WP9 and W9 or start learning objective C or Java.
> -2 votes

---
Tags: xna, directx, windows-phone-7
---


title: OpenGL blending (masking)

text:
# Question
Title: OpenGL blending (masking)
I need some help with OpenGL textures masking. I have it working but need to find some other blending function parameters to work in other way. Now I have:

```
//Background
...code...
    glBlendFunc(GL_ONE, GL_ZERO);
...code

//Mask
...code...
    glBlendFuncSeparate(GL_ZERO, GL_ONE, GL_DST_COLOR, GL_ZERO);
...code...

//Foreground
...code
    glBlendFunc(GL_DST_ALPHA, GL_ONE_MINUS_DST_ALPHA);
...code

```

Now it sets foreground's opacity to 0 (fills with background texture) where mask is transparent. I need it to react to mask's colors. I mean something like setting foregrounds opacity depending on mask's color. For example if mask is black (0.0,0.0,0.0) then the opacity of that place in foreground is 0 (is filled with background), and if mask is white (1.0,1.0,1.0) then the opacity of foreground is 1 (not filled with background). It can be in reverse consequence (white = opacity 0, black = opacity 1). I just need it to work depending on color.

---

**1st** column is my current result. Circle in mask is transparent.
**2nd** column is example of result I am trying to get. Circle in mask is white.
**3rd** column is example of why I want to get it working just like as I said (white mask color = foreground alpha 0, black mask color = foreground alpha 1 or reverse)

**1st** row is background
**2nd** row is mask
**3rd** row is foreground
**4th** row is result

# Answer
Anyway you'll have to use shaders at sometime, because fixed-pipeline is deprecated now.

Lighthouse3D has good GLSL tutorials to start with. There is also tutorial for similar problem to yours.

Shader for your problem:

```
uniform sampler2D backTex,maskTex,foreText;

void main()
{
   float mask;
   vec4 result;

   mask = texture2D(maskTex,gl_TexCoord[0].st).r;
   result = texture2D(backTex,gl_TexCoord[0].st) * (1 - mask);
   result = result + texture2D(foreTex,gl_TexCoord[0].st) * mask;

   result.a = 1.0;

   gl_FragColor = result;
}

```

**Edit:** I've written whole masking application, 100% working.

```
#include <iostream>

#include <GL/glew.h>
#include <GL/glfw.h>
#include <IL/il.h>

using namespace std;

GLuint loadImage ( const char *filename );
extern const char *fsrc, *vsrc;

int main ( int argc, char **argv ) {
    glfwInit();
    glfwOpenWindow ( 800,600,8,8,8,8,8,0,GLFW_WINDOW );

    glewInit();
    ilInit();

    // CREATE TEXTURES
    GLuint background,mask,foreground;

    background = loadImage ( "background.png" );
    mask = loadImage ( "mask.png" );
    foreground = loadImage ( "foreground.png" );

    // CREATE SHADERS
    GLuint fragment,vertex,program;

    fragment = glCreateShader ( GL_FRAGMENT_SHADER );
    vertex = glCreateShader ( GL_VERTEX_SHADER );
    program = glCreateProgram();

    glShaderSource ( fragment, 1, &fsrc, 0 );
    glShaderSource ( vertex, 1, &vsrc, 0 );

    glCompileShader ( fragment );
    glCompileShader ( vertex );

    glAttachShader ( program, fragment );
    glAttachShader ( program, vertex );

    glLinkProgram ( program );

    glUseProgram ( program );

    // BIND TEXTURES TO TEXTURE UNITS
    glActiveTexture ( GL_TEXTURE0 );
    glEnable ( GL_TEXTURE_2D );
    glBindTexture ( GL_TEXTURE_2D,foreground );

    glActiveTexture ( GL_TEXTURE1 );
    glEnable ( GL_TEXTURE_2D );
    glBindTexture ( GL_TEXTURE_2D,mask );

    glActiveTexture ( GL_TEXTURE2 );
    glEnable ( GL_TEXTURE_2D );
    glBindTexture ( GL_TEXTURE_2D,background );

    // SET TEXTURE LOCATIONS FOR SHADER PROGRAM
    glUniform1i ( glGetUniformLocation ( program, "foregroundTex" ), 0 );
    glUniform1i ( glGetUniformLocation ( program, "maskTex" ), 1 );
    glUniform1i ( glGetUniformLocation ( program, "backgroundTex" ), 2 );

    glMatrixMode ( GL_PROJECTION );
    glLoadIdentity();
    glOrtho ( 0,1,0,1,-1,1 );
    glMatrixMode ( GL_MODELVIEW );
    glLoadIdentity();

    while ( glfwGetWindowParam ( GLFW_OPENED ) ) {

        glClear ( GL_COLOR_BUFFER_BIT );

        glBegin ( GL_QUADS );
        glColor4f ( 1,1,1,1 );
        glTexCoord2f ( 0,0 );
        glVertex2f ( 0,0 );
        glTexCoord2f ( 1,0 );
        glVertex2f ( 1,0 );
        glTexCoord2f ( 1,1 );
        glVertex2f ( 1,1 );
        glTexCoord2f ( 0,1 );
        glVertex2f ( 0,1 );
        glEnd();

        glfwSwapBuffers();
    }

    return 0;
}

GLuint loadImage ( const char* filename ) {
    GLuint tex = 0;
    ILuint texid;
    ilGenImages ( 1, &texid );
    ilBindImage ( texid );
    bool success = ilLoadImage ( ( const ILstring ) filename );
    if ( success ) { /* If no error occured: */
        success = ilConvertImage ( IL_RGB, IL_UNSIGNED_BYTE );
        if ( !success ) {
            cerr << "Failed to convert texture\n";
            return 0;
        }

        glGenTextures ( 1, &tex );
        glBindTexture ( GL_TEXTURE_2D, tex );
        glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
        glTexParameteri ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexImage2D ( GL_TEXTURE_2D, 0, ilGetInteger ( IL_IMAGE_BPP ), ilGetInteger ( IL_IMAGE_WIDTH ),
                       ilGetInteger ( IL_IMAGE_HEIGHT ), 0, ilGetInteger ( IL_IMAGE_FORMAT ), GL_UNSIGNED_BYTE,
                       ilGetData() );
    } else {
        cerr << "Failed to load texture\n";
        return 0;
    }
    ilDeleteImages ( 1, &texid );

    return tex;
}

const char *fsrc = "\
uniform sampler2D foregroundTex, maskTex, backgroundTex; \
\
void main() {\
   float mask;\
   vec4 result;\
   mask = texture2D(maskTex,gl_TexCoord[0].st).r;\
   result = texture2D(backgroundTex,gl_TexCoord[0].st) * (1.0f - mask);\
   result = result + texture2D(foregroundTex,gl_TexCoord[0].st) * mask;\
   result.a = 1.0;\
   gl_FragColor = vec4(result);\
}";

const char *vsrc = "\
void main() { \
gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;\
gl_TexCoord[0]  = gl_MultiTexCoord0;\
}";

```
> 1 votes

---
Tags: opengl, objective-c, macos
---


# Question
Title: Aligning bullet's position in Asteroid Game
I'm writing an asteroid game and I would like to align the bullets on the ship's tip. I also want when the ship fires, the bullet gets the same orientation(angle, direction) of the ship and also be fired at a different velocity.

I'm drawing the ship by the following code:

```
gl::drawLine(Vec2f(-43,-52),Vec2f(59,1));
gl::drawLine(Vec2f(-14,-31),Vec2f(-14,38));
gl::drawLine(Vec2f(59,1),Vec2f(-43,54));

```

# Answer
> 1 votes
If *x* and *y* are origins of your ship, then

```
angle = atan2 (y, x);

```

returns its orientation towards *(0, 0)* which is angle represented in radians. Now, if the tip of your ship is *d* points distant from its origin, the location where you should draw the bullet *(x1, y1)* is computed like so:

```
x1 = cos (angle) * d;

```

and

```
y1 = sin (angle) * d;

```

As for the bullet's movement, you should propel it like so:

```
// each tick:
x1 += cos (angle)*speed;
y1 += sin (angle)*speed;

```

where *speed* is the speed of the bullet.

**EDIT:** Just make sure that you compute *angle*, *x1* and *y1* only when the player presses the fire button (or clicks or whatever) and not each time the engine ticks, which would be, as Vaughan Hilts huggested, a waste of cycles.

# Answer
> 1 votes
You can the trigonometric functions to compute the angle at which the bullet leaves. You can do the same for where it leaves using Cos and Sin. In fact, the velocity vector your bullet should leave is x=cos(angle) * speed. Similarly, the same goes for the y component, just use sin.

---
Tags: c++, opengl, mathematics, physics
---


# Question
Title: How is XML being used for a game engine, here?
In this question, the first answer explains a way of defining components of a gaming engine in XML, like this:

```
<?xml version="1.0" encoding="UTF-8"?>
<mobs>
  <mob>
    <personality>Aggressive</personality>
    <intelligence>20</intelligence>
  </mob>
</mobs>

```

Then, states in Java that your mob class would look like this:

```
public class Mob {
  private IPersonality personality;
  private Integer intelligence

  //**  Getters & Setters **//
}

```

What exactly is the XML doing, here? I'm not really familiar with XML, at all.

# Answer
> 11 votes
The **XML** describes one **instance** of a mob, i.e. the traits of one specific mob (it's personal personality and intelligence).

The **Java class** describes the **general structure** of all mobs (their traits: personality and intelligence).

Typically, a game engine would serialize the XML data at runtime to create actual Java `Mob` objects (= instances of the `Mob` class).

# Answer
> 6 votes
Maybe I didn't explain fully,

You implement the loading of the XML to the Class instance ensuring meaning in theory it could just as easily be any data format, json, flat file, Database its how you use the data that decides what it means. The example i provided was instantiating a new instance of IPersonality based on the String within the tags

```
 public IPersonality getPersonality(String personalityName) {
      if(personalityName.equals("Aggressive")) {
        return new AggressivePersonality();
      }
      else if(personalityName.equals("Passive")) {
        return new PassivePersonality();
      }
      else {
         //Maybe allow for no personality (We all know monster like that ;) )
         return null;
      }
    }

```

Here I saying if I find the name aggressive this mob the aggressive personality component.

---
Tags: xml
---


title: Repetition of move in Draughts game

text:
# Question
Title: Repetition of move in Draughts game
I am having a little problem in my draughts game. Lets say my red piece (moving through AI) has arrived at the border of black pieces and now it has become a king, lets assume it is at index 2. Now when its next AI's turn, this piece moves to index 5, thats ok. But on next turn it moves to index 2 and then this transition between index 2 and 5 continues in every turn. I can't figure out whats wrong. I have revised my generate\_moves() and it seems ok. Any idea what can be wrong? – My evaluation function is as follows:

```
public double Evaluation(int type, int aBoard[]) {

  double reds, blacks, ret=0.0;
  int loop;

  for(reds=blacks=loop=0;loop<32;loop++) {
    switch(aBoard[loop]) {
                case 2: //redKingType:
                  reds+=1;
                case 0://redType:
                  reds+=1;
                  break;
                case 3://blackKingType:
                  blacks+=1;
                case 1://blackType:
                  blacks+=1;
                  break;
                default:
                  break;
    }
  }
  switch(type) {
              case 0://redType:
              case 2://redKingType
                if(reds==0) {
                  return 0.0;
                }
                if(blacks==0) {
                  return 24.0;
                }
                ret=reds/blacks;
                    return ret;
              case 1://blackType
              case 3://blackKingType
                if(reds==0) {
                  return 24.0;
                }
                if(blacks==0) {
                  return 0.0;
                }
                ret=blacks/reds;
                   return ret;
              default:
                break;
  }

  return ret;
}

```

Note: I know this a very simple evaluation function ,but please consider the fact that I am doing this for the first time, under a hard deadline.

# Answer
Your evaluation function seems to consider only material, so when there is no obvious tactical lines, your root search function will simply return whatever moves were generated first. This leads to repetitive behaviour; your program is unaware of any potential progress and so simply waits for the opponent to make a mistake or force a tactical line.

To fix this, you need to add positional factors to your evaluation and implement a repetition detection scheme inside your search. The program should play towards improving its position if there are no obvious tactics within the search horizon. If the position has been repeated a number of times, you can return a draw score. If it is propagated to the root as the best score, you can then make a draw offer.
> 2 votes

# Answer
It's pretty common for robots to prefer meaningless to-and-fro moves in games that permit them, and in situations where there is no immediately obvious good move. There's nothing wrong per se; but fixing this is all part of crafting a good program.

The first thing you need to do is detect the repetition and end the game. It may also be useful for the evaluator to score games that end this way as worse than ties, (still better than losses) to add incentive to avoid this behavior.
> 1 votes

---
Tags: game-design, algorithm, ai
---


# Question
Title: How can I implement smart scripting, in my game?
I'm developing a game engine. It is supposed to be an entity/components based one. For developing my game, itself, I thought to use some scripting language to actually create the entities.

For example, if I want to add a kind of monster that is aggressive to the player, it will be an entity with several components; those components will change with the monster type, so if I have one hundred different types of monsters, in my game, I will not have to create a new method for each of them straight in my game code.

Should I use a scripting language to describe this entity, in term of components or is there something else that would work better? More generally, how should I use scripting, in my game?

# Answer
My game uses an entity component framework and uses scripts to define entities (this doesn't directly define behavior, I'll talk more about that at the end). The scripts define the actual components to be used for creating each entity. It uses a simple scripting language I created. Here is a simplified version of one of my scripts:

```
ENTITY:"Goblin"
{
    description="It's currently their age."
    commonname="goblin"
    pluralCommonName="goblins"
    childname="gob'in"
    pluralChildName="gob'ins"
    active=Nocturnal
    tags=Mobile
    baseAttributes="OrganicMobileCreature"

    [Model]{
            meshname="Goblin"
            texturename="GoblinTexture"
    }

    [Motion]{
            maxvelocity=0.01:0.015
            locomotion=Walk,Swim
    }

    [Skills]{
            ALL=0.01:0.05,Mine=8.3:8.8,PlaceCube=8.3:8.8
    }

    [Inventory]{
            maxItems=2
            Allow=ALL
            Disallow=NONE
    }
}

```

Much of that is self describing, but here are some highlights:

* The first section describes the common information for the entity. That includes a description and display names for various aspects of the entity.
* The `baseAttributes` tag references another script file that defines common components that I don't want to have to redefine multiple times. It contains components like `position`, `liferequirements` and so on. If any component is defined here again, this component will overwrite the common one.
* Each `[NAME] { }` set defines a new component that will be added to these entities.
* **This description is not just for a single entity**, it's for all goblins created. You'll see that some of the values have ranges (i.e. `0.01:0.015`), when a new goblin is created it gets created with a component that has a random value in that range. So each goblin will have slightly different skills and slightly different speeds. This setup defines that all goblins will start with really good skills in placing cubes and mining, which is really just for my own testing purposes. But as I'm sure you can guess, it's very easy to change the values to whatever I want.

This whole thing involves creating a custom parser, some kind of structure to hold the entity definitions (I call mine the Lexicon!) and a factory for taking those entity definitions and generating new entities. For me this system is still in its early stages, but it's turning out really, really well. It's a pretty powerful system for quickly defining entities and allows you to make any entity you want using the components you've created. If you're not comfortable creating your own parser, I think XML will work just fine. I converted mine from a pushback recursive parser I wrote for a little made up programming language.

As you can see this defines the entity. I mentioned that it doesn't directly define behavior. It can, however, easily define such things as hated enemies and how aggressively to react to said enemies. This would be as simple as defining whatever component you use to control such behavior. My entities also have a intelligence component (not shown) that defines things like:

* How they path find (simple line-of-sight movement, simple A\*, predictive A\*, etc.)
* How aggressive/defensive they are. Entities can have home zones that will be defended, but maybe not aggressive outside those zones.
* Technology awareness (open doors, use gadgets, avoid traps, etc)
* And more...

However yours is defined, it's your system that will drive the data in that component, which in turn affects the behavior of your entites.
> 18 votes

# Answer
If all you really need is a way of defining the components of a Monster then XML would work well both C# and java have a lightning fast implementation of it.

Your xml could be

```
<?xml version="1.0" encoding="UTF-8"?>
<mobs>
  <mob>
    <personality>Aggressive</personality>
    <intelligence>20</intelligence>
  </mob>
</mobs>

```

Then your Mob class could look like. (Java)

```
public class Mob {
  private IPersonality personality;
  private Integer intelligence

  //**  Getters & Setters **//
}

```

Where IPersonality is an interface.

You could then load your xml and parse each value through a factory.

for example Parse the Personality Value into the PersonalityFactory which is simply:

```
public IPersonality getPersonality(String personalityName) {
  if(personalityName.equals("Aggressive")) {
    return new AggressivePersonality();
  }
  else if(personalityName.equals("Passive")) {
    return new PassivePersonality();
  }
  else {
     //Maybe allow for no personality (We all know monster like that ;) )
     return null;
  }
}

```

Then you could set up a mob like so

```
Mob mob = new Mob();
mob.setPersonality(getPersonality(xmlValue));
mobList.add(mob);

```

The Key is that you engine knows the format of the xml and has a factory for all it needs.

One advantage of xml is that you can define your own schema to ensure that the format is always correct see here.

Hope this helps
> 4 votes

# Answer
Python is fine I think. Often LUA is also a good alternative if you want to add scripting capabilities to your programs.

You could either use XML to describe the behaviour of your monsters, this would involve some coding in the actual game code because you'll save only the "name" or some attributes according to the behaviour (speed, type of weapon the monster uses, etc.) of the behaviour to use in your game code.

If you use a Scriptengine (e.g. LUA) you could transfer this code out from your precompiled program to scriptfiles that are loaded during the runtime. To do this you have to expose the API of your "monsters" to the scriptengine. That allows you to call the methods of the monster-game code from the outside.
> 0 votes

---
Tags: scripting, entity-component
---


# Question
Title: Java: Tile-based Collision Detection with Rectangles
There are a few tile-based collision detection questions out there, but none seemed to suit my need.

I guess I really would like to know why this method for collision detection isn't working.

It updates in a tick() method, but I've also tried updating it in the initializing method. The checkCollisions() starts in a player class, and I'm simply using the returned boolean value to check whether the player can move in that direction or not.

```
public Boolean checkCollision(Player player, Screen screen, Level level)
{
    boolean collides = false;

    for(int i = 0; i < level.tiles.length; i++)
    {
        if(player.getBounds().intersects(level.getBounds(level, i)) && Tile.tiles[i].id == 1)
        {
            collides = true;
        }
    }

    return collides;
}

```

And it's simply an if statement in the tick() method:

```
if(input.right)
    {
        if(Ash.checkCollision(Ash, screen, level) == false && (dirFacing == 2 || dirFacing == 4))
        {
            xScroll++;
        }
        if(deltaMS > 16)
        {
            dirFacing = 2;
        }
        if(deltaMS <= 16)
        {
            dirFacing = 4;
        }
    }

```

Here's my getBounds for the tiles (I stuck it in my Level class because the tiles are created there):

```
public int getX(int i)
{
    return tileX[i];
}

public int getY(int i)
{
    return tileY[i];
}

public Rectangle getBounds(Level level, int i)
{
    return new Rectangle(getX(i), getY(i), 16, 16);
}

```

And I'm trying this method to find the tile's coordinates so I can draw each rectangle for each tile:

```
public void setTileCoords(int[] tiles)
{
    int sum = 0;
    for(int i = 0; i < tiles.length; i++)
    {
        tileX[i] += sum;
        tileY[i] += sum;

        sum += 16;
    }
}

```

Now I feel it's the way I'm rendering the map, since when I try to expand the map to 32 by 32 pixels (which will render 32 by 32 tiles on screen) it sticks with the 16 by 16 tiles but keeps my little rocky outcrop in the top right corner of the map...

Here's my level class where I do some extreme rendering/arrays of tile coordinates:

```
public class Level
{
 int w;
 int h;

public int[] tiles;

public int[] tileX;
public int[] tileY;

public Level(int w, int h)
{
    this.w = w;
    this.h = h;

    tiles = new int[w * h];

    tileX = new int[Tile.tiles.length];
    tileY = new int[Tile.tiles.length];

    setTileCoords(tiles);

    loadMap(0, 0, 0, 0);
}

public void renderBkgrd(int xScroll, int yScroll, Screen screen)
{
    //Bitshifting: 10101000 >> 4  = 1010
    int xo = xScroll >> 4;
    int yo = yScroll >> 4;

    int w = (screen.w + 15) >> 4;
    int h = (screen.h + 15) >> 4;

    screen.setOffs(xScroll, yScroll);

    for(int y = yo; y <= h + yo; y++)
    {
        for(int x = xo; x <= w + xo; x++)
        {
            getTile(x, y).render(x, y, screen);
        }
    }

    screen.setOffs(0, 0);
}

public Tile getTile(int x, int y)
{
    if(x < 0 || y < 0 || x >= w || y >= h) return Tile.rockTile;
    return Tile.tiles[tiles[x + y * w]];
}

//Takes tile and offsets.
public void loadMap(int x0, int y0, int x1, int y1)
{
    Sprite sprite = SpritesManage.Map1[x0][y0];

    for(int y = 0; y < sprite.h; y++)
    {
        for(int x = 0; x < sprite.w; x++)
        {
            if(sprite.pixels[x + y * sprite.h] == -9276814)
            {
                tiles[x + x1 + (y + y1) * h] = Tile.rockTile.id;
            }
            if(sprite.pixels[x + y * sprite.h] == -11731200)
            {
                tiles[x + x1 + (y + y1) * h] = Tile.grassTile.id;
            }
        }
    }
}

public void setTileCoords(int[] tiles)
{
    int sumX = 0;
    int sumY = 0;

    for(int y = 0; y < Tile.tiles.length; y++)
    {
        tileY[y] += sumY;

        for(int x = 0; x < Tile.tiles.length; x++)
        {
            tileX[x] = sumX;

            sumX += 16;
        }

        sumX = 0;
        sumY += 16;
    }
}

public int getX(int i)
{
    return tileX[i];
}

public int getY(int i)
{
    return tileY[i];
}

public Rectangle getBounds(Level level, int i)
{
    return new Rectangle(getX(i), getY(i), 16, 16);
}
  }

```

# Answer
> 2 votes
In

```
public Boolean checkCollision(Player player, Screen screen, Level level)
{
    for(int i = 0; i < level.tiles.length; i++)
    {
        if(player.getBounds().intersects(Tile.rockTile.getBounds(Tile.tiles, i)) && Tile.tiles[i].equals(Tile.rockTile))
        {
           return true;
        }
        else
        {
           return false;
        }
    }

    return false;
}

```

You `return true` if the first tile is colliding, and `return false` if the first is not.

This exits you from the method. You need to do something like this:

```
public Boolean checkCollision(Player player, Screen screen, Level level)
{
    boolean collides = false;

    for(int i = 0; i < level.tiles.length; i++)
    {
        if(player.getBounds().intersects(Tile.rockTile.getBounds(Tile.tiles, i)) && Tile.tiles[i].equals(Tile.rockTile))
            collides = true;
    }

    return collides;
}

```

And if you needed to incorporate a position into that, you could add in a few more variables (integer lists, I believe), that you push the co-ordinates of the collision onto.

# Answer
> 0 votes
Without viewing rest of your code this is a slight guess however

```
Tile.rockTile.getBounds(Tile.tiles, i)

```

`Tile.rockTile` seems like a static value so your bounds may not be changing (ie. x and y are not changed per tile), However level.tiles would make sense as for each tile in that level it would have a different bounds.

Intersects works when 1 rectangle overlaps another this means on a very basic level that corner of the Rectangle is within the other rectangle.

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


# Question
Title: Create shape from points / lines in editor and mathematically calculate nearest points within shape
If I want an editor that accepts "points" of a minimum of three (a triangle) and I just add some points first, like this:

how can I mathematically connect these corners (points) into an object of multiple triangles? so amount of triangles looks like something like this, by connecting nearest point:

and then later render this and also being able to define what it is and check for collisions on this ground, so I can create more than Rectangle based "bricks" on a Platformer for example. Also being able to texturize the whole object without it looking ugly.

Any ideas? Or what is this called in game programming?

# Answer
What you are describing looks to me like a triangle strip. Riemer has a tutorial for creating these in an efficient manner. So if user adds a point you just add one along the bottom of the shape and then create the triangles using the points in a clockwise manner, but the tutorial covers this quite well.

EDIT: For collision detection between points you can linearly interpolate between them and check the height value of your object and the interpolated points.
> 5 votes

---
Tags: c#, xna, 2d, algorithm
---


title: Blender Edge Split Alternative

text:
# Question
Title: Blender Edge Split Alternative
What other options/alternatives are there to "edge split" for smooth shading low poly game models.

As I understand it, edge split does what it say's, its splits the mesh therefore increasing the vert count. I have considered manually marking the edges as sharp however I would imagine this leaves artifacts on the model(in-game) ?

Cheers.

# Answer
> 1 votes
If you want to make an object smooth in a game then you need to use a shader that smooths it by interpolating the normals between vertices (in the game, not in blender of course). You can read more about smooth shading like Gouraud or Phong on wikipedia.

Manually marking the edges sharp in a model would require you to store that as vertex information when passing it to the shader. It is an interesting idea but could probably easier be aquired by drawing different model parts using different shaders in most cases I guess.

---
Tags: blender
---


title: Determine inventory item position shape

text:
# Question
Title: Determine inventory item position shape
Not a great title but couldnt think of a shorter way to describe it.

I am trying to think of the best way to determine the shape of items placed in the players inventory. I guess the best examples to explain would be something like the Horadric Cube in Diablo 2 or I suppose also, the Workbench in Minecraft. There are others, I just can't remember them.

Currently the best way I can think of involves multiplying the cell numbers each item is in. This way I can look at the product of that multiplication and know from a short list of values, what shape the items are in.

**Example**

My inventory is ordered like so:

```
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9

```

I would also have various arrays of preset values like:

```
FourSquares - 40, 180, ..., ...
VLines - 28, 80, ...
HLines - 6, 120, ...
Backslash - 45
Forwardslash - 105

```

etc, etc

So, say the user places items in 1, 2, 4 and 5 - That would give 40 and I could loop through each shape array and determine that it matched a value in the FourSquares array and go from there.

Does this seem like the best way to do it? Is there maybe a way that I wouldnt have to loop through the arrays? Would this be possible with bitwise operations maybe?

# Answer
The product will Not work for this as there are too many collisions (different shapes with the same product). For example, 1 2 4 and 5 == 40, but so does 2 4 5 and 5 8. A number on its own and then the 1 position would also be mathematically the same.

You can use something like what minecraft does and just do a string comparison for patterns that must have matches or character counting for the ones that are shapeless (there is just a boolean that marks a pattern as shapeless or not). The values used in the strings are up for you to decide but here is just a quick example, again using minecraft recipes as a basis.

The stone pick axe recipe. "SSS s s " - This makes a T shape when displayed with 3 characters per row. The S represents stone the 's' represents a stick (this association is also set up within the recipe when it is made). When displayed in the 3x3 grid the 'S' would be across the top with the next two rows containing a space, a 's' and then another space so the handle goes down the middle.

If you wanted to get more tricky you could represent the layouts as bitmasks and then just scan for patterns that way but you would potentially lose the 'What type of material' is there and be reduced to just pattern recognition. This seems to be ok with what you were doing however so I figured I would include it.

Hope this helps.
> 2 votes

# Answer
Multiplying their positions seems like an interesting approach but I am skeptical of it's ability to work in every case you'd want. There are, usually, many ways to multiply numbers to reach a common result which would give false positives (or surprisingly incorrect recipes). For example, `6 * 2 = 4 * 3 = 12`, `8 * 5 = 4 * 2 * 5 = 40`, etc.

I think it depends on exactly what you need to match.

If any types items can be in any orientation, just making a specific shape, you can treat each block as a boolean value (`true` if something is in the slot, `false` if not) and write an algorithm to verify `true`/`false` values for the shapes you're looking for. (I can expand on this if you have specific shapes you'd want help identifying.)

If you need specific items to be in a particular shape regardless of which item is where (like `3 wood` and `1 stone` in a `square`), you can use the above to verify the shape, then check the contents against the required types of objects. For example, if you've verified you have a `square`, check the contents, find you have `3 wood` and `1 stone` in the inventory, then you have a match.

If you need specific items in specific orientation, it's probably best to just maintain a list of usable recipes and verify them each in turn. If you need `wood | stone | wood` across the top row, check against a master recipe list that includes `wood | stone | wood` across the top row one cell at a time (also verifying the other cells are empty) and find you have a match.
> 1 votes

# Answer
Here's an idea. You could store your inventory as a bool array from 0 to 8 (9 spaces total). Step through each n element, and if it's true add 2^n or `1<<n` to a running total. At the end, you'll have a unique number for every possible shape, as each spot is represented by its own bit.

So a square (all positions occupied but the center) would end up being:

```
2^0  + 2^1  + 2^2  + 2^3  + 2^5  + 2^6  + 2^7  + 2^8

```

or

```
1<<0 + 1<<1 + 1<<2 + 1<<3 + 1<<5 + 1<<6 + 1<<7 + 1<<8

```

which ends up being

```
1    + 2    + 4    + 8    + 32   + 64   + 128  + 256

```

and has its own unique identifier of `495` with a binary representation of `0000000111101111` as an unsigned 16-bit integer. Then it's just a matter of cataloging every shape you want and it's value.

If you want the shapes to be able to be anywhere in the grid, then it gets a bit harder. You'll likely have to write a special-case to check for each shape.

For instance, in this array, to check for four squares (which I'm interpreting as 4 items in a square pattern), then you would check if the first item is NOT in positions `2` or `5` (as these sit on the right edge and cannot then have an item to their right), and not in `6`, `7` or `8`, the bottom row, (as there couldn't be any items below them). Then you would check if `n+1` (item to the right), `n+3` (item below), and `n+4` (to the right and below) exist.
> 1 votes

---
Tags: mathematics, algorithm
---


# Question
Title: Cascade(Waterfalls) particles animation - openframeworks, alternatives
Has anyone tried to create a waterfall particles animation using openframeworks? Is it possible? Is it good?

If not, can you recommend any other frameworks for easier creation of cascade animation?

Thanks a LOT!

# Answer
> 2 votes
In addition to Lewis' answer, the ParticleDesigner is easy to use and you can also design a bit using a flash port of the editor.

The presets are xml files anyway. The cool thing is there is also an OpenFrameworks addon for this. Also, if you're not happy with this you can try other ofxAddons or learn how to make a GLSL shader based particle waterfall

# Answer
> 1 votes
If you're working with iOS check out this, they have loads of waterfall emitters.

http://particledesigner.71squared.com/

---
Tags: opengl, animation, particles
---


# Question
Title: Improving the monster tamer battle mechanics: 2 choices
I'm developing a new monster taming/hunting game and I wanted to make some changes to the battle mechanics. Which would you find more fun and can you offer any suggestions to improve on what I've done. I'm leaning more to just option 2 although it will be a bit more difficult to deal with the AI.

Current base for the mechanics:

* 2 monsters face off head to head
* They use different moves to damage each other trying to kill the other.
* Various non damaging moves can be used to (increase/decrease stats, cause poison, paralyzing effects)
* There are different types of attacks that can be resisted or more effective against certain types of monsters (eg. Holy attacks do extra damage to Demons).

Basically, I'm starting with the simple Pokemon style battle. I would like to add either one or both of these changes:

Option 1: Add in a recovery stat for moves so that the "turns" are based on how much the monster has to recover. When a monster uses a move, the move's recovery stat is added to the monster's. When a monster's recovery stat reaches 0 it can perform a move. Explode - A high damaging move requires 50 recovery after being used. Poke - A smaller damaging move requires 20 recovery after being used. (Both start at 0 recovery, A goes first just because)

1. Monster A uses Explode (its recovery is at 50)
2. Monster B uses Poke (its recovery is at 20)
3. a check is done to see which has lower recovery and they go next (20 "time units" goes by and A now has 30 recovery, B is down to 0 and can perform a move again.
4. Monster B uses Poke again (recovery at 20) (A is still at 30)
5. Another 20 "time units" goes by and A is at 10 and B is at 0 again.
6. Monster B can attack again

This adds a timing element to the battle. Instead of each monster being able to attack once a turn, you can use smaller attacks or status changing moves quickly before your opponent recovers from their attack. Status effects may cause a monster to require more recovery each turn (like a slowing effect) or a hasting effect could be applied.

Option 2: Use 2 monsters in the same battle with a forward and rear position. Moves have a range value that determines if you can hit the forward, rear, or both monsters.

I think generally, melee style attacks would be higher damage but only affect the forward monster. You would often want a tank (high defense) monster to take these hits with a ranged attacker in the rear position like an archer or mage. Certain moves could damage both positions and you could have the option of having the monsters switch positions.

I think the strategy wouldn't be limited to a melee tank in the front with ranged in the back, as a melee tank may be susceptible to special attacks and certain monsters would do more damage in the front while being vulnerable to attack.

Example moves that take advantage of this mechanic:

1. Intercept - forward monster takes the next attack aimed at the rear position.
2. Force switch - forces the opponent monsters to switch positions
3. Pierce - 1/2 damage is done to the rear position if an attack on the front is successful.
4. Dragon's breath - all monsters (including your forward position if you are the rear) in front of you are hit with fire damage. (this would be a good move to switch your positions prior to using)
5. Goblin Mortar - fires 3 spaces away (requires the attacker to be in the rear to hit the rear opponent)

# Answer
> 2 votes
Use Option 1.

Option 2 will lead to most of the game being based around finding a way to quickly establish a 2 vs. 1 situation. Front-loaded attacks, crowd control debuffs, and other moves that look fine at first will all quickly get out of hand when they can be combined to remove one character from the match for a few turns.

# Answer
> 1 votes
With option one, the order of attacks becomes important. This causes player to take into account which order they should use the attack in relation to other attacks, even if the attack would not usually depends on each other.

Example (I apologize for the syntax coloring):

```
Poke - 10 damage, 10 recover
Explode - 40 damage, 40 recover
Both players have 50 health
Case #1:
Player 1 - Explode
Player 2 - Poke
Player 2 - Explode
Player 2 Wins
Case #2:
Player 1 - Poke
Player 2 - Explode
Player 1 - Explode
Player 1 Wins

```

This adds a uniques challenge because instead of always simply picking the most powerful attack. In case 1, player two found it useful to use a small attack first, allowing him to get two turns in a row and win. In case 2, player one prevented this.

Each time that the AI gets a turn, it could simply brute force all of the different possible attacks that each player could make and see who ends up with the most health a few turns into the future. This is actually pretty easy for a computer to do, even if there are dozens of attacks for each player to choose from.

When implementing option one, one thing to avoid is a situation of a low recovery time attack paired with a high damage attack. Using the same poke and explode attacks I used above, consider a player at 1 health (and 0 recovery since it is his turn) versus an opponent with 80 health and a 50 recovery. The first player could use the combination poke-poke-poke-poke-explode to kill the opponent without the opponent ever getting another turn to attack.

This negative effect can be countered by making it so that the recovery rates of different attacks are closer to being the same, so no player could ever get five turns in a row.

---

With option two, positioning of monsters is now important. Different attacks now cause different amounts of damages depending on where each monster is located. Players would have to think ahead as as to where to place his monsters to be both defensive and offensive.

This will mean that the AI would have to consider things such as swapping the position of its two monsters such that an attack is more damaging. This could still be solved using the brute force method, but each detail that needs to be taken into account slows the AI down.

Some things to look out for is the strategy of using both of one player's monsters to team up on one of the opponent's monsters. If the number of turns a player gets is at all dependent on the numbers of monsters he has alive, then a 2-1 fight is a very easy win.

---

It is always possible to combine both options as you see fit. They are not conflicting at all.

---
Tags: game-mechanics, combat
---


# Question
Title: Draw a 3D object at specific coordinates on the screen
I'm creating an application which allows the user to manipulate 3D models.

I would like to draw 3 axis representing the world coordinate system in 3D in order to give the user an idea where he is. These axis are represented by a 3D model. Now I want these axis to be always shown at the bottom left of the screen. I know how to draw them but not how to project them at specific coordinates on the screen.

How can i achieve this?

**EDIT**:

I use XNA. The axes have been created with 3DSMax, each axes is a cylinder surmounted by a cone. When I load the 3DSMax file, I get an instance of the Model class.

I've just tried to draw it normally and it appears at the center of the scene. After that, i don't know what to do to make it appears at the bottom left of the screen regardless of where the camera looks, as if that was part of the UI. 3DSMax has the same thing at the bottom left of each frame.

# Answer
First of all pixel on the screen is a ray in your 3d world - all scene behind this pixel.

Second, what you must know, that any point in 3d converted into 2d motinor space via multiplying 3 matrices:

```
pointIn2DSpace = pointIn3DSpace * WorldMatrix * ViewMatrix * ProjectionMatrix

```

So you can do a back conversion, multiplying "monitor" point with inverted WVP matrix:

```
pointIn3DSpace = pointIn2DSpace * Invert(WorldMatrix * ViewMatrix * ProjectionMatrix)

```

Now you can calculate some 3D point behind the pixel to the "depth of monitor". Let x and y will be you coordinates, than you must convert point (x, y, 0) and (x, y, 1) into 3D-space and get some ray from them.

Having two point you can easily get a ray and calculate required position on this ray.

Last step is just find in XNA docs where to get this matrices and do some math. Good luck.
> 3 votes

# Answer
If you want this 3D-model to be in a specific point in relation to your moving camera then just update the position when you update the camera position. If you are using XNA then just do something like:

```
axesPos = camPos + camOri.Front * distZ + camOri.Left * distX+ camOri.Down * distY;

```
> 0 votes

---
Tags: coordinates, projection, screen
---


# Question
Title: Making color of sprite darker or lighter
Is there any way to make a sprite darker or lighter in AndEngine? I dont want to use the alpha thing. Nor I want to loose the texture/design of the image.

# Answer
One way in 2D Android to do darken or perhaps even to make it lighter is to use the lighting color filters:

```
Paint myPaint =  new Paint(Paint.ANTI_ALIAS_FLAG);
myPaint.setColorFilter(new LightingColorFilter(Color.rgb(120, 176, 209),0));

```

> **public LightingColorFilter (int mul, int add)** Since: API Level 1 Create a color filter that multiplies the RGB channels by one color, and then adds a second color, pinning the result for each component to \[0..255\]. The alpha components of the mul and add arguments are ignored.

However, this can a bit diminish the color detail on the sprite.
> 1 votes

# Answer
For my opinion you have to use setColor method of the sprite to make it darker and lighter. To make darker sprite you have to use

```
sprite.setColor(180f / 255f, 180f / 255f, 180f / 255f);

```

To make lighter sprite again you have to use

```
sprite.setColor(1f, 1f, 1f);

```
> 1 votes

---
Tags: android, andengine
---


title: Texturing voxel faces separately

text:
# Question
Title: Texturing voxel faces separately
I am creating a 3D level editor which should be used to generate the very basic layout (level geometry) and a few basic game-logic entities of maps used in my game. So far, I decided to use voxels (i have a `fbx` untextured model file and do **NOT** draw this myself via vertices etc. as I already found tutorials on that which are not suitable for me) as the way to create the level geometry and most of this works fine. The next step would be to implement code that allows me to texturize these cubes by specifically applying textures to faces.

Using something like the following `Draw` method I can apply a `Texture2D` to the whole voxel (so I am not able to chose the face to which I want to apply the texture) and this works fine for now (though I have sometime issues orienting it, which should not be part of this question)

```
public void Draw() {
    foreach(ModelMesh mesh in this.Model.Meshes) {
        foreach(ModelMeshPart part in mesh.MeshParts) {
            BasicEffect effect = (BasicEffect)part.Effect;

            effect.World = this.World;
            effect.View = Engine.View;
            effect.Projection = Engine.Projection;

            if(this.Texture != null) {
                // UNLIT textures
                effect.Texture = this.Texture;
                effect.TextureEnabled = true;
            } else
                // LIT placeholder voxel
                effect.EnableDefaultLighting();
        }
        mesh.Draw();
    }
}

```

I will have about 10 textures which I want to be able to apply programmatically on each face of the voxels - **which approach would you suggest me to achieve the desired result?**

# Answer
For a small amount of voxels you could try cube maps with one texture per voxel. This is however quite wasteful and wasteful, and will not scale. Alternatively, if each face has its own texture coordinates you can create a texture atlas and modify the texture coordinates of each mesh.

The next best thing would be to create a mesh where each `ModelMeshPart` is one face of your cube. Then you can set the texture for each face individually. This will however still not scale very well, but should fast enough for 750 cubes.
> 1 votes

---
Tags: xna, c#, textures, models
---


# Question
Title: What is an efficient way to manage uniforms in a game?
Most engines on the market have their drawbacks and it's difficult to find a simple/light-weight one that's open-source and doesn't have to put you through a rather complex learning process. Writing one is a difficult task on its own, but it might not be a bad idea if what you want that engine to do is to support a specific kind of games (e.g. 2.5 D games on mobile devices).

So, in search for a good game engine architecture, I've found a few logistical issues. Consider this scenario:

***Objects***:

Each object is comprised of two principle structures of render information:

* a *model* (geometry mainly) and
* a *material* (that tells the object what textures and what shaders to use).

Of course, it is natural to allow an object to switch its material definition on the fly. But a material encapsulates the shaders, so these drag along with them some slots for *uniforms* and *vertex attributes*.

Since an *uniform*, for example, can be:

* object specific (color, specular exponent, etc.)
* global/superglobal (lights, weather conditions/fog/wind,etc.) or
* specific to a group of objects (they all have, let's say, a reflectivity factor)

then it means that it's wrong to put them in either the object's property region or in the material's property region. It's clear that both uniforms *and* attributes are always declared in the shader sections of a material, but where their values come from is an enigma in the frames of a pretty general rendering engine. You have to allow for the existence of numerous types (by semnatics!) of uniforms: position, colour, bone matrices, indices, lighting parameters, etc.

---

The big question now: how would you suggest to organize and manage uniforms? (especially the information flow - they're declared by shaders, but their values are supplied by apparently different type of entities - some renderable, some more abstract, being themselves controllers or managers).

# Answer
The way Horde3D (open source OpenGL engine for desktop) handles it is by putting the shader into the material. For instance, we have the following material definition:

```
<Material>
    <Shader source="shaders/water.shader" />
    <ShaderFlag name="_F02_NormalMapping" />

    <Sampler name="albedoMap" map="/textures/smallRock_diffuse.dds" />
    <Sampler name="causticMap" map="/textures/caustics/001.dds" />
    <Sampler name="normalMap" map="/textures/smallRock_normal.dds" />

    <Uniform name="textureMatrixRow0" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow1" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow2" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="textureMatrixRow3" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="fogColor" a="0.0" b="0.0" c="0.0" d="0.0" />
    <Uniform name="texScale" a="1.0" b="0.0" c="0.0" d="0.0" />
</Material>

```

Horde3D says: a uniform is part of the shader and the shader is part of the material. So a material should be able to set its uniform variables.

What they've also introduced is the concept of `ShaderFlag`'s. This is a define in the shader source that turns features on or off. They have a shader preprocessor that resolves these settings to generate the final source. What this allows is for several materials to share the same shader, but with different settings.

For instance, our main character needs animation, so it has the `_F02_Animation` flag, but a rock doesn't need it. The generated source is therefor completely different, but they use the same shader.

In my own engine, I store the uniform variables per shader object. When I render my particle emitters, I enable the particle shader and let every emitter attach their vertex attribute array and textures. So the shaders handles certain uniform variables (projection matrix, corner points for screenspace quad), but the emitters supply their positions, sizes, rotation and color.

This also allows for a fallback path: preferably, a geometry shader is used to convert points to textured quads, but if that capability is unavailable the corner points will be calculated on the CPU.

I can't give you a final and definitive answer (I'm still working this stuff out myself), but a good starting point could also be to look at how Cg shaders abstracts things.
> 3 votes

---
Tags: shaders, architecture, opengl-es2, resource-management
---


# Question
Title: IOS OpenGl transparency performance issue
I have built a game in Unity that uses OpenGL ES 1.1 for IOS. I have a nice constant frame rate of 30 until i place a semi transparent texture over the top on my entire scene. I expect the drop in frames is due to the blending overhead with sorting the frame buffer. On 4s and 3gs the frames stay at 30 but on the iPhone 4 the frame rate drops to 15-20. Probably due to the extra pixels in the retina compared to the 3gs and smaller cpu/gpu compared to the 4s.

I would like to know if there is anything i can do to try and increase the frame rate when a transparent texture is rendered on top of the entire scene.

Please not the the transparent texture overlay is a core part of the game and i can't disable anything else in the scene to speed things up. If its guaranteed to make a difference I guess I can switch to OpenGl ES 2.0 and write the shaders but i would prefer not to as i need to target older devices. I should add that the depth buffer is disabled and I'm blending using SrcAlpha One.

Any advice would be highly appreciated.

Cheers

# Answer
> 6 votes
I've been the graphics performance guy for a few big-name 3D iOS titles, so I completely feel your pain on this one.

My experience has been that transparent pixels are the most expensive thing you can render on modern iOS devices. Your conjecture is right; the greater number of pixels on the iPhone4 really kills its performance in general, and transparent pixels makes it doubly-bad. You'll find that you have the same problem on the iPad 1, as well.

The particularly slow point is the point where the drawing of a pixel needs to check what the color behind it was. This occurs for transparencies, for alpha masking ("discard" statements in shaders), etc.

In order to deal with this, we took a few steps:

* Wherever possible, we made more draw calls in order to draw more opaque textures. For example, we made tree foliage consist of two parts; the opaque bits in the middle, and the transparent bits around the outside. This meant we drew far more triangles and had to perform more draw calls overall, but it reduced the number of transparent pixels on the screen. Similarly, when we wanted a "vignette" effect which applied a circular darkening around the outside of the screen, we did that by drawing small rectangles with the darkness texture at the edges of the screen, instead of by naively drawing a single full-screen quad that covered the whole screen.
* Wherever possible, we used OpenGLES shaders to render the transparency as part of the fragment shader. So inside the fragment shader it would do normal shader activities, but would also check the fragment's position on the screen, and figure out any overlay modifiers which needed to be applied.
* We disabled many shaders and transparency effects on iPhone4 and iPad1, judging that they were too expensive for the hardware.

We also tested (but didn't actually ship with):

* Render into a render target that's only 3/4 of the full screen resolution, and scale it up for display. This made a huge improvement to performance, but we decided the quality loss was unacceptable for our game.

So there are definitely savings which can be made. But I want to stress that you're going to have performance problems on the iPhone 4 and the iPad 1 regardless of what you do; their graphic chips simply aren't fast enough to power their number of pixels, and neither have good shader performance (my tests indicated that their baseline performance running with fixed-function-alike shaders had them running 5-10% slower than they did under the fixed function pipeline). And this was a full-time job for me; if you're in a smaller team, you may not want to invest your man-months in that way.

As a general rule of thumb, your best bet is to limit overdraw as much as you can, and to try to minimise the number of pixels affected by transparency as much as you can (either by making less stuff transparent, or by moving the transparent stuff further away from the camera, so it's not covering as many pixels).

And then you have to decide how low you're willing to go in terms of frame rate on the troublesome iPhone 4 and iPad 1, and start cutting effects in order to meet that target frame rate.

# Answer
> 2 votes
I'm pretty sure you have hit the fillrate limit; since PVR GPUs use a tile-based approach for rendering, drawing transparent parts that affect lots of pixels kills the performance.

Try moving to OES 2 and apply the overlay directly when drawing the geometry, or draw the entire scene to a framebuffer object and blend with your overlay manually. 3GS supports OES 2, and it should be your lowest target device.

# Answer
> 0 votes
I don't think the problem is the transparency, try using an opaque texture instead and see if there is a difference in performance. I think the problem is that you are maxing the rendering bus bandwidth. See here. Try using pvr-compressed textures.

# Answer
> 0 votes
You should draw transparent primitives after opaque for best performance, because PowerVR GPUs use Tile-Based Deferred Rendering.

---
Tags: unity, opengl-es, ios, performance, transparency
---


title: Is my engine concept a good one?

text:
# Question
Title: Is my engine concept a good one?
I'm currently writing a generic engine for my incoming games. I have developed few games already but never with the same "base" and my code was/is quite a mess. The idea was to create an engine that I could use for any type of games.
I have read papers about entity/components managers. Some are using what they call nodes, systems etc... I thought it was a bit confusing, especially the node concept. I plan to not use nodes, and my question essentially is: "Is this a good engine concept"? And if it is not, what improvements could I make?

First, all elements in my game are entities. The player is an entity, any tile of the map or whatever is an entity. An entity (in my engine) is a basic class with a position, and a list of components. In my mind, all "features", "behaviors", etc, must be implemented through components. The entity class will also have an update and a render method. The entity holds an unique special component that is a component that implements an interface 'Renderable' and will handle the rendering of the entity, an entity that does not need to be rendered will not have a render component.

That was for the entity, now about component. Currently in my engine a component is something that brings something to the entity. For example, if I want my entity to be controllable via keyboard or whatever, I will add a component that handles this to my entity. And during the engine update process, the entity manager will update all its entities and each entity will update all its components (or at least the components that need to be updated).

```
class KeyboardControllComponent extends AbstractComponent implements Updatable {

    @override
    public void update() {
        //do the input handling here
    }

```

Basically this component will call another one (a movement component) that will actually apply the movement to the entity.

Also, I have implemented what I call a 'dispatcher' to my engine. It allows all elements to the game (everything in my game extends a *GameElement* class) to dispatch or listen for events. For example, if the hero walks on a specific thing (a trap for example), the component in charge of the hero entity movement/collision will fire an event to all game elements that are actually listening for that kind of events. I will take the example of an interrupter, the hero 'collide' this interrupter, the interrupter component in charge of collision will then fire a event to the entity that represents a door somewhere and open it.

Is this a good concept?

Finally, all game elements are handled by managers. EntityManager, DispatcherManager, SceneManager, etc...

Let me know what you think of my approach. I have not added actual code using the engine to not overload the post but if you want to see it, no problem.

# Answer
> 7 votes
It looks mighty fine to me. I'm using a similar approach in my engine.

My definition of an Entity is that it is an object that can interact in some way with other objects. Right now I have the generic `GameObject` class, with three children: `Player`, `Enemy` and `Bullet`. It also has handles to five different modules:

* ModuleSprite - renders the entity
* ModuleWeapon - allows the entity to shoot weapons
* ModuleScripting - makes the entity scriptable
* ModuleCollision - collision detection
* ModuleParticles - particle effects

There's a hidden benefit to this modular approach: you can build objects from a blueprint! For instance, this is the blueprint for a bullet:

```
name: "Bullet"
type: eBullet
module_sprite {
    sprite: "blast_cool.png"
    render: eCamera
    pivot {
        x: 0.5
        y: 0.5
    }
}
module_collision {
    state: eIncorporeal
    weight: 1.0
    sphere {
        radius: 12.0
    }
}
module_particles {
}

```

I load these blueprints into my global `StateMachine` and now I can spawn a bullet like this:

```
GameObject* result = m_Owner->GetScene()->CreateObject("Bullet", &m_ObjectState);

```

Even though it's silly, I could have my `Bullet` spawn more bullets by adding this to the blueprint:

```
module_weapon {
    weapon {
        name: "Blaster"
        state {
            time_cooldown: 5.0
            time_reload: 50.0
            clip_ammo_left: 10
            clip_ammo_total: 10
            current: 1
        }
    }
}

```

Important to note, though, is that you should make the module interface as simple as possible. You can have either 0 or 1 of each module, but each module can contain 0..n of whatever functionality it manages.

In my case, the `ModuleWeapon` class holds all the weapons for an Entity, with a member that describes the currently active weapon.

---
Tags: entity-system, component-based
---


title: How can I export mudbox joints to .fbx?

text:
# Question
Title: How can I export mudbox joints to .fbx?
When I export my Mudbox mesh (level 1), with its skeleton selected, to a .fbx and import it into unity, I don't get the bones/joints/skeleton/whatever under my mesh in the hierarchy.

Am I missing something?

# Answer
Sorry the bones joint things in Mudbox are not exportable, they aren't real bones like the bones are in Max or Maya, mudbox joints are more like the deformer modifier in 3ds Max. Sorry its not that u are missing anything its just how Mudbox works sorry, I also tryed a similar thing but it didn't work for me either. So don't worry.
> 1 votes

---
Tags: unity, rigging, fbx
---


# Question
Title: Particles/instancing groups in an Entity/Component system
I've been playing with an entity/component/system design recently, and I've come across a couple of stumbling blocks.

**Instancing**

Let's say I have a few hundred "things" (asteroids, chickens, whatever) that are being drawn with instancing. In a classic component hierarchy, I'd have a game object that keeps the individual instance index and vertex buffers, as well as the second dynamic vertex buffer for the instance data (collection of matrices, etc.). That object would be responsible for checking collisions with other objects and between the instances themselves.

In an ES system, I'd like to track each instance as an individual entity, but I don't want to give up simplicity and performance of instancing. The first thing that occurred to me was to create an "instance group" component, with a field that defines a group ID to enable handling of multiple types of instanced geometry.

An "Instance System" would collect those components and maintain the instance vertex buffer. My entity manager already notifies systems when an entity is created or destroyed which makes this part pretty easy to implement.

My confusion comes from how to cleanly integrate that with the rendering system. If each instance appears as a separate entity with a "renderable" component/attribute, the render system will process them individually.

I could:

1. Include a special case for entities that have both a "renderable" and an "instanced" component, but that seems messy and feels like starting down the path of having a huge render system with tons of special cases.
2. Have the render system maintain a collection of instance vertex buffers, query the entity list for "instanced" entities, filter based on a group ID, etc., and render as appropriate, so the render system becomes responsible for maintaining instance collections, but that seems like the wrong place to put that sort of logic.
3. I could also include a single entity in addition to the instances with, say, an "InstanceOutput" component/attribute and a `Renderable` component, and remove the `Renderable` component from the individual instance entities, giving a single render point for all of the instances. This component would probably also server as a place to keep the geometry and persistent instance/vertex buffer.

Is there a better way?

**Rendering**

I have several types of renderable entities. Some have procedural geometry and textures, some are just sprites, some are text displays. What's the best way to differentiate these from the point of view of the rendering system without having to write a massive `switch` statement? In a game object hierarchy, each of these types would have their own `Draw()` method, but moving the logic into a Render System doesn't seem to provide a lot of flexibility in terms of different effect parameters, etc.

# Answer
> 6 votes
You are over generalizing and trying too hard to use what your idea of an entity system is.

Instancing is easily just as simple as having your renderer automatically batch together all renderable objects with the same mesh and materials.

It's not the job of the data or the components to render themselves. It's the job of the rendering system, which should be expected to be intelligent.

There's no reason to have tons of different rendering systems for each type of renderer, either. The difference between a sprite, a mesh, and static terrain all comes down to materials (different vertex shader for bill boarding sprites va lighting meshes) and draw order, all of which can be completely handled by the same system and even the exact same render pipeline.

# Answer
> 5 votes
I think you may be losing some of the performance of instancing if you're making each instance an entity. I think your idea of using a instance group is good. I would then create a system that looks for entities with a instance group component and renders the instances. Like other systems, this system doesn't care about other components the entity has, including renderable. If the entity also had a renderable component that would be picked up by the appropriate system and rendered, but the rendering wouldn't be of the instances. For example, if you had a chicken generator, the instance group system would render all the chickens and the renderable system would render the chicken generator. You can have a separate system that updates the instances within instance group components.

As for other rendering stuff. It would be a simple thing to create a `spriteRender` component, `textRender` component or any other kind of component for each different type of rendering. Then have a system for each component with a different rendering style. For example, my game has a billboard rendering system, a static model rendering system and an animated model rendering system. An entity could have all of them, or any combination. For example a goblin could have an animated model component for its body and a billboard component for a status icon above its head.

---
Tags: entity-system, instancing
---


title: Motion capture for indie developers?

text:
# Question
Title: Motion capture for indie developers?
Several years ago motion capturing was only possible for big name studios due to cost. Now it seems that it is moving into the realm of indie developers due to lowering costs and better technology. I've researched it a bit and seen two major options: IPISoft and iClone which both cost several hundred dollars and use fairly cheap hardware(Kinect or PS3 eye). I was wondering if anyone could recommend any other alternatives?

# Answer
> 6 votes
If you do not want to create your own motion capture data, then there are several motion capture databases available, some of them completely free.

# Answer
> 5 votes
Long-winded answer follows. tl;dr, it's a LOT OF WORK.

I've used iPi Soft and found that it works fairly well, but unsurprisingly you need to do a decent amount of clean-up on the resulting animations, especially if you're using props and such. I've also used Kinect (albeit a year ago when the available free software was less polished), and you get the same thing there, but are *very* limited in what motions you can do, especially from the waist down.

Expect any of these free or low-cost motion capture systems to be a *massive* time sink. Assuming you have a large enough room to do it in, you're going to spend literally days working out the kinks to get a workflow going, and expect upwards of an hour for every couple of seconds of animation in order to "fiddle with it" on the PC to make it smooth and believable as an animation for a game--unless you are an experienced animator with good middleware for this purpose.

If you require relatively few animations and fairly ubiquitous actions (jump, slash, tumble, run, climb, etc), you're honestly better off spending the money for someone else's work. If you're wanting to do something more interesting, just expect to spend loads of time getting rolling. Also keep in mind that being an actor for motion capture actually takes a certain amount of traditional acting skill and a lot of dexterity and stamina. Much like voice acting, it's more demanding than you might think.

If you're wanting a presentable final animation for a game, I would recommend you at least do the trial and then spend the money on iPi Soft or a similar product. In my opinion, for a non-trival motion, a decent animator can rig a model and keyframe the animation orders of magnitude faster than you can get a similar result from single unit Kinect-based solutions.

All of that having been said, if you have the time, doing it this way gives you a lot of appreciation for the animation side of development, and you'll certainly learn a lot.

---
Tags: kinect
---


title: Positioning entities in adjacent maps

text:
# Question
Title: Positioning entities in adjacent maps
Say I have a 2D tile based game engine (I don't, but I will soon). I was wondering how I would manage drawing adjacent maps. That is, imagine we have a map that is 50 by 50 tiles wide. Then next to that, we have another map which of the same size - but they are loaded via separate files. So they are visibly next to each other.

Let's call the first map (the one we are on) A, and the second map B. How would I:

1. Draw the two maps next to each other at the combining point (provided that I have already saved data about what maps are next to each other, and at what point), so they join seamlessly, without the need for a loading screen / "teleport".
2. Manage entity positions. Positions, currently, are managed relatively. That is, each map has it's own (0, 0) tile. How would I manage this when drawing an entity? I was thinking about storing a pointer to the map the entity, and if it happens to change map, the pointer is updated, and we - somehow - find the tile the entity would move on to.

I should mention that only the player will ever need the use for this movement.

Any ideas? Sorry if I wasn't very clear.

# Answer
From your question I assume you're planning to create big world and to minimize ram/bandwidth usage you want to separate this world into many partitions(maps).

Entities with relative position to map can be shifted by partition position during drawing. But this isn't the best idea, because you have to shift all these entities each frame. Better idea would be to shift all entities at loading.

To manage partitions I would recommend to create class Partition for each one and store them into 2D array like tiles. To pick desired partition you'll simple divide position( in computer it should be rounded down ): `partition = partitions[x/50][y/50]` and to pick tile: `tile = partition.tiles[x%50][y%50]` or `tile = partition.tiles[x-partition.x][y-partition.y]`
> 0 votes

# Answer
One simple way to handle this is to simply use absolute positions for everything. When storing maps or entity positions you use and store them absolutely instead of relative to each individual map. This makes entities switching between maps seamless, because they're simply just moving one more position. As an example, your first map would have its bottom corner at (0,0). The next map to the right would have its bottom corner at (50,0) and so on. This does introduce the issue of negative positions. This is not a problem, as long as you're not using the position as an index into an array. If you're wanting to use the position as an index into the array, you would first subtract the offset from center. So the map you have at (50,0) would index into its tile array with `tileArray[xPos - globalX][yPos - globalY]` Where `globalX` and `globalY` would be 50 and 0 respectively.
> 1 votes

# Answer
I assume you want a seamless world:

* For every Map pointers to the adjacent maps should be saved.
* Always load the maps adjacent to the current one so that it always already loaded when you see it.
* This loading should be done in a seperate thread so player doesn't notice the loading times.
* When for any reason the map has not finished loading when the player reaches them, show loading screen.
* The current and the adjacent maps should be drawn.
* Every map should have it's own list of objects.
* Update the entities far away maps less frequent/with less precision.
* Moving entities should sometimes check whether they have crossed the border to a other map and be transferred from one to the other map.
* If your objects are quite big or the map borders are a problem collision checks should include the objects of the adjacent maps, too. This can be optimized by saving how big the biggest object is and then only include the adjacent maps when the object is in a area of the map where this biggest object could possibly overlap.
* Free very far away maps when a certain amount of maps are in memory. (Depending on platform and map-complexity)

---

About the actual question:
The coordinates of the entities themselves should be absolute because relative coordinates would have to be converted whenever you do position depended calculations which should also work over map borders.
> 0 votes

---
Tags: java, maps, slick
---


title: Victory rewards in digital CCG

text:
# Question
Title: Victory rewards in digital CCG
I am currently polishing a digital CCG where people can play against friend and random opponents in a classical Magic the Gathering-like duel CCG.

I plan to award the players with 20 ingame currency units (lets call them gold) for each hour they are playing, 50 for each day they are playing and X for each victory.

Now, the X is what I am trying to calculate here, since I would prefer keeping the currency to a certain value, but also with to entice the players to battle.

I could go with a solid figure, say 25, for beating up an opponent. But that would result in experienced players only beating up newly started players, making the experience lame for both.

I could also make a laddered tier, where you start at level 1, and raise in level as you defeat your opponents, where winning over a player awards you his level x 2 in gold.

Which would you prefer if you were playing a game like this. There is no gold-based scoreboard, but the gold is used to purchase new cards along the way.

# Answer
Defining X is a bit difficult since you didn't say how pricey the cards are you can buy. **The gain has to be balanced with the expenses!**

In my opinion are the daily and hourly bonuses too unbalanced and I think you should get rid of at least one of them. I think it would be better to be payed daily.

Try not making the battle reward based on levels, instead I would use a win/lose statistic and calculate the payment with that. Tell the player before entering a battle the amount of gold he would get so he can choose if he wants to play safe or play with profit in mind.

But that option opens another problem. How would the other player be able to choose his opponent? Maybe only random fights where the game decides who you play with. Maybe you give the player a slider with how much gold he wants to earn and calculate the opponent that way?
> 3 votes

# Answer
As far as the battles go, you could implement a wagering system.

Give each player the ability to wager what they would like to win. The odds would be determined by the player's rating.

Many online games use ELO ratings similar to Chess, or you could use Microsoft's Truskill rating formula.

Once you have a ratings system, you can determine what the odds are using each player's rating, which determines what the player needs to wager to win their desired payout amount.
> 2 votes

# Answer
I think that you should implement some sort of Elo or Elo-like rating system, where the level of a player is determined not by the number of wins, but also by the levels of the players that he is winning against. If you had levels based on the number of defeated opponents, it would allow players to grind experience by defeating a large number of weaker players. The rewards for the match will be based on the rating of the opponent compared to the rating of the player.

One advantage of the Elo system is that given the results of each match, it can estimate the strength of a player's deck, which is then used to compute the rewards.

If a player's odds of winning the match are 2:1, then he should win half as much as his opponent.

Most of the time, players do not like to see their ratings drop. In addition to the rating of a player, you could also add an experience score which goes up when a match is won but never goes down. This experience score would not be used in computing the rewards for a match.
> 0 votes

---
Tags: game-design, game-mechanics
---