# Question
Title: C++ A Star Algorithm [path takes wrong route] using <deque> & unique_ptr
I am having issues, trying to get my A Star algorithm working, the main problem is with my process of the algorithm, I am using something known as the TL engine which has some of its own datatypes and functions but for the most part, I am 90% certain my problem is with my C++ code and not with TL-engine function, specifically with my understanding / implementation of the algorithm.

Figures and Information

My grid is a 10x10 grid, called SNodeCubeArray\[10\]\[10\].

My program reads a txtfile in and sets a base value which determines which bools it will set.

When I generate new rules on the Algorithm I go, I visit the neighbours NESW, and to travel to each node I have a cost assigned to different node types.

Here is an example:

* Normal Nodes always have a cost = 1
* Woods Cost = 2
* Water Cost = 3
* Obstacle / wall = 0 (but is impassable)

Figure 3 explains what happening in more detail.

When I run my AStar algorithm, it performs a very strange path of opennodes, often jumping around and also causing dereferencing iterator problems.

Some functions / variables explanation:

```
gDEST_X & gDEST_Y = dsetination node stored
gSTART_X & gSTART_Y = start node stored
ANodeCubeModels = Model Array

```

This is the `struct` I have declared it is the datatype I'll be using with Unique\_ptr's deque.

```
// Code by ryan newell uclan student G20618255  -> for self reference
struct node
{

public:
  // The Structs actual location in the array eg [3,3]
  int mLoc_X; // Current X- Position in the Node stored
  int mLoc_y; // Current Y- Position in the node stored

  int mHeuristic_Manhattan; // Is the stored nodes manhattan distance

  // These floats are so I can store the coordinates of the linked cubes it should be in.

  //Temporary storage for the string reading.
  char mNodeValue;

  // Declares what kind node it is.
  bool mIsObstacle = false;
  bool mIsWater = false;
  bool mIsWoods = false;
  bool mIsStartNode = false;
  bool mIsDestNode = false;

  //Cost storage heurestic
  int mNodeCost; // The cost to travel between the nodes
  int mAccumulatedCost; // The accumulated cost of the node + its parent

  int mvalue_f; // Is its total score which will equals NodeCost+Heuristic

  //pARENT
  node* m_parent;
};

```

This is my functions section of the code being used, that we need to know about, any functions I haven't likely are TL-engine functions, and tested to work.

```
// sorts the node array by order of total_score
bool CompareNodeScores(unique_ptr<node>& lhs, unique_ptr<node>& rhs)
{
  return lhs->mvalue_f < rhs->mvalue_f;
}

bool check_greater_fcost(
    deque <unique_ptr< node >> &closeList,
    unique_ptr <node> &NewState_n,
    deque <unique_ptr<node>> &openList)
{
  if (openList.empty() == false)
  {
    for (auto it = openList.begin(); it != openList.end(); it++)
    {
      if ((*it)->mLoc_X == NewState_n.get()->mLoc_X &&
          (*it)->mLoc_y == NewState_n.get()->mLoc_y &&
          NewState_n->mvalue_f >= (*it)->mvalue_f)
        return true;

      return false;
    }
  }
  if (closeList.empty() == false)
  {
    for (auto it = closeList.begin(); it != closeList.end(); it++)
    {
      if ((*it)->mLoc_X == NewState_n.get()->mLoc_X &&
          (*it)->mLoc_y == NewState_n.get()->mLoc_y &&
          NewState_n->mvalue_f >= (*it)->mvalue_f)
        return true;

      return false;
    }
  }
}

bool astar_checklists(
  deque <unique_ptr< node >> &closeList,
  unique_ptr <node> &RuleCurrent,
  deque <unique_ptr<node>> &openList,
  unique_ptr <node> &CurrentNode)
{
  // set p to the beginning of the loop
  for (auto it = openList.begin(); it != openList.end(); it++)
  {
    if ((*it)->mLoc_X == RuleCurrent.get()->mLoc_X &&
        (*it)->mLoc_y == RuleCurrent.get()->mLoc_y)
    {
      (*it)->mAccumulatedCost = RuleCurrent->mAccumulatedCost;
      (*it)->mHeuristic_Manhattan = RuleCurrent->mHeuristic_Manhattan;
      (*it)->mNodeCost = RuleCurrent->mAccumulatedCost;
      (*it)->mvalue_f = RuleCurrent->mHeuristic_Manhattan + RuleCurrent->mNodeCost;
      (*it)->m_parent = CurrentNode->m_parent;
      return true;
    }
  }
  // set p to the beginning of the loop
  for (auto it = closeList.begin(); it != closeList.end(); it++)
  {
    if ((*it)->mLoc_X == RuleCurrent.get()->mLoc_X &&
        (*it)->mLoc_y == RuleCurrent.get()->mLoc_y)
    {
      (*it)->mAccumulatedCost = RuleCurrent->mAccumulatedCost;
      (*it)->mHeuristic_Manhattan = RuleCurrent->mHeuristic_Manhattan;
      (*it)->mNodeCost = RuleCurrent->mAccumulatedCost;
      (*it)->mvalue_f = RuleCurrent->mHeuristic_Manhattan + RuleCurrent->mNodeCost;
      (*it)->m_parent = CurrentNode->m_parent;

      openList.push_back(move(*it));
      closeList.erase(it);
      sort(openList.begin(), openList.end(), CompareNodeScores);
      return true;
    }
    else
    {
      return true;
    }
  }
  return false;
}

```

This section is where the main body of the algorithm itself lies, I am not really sure what I am doing wrong, but when I run the program, it does not take the correct route it should take.

```
void AStarFindPathNew(
  I3DEngine* myEngine,
  IModel* ANodeCubeModels[10][10],
  node SNodeArray[10][10],
  int storemLoc_X,
  int storemLoc_y,
  int storedestmLoc_x,
  int storedestmLoc_y)
{
  int xstore = 0;
  int ystore = 0;
  int xplus = 0;
  int yplus = 0;
  bool goal_state_found = false;
  //bool current_is_on_openlist = false;
  //bool current_is_on_closelist = false; previous unused values
  //bool current_is_on_bothlists = false;
  ofstream outfile;
  unique_ptr <node> NewState_n(new node);
  unique_ptr <node> CurrentNode(new node);
  unique_ptr <node> initialState(new node);
  deque <unique_ptr < node > > openList;
  deque <unique_ptr < node > > closeList;

  // Declaring Intial state
  initialState->mLoc_X = gSTART_X;
  initialState->mLoc_y = gSTART_Y;
  initialState->m_parent = 0;
  initialState->mAccumulatedCost = 0;
  initialState->mHeuristic_Manhattan = CalculateManhattan( ANodeCubeModels,
                                                           SNodeArray,
                                                           initialState->mLoc_X,
                                                           initialState->mLoc_y,
                                                           storedestmLoc_x,
                                                           storedestmLoc_y);
  initialState->mvalue_f = initialState->mHeuristic_Manhattan + initialState->mNodeCost;
  DisplayOpenlist(openList, outfile);
  openList.push_front(move(initialState));
  xstore = gSTART_X;
  ystore = gSTART_Y;

  while (!goal_state_found || !openList.empty())
  {
    // Values Value_G = Manhattan Distance = mHeuristic_Manhattan
    // Value: Value_MC = Movement Cost Heuristic  = mNodeCost
    // Value: Value_F = H + MC = m_valuef
    CurrentNode = (move(openList.front()));
    cout << "popped open to New current Node = " <<
      CurrentNode->mLoc_X << ":" << CurrentNode->mLoc_y << endl;
    openList.pop_front();
    //cout << CurrentNode->mLoc_X << "," << CurrentNode->mLoc_y << "  Target: "
    // << gDDEST_X << "," << gDDEST_Y << endl;
    if (CurrentNode->mLoc_X == storedestmLoc_x && CurrentNode->mLoc_y == storedestmLoc_y)
    {
      cout << "Found Path" << endl;
      _getch();
      fRetracesteps(myEngine, ANodeCubeModels, SNodeArray, CurrentNode);
      return;
    }
    DisplayOpenlist(openList, outfile);

    for (int i = 0; i < 4; i++)
    {
      if (i == 0)
      {
        xplus = 0;
        yplus = +1;
      }
      if (i == 1)
      {
        xplus = +1;
        yplus = 0;
      }
      if (i == 2)
      {
        xplus = 0;
        yplus = -1;
      }
      if (i == 3)
      {
        xplus = -1;
        yplus = 0;
      }
      cout << "Generating Rule X:" << xstore + xplus << "Y:" << ystore + yplus << endl;
      //d) i Generate N
      NewState_n.reset(new node);
      NewState_n->mLoc_X = CurrentNode->mLoc_X + xplus;
      NewState_n->mLoc_y = CurrentNode->mLoc_y + yplus;
      NewState_n->mAccumulatedCost = CurrentNode->mAccumulatedCost +
                   SNodeArray[NewState_n->mLoc_X][NewState_n->mLoc_y].mHeuristic_Manhattan;
      NewState_n->mHeuristic_Manhattan = CalculateManhattan(ANodeCubeModels, SNodeArray,
                 NewState_n->mLoc_X, NewState_n->mLoc_y, storedestmLoc_x, storedestmLoc_y);
      NewState_n->mvalue_f = NewState_n->mHeuristic_Manhattan + NewState_n->mAccumulatedCost;
      NewState_n->m_parent = CurrentNode.get();
      cout << NewState_n->m_parent;

      cout << "Checking curent rule for within boundaries" << endl;
      if (!checkcurrentruleinbounds(NewState_n))
      {
        continue;
      }

      NewState_n->mIsObstacle =
        SNodeArray[CurrentNode->mLoc_X + xplus][CurrentNode->mLoc_y + yplus].mIsObstacle;

      cout << "Checking whether the rule is on the lists or has a greater cost" << endl;
      if (astar_checklists(closeList, NewState_n, openList, CurrentNode) &&
          !check_greater_fcost(closeList, NewState_n, openList))
      {
        continue;
      }

      if (NewState_n->mIsObstacle != true)
      {
        //cout << "Setting newstate_n" << NewState_n.get()->mLoc_X <<
          //NewState_n->mLoc_y << NewState_n->m_parent;
        ANodeCubeModels[NewState_n->mLoc_X][NewState_n->mLoc_y]->SetSkin("opennode.png");
        openList.push_back(move(NewState_n));
        sort(openList.begin(), openList.end(), CompareNodeScores);
        cout << CurrentNode->mLoc_X << ":" << CurrentNode->mLoc_y;
      }

      DisplayOpenlistWithScore(openList, outfile);
    }
    cout << "Finished first set of rules" << endl;
    cout << "Close List:" << CurrentNode->mLoc_X <<":"<< CurrentNode->mLoc_y << endl;
    ANodeCubeModels[CurrentNode->mLoc_X][CurrentNode->mLoc_y]->SetSkin("closednode.png");
    closeList.push_back(move(CurrentNode));

    _getch();
    myEngine->DrawScene();
    DelayProc(0.75);
  }
}

```

# Answer
Found the issue with my program, the algorithm was mostly right, I just had to modify my if statements when taking things on and off the closelist to include the the if statement whether it was smaller than the previous route, since we only want to take things off the close list if a better route has been found.

A secondary issue popped up when I realized I was incorrectly allocating terrain types, taking the wrong route round the top because my although my water nodes appeared as water they were actually woods and vice versa.
> 1 votes

---
Tags: c++, path-finding
---


title: Wall-Sliding, Stuck at Corners

text:
# Question
Title: Wall-Sliding, Stuck at Corners
I am having trouble with my 2-D wall-sliding. Namely, when the player avatar collides with the wall, it "snaps" to the corner (see screenshot, below) and sticks there. The red, transparent rectangle is my "wall":

My code is as follows:

"FootRectangle" is your standard xna rectangle. Location is a vector2. The player is moving to a target, which could be anywhere on the screen, which is also a vector2.

```
 if (wall.CollisionRectangle.Intersects(player.FootRectangle))
            {

                // collision above block
                if (player.FootRectangle.Top <= wall.CollisionRectangle.Top)
                {
                    player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Top - player.FootRectangle.Height / 2);
                }

                // collision below block
                else if (player.FootRectangle.Bottom >= wall.CollisionRectangle.Bottom)
                {
                    //player.FootRectangle.Y = block.CollisionRectangle.Bottom;
                    player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Bottom + player.FootRectangle.Height / 2);
                }

                // collision left of block
                if (player.FootRectangle.Left <= wall.CollisionRectangle.Left)
                {
                    player.Location = new Vector2(wall.CollisionRectangle.Left - player.FootRectangle.Width / 2, player.Location.Y);
                }

                // collision right of block
                else if (player.FootRectangle.Right >= wall.CollisionRectangle.Right)
                {
                    player.Location = new Vector2(wall.CollisionRectangle.Right + player.FootRectangle.Width / 2, player.Location.Y);
                }

```

How can I resolve these collisions so that the avatar snaps to a corner and smoothly makes his way to the target destnation?

I attempted to implement a similar solution to that at this post; however, it seemed to stick when the collision occurred.

# Answer
> 0 votes
Taking some inspiration from Aj\_'s answer, I was able to resolve the collision successfully with the following code:

I found that I needed to test for both: `wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y) * rectRatio > wall.CollisionRectangle.Center.X - player.FootRectangle.Center.X`

and

`wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y > wall.CollisionRectangle.Center.X - player.FootRectangle.Center.X`, etc.

Otherwise, the player's foot rectangle would still clip through the corners of the wall rectangle (varied, depending on which test was omitted.

```
                // check for collision
                if (wall.CollisionRectangle.Intersects(player.FootRectangle))
                {
                    // set collision offset
                    int collisionOffset = 4;

                    // find height/width ratio for wall rectangle
                    float rectRatio = wall.CollisionRectangle.Width / wall.CollisionRectangle.Height;

                    // resolve collision from top and right
                    if ((wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y) * rectRatio > wall.CollisionRectangle.Center.X - player.FootRectangle.Center.X ||
                        wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y > wall.CollisionRectangle.Center.X - player.FootRectangle.Center.X)
                    {
                        // right
                        if (player.FootRectangle.Left >= wall.CollisionRectangle.Right - collisionOffset)
                        {
                            player.Location = new Vector2(wall.CollisionRectangle.Right + player.FootRectangle.Width / 2, player.Location.Y);
                        }

                        // top
                        if (player.FootRectangle.Bottom <= wall.CollisionRectangle.Top + collisionOffset)
                        {
                            player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Top - player.FootRectangle.Height / 2);
                        }
                    }

                    // resolve collision from left and bottom
                    if (wall.CollisionRectangle.Center.X - player.FootRectangle.Center.X > (wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y) * rectRatio ||
                        player.CollisionRectangle.Center.X - player.FootRectangle.Center.X > wall.CollisionRectangle.Center.Y - player.FootRectangle.Center.Y)
                    {
                        // bottom
                        if (player.FootRectangle.Top >= wall.CollisionRectangle.Bottom - collisionOffset)
                        {
                            player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Bottom + player.FootRectangle.Height / 2);
                        }

                        // left
                        if (player.FootRectangle.Right <= wall.CollisionRectangle.Left + collisionOffset)
                        {
                            player.Location = new Vector2(wall.CollisionRectangle.Left - player.FootRectangle.Width / 2, player.Location.Y);
                        }
                    }
                }

```

# Answer
> 1 votes
Ask yourself these questions: Does your player get stuck on contact? Does your player on contact 'jitters' more into the wall and then gets stuck, or does your player get stuck when moving or jumping fast into the wall.

If it gets smoothly stuck on contact, you need to improve your guard. Are you absolutely sure that the distance between center of your player and the edge of your foot is `FootRectangle.Width / 2` ? Try changing your inequality to \> and \< instead of \>= and \<=. Or offset your player a little bit more by one pixel or an easy way out, something like (0.51\*player.FootRectangle.Width).

If your player jitters into the wall, the other thing that I can think of when looking at your code is maybe you got the signs of the direction of the velocity vector mixed up. Check if it jitters into the wall. If yes, check that going left is indeed defined by a negative sign (and going up with a positive) as you otherwise move the player more into the wall. Change swap then + and - accordingly when before `FootRectangle.Width / 2`.

(Btw. the way I do resolve stuck collisions is by storing the last known position before the collision and resetting the scene and implement the collision response if this response does not lead to being stuck again (forward check); otherwise set the velocity to the direction of the offset vector.)

# Answer
> 1 votes
I don't exactly know what you meant by 'stuck'. If it's stuck as in 'can't move in any direction' then the problem probably in the offset distance.

Are `FootRectangle.Height`, `FootRectangle.Width, Location.x, Location.y` etc. of type `float` or `int` ? If it's an `int` then dividing it them by 2 (which another `int`) will only yield an `int`. Meaning, something like 3/2 will give you 1 instead of 1.5. Thus messing up your offsetting.

You should use `float` versions of `Rectangle` and `Location` to fix this. Or if your `Location` is of type `float` then you could cast those variables to `float` before doing any operations. Like,

```
player.Location = new Vector2(player.Location.X, (float)wall.CollisionRectangle.Top - (float)player.FootRectangle.Height / 2f);

```

If it's getting 'stuck', or rather 'hit', when you try to move up then it's behaving as expected because `Rectangle.Intersects()` is returning true. This means a really small area of your `FootRectangle`is overlapping the `wall.CollisionRectangle`. If you want to disregard this minor overlap and proceed as if nothing happened, you could use a modified version of `Rectangle.Intersects()`or add some small extra offset to the new location.

```
float smallOffset = .1f;

player.Location = new Vector2(player.Location.X, wall.CollisionRectangle.Top - (player.FootRectangle.Height / 2 + smallOffset) );

```

Remember this would only work if `Location` and `Rectangle` contain `float` variables.

# Answer
> 0 votes
I didn't understand what you mean with 'stuck' but have a look at this post. I shared my simple 2d collision system. Maybe it helps. :)

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


title: Predicting Enemy Movement

text:
# Question
Title: Predicting Enemy Movement
Well I have a simple 2D game where all positions are defined by and X and Y coordinate.

There are objects moving at a constant velocity. And a turret fires a bullet at the X and Y coordinates of the object. By the time the bullet goes to the desired area, the object has already moved.

So i need to adjust the X and Y target positions for the turret to shoot at taking into account the bullet speed and object speed.

Here's an image showing the problem.

# Answer
> 2 votes
I've done something similar in the past and I used a quadratic equation to find the time `t` where the two paths (target and bullet) intersect.

This is what it looks like when implemented using **libGDX**s classes;

```
    private static Vector2 sub(Vector2 lhs, Vector2 rhs) {
        return (new Vector2(lhs)).sub(rhs);
    }

    private static Vector2 calculateFireDirection(Vector2 targetPosition, Vector2 turretPosition, Vector2 targetVelocity, float bulletSpeed) {
        Vector2 turretToTarget = sub(targetPosition, turretPosition);

        float a = targetVelocity.x*targetVelocity.x + targetVelocity.y * targetVelocity.y - bulletSpeed*bulletSpeed;
        float b = 2.0f * targetVelocity.dot(turretToTarget);

        float p = -b / (2 * a);
        float q = (float)Math.sqrt((b * b) - 4 * a * (turretToTarget.x * turretToTarget.y + turretToTarget.y * turretToTarget.y)) / (2 * a);

        float t = Math.max(p - q, p + q);

        if (t > 0) {
            Vector2 tp = new Vector2(targetPosition);
            Vector2 tv = new Vector2(targetVelocity);
            Vector2 collisionPoint = tp.add(tv);

            return sub(collisionPoint, turretPosition);
        }
        else
            return null; // This means the collision will never happen (or happened before the shot was fired, which is nonsensical).
    }

```

I the formulas from somewhere, but I can't remember where.

A full program sample program;

```
public class Program {

    private static Vector2 sub(Vector2 lhs, Vector2 rhs) {
        return (new Vector2(lhs)).sub(rhs);
    }

    private static Vector2 calculateFireDirection(Vector2 targetPosition, Vector2 turretPosition, Vector2 targetVelocity, float bulletSpeed) {
        Vector2 turretToTarget = sub(targetPosition, turretPosition);

        float a = targetVelocity.x*targetVelocity.x + targetVelocity.y * targetVelocity.y - bulletSpeed*bulletSpeed;
        float b = 2.0f * targetVelocity.dot(turretToTarget);

        float p = -b / (2 * a);
        float q = (float)Math.sqrt((b * b) - 4 * a * (turretToTarget.x * turretToTarget.y + turretToTarget.y * turretToTarget.y)) / (2 * a);

        float t = Math.max(p - q, p + q);

        if (t > 0) {
            Vector2 tp = new Vector2(targetPosition);
            Vector2 tv = new Vector2(targetVelocity);
            Vector2 collisionPoint = tp.add(tv);

            return sub(collisionPoint, turretPosition);
        }
        else
            return null; // This means the collision will never happen (or happened before the shot was fired, which is non-sensical).
    }

    private static void runSimulation(Vector2 targetPosition, Vector2 turretPosition, Vector2 targetVelocity, float bulletSpeed) {
        Vector2 direction = calculateFireDirection(targetPosition, turretPosition, targetVelocity, bulletSpeed);

        for(float t = 0; t < 10.0f; t += 0.1f) {
            Vector2 tsp = new Vector2(targetPosition);
            Vector2 tv = new Vector2(targetVelocity);

            Vector2 ssp = new Vector2(turretPosition);
            Vector2 sv = new Vector2(direction);

            Vector2 tp = tsp.add(tv.scl(t));
            Vector2 sp = ssp.add(sv.scl(t));

            float distance = sub(tp, sp).len();

            System.out.println(String.format("At time %.2f; Target=(%.2f, %.2f), Bullet=(%.2f, %.2f) distance=%.4f", t, tp.x, tp.y, sp.x, sp.y, distance));
            if (distance < 0.01f) {
                System.out.println("COLLISION!");
                break;
            }
        }
    }

    public static void main(String[] args) {

        // Input
        Vector2 targetPosition = new Vector2(1, 10);
        Vector2 targetVelocity = new Vector2(1, -1);

        Vector2 turretPosition = new Vector2(0, 0);
        float bulletSpeed = 10.0f;

        runSimulation(targetPosition, turretPosition, targetVelocity, bulletSpeed);
    }
}

```

Gives the output;

```
At time 0,00; Target=(1,00, 10,00), Bullet=(0,00, 0,00) distance=10,0499
At time 0,10; Target=(1,10, 9,90), Bullet=(0,20, 0,90) distance=9,0449
At time 0,20; Target=(1,20, 9,80), Bullet=(0,40, 1,80) distance=8,0399
At time 0,30; Target=(1,30, 9,70), Bullet=(0,60, 2,70) distance=7,0349
At time 0,40; Target=(1,40, 9,60), Bullet=(0,80, 3,60) distance=6,0299
At time 0,50; Target=(1,50, 9,50), Bullet=(1,00, 4,50) distance=5,0249
At time 0,60; Target=(1,60, 9,40), Bullet=(1,20, 5,40) distance=4,0199
At time 0,70; Target=(1,70, 9,30), Bullet=(1,40, 6,30) distance=3,0150
At time 0,80; Target=(1,80, 9,20), Bullet=(1,60, 7,20) distance=2,0100
At time 0,90; Target=(1,90, 9,10), Bullet=(1,80, 8,10) distance=1,0050
At time 1,00; Target=(2,00, 9,00), Bullet=(2,00, 9,00) distance=0,0000
COLLISION!

```

# Answer
> 1 votes
You're already part of the way there with recognising that your targets have a constant velocity - as well as the speed they are moving at, they're also moving in a specific direction (which is the difference between a speed and a velocity). If you know where the bullet is travelling (given its current location and velocity) you can calculate that after *x* time it'll be at a new location. Using a bit of basic maths with this, the position of the turret and the velocity of the bullets it fires, you can then calculate the position you want to be aiming at to hit after *x* time.

---
Tags: java, collision-prediction
---


title: using loop to detect collision in XNA

text:
# Question
Title: using loop to detect collision in XNA
Got a problem, with collision detection, I need to detect collision between bullets and meteors using nested loop for this, but it isn't working.

```
                            }
                }
                    check();
                    LoadMeteors();
        base.Update(gameTime);
    }

    public void LoadMeteors()
    {

        int randY = random.Next(100, 400);
        if (spawn >= 0.5)
        {
            spawn = 0;

                meteors.Add(new Meteor(Content.Load<Texture2D>("Backgrounds/meteori"), new Vector2(800, randY), new Rectangle(0,0,50,50)));
        }
    }

    public void SpawnBullet()
    {

        bullets.Add(new Bullet(Content.Load<Texture2D>("Backgrounds/pula"), new Vector2(rocket.rectangle.X + 20, rocket.rectangle.Y + 20), new Rectangle(0, 0, 10, 5)));
        soundEffect.Play();

    }
    public void check()
    {

        for (k = 0; k < bullets.Count; k++)
        {
            for (i = 0; i < meteors.Count; i++)
            {
                if (bullets[k].rectangle.Intersects(meteors[i].rectangle))
                {
                    meteors[i].isVisible = false;
                }
            }
        }
    }

```

that is my meteor class:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace Rocket
{
   class Meteor
 {
    public Texture2D texture;
    public Rectangle rectangle;
    public Vector2 position;
    public Vector2 velocity;

    public bool isVisible = true;

    Random random = new Random();
    int randX, randY;

    public Meteor(Texture2D newTexture, Vector2 newPosition, Rectangle newRectangle)
    {

        texture = newTexture;
        position = newPosition;
        rectangle = newRectangle;
        randY = random.Next(-4, 4);
        randX = random.Next(-4,-1);

        velocity = new Vector2(7, 0);
    }

   public void Update(GraphicsDevice graphics)
    {

        position -= velocity;
        if (position.X < 0 - texture.Width)
            isVisible = false;
    }
   public void Draw(SpriteBatch spriteBatch)
   {

       spriteBatch.Draw(texture, position, rectangle, Color.White);

   }

}
}

```

and that is my bullet class:

```
    using System;
   using System.Collections.Generic;
  using System.Linq;
  using Microsoft.Xna.Framework;
  using Microsoft.Xna.Framework.Audio;
  using Microsoft.Xna.Framework.Content;
  using Microsoft.Xna.Framework.GamerServices;
 using Microsoft.Xna.Framework.Input;
  using Microsoft.Xna.Framework.Media;

 namespace Rocket
{
class Bullet
{
    public Texture2D texture;
    public Rectangle rectangle;
    public Vector2 position;
    public Vector2 velocity;

    public bool isVisible = true;

    public Bullet(Texture2D newTexture, Vector2 newPosition, Rectangle newRectangle)
    {

        texture = newTexture;
        position = newPosition;
        rectangle = newRectangle;

        velocity = new Vector2(10, 0);
    }

    public void Update(GraphicsDevice graphics)
    {
       position += velocity;
               if (position.X < 0 - texture.Width)
            isVisible = false;
    }
   public void Draw(SpriteBatch spriteBatch)
   {
       spriteBatch.Draw(texture, position, rectangle, Color.Aqua);

   }
    }

```

so, I call function Check(): in update method, than in that function i check for collision, but it isn't detecting collision, also meteor and bullet classes, both have rectangle, I don't get any errors and it seems to be right, thanks for any help!

# Answer
> 1 votes
From your code:

```
for (k = 0; k < bullets.Count; k++)
{
    for (k = 0; k < meteors.Count; k++)
    {
        if (rocket.rectangle.Intersects(meteors[k].rectangle))
        {
            meteors[k].isVisible = false;
        }
    }
}

```

You use the same iterator in both for loops. It also looks as though you are reusing that (global) iterator from somewhere else in the code; Unless you have a very good reason for doing so, you should likely be using local iterators that are initialized in the for loop.

Ex. for(int i = 0; i \< 1000; i++)

A fix for this might be:

```
for (int iB = 0; iB < bullets.Count; iB++)
{
    for (int iM = 0; iM < meteors.Count; iM++)
    {
        if (rocket.rectangle.Intersects(meteors[iM].rectangle))
        {
            meteors[iM].isVisible = false;
        }
    }
}

```

But I don't know how you are specifying the location or bounding box of the actual bullets. At the moment it looks like the rocket.rectangle might be at a fixed location because you never update it's position in these loops.

# Answer
> 1 votes
Best thing you could do here, is just convert your Rectangle variables into a read-only property. This way you only need to update your position, and your Rectangle will always be up to date:

```
class Bullet {
    public Rectangle rectangle {
        get { return new Rectangle((int)position.X, (int)position.y, 10, 5); }
}

class Meteor {
    public Rectangle rectangle {
        get { return new Rectangle((int)position.X, (int)position.y, 50, 50); }
    }
}

```

Replace your "public Rectangle rectangle;" in both your Bullet and Meteor classes with the above Rectangle properties, and it should fix your issue.

# Answer
> 0 votes
Looks like you are only updating the position vector. When you are checking for intersection the rectangles haven't moved.

You could change the rectangles x,y values as well but you have to change your spriteBatch.Draw call and omit the position.

You might be tempted to skip the position vector entirely and only use the rectangles position. I don't think that's a good idea since (as far as I know) the rectangle members are of int type. You would get a very choppy movement or if the velocity is too small, it won't move at all.

# Answer
> 0 votes
I'm a VB person, so I don't know the C syntax, isn't there a **For Each** loop you can use instead of using your k variable? For each will loop all, it doesn't care how many.

---
Tags: xna, collision-detection
---


# Question
Title: How to make it clear that a game is in Beta?
I develop games on ROBLOX which is a site full of user-generated games that are typically free for other users to enjoy. Many users have studios in which they have a consistent set of playtesters, but I am the only developer in the case of my project. Nonetheless, I still have the need to test my game at times, so I recruit random people from the forums of the site (specifically the site's "Scripters forum"). While recruiting from the forums is a reliable and quick way to get players, it may be hard for them to get over the fact that the game is meant to be unfinished.

ROBLOX has a like and dislike system, and during testing I have already received three likes and *one dislike*. The dislike concerns me because I feel that someone probably evaluated my game on the notion of "This game should be working for me, but it's not." when those problems are the purpose of why I recruit people to go to the game in the first place. Many users even absurdly evaluated the game on its artistic value which I believe to be an afterthought in the game development process versus functionality which should be at its core.

**For the future, how do I make it clear that the current game should be evaluated for its functionality, and that in the beta phase, it may or may not work for all users?**

Side note: I do some preliminary testing before I recruit testers to the game, so it works at the very least on my device, but their own experience varies based upon their quality of connection and device.

# Answer
There's a lot of ways to do that.

* Change the title so that it gently says **BETA**
* Put a nice popup or message at the very start saying that this isn't the final version and will be changed, or anything like that.
* Watermark a corner of the window with the message "beta version"
> 4 votes

---
Tags: user-experience, playtesting, beta
---


# Question
Title: Games where the story continues via progeny
In Phantasy Star III: Generations of Doom for the Sega Genesis you periodically marry and then the story carries on through your sons/daughters. In Rogue Legacy when you die you again play on through your decendents (IIRC).

I am working on an RPG and am thinking about a similar concept for a death mechanic. I want dying to cause some of your loot/skills to pass on to your progeny, who can then pick up where you left off (more or less). What are some potential design pitfalls in implementing such a mechanic? One that I already see is that if I make it too punishing, players will revert to last save, not punishing enough and they'll die on purpose.

Bonus points for referencing existing games (other than the two I mentioned).

# Answer
> 13 votes
One option is to simply make dying inevitable in the long run. Let's take Crusader Kings 2, for example. This is kind of a strategy game (the genre is hard to define) which takes place over several hundred years, so your character dying of old age (or sickness, assassination, in battle etc.) and getting replaced with their heir is a regular event in the game. When the player-character dies unintentionally, the player will often say "well, this was bound to happen sooner or later" and continue on with the next heir. A strategic suicide can be beneficial in some situations, but it can be quite difficult to do that, so most players won't bother unless they have a very good reason (like being stuck with a character with abysmal stats and traits).

Conclusion: Make it hard to die intentionally but inevitable to die in the long run, and the player will accept it when it happens.

Another way to make people treat the progeny system as more than just a cheap respawn system is to make sure that each consecutive character looks and plays different than the previous one. By giving the player customization options (but not enough to make them perfect clones of their parent), you can increase the emotional bond to each character and thus make the player reluctant to kill them off needlessly. By making them play different, the player will be compensated for the emotional loss by a new and fresh game experience, so their grief won't be as long.

When your game is story-heavy, you can also force the player to continue on with their next character by killing off their current character if and only if they reach a certain point in the story. When you want to have a plausible and coherent story spanning multiple decades, you will likely have to do this once in a while to skip time. The downside is that you will then have a fixed number of generations per playthrough and must make sure that every new character is properly balanced and playable for the next chapter of the story, so you might lose a lot of potential a progenicy system can offer. A mild example for this is Final Fantasy V where one character of the player's party dies in the course of the story and gets immediately replaced by his granddaughter. However, she inherits his whole character progression and is also otherwise almost mechanically identical to him, so the gameplay effect of this is practically zero.

And then there is the most extreme method to avoid savegame abuse: The roguelike concept. Don't have savegames. Save automatically when quitting but don't allow the player to make selective savegames. That way they are *forced* to accept the death of their character and continue with their heir.

# Answer
> 11 votes
I think one important consideration whenever you incorporate a real-world phenomenon into your game - especially one with huge social implications like family & inheritance - is that **the mechanics you author articulate an opinion of what this phenomenon is, should be, or means**. And how that opinion is read or understood can hinge on cultural factors outside of your direct control.

Rogue Legacy serves as a great example with the fact that your descendants' sexuality is randomly determined.

Since it was released in a time & place where gay rights and even the idea that someone can "be" gay as an innate trait rather than choose to "do" gay(?) are still the subject of some controversy, this drove some strong reactions toward the game.

* In one view, the game was making a strong affirming statement: people can just *be* gay, and they can still be heroes and have families. (From my own perspective as a gay player and game designer, I was very happy to see this. It's rare I get to play a gay character who's not just there to be "THE gay character")
* In another view, the "Gay" trait is doled-out by the same system that gives characters disabilities (and super-abilities, mind you), leading some players to perceive that the game was classifying homosexuality as an illness. (This interpretation's implicit medical model of disability as a negative to be cured is a whole other topic I won't get into right now...)
* The choice to include homosexuality but exclude (or not explicitly mention) bisexuality, pansexuality, asexuality, or other sexualities and gender identities can be read as a value judgement about which identities are real & important.

So the reading of this particular choice in the cultural context the game released into created multiple divergent meanings, which were not all what the creators intended.

There are a lot of sensitive topics that family lines touch, and whether your game implements them or not, and how, can send a powerful message:

* nature vs nurture (Can the apple fall far from the tree?)
* do "the sins of the father" carry down to their children?
* if descendants can have strongly different appearance than their parents (or can't), does this say something about adoption or mixed-race families?
* inheritance - who gets selected as a potential heir? Who doesn't?
* birthright/nepotism - does your heir accrue titles, power, or privilege granted to their ancestors, or do they have to work their way up from zero?
* eugenics - can the player pick and choose partners/offspring to breed a "super-character"?

This isn't an argument against including real-world phenomena with social & cultural connections in your game. It just means that you need to be very conscious of the choices you're making, to ensure they give rise to the meanings you want in your game.

# Answer
> 1 votes
You can use the "legacy" feature to **offer diversity to the game**.

* *Digimon World* is a game where you train/raise a digimon that can evolve, a little like in the Gameboy Pokemon game. Your digimon may die from being old and defeated (although death by fight is not automatic if I remember well). When it dies, you can pick its egg which is a baby digimon that has inherited **some** of the parent's skills. This new Digimon can however evolve in a different way that its parent, thus accumulating **some** of the parent's skills/abilities **plus** his own, which are specific to its training or evolution forms.
* *Spore* is a game where you make slowly evolve your creature from the bacterial state to the "specie able to travel through galaxies" state. Before the "tribe" age, everytime the specie dies you can customize the way the newborn members of the specie look, using the "genes" that the parent has found by having a contact (good or bad, ie. fight or cohabitation) with different species (maybe from the biological point of view, this phenomenon explained by acquiring the gene by some members of your specy procreating with some of the other). These customizations are often usefull (wings, better vision, spikes, more attractiveness...)

If you **combine** the two solutions and adapt it to your scenario, you may end-up with "one kind of cool customization material" that you cannot use as the parent but can be used for the children. The counterpart, is that you may loose some skill/abilities, but (new or previous) skills/abilities can be slowly discovered later without needing to die. Both the skill/abilities and "customization material" should be usefull, but cover different aspects of the game.

Cheap example : you may transmit passive or native spells or mutations to your children, but loose some of the active spells the parent has learnt.

# Answer
> 0 votes
Star Citizen is an upcoming MMO game which will supposedly include character permadeath. Although the medical technology is supposedly at a point that they can resurrect someone who'd be dead by today's standards, eventually a character will die a final death and your possessions are inherited by your next character.

There's talk of the character creation being done at your previous character's funeral, and the possessions being subject to inheritance tax. Maybe you don't have enough money to pay the tax on all of your old character's best ships, so you need to unlock one and do some work to unlock the others?

See: https://robertsspaceindustries.com/comm-link/engineering/12879-Death-Of-A-Spaceman

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


title: MonoGame, sprite to rectangle

text:
# Question
Title: MonoGame, sprite to rectangle
I'm working with MonoGame in VB2015 - please don't give answers that involve using C#.

Anyway, I found a snippet which I converted to VB for pixel collision. The function below accepts two rectangles, then runs a pixel check on the intersection between the two.

What I can't work out is how to send my two sprites (textures) to the function as rectangles. Or if anyone has a alternative, please let me know.

```
  Private Shared Function IntersectPixels(rectangleA As Rectangle, dataA As Color(), rectangleB As Rectangle, dataB As Color()) As Boolean
    ' Find the bounds of the rectangle intersection
    Dim top As Integer = Math.Max(rectangleA.Top, rectangleB.Top)
    Dim bottom As Integer = Math.Min(rectangleA.Bottom, rectangleB.Bottom)
    Dim left As Integer = Math.Max(rectangleA.Left, rectangleB.Left)
    Dim right As Integer = Math.Min(rectangleA.Right, rectangleB.Right)

```

(No, this isn't the whole routine...)

# Answer
You would need to convert your texture into a rectangle, which is just a position and size.

Your entity that is displaying the texture, should have the position, and the texture itself could potentially hold the size (this is completely dependent on how you are currently doing your spritebatch draw calls).

It would end up looking something like:

```
Dim textureRect as Rectangle = new Rectangle(CType(position.x, integer), CType(position.x, integer), texture.Width, texture.Height);

```

If not, can you provide more information about the object that you are trying to create this rectangle from.
> 1 votes

---
Tags: collision-detection, textures, monogame, pixel
---


# Question
Title: How to apply friction vector to acceleration in top-down 2D game?
I'm making a top-down view 2D RPG game, meaning the player can move in any direction on a 2D plane, and I'm trying to implement a somewhat realistic non-orthogonal acceleration/friction physics model for movement.

For instance, if the player's acceleration value is "100", holding the right arrow key will change the player's "input force" vector to (100, 0). If holding both `right` \+ `down`, the force will be roughly
(71, 71) since 712 \+ 712 ≈ 1002. This part is working correctly right now.

The function I'm currently using to update the position looks something like this (Note: I'm not a physics expert):

```
void GameEntity::updateSpritePos( const float timeStep )
{
  // Store old velocity.
  const Vec2D<float> curVel( m_v2Velocity );

  // Get force.
  Vec2D<float> force( m_v2InputForce );

  // Calculate friction.
  Vec2D<float> friction;
  if( curVel.getLength() < m_fFriction * timeStep ) // Make sure the friction doesn't overextend.
    friction = ( -curVel / timeStep );
  else
    friction = -curVel.getNormalized() * m_fFriction; // getNormalized() returns the unit vector.

  // Apply friction.
  force += friction;

  // Calculate acceleration.
  const Vec2D<float> accel( force ); // Since we're not taking mass into account, acceleration = resultant force.

  // Calculate new velocity based on acceleration.
  const Vec2D<float> newVel( curVel + ( accel * timeStep ) );

  // Calculate how much to move using "improved Euler" integration.
  const Vec2D<float> avgVel( ( curVel + newVel ) * 0.5f );
  const Vec2D<float> moveAmount( avgVel * timeStep );

  // Update variables.
  m_c2Position += moveAmount;
  m_v2Velocity = newVel;
  m_v2LastMoved = moveAmount; // Storing this for collision resolution.
}

```

Where `m_fFriction` is a constant float value that can be anywhere above 0.

**The problem** is the way that friction is being applied: If walking in a given direction and then simply letting go of the key, you will glide for the appropriate distance.

But if letting go of the key while also accelerating in a perpendicular direction at the same time, you will glide much further in the original direction. This is not the behavior I want, I want the player to always glide the same distance.

Since I'm currently doing this:

```
friction = -curVel.getNormalized() * m_fFriction;

```

Friction will always be applied in the opposite direction of the current velocity. I'm not sure if this is correct.

I could solve it by doing something like this:

```
if( curVel.x > 0.0f )
    friction.x = -m_fFriction;
else if( curVel.x < 0.0f )
    friction.x = m_fFriction;

if( curVel.y > 0.0f )
    friction.y = -m_fFriction;
else if( curVel.y < 0.0f )
    friction.y = m_fFriction;

```

But then it doesn't work right when walking in a non-orthogonal direction (i.e. diagonally). This is especially bad since I also want to implement joystick support in the future where the force will be applied in the exact direction you're holding the stick.

Is there an easy way to fix this that I have overlooked, or am I getting into deep water here?

**Note:** I don't want to change my code to use a fixed `timestep` for a number of reasons, and I don't want to use damping (e.g. vel \*= 0.99timeStep) since this doesn't create linear deceleration (unless there's a way to make it do that).

# Answer
> 4 votes
To be physical, you need to calculate friction based on the magnitude of your velocity. You can simply remove the if checks when calculating friction and store a "friction constant" instead of a "friction force." You are already essentially doing this because `m_fFriction` is a double and not a vector, you are just thinking about it wrong. The friction constant can be any positive float and is how physicists think about friction anyway. You would then replace

```
Vec2D<float> friction;
if( curVel.getLength() < m_fFriction * timeStep ) // Make sure the friction doesn't overextend.
  friction = ( -curVel / timeStep );
else
  friction = -curVel.getNormalized() * m_fFriction; // getNormalized() returns the unit vector.

```

with

```
Vec2D<float> friction = -curVel * m_fFriction;

```

and continue on like you do for the rest of the function. The friction force is ALWAYS in the opposite direction of velocity, so this is physically accurate.

# Answer
> 0 votes
It looks like you're using acceleration in a weird way in your engine, so I can't give you a 100% fool-proof answer you can directly implement into your code, but I can take a shot at it.

You'd want to apply your friction to your current speed, not your characters acceleration. Try to change your code to this instead:

```
if( curVel.x > 0.0f )
    curVel.x -= m_fFriction;
else if( curVel.x < 0.0f )
    curVel.x += m_fFriction;

if( curVel.y > 0.0f )
    curVel.y -= m_fFriction;
else if( curVel.y < 0.0f )
    curVel.y += m_fFriction;

```

Now as I said previously I'm not sure how your physics engine works, but if you want it to work according to real-world physics the basic structure should be something like this (java pseudo code, but you should get the gist):

```
Vector2 acceleration = new Vector2(0, 0); //Create a new vector to hold acc.
acceleration.x = (object.mass^-1)*(forceDueToInput.x - forceDueToFriction + otherForcesDueToStuff.x) + gravity.x;
//This equation is the same as dividing all those forces by object.mass.
acceleration.y = (object.mass^-1)*(forceDueToInput.y - forceDueToFriction + otherForcesDueToStuff.y) + gravity.y;
//Same as above but for y axis.
//If you have unspecified mass in your game, just use object.mass = 1.

```

and then of course you can calculate speed using this acceleration.

```
Vector2 speed = new Vector2(0, 0);
speed.x += deltaTime * acceleration.x;
speed.y += deltaTime * acceleration.y;
//deltaTime = amount of time the object has traveled since last calculation.
//If you're not using real-time ticks you can leave this as 1;

```

If you want to use a joystick you can calculate what the x and y composants of your force should be by doing this:

```
Vector2 force = new Vector2(0, 0);
force.x = forceDueToInput * cos(alpha);
force.y = forceDueToInput * sin(alpha);
//alpha = the angle of your force in degrees.

```

Hopefully this helps at least a little bit. Feel free to comment if you want additional details about anything or you don't understand.

---
Tags: c++, 2d, physics, movement, vector
---


title: Most optimal way to load 2D world

text:
# Question
Title: Most optimal way to load 2D world
I am creating a 2D car racing game. (Yes, a Hill Climb Racing clone)

What I am doing right now is load 10% of the map every time the user gets to 7%. For example:

Imagine the map has 10km. (10000m)

When the game starts, the game loads the road from -100m to 1000m.

When the user gets to the 700m (7%) mark, the game deletes 0-500m and loads 1000m to 2000m (10%) (Having loaded from 500m to 2000m).

This will happen every 1000m from now on (1700m, 2700m, 3700m).

I used to create the whole world, and with this new method, I increased my mobile phone fps from 32-34 to stable 60 fps. BUT, every time the user is in the 700m mark, the game freezes for 0.55-0.60 seconds. (When I load/delete the new road).

Is there a better way (In terms of FPS (Performance)) to load the world?

# Answer
> 2 votes
You can find all what you need here Tile maps class, and read the section Rendering Tiled Maps

according to Libgdx docs:

> Performance considerations
>
> While we try to make the renderers as fast as possible, there are a few things you can consider to boost rendering performance.
>
> Only use tiles from a single tile set in a layer. This will reduce texture binding. Mark tiles that do not need blending as opaque. At the moment you can only do this programmatically, we will provide ways to do it in the editor or automatically. Do not go overboard with the number of layers.

# Answer
> 3 votes
I don't think you can fix that "loading" issue, if your game has to open a file from HDD, load the content, parse it and draw it there's nothing to do that could speed it up. I would say that, the best you can do is store the whole map in memory and get chunks more often, like 100m sou you should be able to high speed reading from ram and the lag would disappear, and the chunk would be shorter than now, so the transference time would decrease.

Anyways, Why not procedural generation?

# Answer
> 1 votes
I reccomend you delete and load smaller pieces (~50m) at a time to keep a more stable (if not lower) fps.

---
Tags: java, libgdx, box2d, performance, world-design
---


# Question
Title: Anchoring a sprite to a specific x & y on another, regardless of rotation [Gamemaker]
I have a sprite, `sDetritus`, with a corresponding object, `oDetritus`, and an `sTurret` and `oTurret`.

If I apply no rotation (i.e. changing the image\_angle) to `oDetritus`, I can anchor the `oTurret` to a specific position on the ODetritus, using its sprite as a guideline. In this case, the desired x and y for the `oTurret`, in relation to the `oDetritus`'s x and y origin, are *x - 37* and *y + 192*.

I can make the `oDetritus` the `Owner` of the `oTurret`, and make sure that the `oTurret` 'sticks' with the following in its Step event:

```
if instance_exists(Owner) {
x = Owner.x - 37
y = Owner.y + 192
}

```

However, how would I adjust this to account for rotating the image\_angle of the `oDetritus` object underneath? Obviously then the x and y values would be wrong. I have tried using `lengthdir_x` and `lengthdir_y`, but this doesn't seem to be the correct function here.

# Answer
This is classic rotation of a vector. You have your offset vector (-37, 192) which you need to rotate.

```
xoffset = -37;
yoffset = 192;

rotatedxoffset = xoffset * cos(angle) - yoffset * sin(angle);
rotatedyoffset = xoffset * sin(angle) + yoffset * cos(angle);

x = Owner.x + rotatedxoffset;
y = Owner.y + rotatedyoffset;

```

If you are interested in learning why this is the case, you can learn about matrices and 2d transformations.
> 2 votes

---
Tags: coordinates, game-maker
---


title: Java map generation

text:
# Question
Title: Java map generation
What is better way of setting up a map for a java 2D topdown game? Would it be having an ArrayList of tiles, a simple 2D array, a HashMap? (Note: the tiles/blocks or whatever are squared)

# Answer
It depends on what you need to store. If you just want the positions of the tiles, a 2D array is probably the easiest way to store it (unless you have a dynamic world size). If you want the connections (for movement costs, etc.) then a Graph is probably what you want to use.
> 2 votes

# Answer
Usually a single one dimensional array would work fine, just remember that, to get the tile you want you have to use the formula tile\[x +(y\*tiles\_in\_row)\]
> 1 votes

---
Tags: java
---


title: Rotating the playing field. (MonoGame)

text:
# Question
Title: Rotating the playing field. (MonoGame)
My maths isn't as good as it should be, I need to pick up some reference books on Trig.

Could someone give me an idea of the maths if I wanted to revolve many sprites around a central point?

It's a 2D system in MonoGame.

I'm going to try to describe the scenario, I can't think of anything quite like it to reference.

Imagine a game screen, you are looking down on the world, with my character in the middle, my character sprite will never change, but if I turn left or right I want everything else to rotate around the central point. Of course every sprite will have to be moved, and also rotate to account for the spin.

Can someone point me in the right direction? Thanks.

# Answer
> 0 votes
I recall an Amiga game Rotox based on that principle.

To rotate easily look into Vector2.Transform(). You can feed it a matrix such as Rotation and translation matrices.

```
point = Vector2.Transform(point, Matrix.CreateRotationZ(AngleToRotate);
point += originPoint;

```

---
Tags: rotation
---


# Question
Title: How should I rotate vertices around the origin on the CPU?
I have tried using glm::rotate and such. glm::translate works fine, but rotate doesn't work (if I rotate before/after a translation).

Here is my current setup:

```
glm::vec4 Off = glm::vec4(0, 0, 0, 1);
glm::vec4 result = Util::createTransform(offset) * Off;

for (int i = 0; i < Tvertex.size(); i++) {
    Tvertex[i] += glm::vec3(result.x, result.y, result.z);
    Tcolors[i] = currentColor;
}

```

And here is my Util::createTransform:

```
glm::mat4 Util::createTransform(glm::vec3 pos) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::translate(trans, pos);
    return trans;
}

glm::mat4 Util::createTransform(glm::vec3 pos, glm::vec3 rot) {
    glm::mat4 trans = glm::mat4(1.0);
    trans = glm::rotate(trans, glm::radians(rot.x), glm::vec3(1, 0, 0));
    trans = glm::rotate(trans, glm::radians(rot.y), glm::vec3(0, 1, 0));
    trans = glm::rotate(trans, glm::radians(rot.z), glm::vec3(0, 0, 1));
    trans = glm::translate(trans, pos);
    return trans;
}

```

# Answer
It's unclear where your issue lies.

To rotate a vector about the origin, you create a rotation matrix, and then you multiply the vertex by the matrix. In order to create the rotation matrix, you need a rotation axis and an angle.

With glm, you can do it this way:

```
glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f ); // Rotate about z+
float angleRad = glm::half_pi<float>(); // Rotate of a quarter of a turn
glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );

```

Alternatively, you can use a quaternion:

```
glm::quat quatRot = glm::angleAxis( angleRad, v3RotAxis );
glm::mat4x4 matRot = glm::mat4_cast( quatRot );

```

To apply this to a vertex (a point in space), you would then do:

```
glm::vec4 out = matRot * v4In;

```

If you need to rotate about a point that is not the origin, you have to

1. translate the pointToRotate to the origin
2. perform the rotation
3. translate back the point to the original location

To achieve that, you create a translation matrix, and an inverse of that translation. You then 'sandwich' the rotation matrix in-between these other two:

```
glm::vec4
rotateAround(
  glm::vec4 aPointToRotate,
  glm::vec4 aRotationCenter,
  glm::mat4x4 aRotationMatrix )
{
  glm::mat4x4 translate =
    glm::translate(
      glm::mat4(),
      glm::vec3( aRotationCenter.x, aRotationCenter.y, aRotationCenter.z ) );
  glm::mat4x4 invTranslate = glm::inverse( translate );

  // The idea:
  // 1) Translate the object to the center
  // 2) Make the rotation
  // 3) Translate the object back to its original location

  glm::mat4x4 transform = translate * aRotationMatrix * invTranslate;

  return transform * aPointToRotate;
}

```

**Keep in mind that with all the operations done with matrices, the order is important.**

I join the whole test program if you want to play with stuff.

```
#include <iostream>

#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/transform.hpp>

glm::vec4
rotateAround(
  const glm::vec4&   aPointToRotate,
  const glm::vec4&   aRotationCenter,
  const glm::mat4x4& aRotationMatrix )
{
  glm::mat4x4 translate =
    glm::translate(
      glm::mat4(),
      glm::vec3( aRotationCenter.x, aRotationCenter.y, aRotationCenter.z ) );
  glm::mat4x4 invTranslate = glm::inverse( translate );

  // The idea:
  // 1) Translate the object to the center
  // 2) Make the rotation
  // 3) Translate the object back to its original location

  glm::mat4x4 transform = translate * aRotationMatrix * invTranslate;

  return transform * aPointToRotate;
}

int main( void )
{
  {
    glm::vec4 v4In( 2.0f, 0.0f, 0.0f, 1.0f );
    glm::vec4 v4RotCenter( 1.0f, 0.0f, 0.0f, 1.0f );
    glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f );
    float angleRad = glm::half_pi<float>();
    glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );
    glm::vec4 out = rotateAround( v4In, v4RotCenter, matRot );
    std::cout << out.x << " " << out.y << " " << out.z << " " << out.w << " " <<std::endl;
  }

  {
    glm::vec4 v4In( 2.0f, 0.0f, 0.0f, 1.0f );
    glm::vec3 v3RotAxis( 0.0f, 0.0f, 1.0f );
    float angleRad = glm::half_pi<float>();
    glm::mat4x4 matRot = glm::rotate( angleRad, v3RotAxis );
    glm::vec4 out = matRot * v4In;
    std::cout << out.x << " " << out.y << " " << out.z << " " << out.w << " " <<std::endl;
  }
  return 0;
}

```
> 2 votes

---
Tags: c++, rotation, glm
---


# Question
Title: Different physics engines on the client and server sides
I am developing a 2D multiplayer game as follow:

* semi-authoritative server
* handle up to 40 players per game.
* Players and other game objects will interact/collide with each other
* Physics like bouncing are required

Technologies I am planning to use:

* Clien: unity3D (easy to develop + cross-platform)
* Server: node.js + socket.io (easy to deploy and cheap to host)

Considering that most networking solutions for Unity3D are expensive and not suitable for small games/projects and UNET still under development...

By using a different physics engine on the server side like matter.js \+ node.js:

1- Would it affect the gameplay and the game objects synchronization?
2- Would it be impossible or very hard to provide a smooth physics experience to the player?
3- Is there any other issue I should expected to deal with?
4- Is it a bad idea?

Any peace of information will be well appreciated. tks

# Answer
When you use two different physics engines, it will be almost impossible that they will always come to the exact same results. Large physics systems can behave quite chaotically (small changes in variables create drastically different outcomes). So considerable desynchronization will become inevitable.

The most obvious solution would be to keep the physics completely under the authority of the server: Nothing moves until the server says it does. But that will affect the game experience negatively because players will notice the lag. So you will have to use the client-sided physics engine to estimate what the server-sided physics-engine will do and then correct any differences as soon as possible.

You could have the server send the physics-state of all game-objects to the client at regular intervals and then have the client correct all physical attributes as soon as they receive them. How well this works will depend on your game (how much physics interaction you have and how chaotic it will be) and how well you can get the two physics engines to behave nearly the same.
> 5 votes

---
Tags: unity, multiplayer, node.js
---


# Question
Title: C++ Multi-Platform (Windows, Linux, Android) OpenGL(ES) Solutions or Tutorials?
I'm sorry if this has been asked recently and I'm not Googling it right, but I've been digging all week for something.

I've got a game prototype I made in Unity, and I have some decent experience with SDL (1.2 I believe, but the 2.0 stuff is familiar) so I thought I'd take a crack at SDL 2.x + OpenGL while I've got a simple "sprite" based game that could take advantage of some of the blending features OpenGL offers, if nothing else but to practice with it so I'll be more prepared when trying to make a 3D game down the road. Honestly I'd probably be half done with it by now if multi-platform wasn't an issue.

I really want to put this game on Android, I think it's perfect as a mobile app. But nearly every tutorial I can find on SDL+OpenGL seems to include something like GLEW or freeglut or bucks SDL altogether for something like GLFW (which I actually kind of liked). All of these seem like great tools, but they typically don't have much in the way of tutorials or guides on how to get things over to the mobile side... and I'm not quite at the level where I know anything about porting these kinds of tools to Android unless it's a pre-existing build, honestly I don't really feel confident even building development libraries for Windows.

So I'm in some serious need of somebody who maybe has experience with at least Windows+Android or Linux+Android multiplatform development or can at least point me in the right direction for a tutorial/guide/tool/idc that can better explain the porting or cross-development from desktop to Android. Honestly I'd probably even shell out for a good book recommendation or fairly priced paid utility at this point. Heck, I'd probably try a Python or Lua type scripting solution (like that could bind to C/C++ and Java) if it's viable, my only problem there is a limited knowledge of embedding scripting languages into native code.

To clarify: I'm well aware there's not really a write once, deploy everywhere solution for native code like C++. What I'm looking for is some sort of reference how to handle- at least -one of these desktop platforms and Android in OpenGL, whatever windowing/input/etc. tool can be layered with it in a semi-platform independent way. Because, to me at least, it seems to be well under documented or my wheelhouse of SDL experience is crippling me from actually taking advantage of OpenGL and learning it properly.

Thanks for any help you can give, cheers~!

# Answer
> 0 votes
This is a very broad question. I'm assuming you have seen the answer from Kieran Chandler about platform abstraction.

You've mentioned the SDL Library that you want to use. I've used it myself for such a OpenGL cross-platform project. The library provides most of the platform abstraction. Use its functions for all input and output, like accessing files, getting user input and displaying. It provides build files for all the mentioned platforms. Start there with a minimal app, just some 2d graphic output and try to build it on android. Since SDL itself and your code are written in C++, you'll need the Android NDK to compile it. The documentation is sparse, the basic steps are:

1. Write Android.mk build files
2. Compile them with ndk-build

There are some tutorials on this, i.e. here: http://www.dinomage.com/2013/01/howto-sdl-on-android/ Some things may be outdated, and you'll need to put some work into getting it right.

After you have managed to build a minimal example application for all platforms, add OpenGL. SDL has calls to create an OpenGL window for you, after that you are on your own. I have used OpenGL 2.1 for the desktop, and OpenGL ES 2.0 for Android. For Android, I included "SDL\_opengles2.h" and GLES2/gl2.h. For Windows, I used the OpenGL Loader generator (glLoadGen) to create header files for me and included those.

Most calls were the same on mobile and desktop, only some parts needed #ifdefs to differentiate the platforms, for example:

```
#ifdef ANDROID
    glClearDepthf(1.0f);                     //Depth Buffer Setup
#else
    glClearDepth(1.0f);                     //Depth Buffer Setup
#endif

```

I hope this helped so far.

Some of my code can be found here in case you want to take a look: https://github.com/tm4n/t3d Look especially at the gameRenderer.cpp file. Build files for android are unfortunately missing in the repository. Note that this is not a finished engine and the code is not very well structured and documented, but it works on all three platforms.

# Answer
> -1 votes
It doesn't sound like you are ready to take on a large task like this. You need to learn about the underlying concepts and make some smaller projects before you can really move on to making a cross-platform game.

The main point to make about cross-platform games is that you need to have a "Platform Abstraction Layer" which will allow your game to perform tasks without knowing what platform it is running on or knowing anything about the platform. the STL library can do most of this for you, but you'll find that things like the game loop and window creation may need to be handled differently for your different platforms

Simply googling: platform abstraction

should yield sufficient results to get you started, but you will need to have experience in low-level programming, possibly with the Win32 API.

Hope this helps

---
Tags: opengl, c++, android, windows, linux
---


# Question
Title: Faking a 3D object to decrease number of polygons
I'm making a game in unity and I'm building a fence in blender but I want it to be as low poly as possible. My original design was too high poly so I thought, what if I could simply use a cube with some cleverly arranged textures. Like so:

You can see the edges are all looking good but the inside sections are not, i.e there's nothing there... so does anyone know if it's possible to fake those faces that would make it look as though it were a complete mesh. Here's what I'm tring to achieve:

# Answer
If I understand correctly what you want to achieve, you are looking for the concept of "imposters". These are precisely 2D representations of 3D objects, used to decrease the geometric complexity of rendering the 3D environment.

You can think of them pretty much as pictures of the 3D objects that are used as textures of 2D objects. The canonical reference for those is probably the chapter 21 of the book GPU Gems 3, called "True Impostors". It's publicly available here. Another important reference is the chapter 5.7 of the book Game Programming Gems v.2, called "Imposters: Adding Clutter”, in Game Programming Gems 2, Tom Forsyth".

And they can evenly be generated on the fly, to deal with small changes in view-angle or with run-time generated content. Take a look at the great Gamasutra article on the topic, called "Dynamic 2D Imposters: A Simple, Efficient DirectX 9 Implementation". A further development of the concept has appeared at "Billboard Clouds for Extreme Model Simplification".

For a gentle great explanation of the concept, see this blog entry: http://blog.wolfire.com/2010/10/Imposters

Lastly, as you are using Unity, I've heard of a plugin that automatizes such process. It is called Real Imposters LOD System.

UPDATE: for the sake of completion, I thought of adding two things that I remembered of recently. First is: there is a great GDC video where SimCity's art director explains how they have made (heavy) use of imposters to achieve top-notch graphical achievements of that game: "GDC - Building SimCity: Art in the Service of Simulation".. Second, for those interested in Unreal Engine, it has a built-in feature to implement imposters, as can be seen in docs
> 26 votes

# Answer
If you don't need any interaction thought the fence, I mean, by the gaps, I would use a simple transparent rectangle with a texture printed.
> 0 votes

---
Tags: unity, blender, low-poly
---


# Question
Title: OpenGL/GLSL matrix in uniform block confusion
I'm a bit confused about the proper way to send a matrix from my code (C++) into a GLSL shader. My matrix object is stored in row major format in memory. If I use the following shader code it works ok.

```
#version 400 core

layout(location=0) in vec2 VertexPosition;

uniform vec3        VertexColor;
uniform mat3 rotation;

layout(location=0) out vec3 VertexOutputColor;

void main() {
    const vec3 tf_pos = rotation * vec3(VertexPosition, 1.0f);
    gl_Position = vec4(tf_pos, 1.0f);
    VertexOutputColor = VertexColor;
}

```

I set the value from my application like this : glUniformMat3fv(location, 1, GL\_TRUE, (const float\*) &matrix);

However, if I put the matrix in a uniform block like this :

```
#version 400 core

layout(location=0) in vec2 VertexPosition;

uniform vec3        VertexColor;

layout(binding = 0) uniform transforms {
    mat3 rotation;
};

layout(location=0) out vec3 VertexOutputColor;

void main() {
    const vec3 tf_pos = rotation * vec3(VertexPosition, 1.0f);

    gl_Position = vec4(tf_pos, 1.0f);
    VertexOutputColor = VertexColor;
}

```

I get garbage output. For this, I create a uniform buffer object, I allocate a block of memory where I copy the matrix data, then when I draw the object I map the buffer with glMapBufferRange and memcpy the data from the memory block to the pointer returned by glMapBufferRange. I'm probably doing something wrong, but I cannot figure out what.

# Answer
> 0 votes
Ok, I've finally figured it out. After some digging through the OpenGL 4.4 Core Specification, I found this paragraph regarding glGetProgramResourceiv :

*For the property MATRIX\_STRIDE, a single integer identifying the stride between columns of a column-major matrix or rows of a row-major matrix is written to params. For active variables declared a single matrix or array of matrices, the value written is the difference, in basic machine units, between the offsets of consecutive columns or rows in each matrix. For active variables not declared as a matrix or array of matrices, zero is written to params. For active variables not backed by a buffer object, -1 is written to params, regardless of the variable type.*

My code was not accounting for this stride between the columns/rows of the matrix. So basically the data needs to be laid like this in memory, before uploading it to the GPU :

```
const auto m = R3::rotation_z(radians(35.0f));

const float mtx_data[] = {
  m.a00, m.a01, m.a02, 0, // pad to stride of 16 bytes
  m.a10, m.a11, m.a12, 0, // pad to stride of 16 bytes
  m.a20, m.a21, m.a22, 0 // pad to stride of 16 bytes
};

auto ptr = glMapBufferRange(...);
memcpy(ptr, mtx_data, sizeof(mtx_data));

```

Now it works as expected.

---
Tags: opengl, glsl
---


# Question
Title: Is there a 3D format that supports instanced components?
I am looking for a 3D file format that supports instanced components/objects. That is, there is one geometry declaration and then it is instanced in numerous places. Open formats are very much preferred.

# Answer
> 2 votes
Collada (.dae) files seem to have support, according to 5-51 in the 1.4 specification:

> The `<instance_geometry>` element instantiates an object described by a `<geometry>` element.

Collada is supported by most platforms.

---
Tags: 3d, 3d-modeling
---


# Question
Title: Sprite Animation in XAML/C# for Windows 8 Modern UI (Metro)
I'm working on a project that requires doing sprite based animation in XAML / C# for a windows store app. I've worked out a method for displaying the animation, but it causes flickering during the initial load of the images. The method I used basically involves creating a class which subclasses canvas that loops through all children during the its CompositionTarget.Rendering event. If any of the child objects are of type SpriteImage (another class I created that subclasses content control and is a container for the image control that displays the current frame) it calls the update method so that the SpriteImage may display the appropriate bitmap image for the current frame.

I have shared the sample project at the following link: Sample Sprite Animation Project for VS 2012 and Windows 8.

It seems that after the animation has completed one iteration and all of the BitmapImages have been loaded from the source URIs, the animation runs smoothly. I suspect that the BitmapImage is not loaded until the Image who is using it for the source is loaded.

So I was hoping to get two things from the community:

Anyone have any good ideas on how I can use preload those images so that the flicker does not happen?

Anyone have any good ideas on how to get these into a sprite sheet so that I do not have to have use separate files? I haven't found a good way to do it with Win8 XAML / C#.

Any help is greatly appreciated.

# Answer
The flickering problem is because BitmapImage does not load the image really until it's shown.

Consider using WriteableBitmaps instead of BitmapImages and Invalidate() them after setting the Source to ensure it's loaded.
> 1 votes

# Answer
You can use a usercontrol with only 1 canvas inside; in the constructor, you can load all images in a list, and use it to animate your image

```
public sealed partial class sampleSprite : UserControl
{
    List<ImageSource> ImageSources;
    private DispatcherTimer timerLoop;
    int imageIndex;
    public sampleSprite()
    {
        this.InitializeComponent();
        ImageSources = new List<ImageSource>();
        ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/TilePart1.png")));
        ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/TilePart2.png")));
        timerLoop = new DispatcherTimer();
        timerLoop.Interval = TimeSpan.FromMilliseconds(10);
        timerLoop.Tick += timerLoop_Tick;
    }

    protected void timerLoop_Tick(object sender, object e)
    {
        CanvasRoot.Background=new ImageBrush() { ImageSource = ImageSources[imageIndex]};
        imageIndex = (++imageIndex)% ImageSources.Count;
    }

    public void StartAnimation()
    {
        timerLoop.Start();
    }
    public void StopAnimation()
    {
        timerLoop.Stop();
    }
}

```
> -1 votes

# Answer
Here is my implementation based on the answer from S-téphan Wegener.

```
// FOR SPRITE BASED ANIMATION:
// ******************************************************
// *** right now, flickers on first cycle, but NO FLICKER after that unless animation cycle
// *** restart
// *** can fix later some how with creative pre-call/loads
// *** for UWA/XAML Windows10 Image.Source, not Canvas.Background

```

In declarations:

```
List<ImageSource> ImageSources;
int imageIndex;

```

In initial startup declarations:

```
ImageSources = new List<ImageSource>();
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/01.png")));
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/02.png")));
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/03.png")));
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/04.png")));
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/05.png")));
ImageSources.Add((ImageSource)new BitmapImage(new Uri("ms-appx:///Assets/images/06.png")));

```

In run-time:

```
if (OOP.frame == 93) {
    imageIndex = 0; }
if (OOP.frame == 94) {
    imageIndex = 1;}
if (OOP.frame == 95) {
    imageIndex = 2; }
if (OOP.frame == 96) {
    imageIndex = 3; }
if (OOP.frame == 97) {
    imageIndex = 4; }
if (OOP.frame == 98) {
    imageIndex = 5; }

OOP_xaml_image_tag.Source = ImageSources[imageIndex];

```
> -1 votes

---
Tags: c#, sprites, windows-8
---


title: Using variables in other scripts

text:
# Question
Title: Using variables in other scripts
I need to use a variable from the main script of a game which is the score variable `public int scoreCount;` I need it in the main script because it will be needed to update the score when they get past a certain point.

I need to be able to access this variable.. so add or subtract from it i.e. `scoreCount++;` however I am not sure how to do this, I have looked at tutorials and they make no sense for me.. could someone please explain it in more detail.

I also need to be able to use the `public void UpdateScore()` function from the mainscript too, do I just do it the same way as the variable or is there a different method. Thank you.

# Answer
The old Unity docs have some examples. And the Unity Answers site is generally a better place to look for such things. But...

Basically, you need to reference the other gameobject and use GetComponent\<YourScript\>()

So, in the script your working on, you need to declare a public variable that you can assign in the inspector, or you need to use GameObject.Find("OtherGameObjectByName");

If you look at this setup, you can see two gameobjects with each with there own component/script attached. I am using this to illustrate the following code.

The 'ControlObject.cs' attached to 'GameObjectController'.

```
public class ControlObject : MonoBehaviour {

    // There is a better place for this, other than the Start method.
    // but I'm lazy.
    void Start () {

        // This will look for a specific game object.
        GameObject mygo = GameObject.Find("GameObjectOther");
        // if that game object is found...
        if(mygo){

             // you can access any of its components.
             DynamicObject otherguy = mygo.GetComponent<DynamicObject>();

             // Now you can modify public properties or call methods
             otherguy.scoreCount++;
        }
    }
}

```

The 'DynamicObject.cs' attached to 'GameObjectOther'.

```
public class DynamicObject : MonoBehaviour {

    //make sure you have a public propertey
    public int scoreCount = 0;

    //
    void Update () {
        //Do something with scoreCount.

    }
}

```
> 0 votes

# Answer
If it is not necessary to create score variable in your main script and you want to access score even after changing the scene then you can use **Static variables** and access it anywhere, as they don't destroy through out the app life.

Make a class named `Globals.cs` (could be any name) and declare variable there like,

```
public static int SCORE = 0;

```

Save score to this variable before changing the scene, like,

```
Globals.SCORE = score;

```

And get it into another scene like,

```
int score = Globals.SCORE;

```

**NOTE:** Don't forget to reset `Globals.SCORE` to `0` at the start of `GameScene`

```
//==================== OTHERWISE ======================//

```

You can access your main script variable if you are at the same scene by using `FindObjectOfType`.

Assuming that your `MainScript.cs` has a `public` variable.

```
public class MainScript.cs : MonoBehaviour
{
    public int _score = 0; // Initial value
}

```

You can get it in second script by,

```
public class SecondScript : MonoBehaviour
{
    MainScript _mainScript;

    void Start()
    {
        // Getting main script component from hierarchy
        _mainScript = FindObjectOfType<MainScript>();

        // Now you can access your _score variable
        Debug.Log("Score: " + _mainScript._score.ToString());
    }
}

```
> 0 votes

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


# Question
Title: computationally Intensive routine, ThreadPool or new Thread?
I had to write a computationally expensive routine that runs in 20-30ms. This routine cannot run in the main thread since it would kill the frame rate. The routine runs on demand, when some data change.

I wonder what would be better to use in this scenario. While I think ThreadPool will be all right, I wonder what would happen on an extreme scenario where just one core is available. Would it be better than to create a new thread every time and set the priority to below normal? I wonder though if, in this case, I would end up with the routine struggling to complete within a decent time (although waiting 1-2 seconds would be all right)

My guess is that the ThreadPool is always better in a multi-core scenario, however I wonder if in a single core scenario, creating a thread with lower priority could be a better solution (since I don't care if the computation last longer than excepted).

# Answer
> 1 votes
In a single thread system your lower priority thread might never run.

You could check the number of hardware threads and if there's only one you can call Thread.Sleep(x) where x is a number of milliseconds to sleep so the background thread has a chance to run.

That number could be adjusted according to the main thread's frame time to give a % of time to the background thread.

For example if the rendering took 40ms (slow system, 25fps) you could sleep the main thread for 10ms (1/4 of frame time) when the processing thread is active to control (more or less) the amount of time allocated to the background thread to roughly 20%.

(Assuming no other OS threads and apps are running at the same time.)

Or the other way around: you could have the processing thread at a higher or equal priority and sleep that one for ~8ms every ~8ms on a single-thread system but you have to check the time every so often in your processing loop.

Mixing both also helps in some situations as some OSes/kernels will keep going for 10-20ms (or more) before switching threads. For example this was useful to give the audio thread a chance but OS schedulers got a lot better. Since around 2010 I've only seen this issue on some embedded systems (Your mileage may vary).

Regarding the thread pool: For multiple short background tasks that can run in parallel many at the same time (eg: multiple AIs A\* path findings in parallel or particle updates) a thread pool with job batching is the way to go on a multi-core system, but if it's 1 big job (eg: the 1 environment generator/streamer) a dedicated thread is simpler to deal with. This makes it easier to debug, inspect, profile and balance.

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


# Question
Title: What is the difference between a game director and game producer?
I was browsing through the list of games Hironobu Sakaguchi has worked on and noticed that he is credited differently from game to game. Just to cite a few games from that list, he is credited as:

* **Director** in Final Fantasy 1 to 5, The Last Story
* **Producer** in Final Fantasy 6, 7, 9 and Tactics, Lost Odyssey
* **Executive Producer** in Xenogears, Vagrant Story, Final Fantasy 8

This made me realize that I do not know the difference between these positions and in what ways do they contribute to the game development process.

# Answer
What a position means is *far* from standardized in the industry. In general, game producers in big publishers in the US have little to no impact on the actual product. They're facilitators, keeping different departments abreast of things and making sure that all the pieces come together. And again, this is in *general*; this will vary between publishers and developers. And Japan probably has a different structure than the US in terms of the role of the producer.

One constant however is the rule of Executive Producer. Just as with movies, EPs often have little actual power or role in the production. Sometimes, they're purely ceremonial, used as a way to credit someone for part of the work. Some EPs do have some authority, but this is primarily through their role as facilitating communication between the upper level executives and the people actually making the work. When people speak of "Executive Meddling", the EP is often the go-between or facilitator for this.

Thus they can gain de-facto power by simply lying or misrepresenting how things are going in production to the people with actual power. Some EPs have veto power, some don't. Even so, the EP's power is usually via the commandment: "Do this!" Exactly how it gets done tends to be up to the developers. Though again, there are exceptions.

Basically, you can say nothing about how much influence over the production of those games that Sakaguchi had. At best, you can vaguely say that he probably had more direct, intimate control when he was Director, some control as Producer, and probably less moment-to-moment control over things as Executive Producer. Anything more than that is sheer speculation.
> 11 votes

# Answer
Adding to Nicol's answer: Relating to Hollywood, sometimes an "Executive Producer" is a ceremonial title for someone who brings funding to a project (via another investor or their own pocket book). This is more common in the Direct to DVD or B Movie market but isn't uncommon.
> 3 votes

# Answer
Contrary to Niocol's answer , if the Executive Producer title has any relation to it's TV counterpart, an Executive Producer can also be someone who sees a project through from start to finish. For example, Chris Carter was the Executive Producer of all X-Files episodes because he was actively involved in the series from start to finish, approving storylines, working out the general arc of the show, making creative decisions, etc.

With TV, the Exectutive Producer title is less of a position of creativity, and more of a position of responsibility, in the sense that the EP is ultimately responsible for the finished product.

Given Sakaguchi's past work on the Final Fantasy Series, it would make sense for him to be EP on FF8. I imagine in this role he took on the responsibility of seeing FF8 through.
> 2 votes

# Answer
It really varies from shop to shop and even project to project as shops refine their own particular job descriptions and organization.

In general if there is a game director listed this position would be involved with creative decisions and communicating them to the team while the game producer would be more involved with schedule and business decisions and dealing with investors / publishers.

In some shops what they call a producer is also driving creative direction and works close with the discipline leads on creative decisions much like a game director. In other shops the game design lead is effectively the game director. Sometimes the design lead and producer attempt to split the duties of a game director, often with mixed results.
> 1 votes

# Answer
Obviously I'm late to this question by a few years (yikes), but I'll take a swing anyway.

**Producer**

In modern Games, the Producer is usually in charge of getting a *part* of a game done. Many years ago, when game teams numbered in the low 10s of people, they might have handled the entire game. Nowadays, across a lot of the industry this will probably be one vertical or horizontal slice of a game. Some examples of how it might be organized: Multi-player, Tools, UI, Character art, or level design. Depending on the company, they might have creative input (and there may be a complimentary Development Director role), or be more focused on schedule and budget. The pithy answer is: they move the ball forward. If it's a place that allows creative input, they also maintain the creative direction for their defined area.

**Executive Producer**

The EP in games is pretty different than its counterpart in film. The role is usually in charge of a franchise (he/she might manage game development as well, as a 'project lead'). They help define the creative direction and then ensure it is followed. They define and manage the budget for the production. They approve changes to either, and (they should) take the hit when those changes are wrong. They give direction to the creative and engineering leads, and most cases, those people report to them - at least as far as their work on the franchise is concerned. Because we're talking about a franchise, they also direct decisions about patches, expansions and live support. They're involved in marketing and in some cases, sales decisions.

**Game Director**

I've never dealt with this role, but I'm going to say it's probably analogous to Project Lead.
> 1 votes

---
Tags: game-industry
---


# Question
Title: LibGDX: Do I have to dispose a texture if I load it from AssetManager?
```
AssetManager manager = new AssetManager();

manager.load("texture1", Texture.class);
manager.load("texture2", Texture.class);
manager.load("texture3", Texture.class);
//And so on...

```

And then I load it from another screen, do I still have to dispose it? Or manager does it when I call `manager.clear`?

# Answer
> 2 votes
You shouldn't call `dispose` directly on a `Texture` loaded by an `AssetManager`, they are disposed the the `AssetManager` is cleared or disposed or if you call `unload` on the `AssetManager` and pass the `Texture`.

The reason you shouldn't dispose assets from an `AssetManager` is that they can be shared between many other assets (two fonts may use the same texture for example) and the `AssetManager` tracks this by reference counting them so that even if you call `unload` for a texture it will not get unloaded until you also unload the dependant assets.

---
Tags: java, android, libgdx, textures, scene2d
---


# Question
Title: On Android, How can I avoid FPS drops during sensor listener setup/tear down?
When I open my Android app after 5 or 10 seconds it sets up the sensor listener, during which I see clear stuttering and the FPS drops for a second to 40 instead of 60.

Is there a way to avoid this?

I am working in Android Studio with LibGDX.

# Answer
I am not sure what you mean with Sensor Listener, but In case you mean accelerometer and other mobile phone sensonrs. You can disable them with this code:

```
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
config.useAccelerometer=false;
config.useCompass=false;
initialize(new yourGame(), config);

```

More information on the LibGDX Wiki
> 0 votes

---
Tags: android, libgdx, optimization
---


# Question
Title: How do I sync the GameObjects to server in C# unity?
I have been working on Game that consists of 10 Game Objects that have to be sync by the server values. The server decides that which game object will win and then sends command to my side(Client side) but I am not able to match the server values to mine then what can I do to sort out this problem? The track is kind of horse racing track i.e. straight and then circular. Any help would be appreciated :) Thanks in advance

# Answer
> 1 votes
I wonder how are you trying to sync it, the "best" way to do this is via socket connection.

Also, you have to identify the important info that you really need to sync, FE, im developing an MRTS, i have to sync the units but the client doesn´t care about movement speed, attack points, etc, so, in essence i only need send to the client which unit he has to draw, who owns this unit and where it has to be drawn, so, a huge object called "Archer" in my serverside application would be sent to the server as an Int8 array like \[23,1,1851,2434\] (Unit id, owner id, X, Y).

Then, your client only has to draw it.

If you use UDP sockets (fast as hell) and condensed bit data you will be able to do real time sync without any problem.

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


# Question
Title: Speed up loading of png files (used for textures) in Android OpenGL Game
My game has a few texture atlases that need to be loaded (in my XHDPI folder they total 3.49MB) and on a top-end device they don't take that long to load, however on a low-end device they seem to take an age.

An example would be my old Samsung Galaxy Ace which uses the MDPI folder for it's resources (total: 1.51MB), this takes 16 seconds, which I personally consider far too long.

Originally, I had a separate atlas for each sprite, so I merged the majority of my atlases into one big atlas after reading that it may speed things up.

Unfortunately, it hasn't really made any difference to the load-speed.

This is how I'm loading my png files:

```
atlas = BitmapFactory.decodeResource(view.getResources(), R.drawable.atlasimage);

```

As the default load format is ARG\_B8888, I though I'd attempt to load them in RGB565 as this is supposed to be quicker to load and render as well as take up less memory.

So I tried this:

```
BMFOptions = new BitmapFactory.Options();
BMFOptions.inDither=false;
BMFOptions.inPreferredConfig = Bitmap.Config.RGB_565;

atlas = BitmapFactory.decodeResource(view.getResources(), R.drawable.atlasimage, BMF Options);

```

Unfortunately, although this does reduce the quality of the image, it doesn't reduce the load time and yields no noticible performance increase. Also, (and this may be expected), it doesn't reduce the memory footprint of my app.

So my question is how can I optimise this so that my png's are loaded quicker (rendering speed increase not being as important at the moment as load-speed).

# Answer
> 1 votes
I don't think there's any faster way to load bitmaps.

That's an extremely long load time for so little data, are you sure it's not specific to just that device? I have a game that's loading WAY more bitmap data than that (300 files totaling around 20MB) in about the same time on an original Galaxy S.

# Answer
> 0 votes
Looks like putting images in asset folder and loading them using BitmapFactory.decodeStream(ins) would increase loading speed a lot. See this post for details

---
Tags: android, textures, loading, resource-management, png
---


title: Repaint() in gameloop does'nt work

text:
# Question
Title: Repaint() in gameloop does'nt work
Recently I'm working on a PAC-MAN clone.

I created 3 classes:

* **StartingClass** which extends `Jframe` and uses `KeyListener`
* **Board** which extends `Jpanel`
* **Sparx** which is responsible for changing the player's sprite coordinates.

The result is a frame with an unmoving image.

I changed the code in various ways but the result was always the same (well sometimes even worse).

On zetcode.com, kilobolt.com and a few other webpages I found some source code which works on some other concepts, but still I don't know how to fix my code. I'm sure that I'm missing something obvious. Could you tell me what is wrong with my repaint method?

Here's my sourcecode

StartingClass

```
public  class  StartingClass extends  JFrame  implements  KeyListener, Runnable{
public  StartingClass(){
       board=new  Board();

       add(board);

       sparx=new  Sparx();
}

public  static  void  main(String[]  args) {

       new  StartingClass();

}

@Override public  void keyPressed(KeyEvent  arg0) {

       switch(arg0.getKeyCode()){

       case  KeyEvent.VK_UP:

       sparx.moveUp(); break;

       case  KeyEvent.VK_DOWN:

       sparx.moveDown(); break;

       case  KeyEvent.VK_LEFT:

       sparx.moveLeft(); break;

       case  KeyEvent.VK_RIGHT:

       sparx.moveRight(); break; }

}
@Override public  void  run()

{ while(true){

       sparx.update();

       board.repaint();

       try  { thread . sleep (17) ;

        }  catch  (InterruptedException  e)

       { //  TODO  Auto-generated catch block e.printStackTrace();

}

}

}

}

```

Board

```
public  class  Board extends  JPanel{

       Sparx sparx;

       public  Board(){

              sparx=new  Sparx();

}

@Override public void paintComponent(Graphics g) {

       g.drawImage(sparx.getSparx(),  sparx.getSparxX(),  sparx.getSparxY(), null);

 }

}

```

# Answer
> 0 votes
The is no problem with your repaint() method. The problem here is that the Sparx you update and move is a different Sparx then the one you render/paint. In your Board class you create a new Sparx instance and this is the one you render out. This is a different instance from the one you create in your StartingClass and update the position of.

Simply overwrite the Sparx stored in the Board class with the one in the StarterClass class or pass it through the Board constructor when you create the Board.

---
Tags: java, 2d, game-loop
---


title: Inline sprites in Unity's text?

text:
# Question
Title: Inline sprites in Unity's text?
How can I use different materials when using the tag for Unity's rich text syntax?

I want to be able to have sprites that are inline with my text without having to create custom fonts.

Here's what I have so far: Here's the syntax that I'm using for the text in my image:

`Planetary <quad material=1 size=20 x=0.1 y=0.1 width=0.1 height=0.1 /> Intergalactic`

I'm guessing "material=1" refers to the material index of the Text object. How can I set it to use a different material altogether?

Is there a plugin or other resource that makes embedding icons in text easier?

# Answer
As the text system is still the legacy text system, you can't embed images in text. Only option would be to have a layout group and have separate text and image blocks

Alternatively, you can use an asset like TextMeshPro which has a new text implementation which supports this fully (and much more!)
> 2 votes

---
Tags: unity, sprites
---