# Question
Title: SailsJS + Rotational direction coordinates calculation issue
I'm creating a small game to learn how NodeJS & Sails work (and by extension Waterline, Socket.io, Express, and all their components).

I'm using websockets to make the **server** calculate the coordinates. Everything is handled server-side.
The client only receives serialized data in order to redraw the whole canvas.

For debugging purposes, I decided not to redraw but simply "draw" (leaving the old canvas visible) to show you the result.

See below for situation, issue and code.

## The issue

I'm having trouble when **calculating coordinates**.

What I need is a simple **forward/backwards** system, and when pressing `left` or `right` keys, change the direction angle so the character can move in the canvas.

Kinda like the good'ol *Asteroids* retro games.

The issue is the following:

The drawn loops you see shouldn't exist. In fact, they should be **circles**. I drew this by simply pressing either `up` or `down` key, combined with one of `left` or `right` keys.

I think there is an issue in the calculation system...

This shouldn't be a performance issue because each tick occurs at the same interval, so even if it was a performance issue, it should only be related to delay when redrawing the canvas, not such an offset in coordinates calculation...

Any idea ?

### Info about code api

* `moves` contains a javascript object like this:
`{ left:false, right: false, up: false, down: false }`
It is used to check whether the user is "pressing" associated arrow keys.
It is updated each time there is a `keyUp` or `keyDown` event client-side.
* `user.pick` contains the "physical object" to be rendered in the canvas, which contain `x`, `y` coordinates, and information about movement speed and rotation speed.

### Here's the code that handles the coordinates calculation.

```
// Change angle if "left" or "right" is pushed
if (moves.left || moves.right) {
    // let PI2 = 2 * PI;
    let angle = user.pick.angle;

    if (moves.left) {
        angle += user.pick.angleSpeed;
    } else if (moves.right) {
        angle -= user.pick.angleSpeed;
    }

    // Use this to avoid having huge integers to manage
    if (angle < 0) {
        angle = 360 - angle;
    }
    if (angle > 360) {
        angle = angle - 360;
    }

    user.pick.angle = parseInt(angle);
}

// Up and down allow us to move either forwards or backwards.
if (moves.up || moves.down) {

    let moveRatio = moves.up ? 1 : -1;

    let angleRadians = user.pick.angle * (PI / 180);
    let x = user.pick.x + moveRatio * user.pick.speed * Math.sin(angleRadians);
    let y = user.pick.y + moveRatio * user.pick.speed * Math.cos(angleRadians);

    // Avoids collisions with canvas walls
    if (x > 0 && x < user.map.width) {
        user.pick.x = parseInt(x);
    }
    if (y > 0 && y < user.map.height) {
        user.pick.y = parseInt(y);
    }
}

```

# Answer
After having received help in private, let me post the answer here (and thanks a lot for the ones that helped me on Twitter :) )

## First change: angle udpate

A friend of mine who is a mathematician told me that the `angle` security could be handled with a simple modulo.

He gave me the hint to remove this code:

```
if (angle < 0) {
    angle = 360 - angle;
}
if (angle > 360) {
    angle = angle - 360;
}

```

And instead, replace it with this code:

```
if (angle <= 0 || angle >= 360) {
    angle %= 360;
}

```

And it works very well!

Because the issue with the first code was that when the `angle < 0`, it oscillated between 0 and `-speed` (meaning `-10` in my case), so the pointer was moving down and not rotating.

## Second change (and the most important): values rounding

The same friend, and also @voidqk on Twitter, told me to `stop rounding values`.

This is a **great** advice because **I was not rounding values at all**. I was **parsing them to int**.

Meaning I had this:

```
console.info(
    parseInt(1.2), // 1
    parseInt(1.6), // 1
    parseInt(-1.2), // -1
    parseInt(-1.6) // -1
);

```

This was **totally incorrect**.

I replaced everything with `Math.round()` and now it rounds values in a proper way:

```
console.info(
    Math.round(1.2), // 1
    Math.round(1.6), // 2
    Math.round(-1.2), // -1
    Math.round(-1.6) // -2
);

```

The `parseInt()` method introduced an incorrect offset in negative coordinates, whereas `Math.round()` does the job very well and now when I move my pointer and push the `left` arrow key, I can now draw circles :D
> 0 votes

---
Tags: javascript, node.js, websocket
---


title: Open_GL Camera somehow not centered

text:
# Question
Title: Open_GL Camera somehow not centered
I setup my OpenGL viewport via

```
    ViewPort( 0,0,WindowW, WindowH )
    MatrixMode( Projection )
    LoadIdentity()
    MaxY = ClipNear * Tan(FieldOfView * 0.00872664626)
    MaxX = MaxY * Ratio
    Frustrum(-MaxX ,MaxX ,-MaxY ,MaxY ,ClipNear ,ClipFar)
    MatrixMode(ModelView)

```

Then I add rotation and move the Camera accordingly

```
    LoadIdentity()
    Rotated(ry,1,0,0)
    Rotated(rx,0,1,0)
    Translated(z,y,x)

```

However the center of the frustrum is not the middle of the Window. It is slightly right and up in the window.

I'm sure there is a bug in my code but I can't seem to find it. I have checked every place I could think of.

The bug could be caused by setting a wrong viewport however that doesn't seem to be the case as a similar Project (however not using modular code) works fine with the same viewport settings.

The bug could also be caused by setting a wrong Frustrum. However that also works in the other project.

Aside from that I do not know of anything that could cause this.

As my Code is written in a rather weird language posting it here wouldn't do any good.

So my question is what kind of mistake/bug can cause a behaviour like that.

# Answer
> 2 votes
It turns out that my Window had the wrong size. Background: I use a full screen Window that simply has no border. I set the size of that Window to the Screen Resolution. Now the problematic part: While the size of the Window is respecting DPI the resolution returned doesn't which lead to a window thats too large.

---
Tags: opengl
---


# Question
Title: Does Unity 5.4.3 supports backward compatibility with Unity 5.4.2?
I'm currently using Unity 5.4.2 for my video game project, however my friend who assists me in the project uses Unity 5.4.3 instead. Does Unity 5.4.3 supports backward compatibility with projects made with the previous version, in this case, Unity 5.4.2?

*NB: This is the first time I'm asking in Stack Exchange forum. I'm apologize for any mistakes in this question.*

# Answer
> 4 votes
Yes. If you were to update your unity editor to the newer version, it will re-process the project at startup. You should only expect to have problems when upgrading from a much older version than the current one (e.g. Unity 4 to 5) as APIs are revised to reflect major changes in the engine.

@Gnemlock has pointed out the possibility of bugs being introduced when updating to a newer version of Unity. While a noteworthy point, if your friend is successfully working on the project in 5.4.3, it is unlikely that joining him/her is likely to cause you headaches.

@DMGregory has reminded us of the one fundamental truth in these matters: **backing up your project** is the number one way to update with confidence.

---
Tags: unity
---


# Question
Title: Using a Windows forms Textbox control in an XNA game
What I want to do is this: Use a standard Textbox control in an XNA game. This will be the only control used, and the game is designed in xna alone. I (for some reason) cannot get the game to "see" the System.Drawing assembly in the program. I have added the needed reference, but still nothing.

# Answer
You can't use a Textbox control in XNA, as XNA doesn't support drawing Windows Forms. You will need to write your own Textbox control in XNA, or use one of the freely available XNA control libraries that people have made available online.
> 1 votes

---
Tags: xna-4.0, windows, control
---


title: Using Threads to create GameObjects

text:
# Question
Title: Using Threads to create GameObjects
I have this game client which connects to the server and sends requests and getting responses.

I have created a separate thread for listening to the server. Based on the response from the server, I want make GameObjects.

But the problem is, the server response is taken into my game using a separate thread. And as far as I know, we cannot create game objects in unity in any other thread than Main Thread.

How to create game objects based on the server response?

I am new to c# and unity. Sorry if this is a silly question. I did some research on the topic and I couldn't find and answer. There were posts saying to use coroutines; but I can't quite understand them.

# Answer
> 6 votes
One of the options is using the Dispatcher pattern. The idea of this pattern is to create an object for each thread you want to invoke on(main thread in your case) which maintains list of delegates that is being polled and executed(e.g. in `Update` method). Since there is no implementation in Unity I am aware of, you either need to find Dispatcher implementation for Unity or implement it by yourself.

A very minimalist example

```
public class Dispatcher : MonoBehaviour
{
   protected Queue<Action> _pending = new Queue<Action>();

   void Update()
   {
      lock(_pending)
      {
         while(_pending.Count != 0) _pending.Dequeue().Invoke();
      }
   }

   public void Invoke(Action a)
   {
      lock (_pending) {_pending.Enqueue(a);}
   }
}

//spawning enemies from a new thread
public class Spawn: MonoBehaviour
{
    private Dispatcher _dispatcher;//init in Start() or editor

    void asyncSpawn()
    {
       for (int i = 0; i < _targetEnemyCount; i++)
       {
          Thread.Sleep(1000);
          _dispatcher.Invoke( () => spawnEnemy());
       }
    }

   void Start()
   {
      new Thread(() => asyncSpawn()).Start();
   }
}

```

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


title: Stuck space invaders

text:
# Question
Title: Stuck space invaders
I have the following space invaders code which is working pretty well.

On invader creation:

```
//initialise invader counters
step_counter=100;
move_counter=0;
left=true;
move_speed=1;
speed_counter=0;

```

And on invader step:

```
if step_counter > 0 {
   step_counter -= move_speed;
   // Move every fifty steps
   if step_counter % 50 == 0 {
        if left == true {
            x += 15;
            move_counter++;
            // At right of screen, drop and change direction; speed up
            if move_counter == 4 {
                left = false;
                y += 15;
                speed_counter++
                if speed_counter == 5 {
                    move_speed += 1;
                    speed_counter = 0;
                }
            }
        }
        else {
            x -= 15;
            move_counter--;
            // At left of screen, drop and change direction; speed up
            if move_counter == -4 {
                left = true;
                y += 15;
                speed_counter++
                if speed_counter == 5 {
                    move_speed += 1;
                    speed_counter = 0;
                }
            }
        }
    }
}
else {
    // reset counter over 100 steps
    step_counter = 100;
}

```

This is working really nicely, and gives a feeling very close to the original arcade game. However, for some reason the invaders get stuck two thirds of the way down the screen and refuse to go any further.

And ideas why?

# Answer
For anyone who might be interested, this is the solution I've implemented and am 95% happy with:

Invader oncreation script:

```
//initialise invader step counter
step_counter=100;
move_counter=0;
left=true;
speed_counter=100;

```

Invader onstep script:

```
if step_counter > 0 {
   step_counter -= 1;
   // Only move when step gets to 10
   if step_counter == 10 {
        if left == true {
            x += 15;
            move_counter++;
            // Increase speed over 12 (if statement prevents invaders getting stuck bug)
            if speed_counter > 12 {
                speed_counter -= 2;
            }
            // At right of screen, drop and change direction
            if move_counter == 4 {
                left = false;
                y += 15;
            }
        }
        else {
            x -= 15;
            move_counter--;
            // Increase speed if over counter over 12 (if statement prevents invaders getting stuck bug)
            if speed_counter > 12 {
                speed_counter -= 2;
            }
            // At left of screen, drop and change direction
            if move_counter == -4 {
                left = true;
                y += 15;
            }
        }
    }
}
else {
    // reset counter over *speed_counter* steps
    step_counter = speed_counter;
}

```

The other answer was helpful me in working this out!
> 2 votes

# Answer
I'm trying to run the code through in my head, so my apologies here.

Could it possibly be that roughly 2/3 of the way down the screen, that the move\_speed happens such that you can't get to a step\_counter that's a multiple of 50 anymore?

Your loop starts by decrementing step\_counter by move\_speed. For example, if step\_counter starts at 100 and move\_speed is 3, it'll go to 97 in the first iteration of the loop. As the loop progresses, step\_counter will get to 52 and 49, but never 50. You'll never move, because the step\_counter will never be a multiple of 50 (it's never 100 when the check is made, and it can never get to precisely 50).

You might try outputting step\_counter and/or move\_speed to a log file to check.
> 3 votes

---
Tags: movement, game-maker, arcade
---


# Question
Title: Use an image as mask only where pixels are opaque
We are into a game where to build our tile map, we carve on an image with a mask (At first the whole map is an image, and we create holes on it with tiles to create the map and le the background show. It is like substracting instead of adding new tiles in any common tiled based game).

We have done this with just a tile that acts as a mask using stencil buffer. The problem comes when we want to mask with tiles where all their pixels are not opaque, for example a slope. The problem is that it applies the mask as if all the pixels in tile where opaque and we want to apply the mask in two differnet ways:

1) Keep the pixels of the big image where the mask pixels are opaque

2) Mask the pixels of the big image where the mask pixels are transparent (alpha==0)

I have read a lot of info about using stencil and alpha blending but can't make it work. Checking the pipeline order it seems that stencil is applied after the fragment color has been calculated. Is it possible to access the alpha value at stencil stage and write to the stencil as needed to just mask part of the image (tile in my case).

Update to add a visual example:

# Answer
> 1 votes
Well, I finally fixed this using a discard for the pixels I don't want to be tested by stencil. It is working but discard operations are not the most performant :). Depending on the user case it could be a solution. It is in mine.

Cheers.

---
Tags: unity, alpha-blending, stencil
---


title: Check if SDL Window is open

text:
# Question
Title: Check if SDL Window is open
I need to check if the game's SDL Window is open before I can start rendering graphics, normally I would know how to this, but the problem is the window is created in the main class, and I need to check if the window is open in the menu class. How do I check if the window is open in an entirely different class?

# Answer
You dont specify if you are using SDL 1.2, or SDL 2. I will explain it with SDL 1.2.

When yo do a

```
SDL_Surface* = SDL_SetVideoMode(Params...);

```

to create the window, you set the pointer of the window created in your SDL\_Surface\* SDL variable.

The function has two returns.

If has been executed successfully, it will return the pointer of the window. If has NOT been executed successfully, it will return 'NULL';

So, yo need to check if the windows was created checking that pointer. I will copy a segment of my code in SDL:

```
    Window = SDL_SetVideoMode(WindowWidth, WindowHeigth,Bpp, SDL_HWSURFACE | SDL_RESIZABLE);    /// Asigno al Window el puntero asignado de la pantalla creada

    if( Window == NULL )    /// Window inicializado con error
    {
        if(Is_Open) { Log("Inicialize Window error"); } if(Is_Open) { Log(SDL_GetError()); }
        if(Is_Open) { Log("Window", Window); }
        SDL_Quit();
        exit(-1);
    }

```

Try to read the documentation for each function. Its not hard. Docs for SDL 1.2: https://www.libsdl.org/release/SDL-1.2.15/docs/ for SDL 2: https://wiki.libsdl.org/

And if you are using different functions you have 2 choices, make the variable of the window Global, or, passing by parameter to all your functions.

PD: Sorry for my english!
> 2 votes

---
Tags: c++, graphics, sdl
---


# Question
Title: HTML5 realtime MMO games, should I do server side physics update or client side?
I am using socket.io and HTML 5 canvas to build a MMO game as a practice. I finished the client side first and currently I am working on server side. Apparently the position/physics update is on client side for now. But I am facing the decision of moving the position update logic and physics update to the server or leaving them on the client side. If I put the update on the server side I will pass the mousemove/keystrokes to the server. But if I update positions only on clients side I will pass the positinos/directions/speed to the server. Which approach is better in my case?

# Answer
Unless you want players to be able to teleport through walls using their browsers build-in JavaScript debugger, you will have to implement any game mechanics worth manipulating on the server.

This will lead to more noticeable lag, so you might implement it both on the client and the server. That way the client can perform the action locally so the player gets an immediate response to their input, but revert that action when the server says it failed.
> 4 votes

---
Tags: html5, mmo, websocket, realtime
---


# Question
Title: Image Does Not Animate and is Stuck in one Frame
I'm having a problem in my code where the animation from another class does not animate and is stuck in one frame. The image moves across the screen in the right manner though. I know that the problem is somehow related to the UPDATE method of the animation. I have tried every possible solutions in my knowledge to find what causes the error and the solutions I found online were not quite helpful. Any help will be appreciated.

Here's my Code:

LevelOneScreen.java

```
public class LevelOneScreen implements Screen {

    private final MyGame app;
    WalkAnimate walkAnimate;
    private Stage stage;
    private Image levelOneImage;
    private Image holdStartImage;
    public Image walkRightImage;
    public Image walkLeftImage;
    public float deltaTime = Gdx.graphics.getDeltaTime();

    public LevelOneScreen(final ThumbChase app){
        this.app = app;
        this.stage = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));

    }
    @Override
    public void show() {

        Gdx.input.setInputProcessor(stage);
        walkAnimate = new WalkAnimate();
        walkAnimate.update(deltaTime);

        levelOneBackground();
        holdStart();
        ninjaWalk();

    }

    public void holdStart(){
        Texture holdStartTexture = new Texture("HoldStart.png");
        holdStartImage = new Image(holdStartTexture);
        float holdStartImageW = holdStartImage.getWidth();
        float holdStartImageH = holdStartImage.getHeight();
        float holdStartImgWidth = app.screenWidth*0.8f;
        float holdStartImgHeight = holdStartImgWidth *(holdStartImageH/holdStartImageW);
        holdStartImage.isTouchable();
        holdStartImage.setSize(holdStartImgWidth,holdStartImgHeight);
        holdStartImage.setPosition(stage.getWidth()/2-holdStartImgWidth/2,stage.getHeight()/2-holdStartImgHeight/2);
        stage.addActor(holdStartImage);
        holdStartImage.addListener(new ActorGestureListener(){
           /* public void touchDown (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };*/
           public void fling(InputEvent event, float velocityX, float velocityY, int button)  {
               holdStartImage.setVisible(false);
           }
            public void touchDown (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };
            public void touchDrag (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };

        });

        }

    public void levelOneBackground(){
        Texture levelOneTexture = new Texture("BGBlue Resize.png");
        levelOneImage = new Image(levelOneTexture);
        levelOneImage.setSize(app.screenWidth,app.screenHeight);
        levelOneImage.setPosition(0,0);
        stage.addActor(levelOneImage);
        /*levelOneImage.addListener(new ActorGestureListener(){
            public void touchDown (InputEvent event, float x, float y, int pointer, int button){
                holdStartImage.setVisible(false);
            };
        });*/
    }
    public void ninjaWalk(){
        TextureRegion ninjaWalkRight = new TextureRegion(walkAnimate.getCurrentFrameRight());
        TextureRegion ninjaWalkLeft = new TextureRegion(walkAnimate.getCurrentFrameLeft());
        //Texture ninjaWalkRight = new Texture("badlogic.jpg");
        //Texture ninjaWalkLeft = new Texture("badlogic.jpg");
        walkRightImage = new Image(ninjaWalkRight);
        walkLeftImage = new Image(ninjaWalkLeft);
        float walkImageW = walkRightImage.getWidth();
        float walkImageH = walkRightImage.getHeight();
        float walkImageWidth = app.screenWidth*0.25f;
        float walkImageHeight = walkImageWidth*(walkImageH/walkImageW);
        walkRightImage.isTouchable();
        walkLeftImage.isTouchable();
        walkRightImage.setSize(walkImageWidth,walkImageHeight);
        walkLeftImage.setSize(walkImageWidth,walkImageHeight);
        walkRightImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
        walkLeftImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
        walkRightImage.addAction(moveBy(app.screenWidth*0.2f,0,1f));
        stage.addActor(walkRightImage);
        walkRightImage.addListener(new ActorGestureListener(){
            public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
                holdStartImage.setVisible(true);
            }
        });

    }

    @Override
    public void render(float delta) {

        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        //walkAnimate.update(deltaTime);
        update(delta);
    }

    public void update(float deltaTime){
        stage.act(deltaTime);

        stage.draw();
        app.batch.begin();

        app.batch.end();
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();

    }
}

```

WalkAnimate.java

```
public class WalkAnimate {

        public MyGame app;
        public Stage stage;

        private Animation walkAnimationRight;
        private Animation walkAnimationLeft;
        private Texture walkSheetRight;
        private Texture walkSheetLeft;
        private TextureRegion[] walkFramesRight;
        private TextureRegion[] walkFramesLeft;
        private TextureRegion   currentFrameRight;
        private TextureRegion   currentFrameLeft;
        private float stateTime;
        private Rectangle bound; //used for positioning and collision detection
        private static final int  FRAME_COLS_WALK = 3;
        private static final int  FRAME_ROWS_WALK= 2;
        private float screenWidth = Gdx.graphics.getWidth();
        private float screenHeight = Gdx.graphics.getHeight();
        public float currentFrameWidth = (float)(screenHeight*0.15);
        public float currentFrameHeight = (float)(screenHeight*0.15);
        public float walkSheetWidth;
        public float walkSheetHeight;

        public WalkAnimate () {

            walkSheetRight = new Texture("ninjaWalkRight.png");
            walkSheetWidth = walkSheetRight.getWidth();
            walkSheetHeight = walkSheetRight.getWidth();
            TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
            walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
            int index = 0 ;
            for (int i = 0; i < FRAME_ROWS_WALK; i++) {
                for (int j = 0; j < FRAME_COLS_WALK; j++) {
                    walkFramesRight[index++] = tmp[i][j];
                }
            }
            walkAnimationRight = new Animation(0.044f, walkFramesRight);
            stateTime = 0f;

            walkSheetLeft = new Texture("ninjaWalkLeft.png");
            walkSheetWidth = walkSheetLeft.getWidth();
            walkSheetHeight = walkSheetLeft.getWidth();
            TextureRegion[][] tmp1 = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int)walkSheetLeft.getHeight() / FRAME_ROWS_WALK);
            walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
            int index1 = 0;
            for (int i = 0; i < FRAME_ROWS_WALK; i++) {
                for (int j = 0; j < FRAME_COLS_WALK; j++) {
                    walkFramesLeft[index1++] = tmp1 [i][j];
                }
            }
            walkAnimationLeft = new Animation(0.044f, walkFramesLeft);
            stateTime = 0f;

            currentFrameRight = walkAnimationRight.getKeyFrame(stateTime, true);
            currentFrameLeft = walkAnimationLeft.getKeyFrame(stateTime, true);

        }

        public Rectangle getBound(){
            return bound;
        }

        public void update(float delta){
            stateTime += delta;

        }

        public TextureRegion getCurrentFrameRight(){
            return currentFrameRight;

        }
        public TextureRegion getCurrentFrameLeft(){
            return currentFrameLeft;
        }
    }

```

# Answer
> 1 votes
I wrote a `Ninja` class for you. You can test it cause I don't have GDX on this PC here:

```
public class Ninja extends Actor {

    private Animation wLeftAnimation, wRightAnimation;
    private static final int  FRAME_COLS_WALK = 3;
    private static final int  FRAME_ROWS_WALK= 2;
    private float stateTime = 0f;

    public enum Direction{
        LEFT,
        RIGHT;
    }

    private Direction currentDirection = Direction.RIGHT;

    public Ninja(){
        Texture walkSheetRight = new Texture("ninjaWalkRight.png");
        Texture walkSheetLeft = new Texture("ninjaWalkLeft.png");

        TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
        TextureRegion[] walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        int index = 0 ;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                walkFramesRight[index++] = tmp[i][j];
            }
        }

        tmp = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
        TextureRegion[] walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
        index = 0;
        for (int i = 0; i < FRAME_ROWS_WALK; i++) {
            for (int j = 0; j < FRAME_COLS_WALK; j++) {
                walkFramesLeft[index++] = tmp[i][j];
            }
        }

        wLeftAnimation = new Animation(0.044f,walkFramesLeft);
        wRightAnimation = new Animation(0.044f,walkFramesRight);

        setSize(wLeftAnimation.getKeyFrame(0f).getRegionWidth(), wLeftAnimation.getKeyFrame(0f).getRegionHeight());
        setPosition(0,0);
    }

    public void walkLeft(){
        currentDirection = Direction.LEFT;
        clearActions();
        addAction(Actions.moveBy(-5,0));
    }

    public void moveRight(){
        currentDirection = Direction.RIGHT;
        clearActions();
        addAction(Actions.moveBy(5,0));
    }

    @Override
    public void draw(Batch batch, float parentAlpha) {
        super.draw(batch, parentAlpha);

        final float delta = Gdx.graphics.getDeltaTime();
        this.act(delta);

        stateTime += delta;

        TextureRegion currentFrame;
        switch (currentDirection){
            case LEFT:
                currentFrame = wLeftAnimation.getKeyFrame(stateTime, true);
                break;
            case RIGHT:
                currentFrame = wLeftAnimation.getKeyFrame(stateTime, true);
                break;
            default:
                // if you add more states
                currentFrame = wLeftAnimation.getKeyFrame(stateTime, true);
                break;
        }

        batch.begin();
        batch.draw(currentFrame, getX(),getY(),getWidth(),getHeight());
        batch.end();

    }
}

```

Now in your screen you can create a Ninja:

`Ninja ninja;`

in Screen constructor/onCreate() call:

`ninja = new Ninja();`

add it to the stage:

`stage.add(ninja);`

in your `update()` in `Screen` update and draw your stage like this:

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    if(Gdx.input.isKeyPressed(Input.Keys.LEFT))
            ninja.walkLeft();

    if(Gdx.input.isKeyPressed(Input.Keys.RIGHT))
            ninja.walkRight();

    update(delta);
}

public void update(float deltaTime){
    stage.act(deltaTime);
    stage.draw(); // this will draw the ninja cause he's on the stage!
}

```

And you can do some magic with his `moveRight()` and `moveLeft()` methods that I wrote. Check if they work and remove the whole `WalkAnimate` class! Post the errors, cause as I said, I wrote this in a notepad.

**Tip**: Use left and right on keyboard to walk ;)

# Answer
> 1 votes
In `LevelOneScreen`, make your `update` method call `update` on `WalkAnimate`:

```
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    walkAnimate.update(deltaTime);

    update(delta);
}

```

Then, in `WalkAnimate`, make sure you select the correct keyframe in the `update` method:

```
public void update(float delta){
    stateTime += delta;
    currentFrameRight = walkAnimationRight.getKeyFrame(stateTime, true);
    currentFrameLeft = walkAnimationLeft.getKeyFrame(stateTime, true);
}

```

---
Tags: android, libgdx, animation, scene2d, android-studio
---


# Question
Title: draw two models changing the MVP matrix (android opengl)
I'm newbie with opengl2 in android, and I'm making an app in which I'm testing some things. Now I was trying to duplicate a sphere object with a texture, so I thought it was enough to change my MVP matrix applying a small translation to the Model matrix, using same View Matrix and same projection matrix.

```
int[] numIndices = balon.getNumIndices();
ShortBuffer[] indices = balon.getIndices();

GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);
for (int j = 0; j < numIndices.length; j++) {
    GLES20.glDrawElements(GLES20.GL_TRIANGLES,
            numIndices[j], GLES20.GL_UNSIGNED_SHORT,
            indices[j]);
}

GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix2, 0);
for (int j = 0; j < numIndices.length; j++) {
    GLES20.glDrawElements(GLES20.GL_TRIANGLES,
            numIndices[j], GLES20.GL_UNSIGNED_SHORT,
            indices[j]);
}

```

balon is an object of type Sphere. mMVPMatrix and mMVPMatrix2 are the MVP matrices I was talking about. I simply changed the MVP matrix and did the drawing again. The result is that I have the two spheres, but one of them is behaving strangely, appears distorted, the position in which appears is right, the two spheres move along, but one of them changes it's shape.

What I'm missing?, I guess I have to duplicate some things in my code before I do this, but what?, thought that being the same model, this was enough...

This is how I changed the MVP matrix:

```
Matrix.setIdentityM(mModelMatrix, 0);
Matrix.setIdentityM(mModelMatrix2, 0);
Matrix.translateM(mModelMatrix, 0, posX, posY, posZ);
Matrix.translateM(mModelMatrix2, 0, posX+0.5f, posY+0.5f, posZ);

Matrix.multiplyMM(mMVPMatrix, 0, mViewMatrix, 0, mModelMatrix, 0);
Matrix.multiplyMM(mMVPMatrix2, 0, mViewMatrix, 0, mModelMatrix2, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mMVPMatrix, 0);
Matrix.multiplyMM(mMVPMatrix2, 0, mProjectionMatrix, 0, mMVPMatrix2, 0);

```

# Answer
> 1 votes
There probably nothing wrong with your transforms. Your use of `glDrawElements` is definitely wrong. This code draws the model *`numIndices`* times with the wrong arguments passed to `count` and `indices`:

> ### `glDrawElements`
>
> `glDrawElements` — render primitives from array data
>
> ### C Specification
>
> ```
> void glDrawElements(GLenum mode,
>               GLsizei count,
>               GLenum type,
>               const GLvoid * indices);
>
> ```
>
> ### Parameters
>
> `count` Specifies the number of elements to be rendered.
>
> ...
>
> `indices` Specifies a pointer to the location where the indices are stored.

So you may want to call it like:

```
int[] numIndices = balon.getNumIndices();
ShortBuffer[] indices = balon.getIndices();

GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
                      indices.length,
                      GLES20.GL_UNSIGNED_SHORT,
                      null);

GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mMVPMatrix2, 0);
GLES20.glDrawElements(GLES20.GL_TRIANGLES,
                      indices.length,
                      GLES20.GL_UNSIGNED_SHORT,
                      null);

```

# Answer
> -1 votes
I don't know why, but cloning mModelMatrix2 into mTempMatrix2 and using that as the operand in Matrix.multiplyMM instead of directly using mModelMatrix2, solved the problem

```
    float[] mTempMatrix2 = mModelMatrix2.clone();
    Matrix.multiplyMM(mModelMatrix2, 0, mTempMatrix2, 0, mRotationMatrix, 0);

```

---
Tags: opengl, android
---


# Question
Title: Determine "bounding box size" (not scale) of model in MonoGame
I'm working on integrating some the 3D models I import into my physics system by trying to take their "size" and use that as the side for objects within my physics system. When I say size, I'm referring essentially to a bounding box size around my model. Here's an example of a test level layout I'm designing:

All of the cubes below are 1x1 units in Blender (measuring from the center), so I've been able to just code in those assumptions. However, it starts to get more interesting when you consider the slope and smaller platform I have.

For the slopes, I've found an easy hack for the time being (as long as their size remains 1x1). However, the platforms are throwing me off. A few things to call out with the platform model:

* The model itself is centered at (0,0,0) and no scaling was done on the model itself in **Object Mode**
* I scaled down the Z of the model in **Edit Mode**, while the model itself remains at (1,1,1) scaling

I'm now trying to figure out how to get some form of size for the model. For what I'm looking for, if we assume the cubes I have are bounds box size of (1,1,1), then this platform would be a bounding box size of (1, 1, .25). I would assume that I would need to look at the model's meshes to determine this, but I'm not entirely sure

Any help on this would be appreciated. Thanks!

# Answer
After doing some more digging for a few hours, I found an old solution from XNA that still works in MonoGame: "How do I create a bounding boxes with XNA 4.0?

I've tweaked the solution above to simply get me the min and max points WITHOUT using the world transform (as I don't care where it's positioned, just the default size). This is set up as a class function for my Model wrapper class, but can obviously be tweaked to take a Model as a parameter:

```
    public BoundingBox GetBounds()
    {
        Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
        Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

        foreach (ModelMesh mesh in this.Model.Meshes)
        {
            foreach (ModelMeshPart meshPart in mesh.MeshParts)
            {
                int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride;
                int vertexBufferSize = meshPart.NumVertices * vertexStride;

                int vertexDataSize = vertexBufferSize / sizeof(float);
                float[] vertexData = new float[vertexDataSize];
                meshPart.VertexBuffer.GetData<float>(vertexData);

                for (int i = 0; i < vertexDataSize; i += vertexStride / sizeof(float))
                {
                    Vector3 vertex = new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]);
                    min = Vector3.Min(min, vertex);
                    max = Vector3.Max(max, vertex);
                }
            }
        }

        return new BoundingBox(min, max);
    }

```
> 1 votes

---
Tags: 3d, monogame, models, 3d-meshes, mesh
---


# Question
Title: Is it possible to make a pseudo isometric game with phaser?
If I use the isometric plugin for Phaser, I end up with something like the third case of the following picture:

I would like to create a world in pseudo isometric, with only one axis tilted. This would be the second case in the picture.

Is it possible to achieve that with Phaser? With or without the Isometric plugin? If Phaser can't handle it, is there an open-source/free alternative for this kind of setup?

# Answer
> 3 votes
Phaser handles this out of the box using sorting based on the y index. I have used this exact technique too to create stacked sprites so the elements at the bottom of the screen are drawn over the ones above.

https://phaser.io/examples/v2/groups/depth-sort

The trick used in Phaser is to sort the z index based on the y index so the characters sprite is drawn at the correct depth.

---
Tags: phaser
---


title: Card Masking in Phaser

text:
# Question
Title: Card Masking in Phaser
Good Day, I'm new to Phaser and still learning about it to. I am challenging my self to create a simple animation of a card flip somewhat realistic rather that making use of a scale.

This is something that I already started, But having trouble to attain what i need.

See this link http://sopronioli713.github.io/card\_masking.

Here is my source code

```
<html>
<head>
    <title>Card Masking Flipping Card</title>
</head>
    <div class="canvas"></div>
<body>

    <script type="text/javascript" src="jquery-2.1.3.min.js"></script>

    <script type="text/javascript" src="phaser.js"></script>

    <script type="text/javascript">

        $(document).ready(function(){

            var game = new Phaser.Game(1024, 768, Phaser.AUTO, 'canvas', {
                init : init,
                preload : preload,
                create : create,
                update : update
            });

            function init() {

            };

            function preload() {
                game.load.image('back', '--.png');
                game.load.image('front', 'XRC.png');
                game.load.image('de', 'de.jpg');
            };

            function create() {

                game.add.sprite(550, 100, 'de');

                var cardfront = game.add.sprite(400, 250, 'front');
                    cardfront.anchor.setTo(0.5,0.5);

                var cardback = game.add.sprite(150, 250, 'back');
                    cardback.anchor.setTo(0.5,0.5);

                var tlx = cardback.x - (cardback.width / 2);
                var tly = cardback.y - (cardback.height / 2);
                var blx = tlx;
                var bly = cardback.y + (cardback.height / 2);
                var rtx = cardback.x + ((cardback.width / 2));
                var rty = tly;
                var rbx = cardback.x + (cardback.width / 2);
                var rby = bly;

                var mask = game.add.graphics(tlx, tly);

                    mask.beginFill(0xFF3300);

                    mask.lineStyle(2, 0xffd900, 1);
                    // draw a shape
                    mask.lineTo(0, cardback.height - 100);

                    mask.lineTo(100, cardback.height);

                    mask.lineTo(cardback.width, cardback.height);

                    mask.lineTo(cardback.width, 0);

                    mask.endFill();

                    cardback.mask = mask;

                // mask for front card
                var draw_front = game.add.graphics(tlx, tly + (cardback.height - 100));
                    draw_front.beginFill(0xFF3300);
                    draw_front.lineStyle(2, 0xffd900, 1);
                    draw_front.lineTo(100, 0);
                    draw_front.lineTo(100, 100);
                    draw_front.endFill();

                var txt = game.add.text(5,0, 'What i want to attain is that \n i want to draw portion of the front card \n to the orange area', {
                    font: "24px arial",
                    fill: "#FFF",
                    align:'right',
                    fontWeight:'bold',
                    anchor: '0.5,0.5'
                });

                var txt = game.add.text(600,50, 'Output that i want to attain', {
                    font: "24px arial",
                    fill: "#FFF",
                    align:'right',
                    fontWeight:'bold',
                    anchor: '0.5,0.5'
                });

            };

            function update() {

            };
        });
    </script>

</body>

</html>

```

# Answer
It looks like you can do this using alpha masking with the bitmapdata type

https://phaser.io/examples/v2/sprites/mask

```
    //  Here we add a Sprite to the display list
sprite = game.add.sprite(0, 0, 'chaos');
sprite.scale.set(2);

//  A mask is a Graphics object
mask = game.add.graphics(0, 0);

//  Shapes drawn to the Graphics object must be filled.
mask.beginFill(0xffffff);

//  Here we'll draw a circle
mask.drawCircle(100, 100, 100);

//  And apply it to the Sprite
sprite.mask = mask;

```

In their example they draw dynamically so it's entirely possible to have the full card reveal be driven by this technique. Good luck!
> 1 votes

---
Tags: rendering, html5, html-canvas, card-game, phaser
---


title: Sync bullets node.js phaser.io

text:
# Question
Title: Sync bullets node.js phaser.io
i am currently having a struggle thinking about syncing bullets. I am using node js and phaser.io and I am creating top-down shooter.

1. I would do it like this: Player shoots a bullet. Player sends information where that bullet is Player2 gets information and updates their bullet.

But the problem is, when client window is out of focus. Physics are paused and so are bullet movement, which is horrible for multiplayer game.

How can I achieve synced bullet across two or more clients .

I tried searching for information about server sided physics for node, but I really couldn't find any.

Thanks

# Answer
You need to go with a Server style architecture. By that I mean that all clients connect to a single instance, which would be hosted on the computer of the person that creates the server. Essentially, the clients don't keep track of the entities, that's the server's job. The players ping the server, and update their client with the information it provides. Think of it more like a nexus, where all players talk and communicate with each other through a single hub.
> 1 votes

# Answer
I'm not sure what you want to achieve. You could avoid pausing the game when it is out of focus:

```
game.stage.disableVisibilityChange = true;

```

or given the latest position of the bullets just update them when the game is unpaused. In this case is possible that the bullets have hit something/someone and no longer exists, but the general idea is to update the client with the latest status given by the server.
> 0 votes

---
Tags: javascript, phaser
---


# Question
Title: Rotating camera based on player's rotation
I'm trying to have a camera rotate mirror the player's rotation, however, this isn't happening and the camera isn't rotating at all. Can anyone explain what I'm doing wrong and how to fix it?

```
public class PlayerActions:MonoBehaviour{
    Camera mainCamera;
    public Rigidbody player;
    public GameObject playerShot;
    public Transform shotSpawn;
    public Boundary boundary;

    public int speed;
    public int tilt;
    public int bank;
    public float fireRate;
    private float shotDelay;

    void Start(){
        mainCamera = Camera.main;
        player.GetComponent<Rigidbody>();
    }

    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(moveHorizontal, moveVertical, 0f);
        player.velocity = move * speed;
        player.position = new Vector3(Mathf.Clamp(player.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp(player.position.y, boundary.yMin, boundary.yMax), 0f);
        transform.rotation = Quaternion.Euler(0f, 0f, player.velocity.x * -bank);
    }

    void Update(){
        if(Input.GetKey("space") && Time.time > shotDelay){
            shotDelay = Time.time + fireRate;
            Instantiate(playerShot, shotSpawn.position, shotSpawn.rotation);
        }
    }
}

```

As it's working now, the player is rotating, but the camera isn't.

If you notice in the video linked below, the ship is rotating, but if you look at the static asteroid, you'll notice that the camera isn't. Not Rotating Game View Not Rotating Editor View

**Heirarchy**

**Inspector**

# Answer
> 2 votes
I think the problem here is that you're applying the rotation to the RigidBody of the player, and not to the GameObject transform. It also looks like you're modifying the velocity *and* position of the RigidBody, which may lead to unexpected results (e.g. the physics engine will be trying to reconcile the new velocity with the new position)

To answer your main question though, I think that simply applying your calculation to the GameObject and not the RigidBody should solve your issue, like so:

```
public class PlayerActions : MonoBehaviour{
    // ...
    void FixedUpdate(){
        float moveHorizontal = Input.GetAxis("Horizontal");
        float moveVertical = Input.GetAxis("Vertical");

        Vector3 move = new Vector3(moveHorizontal, moveVertical, 0f);
        player.velocity = move * speed;
        player.position = new Vector3(Mathf.Clamp(player.position.x, boundary.xMin, boundary.xMax), Mathf.Clamp(player.position.y, boundary.yMin, boundary.yMax), 0f);
        // Apply rotation to the GameObject
        transform.rotation = Quaternion.Euler(0f, 0f, player.velocity.x * -bank);
    }

    void Update(){
        if(Input.GetKey("space") && Time.time > shotDelay){
            shotDelay = Time.time + fireRate;
            Instantiate(playerShot, shotSpawn.position, shotSpawn.rotation);
        }
    }
}

```

Notice that there should now be no need to change the camera rotation, as Unity should deal with this for you

# Answer
> 1 votes
1. "mainCamera" is accessing the Gameobject with the Tag "MainCamera".

To see if its the right camera use: Debug.Log(mainCamera);

2. As far as I understood you want the Camera to move always behind the player (like 3rd person) or inside the player (like in a FPS)

if you want that:

You can either Parent the Camera to the Player. (So the Player Gameobject has a child Gameobject: "Camera")

Or you can Calculate the current position of the Camera. Calculating a Parent/Child relationsship is for pretty advanced users though.

EDIT: 3. As far as I can see, you already parented already a camera to another GameObject ( I assume its the player)

Try using not the rigidbody.rotation but "transform.rotation"

be warned: It should already work if the camera is parented. are you sure you are not modifying the camera position/rotation somewhere else?

# Answer
> -1 votes
Just write mainCamera.forwar = player.forward in your FixedUpdate that will make the camera face the back of the player.

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


# Question
Title: LibGDX - how to change FreeType Font color and screen coordinates
How can I change my `FreeType` Font color? I want to set custom color. I tried do this by using `Color color = new Color()` but don't work.

And second: can I change my screen coordinates? I use two different cameras. First camera for game and second for text. When I draw text in the (0,0) position, my text is in the center of the screen but I want to have (0,0) in the lower left corner. How do that?

# Answer
When you generate a font you get a `BitmapFont` object.

You can set it's color like this:

```
BitmapFont someFont = freeTypeGenerator.getFont(); // or something like that
someFont.setColor(Color.RED);

```

Also, it's better to change widgets colors, not fonts, for example if you have a Label with the font created above, you can change label's color:

```
label.setColor(Color.RED);

```

For coordinates read about viewports here: https://github.com/libgdx/libgdx/wiki/Viewports

**How to create a color?**

Colors in our world contain 4 values - R, G, B and A which means red, green, blue and alpha channel.

RGB are for colors and A is for transparency.

If you want your color to be *RED*, you set *RED* to 1, *BLUE* to 0 and *GREEN* to 0

If you want your color to be *HALF RED* and *HALF BLUE* you set *RED* to 0.5f, *BLUE* to 0.5f and *GREEN* to 0f.

If you look into the `LibGDX` source, Color constructor takes 4 parameters (R,G,B and A) and these values must be in range `0-1f`. It means that if you set your color to `new Color(0,0,0,1)` \- it will be a black color. If you set it to `new Color(1,1,1,1)` \- you'll get a white color. As you can see, maximum value for R, G, B and A is 1. So how to create Colors from RGB values like 77,55,133? You just divide it by `255f` and you'll get your R, G and B values.

Correct way:

```
Color color = new Color(255f/255f, 183f/255f, 77f/255f, 255f/255f);

```
> 1 votes

---
Tags: java, android, libgdx
---


# Question
Title: How do you increase the spacing on text within LibGDX labels
So I'm following along with some tutorials for creating an application with LibGDX, and when I go to print parts of the UI to the screen, the text is all bunched up. How do I increase the spacing, or is it due to something else I've done?

```
....
    game = gam;
    stage = new Stage(new StretchViewport(800, 400));
    Gdx.input.setInputProcessor(stage);
    uiSkin = new Skin(Gdx.files.internal("uiskin.json"), new TextureAtlas(Gdx.files.internal("uiskin.atlas")));
    Label nameLabel = new Label("Name:", uiSkin);
    TextField nameText = new TextField("", uiSkin);
    Label addressLabel = new Label("Address:", uiSkin);
    TextField addressText = new TextField("", uiSkin);

    table = new Table();
    table.add(nameLabel).expandX();
    table.add(nameText).width(200);
    table.row();
    table.add(addressLabel);
    table.add(addressText).width(200);
    table.setFillParent(true);
    stage.addActor(table);
    table.setDebug(true);

```

# Answer
Okay, feeling silly now. It was due to the fact that I set such an odd aspect ratio when I initialised my Stage. I passed in half the width and height of the phone screen instead, and it comes up a lot neater.
> 1 votes

# Answer
For later questions, to answer them directly - there are parameters in fonts that are responsible for line height and it's spacing in LibGDX.

You can find it in your `.fnt` file and `BitmapFontData`.

**.fnt file:**

**BitmapFontData**:
> 0 votes

---
Tags: android, libgdx
---


# Question
Title: How can I put my Java game in my Weebly Website?
I'm making a Java application (not applet), a game, which I want people to play through my weebly website because problems came for most of my friends PC's like the assets aren't appearing and the game is really slow.

**And what I want is to do is to put my Java game into my weebly website so my friends can play it without any problem.**

Should I make any changes to my program from Java application to an applet (please tell how because I don't know how), should I change Eclipse IDE which is the one I currently use to some other like NetBeans IDE? I'm not sure but I hope you all can help.

# Answer
> 2 votes
Looks like we need to clarify a few things :

1. Changing your IDE is pretty unlikely to change anything to your problem. An IDE is just a tool to help you work, once you have your final application it does not matter which IDE you used.
2. Making your game an applet is also very unlikely to improve your performance problems as well as missing assets. Imho it will be even worse. You make an applet when you want to make it easier to the user to access the game as they do not need to download it, that's all. You should know that since 2013 and Oracle's change of policy concerning JWS and Applets, it has become a pain in the \*** to deploy them.
3. If some of your friends do not see your assets, it is most likely due to something you did wrong. All you need to do is try to find what. Changing to Applets, or switching to javascript/C++/Python is not going to help.

---
Tags: java, web
---


# Question
Title: Difference between column- and row vector matrix multiplication (vector transform)
Let's say we have a 4-by-4 matrix \\$A\\$ which represents some transformation.

We can use this matrix to transform a vector in two ways.

* \\$Ax\\$ by assuming \\$x\\$ is a 4-by-1 column vector.
* \\$xA\\$ by assuming \\$x\\$ is a 1-by-4 row vector.

Up until yesterday, I have not seen this \\$xA\\$ variant and I thought it was unnecessary. Then I came across this DirectX code from Microsoft.

This function takes *just* the projection matrix, computes the inverse projection matrix and then does this \\$xA\\$ variant (not \\$Ax\\$) to transform (or unproject) a bunch of coordinates.

At first, I wasn't looking and did \\$Ax\\$ which came out nonsensical and now I'm trying to understand why.

I've noticed that \\$Ax = xA^T\\$ but when I look at the way the matrix multiplication is carried out. The components that make up the result are very different depending on whether I use \\$Ax\\$ or \\$xA\\$ (as it should be, matrix multiplication is not commutative).

The analytic solution for \\$Ax\\$ (3-by-3 matrix and row vector)

$$ \begin{pmatrix} x \\ y \\ z \end{pmatrix} \cdot \begin{bmatrix} a & b & c \\ d & e & f \\ g & h & i \end{bmatrix} = \begin{pmatrix} ax + dy + gz \\ bx + ey + hz \\ cx + fy + iz \end{pmatrix} $$

The analytic solution for \\$xA\\$ (3-by-3 matrix and column vector)

$$ \begin{bmatrix} a & b & c \\ d & e & f \\ g & h & i \end{bmatrix} \cdot \begin{pmatrix} x \\ y \\ z \end{pmatrix} = \begin{pmatrix} ax+by+cz \\ dx+ey+fz \\ gx+hy+iz \end{pmatrix} $$

I use Mathematica to test these things. On a hunch I tried the analyitic solution for \\$xA\\$ with the elements of \\$A\\$ transposed manually and of course, I get:

$$ \begin{bmatrix} a & d & g \\ b & e & h \\ c & f & i \end{bmatrix} \cdot \begin{pmatrix} x \\ y \\ z \end{pmatrix} = \begin{pmatrix} ax+by+cz \\ dx+ey+fz \\ gx+hy+iz \end{pmatrix} $$

Which is equivalent to \\$Ax\\$ except we now have a column vector not a row vector. I'm assuming all of this is purely conventional (and depends on whether I'm assuming row- or column-major matrix layout). It looks like I might have answered the question my self but if I'm wrong about anything here please correct me.

# Answer
I think the answer I was looking for was laid out in **@DmitryTolmachov**'s comment.

> Row-major vs column-major is the one of main differences between OpenGL and DirectX. It seems OpenGL uses column-major, while DirectX uses row-major. It's pure conventional, but it starts to matter in what order to perform matrix vs vector multiplication in shader. In GLSL shader if use OpenGL based math library you would use "Ax" convention, but if you use DirectX based math library for your OpenGL app, you would need to use "xA convention". Also this makes difference in what order you need to multiply your matrices.

We can turn row-major into column-major by transposing the matrix. In my particular case I have been using row-major for my 4-by-4 matrix. I then transpose these matrices when I send them to OpenGL (I use OpenGL).

Since I'm using a row-major convention for my matrix math library, transforming a vector must be implemented as `xA`. If I use a column-major convention I implement vector transform as `Ax`.

It doesn't matter which you use but you cannot mix them (that would be undefined behavior) and the end result must be compatible (with regards to their respective shader language) with the 3D API we're using, be it DirectX or OpenGL or something else.
> 2 votes

---
Tags: mathematics, directxmath
---


# Question
Title: Why is my A* object resetting to (0, 0, 0), instead of following its path?
I'm working on an RTS project, and I'd like to use the A\* Project by Aron Granberg to navigate around obstacles. The problem is that the correct path is displayed in the scene, the unit is still walking forwards, but the unit just jumps to (0, 0, 0). As is, this as a workaround to have some progress in my build script.

Why is my A\* object resetting to (0, 0, 0), instead of following its path?

---

I don't know where I made the mistake that leads to this behavior. Here is script responsible for the movement:

```
using UnityEngine;
using Pathfinding;
using RTS;

public class Unit : WorldObject
{
    public float moveSpeed;
    public Path path;
    public float nextWaypointDistance = 3;

    private int currentWaypoint = 0;

    protected override void Update()
    {
        Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;

        MakeMove(dir);

        if (Vector3.Distance(transform.position, path.vectorPath[currentWaypoint])
            < nextWaypointDistance)
        {
            currentWaypoint++;
            return;
        }
    }

    private void MakeMove(Vector3 dir)
    {
        transform.position
            = Vector3.MoveTowards(transform.position, dir, Time.deltaTime * moveSpeed);
    }
}

```

# Answer
Your problem is that your providing a normalised direction as the second parameter for `Vector3.MoveTowards()`, where the second parameter is *suppose* to be the target coordinates. As you have already found out, supplying *target* instead of *direction* fixes your problem.

---

Let's take a look at the API resource.

> # Vector3.MoveTowards
>
> public static Vector3 **MoveTowards**(Vector3 **current**, Vector3 **target**, float **maxDistanceDelta**);
> **...**
>
> ## Description
>
> Moves a point current in a straight line towards a target point.
> **The value returned by this function is a point `maxDistanceDelta` units closer to a target/ point along a line *between* `current` and `target`.**
> **...**
> <sub>\- Unity API: Vector3.MoveTowards</sub>
> 1 votes

# Answer
The problem was found:

Changing `Vector3 dir = (path.vectorPath[currentWaypoint] - transform.position).normalized;` to `Vector3 dir = path.vectorPath[currentWaypoint] worked.`

But I still have no clue, why.
> 0 votes

---
Tags: unity, c#, path-finding
---


# Question
Title: NullReferenceException in StartCoroutine method
Maybe it's a repeated subject in the community but other answers didn't solved my question...

I tried as the tutorial: http://answers.unity3d.com/questions/11021/how-can-i-send-and-receive-data-to-and-from-a-url.html and worked fine in start method but when I try:

```
public Class A
 {
 //    ...CODE...
 new B().JSONRequest(jsonString);
 }

public Class B
{

public void JSONRequest(string json) {
string url = URL.LOCAL.url;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
UTF8Encoding encoding = new System.Text.UTF8Encoding();
WWW request = new WWW(url, encoding.GetBytes(requisicaoJSON.ToCharArray()), HashtableToDictionary<string, string>(postHeader));
 print("Request: "+request);

StartCoroutine(WaitForRequest(request));
}

IEnumerator WaitForRequest(WWW www)
{
    yield return www;
        // check for errors
        if (www.error == null)
        {
            Debug.Log("WWW Ok!: " + www.data);
        } else {
            Debug.Log("WWW Error: "+ www.error);
        }
    }
}

```

It gives me in the StartRoutine line: *NullReferenceException UnityEngine.MonoBehaviour.StartCoroutine (IEnumerator routine) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineMonoBehaviourBindings.gen.cs:61*

Console prints *Request: UnityEngine.WWW* so it does not appear to be null. –

# Answer
> 6 votes
A bit of background on this:

StartCoroutine is a method provided by the MonoBehaviour base class.

MonoBehaviours are designed to be attached as components to GameObjects - Unity will warn you if you try to construct one with `new`, instead you should create them via `gameObject.AddComponent<MyMonoBehaviourType>()`

The GameObject is how the engine keeps track of MonoBehaviours from one frame to the next, so it's critical to methods designed to execute over multiple frames, ie. Coroutines. During `StartCoroutine()`, Unity will try to register the relationship between the coroutine and its parent GameObject (so that if the GameObject is destroyed/disabled, its coroutines can be stopped and not leaked). If it doesn't find a GameObject it will throw a null reference exception.

So, the fix is to ensure every MonoBehaviour is created as part of a GameObject - never construct them free-floating.

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


# Question
Title: How to code C# to allow one tap to cause the character to jump for Android device in 3d game
Is there a native unity 5 to implement one tap to have the character to jump.? My game is 3d and I want to tap anywhere once or in the character.

I found a MobileTiltController as part of the CrossPlataformInput but I don't see a jump option. My Character is a rolling ball. Can anybody show me the code to do this.? I've used different codes found in internet but they don't work. for example this link says to use the code below, but AddForce is not found.

```
if(Input.GetMouseButtonDown(0)) rigidbody.AddForce(Vector3.up*popForce,ForceMode.Force);

```

I don't know how to build the whole C# file. (update, start...)

Other codes are counting the number of taps but I don't know what to do after that.

# Answer
I was able to complete the whole file based on the code above. It is basic, but this works fine for now. Credit to Raja Biswas

```
using UnityEngine;
using System.Collections;

public class adr_balance : MonoBehaviour {

    GameObject player;
    Rigidbody rigidbody;
    float popForce=100f;

    void Start(){
        rigidbody = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        if(Input.GetMouseButtonDown(0))
            rigidbody.AddForce(Vector3.up*popForce,ForceMode.Force);

    }

}

```
> 0 votes

---
Tags: unity, android
---


# Question
Title: ERROR : Destroying assets is not permitted to avoid data loss
I want my gameObject named lvl\_01 to destroy when I click left or right arrow key but it's keep showing this error "Destroying assets is not permitted to avoid data loss" instead of destroying that gameObject, Can anybody please tell me what is going wrong around here.

```
using UnityEngine;
using System.Collections;

public class Level_01Text : MonoBehaviour {
public GameObject lvl_01;
// Use this for initialization
void Start () {
    Instantiate (lvl_01);
}

// Update is called once per frame
void Update () {
    if((Input.GetKey(KeyCode.RightArrow)) || (Input.GetKey(KeyCode.LeftArrow)))
    {
        Destroy (lvl_01);
        Debug.Log ("Something is seriously going wrong around here");
    }
}

}

```

# Answer
> 2 votes
You're trying to destroy the prefab, which Unity does not allow.

In `Start` function you instantiated the GameObject (a Prefab) which was assigned in inspector. Therefore, the instantiated GameObject "lvl\_01" contains reference to Original Prefab, destroying which will also destroy the Prefab.

What you should do is define an empty GameObject (let's call it `temp`) and give it the reference to your instantiated prefab and Destroy as required.

```
using UnityEngine;
using System.Collections;

public class Level_01Text : MonoBehaviour {
public GameObject lvl_01;
GameObject temp;

// Use this for initialization
void Start () {
    temp = Instantiate (lvl_01);
}

// Update is called once per frame
void Update () {
    if((Input.GetKey(KeyCode.RightArrow)) || (Input.GetKey(KeyCode.LeftArrow)))
    {
        Destroy (temp);
        Debug.Log ("Something is seriously going wrong around here");
    }
}

}

```

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


title: Setting up a singleton class in Unity

text:
# Question
Title: Setting up a singleton class in Unity
I have spent a long time (4-5 hours) digging around as to why my version of the Breakout Unity Tutorial was not working. There where repeated errors of

> NullReferenceException: Object reference not set to an instance of an object xxxxxxx

when running the game and calling Game Manager scripts from other scripts in the game.

After much reading up on vaguely useful questions and answers on here I know well enough what the error text means, but the answers on here that describe the error in detail do not reference how to solve this issue on an instance of a singleton.
Elsewhere I found a solution, and want to show this solution as I figure that can help a lot of other people searching for why this issue occurs:

Qualifier:
**There is an inconsistency with the Breakout Tutorial**

see the instantiation of the Game Manager class:

```
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GM : MonoBehaviour {

    public int lives = 3;
    public int bricks = 20;
    public float resetDelay = 1f;
    public Text livesText;
    public GameObject gameOver;
    public GameObject youWon;
    public GameObject bricksPrefab;
    public GameObject paddle;
    public GameObject deathParticles;

    /***
     * The below sets the Game Manager Class (GManager) as an instance so is a
     * static variable. This means its accessed via the class rather than via
     * an instance of the class.
     * This means Game Manager can be reached from other scripts with code
     * `GManager.instance.xxx = whatever`
     * So only one GManager instance will be running. This is a singleton pattern.
     ***/
    public static GM instance = null;

    private GameObject clonePaddle;

    // Use this for initialization
    void Awake ()
    {
        if (instance == null)
            instance = this;
        else if (instance != this)
            Destroy (gameObject);

        Setup();

    }

    public void Setup()
    {
       ...
    }

```

Please read my solution below:

# Answer
**November 2016** \- How to set up a singleton to avoid `NullReferenceError`s.

Solution working with Unity 5.4.2f2

As detailed by this very good post by Clear Cut Games, we need to check not only for if `instance = this` *but also* if `instance = null` and if so then destroy and regenerate the instance of the class.

So the above `Awake` code should be rewritten as:

```
void Awake () {
    /***
     * Enforce Singleton Pattern described above.
     ***/
    if(instance != this && instance != null)
    {
        Destroy(gameObject);
    }
    instance = this;
    Setup();

}

public void Setup()
{
   ....
}

```

It seems the tutorial made some assumptions about the instance value on awake and didn't check both values. This really confused me so to go over what changed:

If the instance is set (loaded) and is not **`this`** instance, then it is destroyed . This enforces singleton pattern.

If the instance is not `null` , so it is set, and yet is not **`this`** then the instance is destroyed.

After this, the instance becomes the current one defined as `this`.

---

There may well be variations on this rearrangement which work better for class calls that may have potentially more than one instantiation (unlike in this referenced tutorial), so please feel free to add a complete answer for other logics.

For that reason this is a community wiki :). Please improve my answer!!
> 0 votes

---
Tags: unity
---


# Question
Title: Converting an XNA game from WINDOWS to XBOX
I have an XNA game for WINDOWS which I want to work on XBOX also.

I've designed the game so that when I want to connect it to an XBOX, all I have to do is supply a different input class,

And I would do that by checking with the preprocessor macros and checking if it's windows or xbox.

But then, when I tried to do `Create a copy of this project for XBOX` in VisualStudio, it created several new projects (the real XNA project and some of it's dependencies), and it complained about things not working for `C# 3.0` and that I should use `C# 4.0` instead, which I didn't find out how to do either.

What's the correct way to make both WINDOWS and XBOX versions of an XNA game?

And also, how do I really run the game on XBOX? I haven't found a good tutorial on how I do that... also I don't have an XboxLive membership so if there's a hacky way to do that, it's better

# Answer
> -1 votes
If you've already supplied the input methods, then this code should work (change in Program.cs)

```
#if XBOX
static void Main (string[] args)
{
    using (Game1 game = new Game1())
    {
        game.Run();
    }
}
#endif

```

When you open a new project, the #if says WINDOWS || XBOX, but, if you just want an Xbox game, then change it to Xbox only.

---
Tags: xna, windows, xbox
---


# Question
Title: Storing wins and losses locally in Unity
I am writing here as I have made a game in Unity where I want to store how many wins/losses a player has. The way I am thinking to do it is by putting 2 counters; One for every time a player wins, and one for every time a player loses. What I do when a player wins or loses is that he can shoot something and restart the game; I load scene 0 here. I know that the counters will reset once the player closes the application, but that doesn't matter.

Anyway, is there a better way to do it?

The other thing I am thinking about is storing how many times a player has played the game in total, and this has to be stores locally too and must not get reset when the player closes the application. How is this done?

# Answer
> 0 votes
If you want settings to persist after the application is closed, you should be using `PlayerPrefs`. To set a value, you use the functions provided by the `PlaylerPrefs` class (`SetInt`, `SetFloat`, `SetString`)

```
PlayerPrefs.SetInt("Score", 10);
PlayerPrefs.Save();

```

When you want to retrieve this setting you would use the appropriate `Get` function:

```
int score = PlayerPrefs.GetInt("Score");

```

You can also clear the player preferences data:

```
PlayerPrefs.DeleteAll();
PlayerPrefs.Save();

```

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


title: DirectX Tessellation Cracks

text:
# Question
Title: DirectX Tessellation Cracks
I have the following simple patch function in DX11, but I keep getting rips, and when I look at the wireframe its clear that adjacent edges are not getting the same tessellation factor. The CalcTessFactor() function just does a distance from the camera to the point passed, so should always give the same value for the same edge center that I pass in.

```
PatchTess patchFunction_Far(InputPatch<VertexToPixel_Far, 3> patch, uint patchID : SV_PrimitiveID)
 {
  PatchTess pt;

 // Compute midpoint on edges, and patch center
  float3 e0 = 0.5f*(patch[0].WorldPosition + patch[1].WorldPosition);
  float3 e1 = 0.5f*(patch[1].WorldPosition + patch[2].WorldPosition);
  float3 e2 = 0.5f*(patch[2].WorldPosition + patch[0].WorldPosition);
  float3  c = (patch[0].WorldPosition + patch[1].WorldPosition + patch[2].WorldPosition) / 3.0f;

 pt.EdgeTess[0] = CalcTessFactor(e0);
  pt.EdgeTess[1] = CalcTessFactor(e1);
  pt.EdgeTess[2] = CalcTessFactor(e2);

 pt.InsideTess = CalcTessFactor©;

 return pt;
 }

```

My patches are triangles.

Is there something I'm doing trivially wrong here (like assuming that EdgeTess\[0\] is correctly assumed to be edge 0-1, rather than edge 2-\>0 for instance ? - its a wild guess..

# Answer
For the record - the cracks were appearing becasue I got the index of the ptEdgeTess assignment wrong. The correct code is;

```
pt.EdgeTess[2] = CalcTessFactor(e0);
pt.EdgeTess[0] = CalcTessFactor(e1);
pt.EdgeTess[1] = CalcTessFactor(e2);

```
> 1 votes

---
Tags: directx11
---


# Question
Title: Calculate distance from the centre to the edge of a cube in OpenGL
I'm trying to calculate the distance between a central point on a cube and anywhere on the surface of the cube, depending on the location of a second 3D point.

I have two vertices in 3D; `Q` and `P`. `Q` is the centre of the cube, `P` is a random point outside of the cube. I also have a known size of the cube, where distance across is `d`.

If I have the normalised vector of `u`, which is `Q->P`, how do I calculate the distance from the centre to where it hits the surface of the cube? I could not find the answer to this anywhere,on the Stack Exchange.

# Answer
> 1 votes
Because your ray starts at the centre of the cube, you can easily tell which face of the cube it hits. Simply find the component of `u` that has the largest magnitude - it's one of the faces with normals pointing along that axis. The sign of that component will tell you which of those two faces it intersects.

For example, if `u` is `(3, -5, 4)` then it hits the face of the cube with its normal pointing in the `(0, -1, 0)` direction (probably the bottom one, but it depends on your coordinate system).

From there you can do a ray vs plane intersection against that cube face.

However, you can simplify that process. In our example, we know that the point of intersection on the y axis is `-d/2`. So you can just scale `u` by `d/(2*5)` to make the y component end up where we want it. That gives us `(3d/10, -d/2, 4d/10)`. If I haven't made any silly mistakes that will be your intersection point on the cube.

---
Tags: opengl, c++, linear-algebra, raytracing
---


# Question
Title: I need my timer to go up every 30 seconds
I wrote code for a jackpot to increase from one date to the next, and it works beautifully. The client wants the numbers to stay put for a while, and then increase.

---

This is the code:

```
if (timerRunning1)
{
    timerValue1 += Time.deltaTime * 14.4 * (timerValue1F - timerValue1)
                / (finish1 - start).TotalSeconds;

    Jack1.text = timerValue1.ToString ("F2");

    //PlayerPrefs.SetFloat ("Jackpot1", float.Parse(Jackpot1.text));
    //PlayerPrefs.SetFloat ("Jackpot1f", float.Parse(Jackpot1F.text));

    if (timerValue1 > (timerValue1F - 0.1))
    {
        timerRunning1 = false;
        print ("ALTO");

        PagPrincipal.SetActive (false);
        Victoria.SetActive (true);

        Debug.Log ("FUNCIONA!!!");

        Invoke ("apagavictoria", 10f);

    }
}

```

---

I tried `WaitForSeconds(30f)`, and it didn't work. How can I make my timer go up every 30 seconds?

# Answer
> 2 votes
Ultimately, there are several ways to do this. `WaitForSeconds` can be used *inside a Co-routine*, but I would recommend simply keeping your own count, or using `MonoBehaviour.Invoke()`.

Each method essentially requires a class that inherits from `MonoBehaviour`, but you *should* be doing so, regardless. You will also want a function that increases the jackpot. We will assume this function is called `IncreaseJackpot()`. All you need to do, now, is know when to call it.

---

# `MonoBehaviour.Invoke` and `MonoBehaviour.InvokeRepeating`

Let's take a look at the Unity API.

> ## MonoBehaviour.Invoke
>
> public void **Invoke**(string **methodName**, float **time**);
> ***...***
> **Description**
> Invokes the method `methodName` ***in `time` seconds***.
> \- Unity API Reference: MonoBehaviour.Invoke
>
> ---
>
> ## MonoBehaviour.InvokeRepeating
>
> public void **InvokeRepeating**(string **methodName**, float **time**, float **repeatRate**);
> ***...***
> **Description**
> Invokes the method `methodName` in `time` seconds, then repeatedly every `repeatRate` seconds.
> \- Unity API Reference: MonoBehaviour.InvokeRepeating

Using these methods, you could repeatedly call `Invoke("Increase Jackpot", 30f)`, or you could simply call `InvokeRepeating("IncreaseJackpot", 30f, 30f)`.

# Keeping a Manual Timer

It is also fairly easy to keepbtrack of time using `Time.deltaTime` and your `Update()` function, as `Time.deltaTime` tells us the time since the *last* call to `Update()`.

```
float jackpotTimer = 0f;

public void Update()
{
    jackpotTimer += Time.deltaTime`;

    if(jackpotTimer >= 30f)
    {
        IncreaseJackpot();
        jackpotTimer -= 30f;
    }
}

```

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


# Question
Title: Moving a particle around an Archimedean spiral at a constant speed
I want to move a particle in a spiral at a constant speed. Note that that is *not* a constant angular speed. This is proving rather difficult, and I'll go through my method so far below.

The spiral in question is a classic Archimedean spiral with the polar equation `r = ϑ`, and the parametric equations `x = t*cos(t), y = t*sin(t)`. This looks like this:

I want to move a particle around the spiral, so naively, I can just give the particle position as the value of t, and the speed as the increase in t. That way the particle moves round the spiral at a constant angular speed. However, this means that the further out from the centre it gets, the faster its (non angular) speed becomes.

So, instead of having my speed in the increase in t, I want my speed as the increase in arc length. Getting the arc length of a spiral is the first challenge, but due to the fact that the Archimedean spiral I am using isn't too insane, the arc length function is , where `a = 1`. This allows me to convert theta values to the arc length, but that is the precise opposite of what I need. So I need to find the inverse of the arc length function, and at that hurdle, Wolfram-Alpha has failed me.

So is it possible to find the inverse of the arc length function? The function is a one to one mapping, if you exclude negative values of theta.

Thanks,

Laurie

# Answer
Let's complicate your spiral:

be

in your case f(t) := t, in mine f(t) := 1 (so i pay back my complications with simplifications :)

If you want to go at a certain speed in this degenerate spiral (a circle) you have to know how long is your spiral in a round so you can say how much rounds per second do to be sure that your point travels with the desired speed.

Now we know that each complete round in a circle is 2·*π·r* long: 2·*π·1* in our case; if *ω* is the revolution speed (in rounds per seconds) the speed *V* will be *V* = 2·*π·1·ω* or in a more general way:

if *r* is the general radius; this tell us that:

if r is a function of t we can say:

in my "complicated" case this can be rewrite as follow:

in your "simplificated" case the answer is:

You know your desidered constant speed V, you know: 2, *π* and *t* is your variable: you know everything and you are ready to go!

*the circle approximation for the infinitesimal neighbourhood of the spiral in t*

**\[DISCLAIMER\]**

This is not intended to be a rigorous mathematical treatment: it does not take into account the contribution of the differential of *f* nor say what types of function can not be used.
> 12 votes

# Answer
If you don't mind an assumption that gets fairly accurate quite quickly, this simple solution works quite well:

```
theta = r = sqrt(2) . sqrt({time})

```

This is parametric in time, which is quite handy. However, to get this I needed to assume that the motion is roughly circular -- ie. the instantaneous linear velocity is proportional to the radius times the angular velocity:

```
{velocity} ~= {radius} . d{theta} / d{time}

```

To show that the solution works, plug it into `d{theta} / d{time}`:

```
d{theta} / d{time} = d(sqrt(2).{time}^(1/2)) / d{time}
                   = (sqrt(2) / 2) . {time}^(-1/2))
                   = 1 / {theta}
                   = 1 / {radius}
=> {velocity} = {radius} / {radius} = 1, as required.

```

At `{time}=1`, this places a point at distance `sqrt(2)` from the origin. After this, the approximation improves significantly: the separation (linear, not along the path) between subsequent points is 1.13, 1.08, 1.06. After 100 points the separation is less than 1.0023.
> 2 votes

# Answer
While looking for a solution of computing the angle that corresponds to a certain arc length, I stumbled upon this question and the current answer. Unfortunately, neither this answer nor any other resource that I found on the web could directly be used for an implementation.

Obviously, computing the inverse of the arc length function (that was also provided in the question) is very difficult. But an approximation of this inverse using Newtons Iterative Method is possible. The following is a class that mainly offers two methods:

* `computeArcLength(double alpha, double angleRad)`: Computes the arc length of a point on the Archimedean Spiral where `alpha` is the distance between successive turnings, and `angleRad` is the angle in radians
* `computeAngle(double alpha, double arcLength, double epsilon)`: Computes the angle at which the point for the given arc length is located on the Archimedean Spiral, where `alpha` is the distance between successive turnings, and `epsilon` is the approximation threshold for the Newton Iteration

The code is implemented here in Java, but these core methods should be fairly language-agnostic:

```
import java.awt.geom.Point2D;

/**
 * A class for computations related to an Archimedean Spiral
 */
class ArchimedeanSpiral
{
    /**
     * Computes an approximation of the angle at which an Archimedean Spiral
     * with the given distance between successive turnings has the given
     * arc length.<br>
     * <br>
     * Note that the result is computed using an approximation, and not
     * analytically.
     *
     * @param alpha The distance between successive turnings
     * @param arcLength The desired arc length
     * @param epsilon A value greater than 0 indicating the precision
     * of the approximation
     * @return The angle at which the desired arc length is achieved
     * @throws IllegalArgumentException If the given arc length is negative
     * or the given epsilon is not positive
     */
    static double computeAngle(
        double alpha, double arcLength, double epsilon)
    {
        if (arcLength < 0)
        {
            throw new IllegalArgumentException(
                "Arc length may not be negative, but is "+arcLength);
        }
        if (epsilon <= 0)
        {
            throw new IllegalArgumentException(
                "Epsilon must be positive, but is "+epsilon);
        }
        double angleRad = Math.PI + Math.PI;
        while (true)
        {
            double d = computeArcLength(alpha, angleRad) - arcLength;
            if (Math.abs(d) <= epsilon)
            {
                return angleRad;
            }
            double da = alpha * Math.sqrt(angleRad * angleRad + 1);
            angleRad -= d / da;
        }
    }

    /**
     * Computes the arc length of an Archimedean Spiral with the given
     * parameters
     *
     * @param alpha The distance between successive turnings
     * @param angleRad The angle, in radians
     * @return The arc length
     * @throws IllegalArgumentException If the given alpha is negative
     */
    static double computeArcLength(
        double alpha, double angleRad)
    {
        if (alpha < 0)
        {
            throw new IllegalArgumentException(
                "Alpha may not be negative, but is "+alpha);
        }
        double u = Math.sqrt(1 + angleRad * angleRad);
        double v = Math.log(angleRad + u);
        return 0.5 * alpha * (angleRad * u + v);
    }

    /**
     * Compute the point on the Archimedean Spiral for the given parameters.<br>
     * <br>
     * If the given result point is <code>null</code>, then a new point will
     * be created and returned.
     *
     * @param alpha The distance between successive turnings
     * @param angleRad The angle, in radians
     * @param result The result point
     * @return The result point
     * @throws IllegalArgumentException If the given alpha is negative
     */
    static Point2D computePoint(
        double alpha, double angleRad, Point2D result)
    {
        if (alpha < 0)
        {
            throw new IllegalArgumentException(
                "Alpha may not be negative, but is "+alpha);
        }
        double distance = angleRad * alpha;
        double x = Math.sin(angleRad) * distance;
        double y = Math.cos(angleRad) * distance;
        if (result == null)
        {
            result = new Point2D.Double();
        }
        result.setLocation(x, y);
        return result;
    }

    /**
     * Private constructor to prevent instantiation
     */
    private ArchimedeanSpiral()
    {
        // Private constructor to prevent instantiation
    }
}

```

An example of how to use this for the goal described in the question is given in this snippet: It generates a certain number of points on the spiral, with a desired (arc length!) distance between the points:

```
import java.awt.geom.Point2D;
import java.util.Locale;

public class ArchimedeanSpiralExample
{
    public static void main(String[] args)
    {
        final int numPoints = 50;
        final double pointArcDistance = 0.1;
        final double alpha = 0.5;
        final double epsilon = 1e-5;

        double totalArcLength = 0.0;
        double previousAngleRad = 0.0;
        for (int i=0; i<numPoints; i++)
        {
            double angleRad =
                ArchimedeanSpiral.computeAngle(alpha, totalArcLength, epsilon);
            Point2D point =
                ArchimedeanSpiral.computePoint(alpha, angleRad, null);
            totalArcLength += pointArcDistance;

            // Compute and print the arc lengths, for validation:
            double currentArcLength =
                ArchimedeanSpiral.computeArcLength(alpha, angleRad);
            double previousArcLength =
                ArchimedeanSpiral.computeArcLength(alpha, previousAngleRad);
            double arcDistance = (currentArcLength - previousArcLength);
            System.out.printf(Locale.ENGLISH,
                "Point (%6.2f, %6.2f  distance in arc "
                + "length from previous is %6.2f\n",
                point.getX(), point.getY(), arcDistance);

            previousAngleRad = angleRad;
        }
    }
}

```

The *actual* arc length distance of the computed points is printed, and one can see that they are in fact equidistant, with the desired arc length distance.
> 0 votes

# Answer
I'm struggling with this too.

What I'm doing is keeping the velocity constant, and changing the direction of the object.

If I make is so the angle (in degrees) is equal to the distance from the origin, times a constant, i get a nice perfect archimedean spiral. larger constants get less space between the lines. Only issue is if the speed is too high, then it jumps the track and messes up. so tighter spirals require a slower speed to reliably trace.

`direction = ((spiral_factor*(current_distance) mod 360);`

Where current\_distance is the radius drawn from the location to the spawn point in pixels, grabbed by an engine function that gives it to me.

What's driving me up the wall is the inverse. placing the object at the OUTSIDE and having it trace the Archimedean spiral INWARDS. Moving the particle the opposite way doesn't work. that just rotates the spiral 180 degrees. inverting the direction gives a clockwise one.
> 0 votes

---
Tags: mathematics, geometry
---


title: VBO Performance issues

text:
# Question
Title: VBO Performance issues
I'm making a 2D Tile based game in OpenTK at the moment. Performance was really bad (laggy and slow) with direct drawing, so I switched to VBOs. The performance hasn't changed, it might even be slower than it was.

I render the tiles from a list, but use a single VBO.

```
public void DrawTiles()
        {
            foreach(Tile t in Tiles)
            {
                if(t != null)
                {
                    GL.Color4(System.Drawing.Color.White);
                    GL.BindTexture(TextureTarget.Texture2D, Global.LoadTexture(t.TileTexture.Path, 1));
                    var i = (CellNum * CellSize) / 2;
                    GL.PushMatrix();
                    GL.Translate((t.Position.X * CellSize) - i, 0, (t.Position.Z * CellSize) - i);
                    var x = CellSize;
                    verts = new Vector3[8]
                    {
                        new Vector3(0, 0, 0), new Vector3(0, 0, 0),
                        new Vector3(x, 0, 0), new Vector3(1, 0, 0),
                        new Vector3(x, 0, x), new Vector3(1, 1, 0),
                        new Vector3(0, 0, x), new Vector3(0, 1, 0)
                    };

                    GL.EnableClientState(ArrayCap.VertexArray);

                    GL.EnableClientState(ArrayCap.TextureCoordArray);

                    GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
                    GL.BufferData<Vector3>(BufferTarget.ArrayBuffer, (IntPtr)(Vector3.SizeInBytes * CellNum), verts, BufferUsageHint.StaticDraw);
                    GL.BindBuffer(BufferTarget.ArrayBuffer, 0);

                    GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
                    GL.VertexPointer(3, VertexPointerType.Float, Vector3.SizeInBytes * 2, 0);
                    GL.TexCoordPointer(3, TexCoordPointerType.Float, Vector3.SizeInBytes * 2, Vector3.SizeInBytes);
                    GL.DrawArrays(PrimitiveType.Quads, 0, verts.Length / 2);
                    GL.Flush();
                    GL.PopMatrix();
                }
            }
        }

```

That method is called in OnRenderFrame, CellSize and CellNum tell me how big the tiles are supposed to be and how many there are each side of the grid. Even if I run say a 20 tile grid, my program is incredibly laggy.

Does any one know a more efficient way to render these tiles, or better yet, speed up my current method?

# Answer
The important thing to realise, as you've discovered, is that VBOs aren't a magic wand that makes everything run faster under every circumstance. Specifically, you're only going to see a meaningful performance improvement with VBOs if you're bottlenecked on getting your vertex data from the CPU to the GPU. If you're not so bottlenecked, then the potential performance improvement that VBOs offer doesn't apply to you.

It's quite safe to assume that drawing 20 quads is not so bottlenecked; glBegin/glEnd code is **perfectly fine** for this kind of workload, unless you have an actual reason to do otherwise (such as wanting to use a core profile). Remember: Quake used glBegin/glEnd code in 1996, drew several hundred polygons per frame, and ran plenty fast enough on hardware of that time.

You've also discovered that a bad VBO implementation (and your's is one) can run slower than glBegin/glEnd code. The way to use a VBO properly is to batch up a lot of vertices then submit them all in a single draw call. So rather than filling a VBO with a single quad at a time, instead you pre-allocate a large VBO (how large? depends on your program, but several hundred or even thousand quads would not be unreasonable), fill it up, then make a single glDrawArrays call with it.

If the data doesn't need to change then you just reuse the VBO from the previous frame. There's definitely no need to recreate it.

So given that you've not got a bottleneck that's adressable by a VBO, yet you're still running slow, it's obvious that you must be bottlenecked elsewhere.

Looking over your code, I can see a number of things that are candidates for improvement, but the main one that jumps out at me is your `Global.LoadTexture` call. Are you reloading textures from disk every frame? Yes, that would make it slow.

A second thing is your use of the old matrix stack. For your use case, this gets you nothing in terms of performance - don't get the idea that just because it's a GL call it means it runs on the GPU, because the old matrix stack doesn't. Furthermore, you're inserting state changes between each draw call that will prevent the driver from being able to batch up work (you've another case of this I'll come to later). Get rid of that and just put the final positions directly into your glVertex calls (or VBO); your GPU will thank you for it.

Thirdly, that glFlush call is completely unnecessary and is once again preventing the driver from batching up work. Get rid of that too.

So, sort these out first, retaining your old glBegin/glEnd code, and then you'll be able to determine if glBegin/glEnd code is actually a problem for you or not before doing anything else.
> 0 votes

---
Tags: c#, performance, vbo, opentk
---


# Question
Title: Are there well known algorithms for efficient map knowledge?
The question subject's is a little confusing, but I had no better way to express my train of thought. I'm working on an RPG at the moment, and I have a question. Using SARSA (State-Action-Reward-State-Action), I'm building a smart brain by training it through a reward system. Right now, what I want is to improve the learning process when moving each unit of the party, the selected actions will impact the team as a whole.

Moving to attack an enemy on which I have a tactical advantage, such as when a knight attacks a wizard, the wizard being weak on physical attacks, will get more damage out of the attack. The brain starts to understand that doing this gives a better reward. But, doing so could lead a unit to attack an enemy that has a tactical disadvantage against it but it has friends that can help him defeat the foe.

What I'm looking for is the following: Is there any algorithm that can parse a given data structure representing a map and see whether or not I'm moving toward a bad or good position depending on some variables such as moving toward target, target has friendly surrounding, moving toward treasure chest and etc.

I'm not looking for someone to write down an implementation for me, just to point me in the good direction because I have no idea what I'm looking for. If you're well versed in what I'm speaking and willing to give me a sample algorithm that I should follow and adapt for my game, I will gladly refer you in my prototype and send you a link once the prototype is playable!

# Answer
Influence maps are data structures that model various relationships with respect to their locations, and typically assume that the impact of these relationships spread outward across space and/or time. For instance, positions close to cover would be considered safer than those further away. Similarly, regions with recent enemy sightings might be considered more confrontational than those that have not recently observed enemy movement. As an illustration, here's a screenshot from Brian Wanjir's project where he uses influence maps to modify path finding in order to avoid enemy turrets:

Alex Champandard identifies the following as the three core strengths of influence maps:

> * Situation Summary — Influence maps do a great job of summarizing all the little details in the world and making them easy to understand at a glance. Who's in control of what area? Where are the borders between the territories? How much enemy presence is there in each area?
> * Historical Statistics — Beyond just storing information about the current situation, influence maps can also remember what happened for a certain period of time. Was this area being assaulted? How well did my previous attack go?
> * Future Predictions — An often ignored aspect of influence maps, they can also help predict the future. Using the map of the terrain, you can figure out where an enemy would go and how his influence would extend in the future.

Offhand, I know that in one form or another, they've been used in Ground Control 2, World In Conflict, Kohan 2, Axis & Allies and Killzone 2 & 3.

In terms of references, the earliest source I know of is Paul Tozour's "Influence Mapping" in *Game Programming Gems 2*. They also surface fairly often in the AI Game Programming Wisdom series; here's a partial list of related articles:

* Recognizing Strategic Dispositions: Engaging the Enemy, by Steven Woodcock in *AI Game Programming Wisdom*
* Strategic Decision-Making with Neural Networks and Influence Maps, by Penny Sweetser in *AI Game Programming Wisdom 2*
* Prioritizing Actions in a Goal-Based RTS AI, by Kevin Dill in *AI Game Programming Wisdom 3*
* Spatial Reasoning for Strategic Decision Making, by Kevin Dill in *Game AI Pro 2*

Given that influence maps have been used in a wide variety of AI contexts (including neural nets), I suspect they would work equally well with SARSA.

WorldCat might help you find a library copy near by. Also, some of the source code is available on line. Personally, I found the series to be a good investment, but your mileage may vary.
> 10 votes

# Answer
Well, since you want to include the particulars of your combat system, nothing will work out of the box. In general, an AI should consist of 3 parts: percepts, model, decision maker.

The percepts are simply information you feed in about the current situation. I'll want a measure of closeness to some destination. The usual A\*/Dijkstra's should be fine. You will also need to feed in adjacency or closeness information for enemies/allies. Again, you can just calculate the distance between characters. You will also need to give characters' current states (hp, buff/debuffs, etc).

I don't know much about SARSA but it looks like it takes the place of the model. It will take in the information about the current state, use it to change it's overall state, compare against some machine learning model, whatever, then decide what to do.

The list of decisions is again determines by your combat system, but it's whatever actions your AI character can currently do. Your model will hopefully generate some sore of level of utility for each action, and then you can just execute the action with the highest utility.
> 1 votes

---
Tags: ai, rpg, strategy
---