# Question
Title: Making the ball go faster makes collision detection impossible
I have a simple tennis game like Breakout. I have a ball, and a racquet made from a long rectangle. The ball bounces around the walls, and the game terminates when the ball hits the floor. To prevent this, I have a long racquet I can move horizontally that the ball can hit. Each time the ball hits the racquet, the speed of the ball increases.

The speed increases by adding to the number of pixels for each increment of the ball. This means that after a while (around 50 hits), the steps of the ball become quite long. The ball moves at 50 px per frame. With long steps, the ball might just jump over the racquet, and not detect collision.

To prevent this, I was thinking of incrementing the FPS, instead, and keeping the ball speed fixed. This would probably work, but I don't think changing the FPS is the right solution. How should I go about solving collision detection at higher speeds?

# Answer
What you're looking for is called Continuous Collision Detection.

A simple implementation would be to do a raycast after each step to see if something was in between the two steps.

If you don't have access to physics simulations like raycasts, you could also slowly resolve the collision yourself over multiple iterations.
> 3 votes

# Answer
**Note**: In the solution uses the previous position to check for collisions over multiple iterations. It is not perfect, I explain why.

## Keep the old position

The key to detect if the ball has gone through an obstacle is to keep track of where it was, so you can check if the segment from where it was to where it is now intersects the obstacle.

To implement the check, you break down the obstacle into segments. For each one, you check if the segment formed by the old to the new position collides with it. Some optimizations are possible when the obstacles are axis-aligned rectangles.

That is enough to handle collisions with stationary obstacles. As far as the obstacle don't move, there is no problem.

## The moving racquet

When you have a moving obstacle, it becomes trickier... if the obstacle approaches the ball from behind, the old position would be inside the obstacle before the ball itself. This will make the detection fail. In addition, this problem will happen even at small speed.

The solution is to work in the frame of reference of the obstacle. That way, for all uses and purposes, the obstacle is stationary. There is no need to convert the speed vector to the other system; all you need to convert is the segment from the old to the new position, then use that transformed segment to check for collisions.

The implementation is simple; add the displacement of the obstacle since the last update to the old position of the ball, et voila.

*You may also want to compute the instantaneous velocity of the racquet, and add that to the speed of the ball... otherwise it feels odd that you push the racquet against the ball and it just sort of "sweeps it" without changing the speed. To clamp the speed added by the racquet is strongly advised!*

**WARNING**: Do not allow the racquet to overlap the wall. If you trap the ball, and then push to the wall overlapping the racquet on it... well, the ball have literally no space to go. You either end up with an error, a ball going at "astronomical" speeds, or something like that. If the racquet is pushing the ball against the wall, make sure that the distance from the racquet to the wall is enough for the ball to be there!

## Too many bounces

What will happen if the result of solving a collision places the ball inside of another obstacle? Well, you will have to solve collision again, and again, until, eventually, it solves it.

Sometimes the previous position of the ball is inside of an obstacle that is hitting it from behind, pushing the ball into another obstacle. On the next iteration, the ball will move out of that obstacle... into the one that hit it first... but the old position is inside of that obstacle!

To solve this, update the old position between iterations, by always placing it at the boundary of the last hit object.

---

Sometimes, that same situation happens at high speed. In particular it will happen if you are an obstacle towards the ball, adding speed to it (I told you to clamp it!). If the speed is, too high it will take too many iterations to solve the collision.

Too many iterations means performance degradation. I have opted to implement an upper bound to the number of iterations... the result is that you can push balls outside of the world. This happens, in particular, when the speed is astronomical (the distance the ball would cover in one update is larger than the size of the world).

Allowing a high enough number of iterations works in most cases. Testing advised.

## Working implementation

The following code implements collision of "balls" with rectangular obstacles. Actually, it only uses point collision (the radius of the balls is ignored), you should be able to fix that.

The interface of the snippet is as follows:

* To move the racquet: move the mouse pointer.
* To add a ball: 1) define the position by clicking. 2) Define the speed by clicking in the position where the ball should be after 1 second.
* To increase the speed: press "\*"
* To decrease the speed: press "/"
* To reset the speed: press "."
* To increase the update interval: press "+"
* To decrease the update interval: press "-"
* To reset the update interval: press "0"

The code implements a limit to the number of iterations used to solve collisions, and allows the racquet to transfer velocity to the balls. There is a chance that you can push a ball outside of the world.

Constraints:

* The code will not allow the racquet to touch the walls of the world.
* The code will not allow the update interval to reach zero.
* The code... will allow you to set a negative speed multiplier and solve collisions in reverse!

```
var time = (new Date()).getTime(); // time in milliseconds
var racquetElement; // the svg rect for the racquet
var balls = []; // array with all the balls
var speedMultiplier = 1; // to make the world go faster!
var interval = 25; // requested milliseconds between updates
var control = {x: 50, y:50}; // Magical (no, actually the ugly GUI code below handles it)
var racquetObstacle = {x1: 0, x2: 100, y1: 0, y2: 100, x: 50, y:50}; // racquetObstacle controlled by the player
var obstacles = [
  {x1: -Infinity, x2: 0, y1: -Infinity, y2: Infinity}, // left wall
  {x1: 1000, x2: Infinity, y1: -Infinity, y2: Infinity}, // right wall
  {x1: -Infinity, x2: Infinity, y1: -Infinity, y2: 0}, // top wall
  {x1: -Infinity, x2: Infinity, y1: 1000, y2: Infinity}, // bottom wall
  racquetObstacle
]

function update()
{
  // get elapsed time from last iteration
  // divided by 1000 to get seconds
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;

  // Take the speed of the racquetObstacle
  racquetObstacle.deltaX = control.x - racquetObstacle.x;
  racquetObstacle.deltaY = control.y - racquetObstacle.y;
  // update the obstacle of the racquetObstacle
  racquetObstacle.x1 = control.x - 50;
  racquetObstacle.x2 = control.x + 50;
  racquetObstacle.y1 = control.y - 50;
  racquetObstacle.y2 = control.y + 50;
  // store the position to be able to compute next speed
  racquetObstacle.x = control.x;
  racquetObstacle.y = control.y;

  // Iterate over the balls
  for (var ballIndex = 0; ballIndex < balls.length; ballIndex++)
  {
      let ball = balls[ballIndex];
      // Get old coordinates.
      let ox = ball.x, oy = ball.y;
      // Get the effective speed, including multiplier
      let speedX = ball.speedX * speedMultiplier, speedY = ball.speedY * speedMultiplier;
      // Compute new position for the ball
      ball.x = ball.x + speedX * elapsed;
      ball.y = ball.y + speedY * elapsed;
      // --------------
      // Obstacle collision
      // --------------
      let count = 0;
      do
      {
        count++;
        ball.collided = false;
        for (var obstacleIndex = 0; obstacleIndex < obstacles.length; obstacleIndex++)
        {
          let obstacle = obstacles[obstacleIndex];
          if (!("deltaX" in obstacle)) obstacle.deltaX = 0;
          if (!("deltaY" in obstacle)) obstacle.deltaY = 0;
          let oldX = ox + obstacle.deltaX, oldY = oy + obstacle.deltaY;
          let inHorizontalRange = ball.x > obstacle.x1 && ball.x < obstacle.x2;
          let inVerticalRange = ball.y > obstacle.y1 && ball.y < obstacle.y2;
          // check if we have collided with this obstacle
          // we have to check if we have passed any of the walls of the obstacle
          if (
            oldX < obstacle.x1 && ball.x > obstacle.x1 // entered from the left
            && inVerticalRange // in vertical range
          ){
            ox = obstacle.x1;
            ball.x = obstacle.x1 - (ball.x - obstacle.x1);
            ball.speedX = -ball.speedX + Math.min(1000, Math.max(-1000, obstacle.deltaX / elapsed));
            ball.collided = true;
          }
          if (
            oldX > obstacle.x2 && ball.x < obstacle.x2 // entered from the right
            && inVerticalRange // in vertical range
          ){
            ox = obstacle.x2;
            ball.x = obstacle.x2 + (obstacle.x2 - ball.x);
            ball.speedX = -ball.speedX + Math.min(1000, Math.max(-1000, obstacle.deltaX / elapsed));
            ball.collided = true;
          }
          if (
            oldY < obstacle.y1 && ball.y > obstacle.y1 // entered from the top
            && inHorizontalRange // in horizontal range
          ){
            oy = obstacle.y1;
            ball.y = obstacle.y1 - (ball.y - obstacle.y1);
            ball.speedY = -ball.speedY + Math.min(1000, Math.max(-1000, obstacle.deltaY / elapsed));
            ball.collided = true;
          }
          if (
            oldY > obstacle.y2 && ball.y < obstacle.y2 // entered from the bottom
            && inHorizontalRange // in horizontal range
          ){
            oy = obstacle.y2;
            ball.y = obstacle.y2 + (obstacle.y2 - ball.y);
            ball.speedY = -ball.speedY + Math.min(1000, Math.max(-1000, obstacle.deltaY / elapsed));
            ball.collided = true;
          }
        }
      } while (ball.collided && count < 1000);
      // update the ball
      ball.setAttribute("cx", ball.x);
      ball.setAttribute("cy", ball.y);
  }
  // update racquetObstacle
  if (racquetElement !== null)
  {
    racquetElement.setAttribute("x", control.x - 50);
    racquetElement.setAttribute("y", control.y - 50);
  }
  // update time
  time = new_time;
  setTimeout(update, interval);
}

// --------------
// Ugly UI code
// --------------
var world;
function getNode(n, v){
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v) n.setAttributeNS(null, p, v[p]);
  return n;
}
jQuery(document).ready(function(){
  world = document.getElementById("world");
  racquetElement = document.getElementById("racquet");
  var tmp = null, arrow = null;
  $(world).on('mousemove', function(e){
    let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
    if (arrow !== null){
      tmp.speedX = x - tmp.getAttribute("cx"); tmp.speedY = y - tmp.getAttribute("cy");
      arrow.setAttribute("x2", x); arrow.setAttribute("y2", y);
    }
    control.x = Math.min(949, Math.max(51, x)); control.y = Math.min(949, Math.max(51, y));
  });
  jQuery(world).click(function(e){
    if (tmp === null){
      let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
      tmp = getNode('circle', {cx: x, cy: y, r:5}); tmp.x = x; tmp.y = y;
      arrow = getNode('line', {x1: x, x2: x, y1: y, y2: y, "stroke-width":1, stroke:"black"});
      world.appendChild(tmp); world.appendChild(arrow);
    }else{
      world.removeChild(arrow);
      balls.push(tmp);
      tmp = null; arrow = null;
    }
  });
  $(document).keypress(function(e){
    if (e.key === '+') interval += 25;
    if (e.key === '-') interval = Math.max(25, interval - 25);
    if (e.key === '0') interval = 25;
    if (e.key === '*') speedMultiplier += 0.1;
    if (e.key === '/') speedMultiplier -= 0.1;
    if (e.key === '.') speedMultiplier = 1;
  });
  setTimeout(update, interval);
});
```

```
body{margin:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="world" viewBox="0 0 1000 1000">
<rect id="racquet", x="0" y="0" width="100" height="100" fill="aqua" stroke:"black" stroke-width:"1">
</svg>
```

Open in full page for the best experience ;)

---

## Bounce Order

There is a bug in the code above. If the ball is moving fast enough to collide with multiple objects, the first object in the list is the one that bounces it back... instead of the closes to the ball. Sometimes the bounce back will place the ball after one of the prior obstacles.

Instead of checking for each obstacle and moving the ball immediately, we should be picking the closest obstacle. Since we need to check distance, we really need to compute the collision point (instead of the "cheap" solution above).

I have also added a change of color to the racquet when a collision could not be resolved in the number of iterations given.

Improved version:

```
var time = (new Date()).getTime(); // time in milliseconds
var racquetElement; // the svg rect for the racquet
var balls = []; // array with all the balls
var speedMultiplier = 1; // to make the world go faster!
var interval = 25; // requested milliseconds between updates
var control = {x: 50, y:50}; // Magical (no, actually the ugly GUI code below handles it)
var racquetObstacle = {x1: 0, x2: 100, y1: 0, y2: 100, x: 50, y:50}; // racquetObstacle controlled by the player
var obstacles = [
  {x1: -Infinity, x2: 0, y1: -Infinity, y2: Infinity}, // left wall
  {x1: 1000, x2: Infinity, y1: -Infinity, y2: Infinity}, // right wall
  {x1: -Infinity, x2: Infinity, y1: -Infinity, y2: 0}, // top wall
  {x1: -Infinity, x2: Infinity, y1: 1000, y2: Infinity}, // bottom wall
  racquetObstacle
]

function update()
{
  // get elapsed time from last iteration
  // divided by 1000 to get seconds
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;

  // Take the speed of the racquetObstacle
  racquetObstacle.deltaX = control.x - racquetObstacle.x;
  racquetObstacle.deltaY = control.y - racquetObstacle.y;
  // update the obstacle of the racquetObstacle
  racquetObstacle.x1 = control.x - 50;
  racquetObstacle.x2 = control.x + 50;
  racquetObstacle.y1 = control.y - 50;
  racquetObstacle.y2 = control.y + 50;
  // store the position to be able to compute next speed
  racquetObstacle.x = control.x;
  racquetObstacle.y = control.y;

  // Iterate over the balls
  for (var ballIndex = 0; ballIndex < balls.length; ballIndex++)
  {
      let ball = balls[ballIndex];
      // Get old coordinates.
      let ox = ball.x, oy = ball.y;
      // Get the effective speed, including multiplier
      let speedX = ball.speedX * speedMultiplier, speedY = ball.speedY * speedMultiplier;
      // Compute new position for the ball
      ball.x = ball.x + speedX * elapsed;
      ball.y = ball.y + speedY * elapsed;
      // --------------
      // Obstacle collision
      // --------------
      let count = 0;
      let collision = null;
      do
      {
        count++;
        collision = null;
        for (var obstacleIndex = 0; obstacleIndex < obstacles.length; obstacleIndex++)
        {
          let obstacle = obstacles[obstacleIndex];
          if (!("deltaX" in obstacle)) obstacle.deltaX = 0;
          if (!("deltaY" in obstacle)) obstacle.deltaY = 0;
          let oldX = ox + obstacle.deltaX, oldY = oy + obstacle.deltaY;
          let inHorizontalRange = ball.x > obstacle.x1 && ball.x < obstacle.x2;
          let inVerticalRange = ball.y > obstacle.y1 && ball.y < obstacle.y2;
          // check if we have collided with this obstacle
          // we have to check if we have passed any of the walls of the obstacle
          if (
            oldX < obstacle.x1 && ball.x > obstacle.x1 // entered from the left
            && inVerticalRange // in vertical range
          ){
            let candidate = {x: obstacle.x1, y: oy + obstacle.x1 * (ball.y - oy)/(ball.x - ox), direction: "left", deltaX: obstacle.deltaX, deltaY: obstacle.deltaY};
            candidate.distance = Math.sqrt((candidate.x - ox) * (candidate.x - ox) + (candidate.y - oy) * (candidate.y - oy));
            if (collision === null || collision.distance > candidate.distance)
            {
              collision = candidate;
            }
          }
          if (
            oldX > obstacle.x2 && ball.x < obstacle.x2 // entered from the right
            && inVerticalRange // in vertical range
          ){
            let candidate = {x: obstacle.x2, y: oy + obstacle.x2 * (ball.y - oy)/(ball.x - ox), direction: "right", deltaX: obstacle.deltaX, deltaY: obstacle.deltaY};
            candidate.distance = Math.sqrt((candidate.x - ox) * (candidate.x - ox) + (candidate.y - oy) * (candidate.y - oy));
            if (collision === null || collision.distance > candidate.distance)
            {
              collision = candidate;
            }
          }
          if (
            oldY < obstacle.y1 && ball.y > obstacle.y1 // entered from the top
            && inHorizontalRange // in horizontal range
          ){
            let candidate = {y: obstacle.y1, x: ox + obstacle.y1 * (ball.x - ox)/(ball.y - oy), direction: "top", deltaX: obstacle.deltaX, deltaY: obstacle.deltaY};
            candidate.distance = Math.sqrt((candidate.x - ox) * (candidate.x - ox) + (candidate.y - oy) * (candidate.y - oy));
            if (collision === null || collision.distance > candidate.distance)
            {
              collision = candidate;
            }
          }
          if (
            oldY > obstacle.y2 && ball.y < obstacle.y2 // entered from the bottom
            && inHorizontalRange // in horizontal range
          ){
            let candidate = {y: obstacle.y2, x: ox + obstacle.y2 * (ball.x - ox)/(ball.y - oy), direction: "top", deltaX: obstacle.deltaX, deltaY: obstacle.deltaY};
            candidate.distance = Math.sqrt((candidate.x - ox) * (candidate.x - ox) + (candidate.y - oy) * (candidate.y - oy));
            if (collision === null || collision.distance > candidate.distance)
            {
              collision = candidate;
            }
          }
        }
        if (collision === null)
        {
          break;
        }
        else
        {
          if (collision.direction === "left")
          {
            ox = collision.x - collision.deltaX;
            ball.x = collision.x - (ball.x - collision.x);
            ball.speedX = -ball.speedX + Math.min(1000, Math.max(-1000, collision.deltaX / elapsed));
          }
          else if (collision.direction === "right")
          {
            ox = collision.x - collision.deltaX;
            ball.x = collision.x + (collision.x - ball.x);
            ball.speedX = -ball.speedX + Math.min(1000, Math.max(-1000, collision.deltaX / elapsed));
          }
          else if (collision.direction === "top")
          {
            oy = collision.y - collision.deltaY;
            ball.y = collision.y - (ball.y - collision.y);
            ball.speedY = -ball.speedY + Math.min(1000, Math.max(-1000, collision.deltaY / elapsed));
          }
          else if (collision.direction === "bottom")
          {
            oy = collision.y - collision.deltaY;
            ball.y = collision.y + (collision.y - ball.y);
            ball.speedY = -ball.speedY + Math.min(1000, Math.max(-1000, collision.deltaY / elapsed));
          }
        }
      } while (count < 10000);
      if (count === 10000)
      {
        racquetElement.setAttribute("fill", "red");
      }
      // update the ball
      ball.setAttribute("cx", ball.x);
      ball.setAttribute("cy", ball.y);
  }
  // update racquetObstacle
  if (racquetElement !== null)
  {
    racquetElement.setAttribute("x", control.x - 50);
    racquetElement.setAttribute("y", control.y - 50);
  }
  // update time
  time = new_time;
  setTimeout(update, interval);
}

// --------------
// Ugly UI code
// --------------
var world;
function getNode(n, v){
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v) n.setAttributeNS(null, p, v[p]);
  return n;
}
jQuery(document).ready(function(){
  world = document.getElementById("world");
  racquetElement = document.getElementById("racquet");
  var tmp = null, arrow = null;
  $(world).on('mousemove', function(e){
    let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
    if (arrow !== null){
      tmp.speedX = x - tmp.getAttribute("cx"); tmp.speedY = y - tmp.getAttribute("cy");
      arrow.setAttribute("x2", x); arrow.setAttribute("y2", y);
    }
    control.x = Math.min(949, Math.max(51, x)); control.y = Math.min(949, Math.max(51, y));
  });
  jQuery(world).click(function(e){
    if (tmp === null){
      let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
      tmp = getNode('circle', {cx: x, cy: y, r:5}); tmp.x = x; tmp.y = y;
      arrow = getNode('line', {x1: x, x2: x, y1: y, y2: y, "stroke-width":1, stroke:"black"});
      world.appendChild(tmp); world.appendChild(arrow);
    }else{
      world.removeChild(arrow);
      balls.push(tmp);
      tmp = null; arrow = null;
    }
  });
  $(document).keypress(function(e){
    if (e.key === '+') interval += 25;
    if (e.key === '-') interval = Math.max(25, interval - 25);
    if (e.key === '0') interval = 25;
    if (e.key === '*') speedMultiplier += 0.1;
    if (e.key === '/') speedMultiplier -= 0.1;
    if (e.key === '.') speedMultiplier = 1;
  });
  setTimeout(update, interval);
});
```

```
body{margin:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="world" viewBox="0 0 1000 1000">
<rect id="racquet", x="0" y="0" width="100" height="100" fill="aqua" stroke:"black" stroke-width:"1">
</svg>
```
> 1 votes

---
Tags: collision-detection
---


title: Why glDrawElements draws nothing?

text:
# Question
Title: Why glDrawElements draws nothing?
I tried to implement indexed draw, but when I call I got nothing on screen. Even more strange that I wasn't get any error when call it and buffer variables packed right.

There my constructor:

```
Mesh::Mesh(Shader &shader, std::vector<GLuint>* indices, std::vector<VertexData>* vertices) {
shaderProgram = &shader;
_meshLenght = (GLsizei) indices->size();
_indices = indices;

glGenBuffers(1, &_ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->size(), indices, GL_STATIC_DRAW);

//create one here
glGenVertexArrays(1, &_vao);
glBindVertexArray(_vao);

std::vector<glm::vec3> positions {};
std::vector<glm::vec3> normals {};
std::vector<glm::vec2> texture {};

for (size_t i = 0; i < vertices->size(); ++i) {
    positions.push_back(vertices->at(i).positions);
    normals.push_back(vertices->at(i).normals);
    texture.push_back(vertices->at(i).texCoords);
}

glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*(positions.size()+normals.size()), nullptr, GL_DYNAMIC_DRAW);

glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(glm::vec3)*positions.size(), positions.data());
glBufferSubData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*positions.size(), sizeof(glm::vec3)*normals.size(), normals.data());

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast<const void*>((sizeof(glm::vec3) * positions.size())));

glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}

```

And there my draw code:

```
void Mesh::Draw() {
glBindVertexArray(_vao);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
if (_ebo==0)
    glDrawArrays(GL_TRIANGLES, 0, _meshLenght);
else {
    glDrawElements(GL_TRIANGLES, _meshLenght, GL_UNSIGNED_INT, nullptr);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}

```

Also show my vertices info screenshot:

And if you need have apitrace trace file: https://drive.google.com/file/d/0B-dWIpzqq91mQXVIeHhTOHFhRkU/view?usp=sharing

# Answer
> 1 votes
```
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->size(), indices, GL_STATIC_DRAW);

```

This is wrong. `indices->size()` is the number of indices you have, but yet we see from the documentation (my emphasis):

> *size* Specifies the **size in bytes** of the buffer object's new data store.

Use `indices->size() * sizeof (GLuint)` instead.

You should also be using `&indices[0]` for the *data* parameter instead of just `indices`.

---
Tags: opengl
---


# Question
Title: Adding components to a GameObject referenced within code
So in my project, I have a class called **ComponentRegistry**. The idea of this class is to store a dictionary of components and their names. For example:

```
    public Dictionary<string, MonoBehaviour> registry;
    public MonoBehaviour testComponent;

    void Start(){
        registry = new Dictionary<string, MonoBehaviour> ();
        registry.Add ("TestComponent", testComponent);
    }

    public MonoBehaviour GetScript(string name)
    {
        return registry[name];
    }

```

Then in a separate class, I will access this dictionary using a string in order to retrieve the associated component, subsequently adding the associated component to the gameObject.

```
    foreach (string comp in blockInfo.components) {

    //For each of the components that need to be added

        gameObject.AddComponent(ScriptMaster.compReg.GetScript(comp));

        //I know this is incorrect, but the idea is there
}

```

Just for understanding, **compReg** is an instance of the **ComponentRegister** class stored as a static variable within my **ScriptMaster** class.

But no matter what I try, I have not been able to get this to work. I have switched endlessly between different formatting of adding components to gameObjects, alternating between using Components and MonoBehaviours, adding by type.

Thank you for any insight.

# Answer
> 0 votes
You probably wanted to create new instance of said script instead of passing reference to an existing instance. In order to do that, you can either implement the Factory pattern, or one of the `IConeable` variations/semantics - which would also allow you to have several "default" settings of one script.
Alternatively, if you need *just* "get an instance by type name" semantics, you can use the Activator.CreateInstance():

```
//you should be able to get the correct name by typeof(T).FullName
// or instance.GetType().FullName
foreach (string compTypeName in blockInfo.components)
  gameObject.AddComponent(Activator.CreateInstance(null, compTypeName ).Unwrap());

```

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


# Question
Title: Detect transform from detection of QR code?
I want to calculate the transform I need to render a 3D object in my world.

How I see my idea:

* You open a camera
* You point it at a QR code
* The app detects the QR code and returns the 4 corners and the correct direction
* The app calculates the transform that this QR code is currently at (I need help with this step)
* The app uses that transform to render the 3D object in a fixed position over the QR code

I want something like Vuforia, but for QR codes (as they are used often).

I don't really know how I can extract the transform from the detected QR code (I will get the location of the 4 corners)

# Answer
> 5 votes
## Deriving the transformation

Note that the transformation of the QR code captured by the camera is a perspective transformation. As such, no amount of affine transformation can emulate it (translating, scaling, rotating, shearing, and reflecting are not enough).

From the surface where the QR code is to the image, a perspective transformation is applied. Your task is to solve a projection matrix for that transformation.

---

Ok, we are looking for a matrix such that

```
image_point = M * world_point

```

This matrix needs to be a 3 by 3 matrix to be able to express the projection we need. Which also means we will augment the vectors with an additional value:

```
+-           -+   +-       -+   +-       -+
| image_x * w |   | a  b  c |   | world_x |
| image_y * w | = | d  e  f | * | world_y |
|       w     |   | g  h  1 |   |    1    |
+-           -+   +-       -+   +-       -+

```

Observe that:

```
image_x * w = a * x + b * y + c
image_y * w = d * x + e * y + f
w = gx + hy + 1

```

Therefore

```
image_x = (a * x + b * y + c) / (g * x + h * y + 1)
image_y = (d * x + e * y + f) / (g * x + h * y + 1)

```

---

Remember that the above formulas are the transformation of a point in the real world to a point in the image.

We also know the positions where they ended up in the camera... now you have to solve the equation system to find out the values of the constants `a`, `b`, `c`, `d`, `e`, `f`, `g`, and `h` that form the projection matrix.

For the positions in the real world, we will say that the first point is in position `(0, 0)` in the world, and that the next is at `(S, 0)`, the other at `(0, S)` and the fourth point will be at `(S, S)`. Where `S` is the desired size in the final image.

Those are seven incognitas, for eight equations (two for each one of the four points). This is doable.

Once you have the projection matrix, you can:

* apply the inverse of the transformation to the image, and that will result in an image where the square is a square (within measurement error).
* apply it to 3D models to match the perspective of the camera.

---

Ok, four points:

```
image_x1 = (a * x1 + b * y1 + c) / (g * x1 + h * y1 + 1)
image_y1 = (d * x1 + e * y1 + f) / (g * x1 + h * y1 + 1)

image_x2 = (a * x2 + b * y2 + c) / (g * x2 + h * y2 + 1)
image_y2 = (d * x2 + e * y2 + f) / (g * x2 + h * y2 + 1)

image_x3 = (a * x3 + b * y3 + c) / (g * x3 + h * y3 + 1)
image_y3 = (d * x3 + e * y3 + f) / (g * x3 + h * y3 + 1)

image_x4 = (a * x4 + b * y4 + c) / (g * x4 + h * y4 + 1)
image_y4 = (d * x4 + e * y4 + f) / (g * x4 + h * y4 + 1)

```

Replace with our invented world coordinates:

```
image_x1 = (a * 0 + b * 0 + c) / (g * 0 + h * 0 + 1)
image_y1 = (d * 0 + e * 0 + f) / (g * 0 + h * 0 + 1)

image_x2 = (a * S + b * 0 + c) / (g * S + h * 0 + 1)
image_y2 = (d * S + e * 0 + f) / (g * S + h * 0 + 1)

image_x3 = (a * 0 + b * S + c) / (g * 0 + h * S + 1)
image_y3 = (d * 0 + e * S + f) / (g * 0 + h * S + 1)

image_x4 = (a * S + b * S + c) / (g * S + h * S + 1)
image_y4 = (d * S + e * S + f) / (g * S + h * S + 1)

```

Remove the zero terms:

```
image_x1 = c
image_y1 = f

image_x2 = (a * S + c) / (g * S + 1)
image_y2 = (d * S + f) / (g * S + 1)

image_x3 = (b * S + c) / (h * S + 1)
image_y3 = (e * S + f) / (h * S + 1)

image_x4 = (a * S + b * S + c) / (g * S + h * S + 1)
image_y4 = (d * S + e * S + f) / (g * S + h * S + 1)

```

Look, we have c and f right off the bat (remember that you have all the coordinates in the image). That's the equation system to solve.

I will assume S = 1, to keep it simple. Will come back to this point.

```
image_x1 = c
image_y1 = f

image_x2 = (a + image_x1) / (g + 1)
image_y2 = (d + image_y1) / (g + 1)

image_x3 = (b + image_x1) / (h + 1)
image_y3 = (e + image_y1) / (h + 1)

image_x4 = (a + b + image_x1) / (g + h + 1)
image_y4 = (d + e + image_y1) / (g + h + 1)

```

Now, solve for a, d, b and e:

```
image_x2 * (g + 1) - image_x1 = a
image_y2 * (g + 1) - image_y1 = d

image_x3 * (h + 1) - image_x1 = b
image_y3 * (h + 1) - image_y1 = e

```

Replace:

```
image_x4 = ((image_x2 * (g + 1) - image_x1) + (image_x3 * (h + 1) - image_x1) + image_x1) / (g + h + 1)
image_y4 = ((image_y2 * (g + 1) - image_y1) + (image_y3 * (h + 1) - image_y1) + image_y1) / (g + h + 1)

```

Solve for g:

```
image_x4 = ((image_x2 * (g + 1) - image_x1) + (image_x3 * (h + 1) - image_x1) + image_x1) / (g + h + 1)

=>

g = (-image_x1 -(h + 1) * image_x4 + h * image_x3 + image_x3 + image_x2) / (image_x4 - image_x2)

```

Replace in the final equation:

```
image_y4 = ((image_y2 * (((-image_x1 -(h + 1) * image_x4 + h * image_x3 + image_x3 + image_x2) / (image_x4 - image_x2)) + 1) - image_y1) + (image_y3 * (h + 1) - image_y1) + image_y1) / (((-image_x1 -(h + 1) * image_x4 + h * image_x3 + image_x3 + image_x2) / (image_x4 - image_x2)) + h + 1)

```

Solve for h:

```
h = (image_x1 * (image_y2 - image_y4) + image_y1 * (image_x4 - image_x2) + image_x2 * image_y3 - image_y2 * image_x3 + image_x3 * image_y4 - image_y3 * image_x4)/(image_x2 * (image_y4 - image_y3) + image_y2 * (image_x3 - image_x4) - image_x3 * image_y4 + image_y3 * image_x4)

```

Finally, we have h in terms of positions in the image!

Go ahead, and replace it on `g`... having `g` and `h` you should be able to solve `a`, `b`, `d`, `e`. I am not posting any of that here because the expressions are too large.

Suffice to say that you may compute `h`, and plug it on the formula for `g`. Then plug them in the formulas for `a`, `b`, `d`, `e` that I used above. With that, you will have all the terms for the perspective matrix.

---

Since we got rid of `S` to keep it simple...

* If you want to transform from world coordinates to image coordinates first scale by `1/S` then apply the perspective transformation. This is the operation used to place an object in the image.
* If you want to transform from image coordinates to world coordinates, apply the inverse transformation and then scale by `S`. This would be operation used, to get the image captured by the camera and transform it to true shape.
* If you want to place 3D models, scale them to the factor `S` you wanted before applying the perspective transformation.

Notes:

+ The origin is whichever you chose as first point, since we assumed it is at `(0, 0)` on the captured surface.
    + The transformation matrix we found is for 2D. Without knowledge of the real size of the QR (or some other reference information), we cannot really tell how far it is. You may have to add a scaling factor for the third dimension.
    + Similarly, the matrix has no concept of what side is up or down. You may have to add a transformation that flips the third dimension.

*I have not tested placing 3D objects*

---

## Demonstration

When I implemented this, I discovered that there is a problem when image\_x4 is equal to image\_x2. The problem is that you get division by zero when computing g... I have tweaked this by replacing zero by epsilon.

Note: the inverse matrix for 2D non-affine transformation similar to the one presented above is the Adjugate matrix:

```
+- -+   +-     -+   +-                    -+
| x |   | a b c |   | x′*w′ = ax + by + c  |
| y | * | d e f | = | y′*w′ = dx + ey + f  |
| 1 |   | g h i |   |   w′  = gx + hy + i  |
+- -+   +-     -+   +-                    -+

=>

+-  -+   +-                 -+   +-   -+
| x′ |   | ei-fh ch-bi bf-ce |   | x*w |
| y′ | * | fg-di ai-cg cd-af | = | y*w |
| 1  |   | dh-eg bg-ah ae-bd |   |  w  |
+-  -+   +-                 -+   +-   -+

```

The code below does not include a method to compute an "inverse matrix" but to apply the inverse transformation of a given matrix.

```
/**
* @export
* */
var Matrix = (function () {
    /**
    * @constructor
    * @param {number} a
    * @param {number} b
    * @param {number} c
    * @param {number} d
    * @param {number} e
    * @param {number} f
    * @param {number} g
    * @param {number} h
    * @param {number} i
    */
    function Matrix(a, b, c, d, e, f, g, h, i) {
        if (typeof g === "undefined") { g = 0; }
        if (typeof h === "undefined") { h = 0; }
        if (typeof i === "undefined") { i = 1; }
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
        this.e = e;
        this.f = f;
        this.g = g;
        this.h = h;
        this.i = i;
    }
    /**
    * @param {number} x
    * @param {number} y
    * @return {Matrix}
    * @export
    */
    Matrix.translation = function (x, y) {
        return new Matrix(1, 0, x, 0, 1, y, 0, 0, 1);
    };

    /**
    * @param {number} theta
    * @return {Matrix}
    * @export
    */
    Matrix.rotation = function (theta) {
        return new Matrix(Math.cos(theta), -Math.sin(theta), 0, Math.sin(theta), Math.cos(theta), 0, 0, 0, 1);
    };

    /**
    * @param {number} scale
    * @return {Matrix}
    * @export
    */
    Matrix.scale = function (scale) {
        return new Matrix(scale, 0    , 0,
                          0    , scale, 0,
                          0    , 0    , 1);
    };

    /**
    * @param {Matrix} a
    * @param {Matrix} b
    * @return {Matrix}
    * @export
    */
    Matrix.product = function (a, b) {
        return new Matrix((a.a * b.a) + (a.b * b.d) + (a.c * b.g), (a.a * b.b) + (a.b * b.e) + (a.c * b.h), (a.a * b.c) + (a.b * b.f) + (a.c * b.i), (a.d * b.a) + (a.e * b.d) + (a.f * b.g), (a.d * b.b) + (a.e * b.e) + (a.f * b.h), (a.d * b.c) + (a.e * b.f) + (a.f * b.i), (a.g * b.a) + (a.h * b.d) + (a.i * b.g), (a.g * b.b) + (a.h * b.e) + (a.i * b.h), (a.g * b.c) + (a.h * b.f) + (a.i * b.i));
    };

    /**
    * @param {Matrix} m
    * @param v
    * @export
    */
    Matrix.transform = function (m, v) {
        var w = v.x * m.g + v.y * m.h + m.i;
        return {x: (v.x * m.a + v.y * m.b + m.c) / w, y:(v.x * m.d + v.y * m.e + m.f) / w};
    };

   /**
    * @param {Matrix} m
    * @param v
    * @export
    */
    Matrix.transformInverse = function (m, v) {
        var w = (v.x*(m.d*m.h-m.e*m.g)+v.y*(m.b*m.g-m.a*m.h)+m.a*m.e-m.b*m.d);
        var y = (v.x*(m.f*m.g-m.d*m.i)+v.y*(m.a*m.i-m.c*m.g)+m.c*m.d-m.a*m.f)/w;
        var x = (v.x*(m.e*m.i-m.f*m.h)+v.y*(m.c*m.h-m.b*m.i)+m.b*m.f-m.c*m.e)/w;
        return {x:x, y:y};
    };

    /**
    * @param a
    * @param b
    * @param c
    * @param d
    * @return {Matrix}
    * @export
    */
    Matrix.perspective = function (a, b, c, d) {
        var _hd = (b.x * (d.y - c.y) + b.y * (c.x - d.x) - c.x * d.y + c.y * d.x);
        if (_hd === 0) _hd = Number.EPSILON;
        var _h = (a.x * (b.y - d.y) + a.y * (d.x - b.x) + b.x * c.y - b.y * c.x + c.x * d.y - c.y * d.x) / _hd;
        var _gd = (d.x - b.x);
        if (_gd === 0) _hd = Number.EPSILON;
        var _g = (-a.x - (_h + 1) * d.x + _h * c.x + c.x + b.x) / _gd;
        var _a = b.x * (_g + 1) - a.x;
        var _d = b.y * (_g + 1) - a.y;
        var _b = c.x * (_h + 1) - a.x;
        var _e = c.y * (_h + 1) - a.y;
        var _c = a.x;
        var _f = a.y;
        var _i = 1;
        return new Matrix(_a, _b, _c, _d, _e, _f, _g, _h, _i);
    };
    return Matrix;
})();

var time = (new Date()).getTime(); // time in milliseconds
var polygon =[{x:60,y:20},{x:100,y:40},{x:100,y:80},{x:60,y:100},{x:20,y:80},{x:20,y:40}];
var angularSpeed = Math.PI / 2;
var source;
var target;
var a = null; var b = null; var c = null; var d = null;
function update()
{
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;
  let angle = angularSpeed * elapsed;
  let translation = Matrix.translation(-60, -60);
  let rotation = Matrix.rotation(angle);
  let matrix = Matrix.product(rotation, translation);
  let points = '';
  for (let index = polygon.length - 1; index >= 0; index--)
  {
      polygon[index] = Matrix.transformInverse(translation, Matrix.transform(matrix, polygon[index]));
      points += polygon[index].x + ", " + polygon[index].y + " ";
  }
  source.setAttribute("points", points);
  if (a !== null && b !== null && c !== null && d !== null)
  {
    points = '';
    let perspective = Matrix.perspective(a, b, d, c);
    for (let index = polygon.length - 1; index >= 0; index--)
    {
        var tmp = Matrix.transform(perspective, Matrix.transform(Matrix.scale(1/120), polygon[index]));
        points += tmp.x + ", " + tmp.y + " ";
    }
    target.setAttribute("points", points);
  }
  time = new_time;
}

// --------------
// Ugly UI code
// --------------
var world;
function getNode(n, v){
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v) n.setAttributeNS(null, p, v[p]);
  return n;
}
jQuery(document).ready(function(){
  world = document.getElementById("world");
  source = document.getElementById("source");
  target = document.getElementById("target");
  var arrow = null;
  var ab = null; var bc = null; var cd = null; var da = null;
  $(world).on('mousemove', function(e){
    let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
    if (d === null)
    {
        if (c === null)
        {
            if(b === null)
            {
                if (a === null)
                {
                    /**/
                }
                else
                {
                    arrow.setAttribute("x1", a.x); arrow.setAttribute("y1", a.y);
                    arrow.setAttribute("x2", x); arrow.setAttribute("y2", y);
                }
            }
            else
            {
                arrow.setAttribute("x1", b.x); arrow.setAttribute("y1", b.y);
                arrow.setAttribute("x2", x); arrow.setAttribute("y2", y);
            }
        }
        else
        {
            arrow.setAttribute("x1", c.x); arrow.setAttribute("y1", c.y);
            arrow.setAttribute("x2", x); arrow.setAttribute("y2", y);
        }
    }
  });
  jQuery(world).click(function(e){
    let x = e.pageX * 1000 / $(world).width(); let y = e.pageY * 1000 / $(world).height();
    if (d === null)
    {
        if (c === null)
        {
            if(b === null)
            {
                if (a === null)
                {
                    a = {x: x, y:y};
                    arrow = getNode('line', {x1: x, x2: x, y1: y, y2: y, "stroke-width":1, stroke:"black"});
                    world.appendChild(arrow);
                }
                else
                {
                    b = {x: x, y:y};
                    ab = getNode('line', {x1: a.x, x2: b.x, y1: a.y, y2: b.y, "stroke-width":1, stroke:"red"});
                    world.appendChild(ab);
                }
            }
            else
            {
                c = {x: x, y:y};
                bc = getNode('line', {x1: b.x, x2: c.x, y1: b.y, y2: c.y, "stroke-width":1, stroke:"red"});
                world.appendChild(bc);
            }
        }
        else
        {
            d = {x: x, y:y};
            cd = getNode('line', {x1: c.x, x2: d.x, y1: c.y, y2: d.y, "stroke-width":1, stroke:"red"});
            world.appendChild(cd);
            da = getNode('line', {x1: d.x, x2: a.x, y1: d.y, y2: a.y, "stroke-width":1, stroke:"red"});
            world.appendChild(da);
            world.removeChild(arrow);
            arrow = null;
        }
    }
    else
    {
        a = null;
        b = null;
        c = null;
        d = null;
        world.removeChild(ab);
        world.removeChild(bc);
        world.removeChild(cd);
        world.removeChild(da);
        ab = null;
        bc = null;
        cd = null;
        da = null;
    }
  });
  setInterval(update, 40);
});
```

```
body{margin:0}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<svg id="world" viewBox="0 0 1000 1000">
<polygon id="target" points="60,20 100,40 100,80 60,100 20,80 20,40" fill="aqua" />
<rect id="ref", x="0" y="0" width="120" height="120" fill="white" stroke="black" stroke-width="1"></rect>
<polygon id="source" points="" fill="red"/>
</svg>
```

To use the demo, click in the background to draw a quadrilateral by clicking in the four corners. The code will transform the rotating hexagon to the quadrilateral you draw. Clicking again will remove the quadrilateral and allow you to draw a new one.

Note: it assumes that whatever you draw is a convex cuadrilateral, no validation is made on that.

---
Tags: transformation, augmented-reality
---


# Question
Title: When creating an FPS style game, how should the iron sights be setup?
I am working on creating an FPS style game for learning purposes. I previously was using self created animations for aiming down the iron sights of a gun. The animation would play when you zoom to iron sights and it would hold it there as long as you have the mouse held down. However, talking to a high rated designer, he told me usually it is done with a second camera that sits perfectly aligned with the guns iron sights. I would imagine you would still have to have an animation that then transitions you into that iron sight camera though. Now my animation works fine but I feel I may run into a problem later down the road if I am approaching it the wrong way from the start.

Can someone verify the right way to do this and explain why it is?

# Answer
There is very rarely any one "right" way to solve this kind of problem, only various ways with pros and cons. The onus is on you to evaluate which pros and which cons matter for *your* specific project and make a choice accordingly.

If your animation-based approach is working for you, you're probably fine.

That said, with the animation approach you're relying on the author of the animation to build it such that the sights end up in the correct spot. It seems likely that human error during an animation tweak could result in the sights being incorrectly aligned. Changes to other game camera properties might cause the animation to fall out of alignment as well.

An approach that, in code, simply finds a camera alignment (possibly using two tagged markers on the gun model) and holds that alignment is perhaps less likely to be subject to this error. Of course, you lose some control over the transition to and from iron sights mode, unless you combine both approaches.

An animation-based approach might also require you to toggle your gun sway off in order to maintain the alignment, whereas the algorithmic alignment approach can always keep the sights in the right spot. Of course, you probably still want to disable or reduce any swaying anyway, since it *should* be less pronounced when holding the gun in a more stable position.

There's a lot of little pluses and minuses like this you have to take into account when making your decision.
> 2 votes

# Answer
A good approach may be to keep your animation "close" and then interpolate the camera's position between both modes while the gun is rising or dropping.

This could even give the effect that the shooter is leaning his head to the side and up to the sighting position.
> 0 votes

---
Tags: unity
---


# Question
Title: Creating straight lines between two Vectors? (and slopes?) (interpolation??) libgdx java
I am trying to make a game with very basic physics (just gravity at this stage). Without using box2d How is the best way to create the solid ground. I will be wanting to make ramps soon, but at this moment i am even stuck trying to make flat ground.

The approach i've been researching involves 'interpolation' between 2 or more vector2's , this sounds perfect for me as I only need very basic levels (think Excitebike for NES) so I want to be able to provide my level-creator class with just a bunch of height values and i want it to create invisible straight lines joining up those height points.

As i said ive seen about "interpolation" in the vector2 or the libgdx.math classes but I'm very confused on how to go about using those commands.

As usual any help is much appreciated, thanks for reading

(EDIT: I am thinking I could use Rectangles between the straight parts but is this going to work when i start introducing sloped ground?)

for example i have the green dots saved as vector2 and i need a method that makes the lines between (straight lines is fine no need for curves etc)

# Answer
## Introduction

I am not familiar with libgdx, yet I can explain a general solution.

We start by the fact that you have a list or array with `Vector2` that represent the terrain. You want to sort this list by the x coordinate, for ease of searching.

*If the list is too large, you may want to move to a hierarchical structure. That is beyond the scope of this post.*

Now, if you need to find the height of the ground on a position `X`, you will search on your data structure for:

* The last `Vector2` with an x coordinate lesser or equal than the place where you need to check (I will call it `A`).
* The first `Vector2` with an x coordinate with the greater or equal than the place where you need to check (I will call it `B`).

If both `Vector2` are have the same x coordinate (that is a vertical cliff) then the height of the terrain is the bigger lower of the y coordinates among the two `Vector2`. Lower because the coordinate system starts at the upper left corner.

Otherwise, you need a linear interpolation between the two points.

---

The idea here is that you have a game object in some location on the map, this game object is falling due to gravity... and you need to know if it is about to thit the ground.

So, let's say that the position of this entity is `(X, Y)`, we will need this `X` to find the segement `A, B` of the ground to compare with.

Once we have found `A` and `B` we can find the height of the ground just below the entity

---

Let's say that the player is falling, and we compute that the next position of the player will be `(X, Y)`. We can then use the method below to find if that is below the ground by comparing `Y` to the height we find.

If it is below the ground, we may want to set `Y` to the height of the ground to make the entity stick to it. Or we may compute a bounce, something like this:

```
float height = getGroundHeight(X);
Y = height - (Y - height)

```

Note: bouncing also requires to reflect the direction of the speed. And this is diregarding the angle. That's another topic.

---

## Finding the vectors

```
<rant>
Java is a disgrace!
I was hoping you could easily do a binary search to find the the vectors on a list...
But no, you can't, even if you write a custom Comparator, because the method for binary search only takes values of the same type of the collection.
Which means you either use the inneficient solution of creating an object just to search, or you iterate yourself, which is error prone.
Thank you for reminding me why I don't use Java.
</rant>

```

I would like to tell you that you should be using an `ArrayList<Vector2>` sorted by the x coordinated of the vectors, and you should be using a binary search because it is more efficient. In fact, I would like to tell you that if you can put your vectors in a tree (an AVL for example) you could get a better performance.

But I don't have the patience to do any of that on Java. So you get an array and a for loop:

```
Vector2[] vectors = getVectors(); // load your vectors or whatever
// ...
public float getGroundHeight(float X)
{
    int length = vectors.size();
    Vector2 A = null; Vector2 B = null;
    for (int index = 0; index < length; index++)
    {
        Vector2 current = vectors.get(index);
        if (current.x > X)
        {
            if (index > 0)
            {
                A = vectors.get(index - 1);
                B = current;
                break;
            }
            else
            {
               // The player is before the ground starts
               // let's say you can fall forever
               return Float.POSITIVE_INFINITY;
            }
        }
    }
    if (A == null)
    {
        // The player is after the ground ends
        // let's say you can fall forever
        return Float.POSITIVE_INFINITY;
    }
    if (A.x == B.x)
    {
        return A.y > B.y ? A.y : B.y;
    }
    Vector2 solution = getSolution(A, B); // the code implemented below
    return solution.y;
 }

```

I hope this code is self explanatory. It may need some tweaking for what you want to do (in particular, those `Float.POSITIVE_INFINITY`) and it is the naive approach, so it isn't very efficient... but should get the idea accross.

`getSolution` is what we will be implementing the rest of the post.

---

## Using slope

When using the slope, we are taking advantage of the orientation of the segment. We know that the segment is not vertical. If it were, we would get a division by zero when we reach the computation of the slope `slope = diff.y / diff.x`.

Futhermore, this approach will only work on 2D. Once we go to higher dimensions it is no longer effective.

So, you can consider the slope method an optimization for the case where we know that we are working on 2D and the segment is not vertical.

This approach comes from linear algebra.

Start with the difference:

```
diff = B - A

=>

diff.x = B.x - A.x
diff.y = B.y - A.y

```

This vector represents how much does the segment advance in x and y from the point A to the point B.

By using it, it is easy to get the `slope`:

```
slope = diff.y / diff.x

```

This is how much does the segment advance in y for each pixel it advances in x. We will use it to find how much the segment has advanced when we are at the position `X`:

```
delta.x = X - A.x
delta.y = slope * delta.X

```

Here, `delta.x` is how far from `A` is `X` horizontally. We multiply it by the `slope` to get how much had the segment advanced vertically at that point (`delta.y`).

The only thing missing is to add the start of the segment to it:

```
solution.x = X
solution.y = delta.y + A.y

```

Here the vector `solution` is the point on the ground at the coordinate `X`.

---

## Using vector projection

The advantage of the vector projection approach is that it will work in any situation, no matter what. It will continue to be useful even on 4D and beyond, no need to worry about.

This approach comes from analytical geometry.

Again, we start with the difference, the same way as above. Then we built a temporal vector to project onto the segment:

```
tmp.x = X - A.x
tmp.y = 0

```

Then the projection is:

```
delta = diff * (diff · tmp) / |diff|^2

```

Where "\*" denotes scalar product, "·" denotes dot product, and "||" denote the norm of the vector.

We can understand this as using the director vector for `diff` (`diff / |diff|`) and scale it to `(diff · tmp) / |diff|`... that last part is how much we have to advance *in the diagonal* from `A` to `B` to get to the solution.

Let's break that formula down:

```
delta.x = diff.x * (diff.x * tmp.x + diff.y * tmp.y) / (diff.x * diff.x + diff.y * diff.y)
delta.y = diff.y * (diff.x * tmp.x + diff.y * tmp.y) / (diff.x * diff.x + diff.y * diff.y)

```

We end by adding `delta` to `A`:

```
solution.x = delta.x + A.x
solution.y = delta.y + A.y

```

Note: `delta.x + A.x` sould be equal to `X`.

---

## Using interpolation function

The interpolations are based on the same principles as the vector projection, but they provide additional flexibility by abstracting the "easing" of the values.

Here the challenge is to figure out how much do you have to advance *in the diagonal* from `A` to `B`. We already saw the formula for that:

```
alpha = (diff · tmp) / |diff|;

```

Another approach to get it is with trigonometry, but I'll not go into that.

This value alpha is what you would feed into the interpolation function.

In practice this solution will probably be more expensive because the implementation will add an additional step to support the easing the values (a task delegated to the `Interpolation` class). I would not use it unless I need it. It is here for sake of completness (and also because I'm learning a bit of Libgdx by doing so).

---

Addendum: what the above gives you is the point on the ground. You still need to check if the player (or whatever object) is about to go below it (here below, means a greater value, because the coordinate system starts at the upper left corner), and have stick to the ground, bounce, or whatever.
> 2 votes

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


title: How to properly rotate a Turret?

text:
# Question
Title: How to properly rotate a Turret?
I'm having problems understanding how to properly rotate a Turret. Using Unity Editor, I've simulate turret movement, so I take note that turret can move with this clamp factor (for instance):

( value expressed in euler angles )

X = 1-4

Y = 0-0

Z = 98-100

I've write this code but it not works properly:

```
float rotX = Random.Range (Cannon1MinX, Cannon1MaxX);
float rotY = Random.Range (Cannon1MinY, Cannon1MaxY);
float rotZ = Random.Range (Cannon1MinZ, Cannon1MaxZ);

Cannon1.transform.Rotate (new Vector3 (rotX, rotY, rotZ),Space.World);

```

Every time I've to work with rotation i become mad :(

What is wrong ? Thanks

# Answer
If you use Euler angles to rotate it might lead to Gimbal Lock. To properly rotate your turret you will need to use Quaternion.

---

If you simply need a turret to look on some object rotating all axis, you can use `transform.LookAt(Vector3 positionOfTheEnemy)`.

You can restrict this rotation too, for example, before calling previous method, you need to set the Y position to position of the object you are trying to rotate. Meaning that no rotation is required for some axis because "it is aligned with object you are trying to rotate"(actually it's not, but we make it think so).

```
Vector3 positionOfTheEnemy = enemy.transform.position; // Creates a new object type of Vector3 because it's struct, so it has no reference to enemy position
positionOfTheEnemy.y = turretTransform.position.y;
turretTransform.LookAt(positionOfTheEnemy);

```

---

If you need some kind of specific rotation you can use:

`transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, valueBetween0And1);` Quaternion.Slerp

`transform.rotation = Quaternion.Lerp(currentRotation, targetRotation, valueBetween0And1);` Quaternion.Lerp

---

If you need to rotate it by euler angles - you can use `Quaternion.Euler()`.

And many other methods and things that quaternions can do.
> 2 votes

# Answer
If you see in the example: https://docs.unity3d.com/ScriptReference/Transform.Rotate.html

```
// Rotate the object around its local X axis at 1 degree per second
    transform.Rotate(Vector3.right * Time.deltaTime);

```

Move one axes at a time and see how the value are moving for your need, example:

```
transform.Rotate(Vector3.right * x);                // for X+ axis
transform.Rotate(Vector3.up * y);                   // for Y+ axis
transform.Rotate(Vector3.forward * z);              // for Z+ axis

```

Then you can tweak them accordingly.

Note: Try a constant value and generate random values one axis at a time, otherwise it wont make sense as the turret moves.
> 1 votes

---
Tags: unity, rotation
---


# Question
Title: Can I change the background color where a sprite is shown in the inspector?
this is how a sprite shows in the inspector. It's white pixelart with transparent background. Is there a way to change the background checkered pattern color in the inspector so I can actually see the sprite?

Note: I don't want to change any color in the game, just the background in the inspector, in the editor, so there's some contrast and I can actually see the sprite pattern.

# Answer
> 2 votes
# Use a custom editor with sprite preview

**(EDIT: now supports multi-sprite images)**

1. Create an empty script (or use one you already got), let's call that `TestScript`.
2. Place this script on an empty game object.
3. Add a *Sprite Renderer* component to that object.
4. Add another script, let's name it `SpritePreview`. It should inherit from `Editor`. You can place the code for that class in the same file as the `TestScript`.

**SpritePreview**

```
[CustomEditor(typeof(TestScript))]
public class SpritePreview : Editor {
    public override void OnInspectorGUI() {
    var sr = ((TestScript)target).GetComponent<SpriteRenderer>();

    // it's not enough to check for the renderer as it might be empty
    if (sr && sr.sprite) {

        // we need the rect in pixels to reserve space in the layout system
        // we also use it for calculating the rect in percentage
        var rect = sr.sprite.rect;

        // reserve a rect in the layout of the editor, we will draw the sprite there
        var destRect = GUILayoutUtility.GetRect(rect.width, rect.height);

        // the texture, this object contains all of the sprites in case of a multiple sprites image
        var texture = sr.sprite.texture;

        // calculate the rect of the selected sprite as a percentage of the sprite sheet
        // this is how TexCoords work
        var rectAsPercentage = new Rect(rect.x / texture.width, rect.y / texture.height,
                               rect.width / texture.width, rect.height / texture.height);

        // draw the selected sprite
        GUI.DrawTextureWithTexCoords(destRect, texture, rectAsPercentage);
    }
    }
}

```
5. Now select a sprite in the sprite renderer.
6. You will see the preview in the editor, with grey background, like this:

## EDIT: i've updated the script to also work with multiple sprite resources:

# Answer
> 0 votes
You can change texture type to advanced and uncheck Alpha Is Transparency checkbox. It still behaves as Sprite in the game as far as I tried, though be careful about other values and read about them before changing. Sprite still has transparency in the scene and the game views.

---
Tags: unity, sprites
---


title: Software and Hardware Rendering

text:
# Question
Title: Software and Hardware Rendering
From what I understand, the main difference between software rendering and hardware rendering is that in software rendering you use the CPU to determine what to color each pixel, and in hardware rendering you let the GPU take care of calculations and determine how to draw each pixel.

However, in the end, isn't an API such as OpenGL still required to do the actual drawing no matter which method you pick? I saw a basic software rendering engine that someone built, and the person said he still used OpenGL to do the actual drawing after using the CPU to do the rendering. So is an API like OpenGL or DirectX still required in the end? And if so, is it true that a computer must at least have an integrated GPU or dedicated GPU to display anything at all?

# Answer
> 3 votes
> From what I understand, the main difference between software rendering and hardware rendering is that in software rendering you use the CPU to determine what to color each pixel, and in hardware rendering you let the GPU take care of calculations and determine how to draw each pixel.

Basically, yes. The difference is that you have *complete* control over a software rendering pipeline, because you're building it on generalized computational hardware. A modern GPU is a much more specialized machine, and even though they are reasonably programmable these days, there are still aspects of them that are not, and they are still purpose-built to accomplish their task in a very particular fashion.

> However, in the end, isn't an API such as OpenGL still required to do the actual drawing no matter which method you pick?

Yes, *some* API that ultimately deals with communicating with the graphics hardware is required. While modern versions of operating systems generally composite their windows with OpenGL or D3D, this is only relatively recently the case. Older operating systems would have talked to different drivers to get pixel data from their drawing APIs (such as GDI, for Windows) pushed across to whatever graphics hardware was attached; typically direct access to the video memory was exposed via some mechanism.

> I saw a basic software rendering engine that someone built, and the person said he still used OpenGL to do the actual drawing after using the CPU to do the rendering.

In a modern machine, you can no longer get direct access to video memory, so modern software rendering pipelines tend to do everything on the CPU until they have a final, rasterized 2D image. Then they "blit" that image to the screen by rendering it as a fullscreen quad with some hardware graphics API like OpenGL.

> And if so, is it true that a computer must at least have an integrated GPU or dedicated GPU to display anything at all?

Yes. All computers need some kind of hardware to convert visual information to an output device. The specific term "GPU" was pushed in the late 90s, mainly by Nvida, so prior to that we tended to call these chips different things, but ultimately some kind of hardware was always involved.

---
Tags: opengl, rendering, software-rendering
---


# Question
Title: How to continue firing when button is touched?
How to continuos firing when user touch (and keep press) a button in Android/iOs?

Using onClick, i can fire only one shot.

Is there an event like "keep-touch" ?

Thanks

# Answer
> 2 votes
Check this example on using touch on Mobile devices: https://docs.unity3d.com/Manual/MobileInput.html

Similarly you can use this code to use a boolean variable to start and stop shooting based on touch

```
// global
bool bContinuousShoot = false;

// In Update loop
for (var touch : Touch in Input.touches) {
    if (touch.phase == TouchPhase.Began) {
        bContinuousShoot = true;
        // You code goes here...
    } else if(touch.phase == TouchPhase.Ended) {
        bContinuousShoot = false;
    }
}

```

TouchPhase reference: https://docs.unity3d.com/ScriptReference/TouchPhase.html

# Answer
> 1 votes
Supposing you are working with UGUI buttons, you can attach pointer down and pointer up listeners to the buttons. I haven't tested the following code, tell me if you have any problem.

```
// At the top of your file
using UnityEngine.UI ;

// ...

// Class member
public float fireRate = 0.1f ;

// Drag & Drop the UI button in this field of the inspector
[SerializeField]
private Button shootButton ;

private bool continuousShoot = false ;

private float nextShootTime = 0 ;

private void Awake()
{
    if( shootButton == null )
        throw new Exception("You haven't assigned a button on the inspector");

    EventTrigger eventTrigger = shootButton.AddComponent<EventTrigger>( );

    // Pointer down
    EventTrigger.Entry pointerDownEntry = new EventTrigger.Entry( );
    pointerDownEntry.eventID = EventTriggerType.PointerDown;
    pointerDownEntry.callback.AddListener( ( data ) => { EnableContinuousShoot(); } );
    eventTrigger.triggers.Add( pointerDownEntry );

    // Pointer up
    EventTrigger.Entry pointerUpEntry = new EventTrigger.Entry( );
    pointerUpEntry.eventID = EventTriggerType.PointerUp;
    pointerUpEntry.callback.AddListener( ( data ) => { DisableContinuousShoot() ; } );
    eventTrigger.triggers.Add( pointerUpEntry );
}

private void Update()
{
    if( continuousShoot && Time.time > nextShootTime )
    {
        nextShootTime = Time.time + fireRate ;
        Shoot() ;
    }
}

private void Shoot()
{
    // Your code here
}

private void EnableContinuousShoot()
{
    continuousShoot = true ;
}

private void DisableContinuousShoot()
{
    continuousShoot = false;
}

```

---
Tags: unity
---


# Question
Title: Re scaling an object from its current scale to a scale of 0
I want to have an animation which starts at a starting scale of whatever the current gameObject's scale (i.e 1, 1, 1 or 2, 3, 2) is which then end at a scale of 0, 0, 0.

The problem is that Unity's animator has fixed values and so, I cannot make one animation that would easily apply to every object.

I'm fine with using C# code to do this but I haven't been able to find anything that works yet. Thanks for your help!

# Answer
You have to take 2 things into account:

* duration
* current scale value

Scale property is a Vector3 (x,y,z) and you want to go from initial\_scale\_value to Vector3.Zero. Here is an example you can use in a coroutine.

```
private IEnumerator Unscale()
{
    float ratio = 0;
    float duration = 5; // let's say we want a 2s animation
    float start_time = Time.time; // time when the animation began
    Vector3 initial_scale_value = transform.localScale;
    do
    {
        yield return new WaitForEndOfFrame(); // wait for next frame
        ratio = (Time.time - start_time) / duration; // update the ratio value at every frame
        transform.localScale = Vector3.Lerp(initial_scale_value, Vector3.zero, ratio); // apply the new scale
    } while (ratio < 1);
}

```

However, even if you can do it using a few lines of code, if you need to do that kind of stuff often I recommend you to use a Tween engine, such as DOTween that I strongly recommend (I used it a lot and it does awesome things with great performances).
> 0 votes

---
Tags: unity, c#, animation, gameobject, scale
---


# Question
Title: Convert a transformation matrix from world-space to camera-space using Eigen
I have a transformation matrix, in world space. I need to convert it to local(camera) space.

I have done the reverse of this (Local - to - world) using:

```
Eigen::Matrix3f R0; //rotation matrix
Eigen::Vector3f T0; // xyz translation values
Eigen::Vector3f C0; //result

R0.transposeInPlace();  //invert rotation matrix

C0 = -R0 * T0;   //return world-space coordinate

```

Can I simply run this exact same thing to invert it the other way? Or is it a different equation?

# Answer
Aha, to solve the reverse, i can simply use:

```
Eigen::Matrix3f R0; //rotation matrix in world space
Eigen::Vector3f T0; // xyz translation values in world space
Eigen::Vector3f C0; //result

R0.transposeInPlace();
C0 = -R0 * T0;

```

So it is the same equation.
> 1 votes

---
Tags: c++, matrix, transformation
---


# Question
Title: Unity 5.5.1f1 new UI system: Button in scrollview is not working on Android. Is this known issue? Is there a workaround?
It works perfectly in the editor, but on Android it only sometimes registers an OnClick when I press it with my finger.

I'm on Unity 5.5.1f1

Is this a known issue? I'll post some videos of it if no-one has seen this before.

The scrollview is based on the default one from the Create\UI\scrollview menu Ive added a vertical layout group to it, to which I add prefabs that contain buttons. These are the buttons that are not working. The canvas is in front of the camera in worldspace and is scaled down to 0.02 in X and Y

VVVVVVVVVVV UPDATE VVVVVVVVVVVVV

I wrote my own workaround using 2D colliders instead of buttons The colliders are registering hits just fine. But when I wrote a class to not register hits if the scrollview moves, I get similar behaviour! Heres the crude little workaround class I wrote..

```
public class ScrollButton : MonoBehaviour
{
    public StoreItem Item;

    bool FingerDownOnMe;

    public void BeOnClicked()
    {
        VisualDebuggerRef.SetTxt("a store button" + " " + Random.Range(0, 10000));
        FingerDownOnMe = true;
    }

    // This is called on all these objects whenever the scrollview moves
    public void ScrollviewMoved()
    {
        FingerDownOnMe = false;
    }

    void Update()
    {
        // 'UppedthisFrame' will be true whenever any touchs phase == TouchPhase.Ended
        if (Refs.man.Clickdetect.UppedthisFrame && FingerDownOnMe)
        {
            FingerDownOnMe = false;
            Item.ButtonHit();
        }
    }
}

```

I'm guessing Unities UI classes work in a somewhat similar way to my workaround one. The problem is that the scrollview is registering as being moved when it should not be. This may be because of my test device which is an S7. Maybe the touch resolution is so high it is registering movement that is smaller than one pixel??

Also maybe the fact the the entire canvas has been scaled down could be affecting this? Say Unities classes have a distance threshold, if they are not taking into account scale then working on a scaled down canvas might make the distances they are using too big, so the threshold is reached too easily

Im going to add a distance limit to my workaround...

VVVVVVVVVVVVV UPDATE2 VVVVVVVVVVVVVVVV

This workaround code using colliders works perfectly..

```
public class ScrollButton : MonoBehaviour
{
    const float scrollThreshold = 0.25f;

    public StoreItem Item;

    bool FingerDownOnMe;
    Vector3 HitPos;

    public void BeOnClicked()
    {
        //VisualDebuggerRef.SetTxt("a store button" + " " + Random.Range(0, 10000));
        FingerDownOnMe = true;
        HitPos = transform.position;
    }

    void Update()
    {
        // 'UppedthisFrame' will be true whenever any touchs phase == TouchPhase.Ended
        if (Refs.man.Clickdetect.UppedthisFrame)
        {
            if (FingerDownOnMe && Mathf.Abs((transform.position - HitPos).y) < scrollThreshold) Item.ButtonHit();

            FingerDownOnMe = false;
        }
    }
}

```

I'm going to report this issue as a bug to Unity

# Answer
This is a bug in Unity. (see more details on how I figured this out in question) I reported it. from unity QA...

" Hey,

We have been able to reproduce this bug and have sent it for resolution with our developers.

We highly appreciate your contribution. If you have further questions, feel free to contact us.

Regards, \[Name removed\] QA Team "
> 0 votes

---
Tags: unity, android
---


title: glDrawElements/Arrays not working

text:
# Question
Title: glDrawElements/Arrays not working
Given the following OpenGL call stack.

According to my knowlegde, the calls to glDrawElements/Arrays are ok.(?)

But, they do not draw anything. (There is no triangle)
The calls to glBegin() and glVertex() works fine.

Full source: here

# Answer
> 1 votes
Turns out LWJGL does not allow the use of .wrap() to create a FloatBuffer?
Use BufferUtils.createFloatBuffer(), then put() and flip().

Ive created an issue on their github to see the answer

# Answer
> 0 votes
At https://github.com/stelar7/engine/blob/master/src/main/java/no/stelar7/engine/rendering/buffers/VertexBufferObject.java#L54 you have:

```
glBufferData(type, data, draw);

```

And likewise at your other glBufferData call.

These are not legal glBufferData calls; please see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBufferData.xhtml

```
void glBufferData( GLenum target,
                   GLsizeiptr size,
                   const GLvoid * data,
                   GLenum usage);

```

As you'll see, glBufferData actually has 4 parameters, with the second one - `GLsizeiptr size` \- being the one that is missing from your calls. It's also important that this is the size of the `data` parameter in bytes, and *not* the number of items in an array.

# Answer
> 0 votes
You should bind the element array before you draw something with it. It's not a problem now, because you only have a single element buffer, but if you want to draw multiple meshes, it's necessary.

You don't actually need to disable anything, it only introduces unnecessary function calls.

---
Tags: opengl, java, lwjgl, lwjgl3
---


title: Too slow for cycle in Pygame

text:
# Question
Title: Too slow for cycle in Pygame
I'm using Pygame for Python 2 and I have the following code:

```
self.radius = 100
self.light = pygame.Surface((2*self.radius, 2*self.radius), pygame.SRCALPHA)
self.light.fill((0, 0, 0, 0))
pygame.draw.circle(self.light, (255, 255, 255), (self.radius, self.radius), self.radius)
alphas = pygame.surfarray.pixels_alpha(self.light)
for x, col in enumerate(alphas):
    for y, pixel in enumerate(col):
        pixel = 255 - f.distance(pygame.Rect(x, y, 1, 1), pygame.Rect(self.radius, self.radius, 1, 1))

```

Basically this code creates a new surface, makes it transparent so that it doesn't interfere with the background, draws a circle on it, and then makes two nested `for` cycles, going through all of the pixels. The problem is, these `for`s are too slow. How can I improve their performance?

# Answer
> 4 votes
Your problem here is that this does not work for CPU, it should be done using GPU, probably you can access it in pygame. It's the work of pixel shader and it works on very low level, with thousands of microprocessors that have no memory - that what makes it so fast to process each pixel.

When you are trying to do it in loops - its complexity is \\$O(n m)\\$, so you are asking your processor to go through 1920 * 1080 items on 1 thread, for example, its a resolution. Which makes it 2073600 times of CPU cycles, which is quite long. When GPU would take them one by one in 320 threads (it depends on card model) or more. Plus python is very slow in comparison to C or C++, so writing game on it might be quite difficult. Though python is written in C, so maybe there are shaders in pygame - you should check this out.

Can't you use semi-transparent texture for that? Also, you can try to find better algorithm that is probably \\$O(nlog\_2(m))\\$. I would also limit the amount of pixels to process to only area that pixels can be lit.

And the last thing, if you are changing textures of sprites on the background - it's bad because you would have to turn them back when area is not lit. So it's better to draw some texture over it.

---
Tags: performance, python, pygame
---


title: OpenGL scissor odd behaviour

text:
# Question
Title: OpenGL scissor odd behaviour
I am currently developing a GUI app using OpenGL with OpenTK as interface in C#.

The viewport is set to the entire window space (0,0,width,height) and an ortho transformation is applied like this:

```
GL.MatrixMode(MatrixMode.Projection);
GL.LoadIdentity();
GL.Ortho(0, width, height, 0, 0f, 1f);

```

With this I can draw objects just like I would do in GDI+ using X,Y coords.

The issue appears when I want to clip elements within their parent's area. I am doing it using glScissor. I am using a stack to keep trace of the scissored areas like so: static Stack stack = new Stack();

```
internal static void Scissor(Rectangle rect)
{
    applyScissor(rect);
    if (stack.Count == 0) GL.Enable(EnableCap.ScissorTest);
    stack.Push(rect);
}

internal static void RemoveScissor()
{
    if (stack.Count == 0) throw new Exception("Unblanaced stack.");
    stack.Pop();
    if (stack.Count == 0)
    {
        GL.Disable(EnableCap.ScissorTest);
    }
    else
    {
        var rect = stack.Peek();
        applyScissor(rect);
    }
}

static void applyScissor(Rectangle rect)
{
    GL.Scissor(rect.X, rect.Y, rect.Width, rect.Height);
}

```

It works fine whenever the height is "big" enough but if the values for the height given to the scissor are "small" it doesn't work.

Example without scissors:

Example with scissor

Example when I scissor with half the needed height:

(In the last case I cannot understand why it shows the bottom half instead of the top half.)

Basically there is an element (the blue box and the text) within the red box with a blue border that should be clipped within and there should be only a small portion of the A visible but at the very least the blue rectangle should be visible. However it is not. :/ The scissor test does work fine however if the height is "big" enough as I mentioned, being able to move the red box with blue borders outside the area of its parent and it wouldn't be visible.

I need to know why that is and how to fix it.

PS. The issue is not only on OS X so it's not the platform.

PS2. I did check the values given to the scissor and they are correct. The area of the red box with blue border is 175,20 with size 36x36.

# Answer
Turns out the Scissor function uses the y value wrong for whatever reason. In my case I would need to alter the y value to

```
windowHeight - scissorHeight - y

```

The actual call would look like this

```
internal static void ApplyScissor(Rectangle rect)
{
    GL.Scissor(rect.X, windowHeight - rect.Height - rect.Y, rect.Width, rect.Height);
}

```

If anyone has any clue of why that is please let me know. In a sense it wants me to give the bottom left corner, but that really doesn't make any sense.
> 1 votes

---
Tags: c#, opengl, .net, opentk
---


title: Gfx.WaitForPresent performance issue

text:
# Question
Title: Gfx.WaitForPresent performance issue
I am making a 2D mobile game and it runs really well (60 fps) on my phone. However, in some cases the performance goes down drastically to the point where it runs at 20 fps or even less. It happens at random times so I can't pinpoint what is causing this. During the performance decrease Gfx.WaitForPresent appears in my profiler which eats a lot of power. I am aware that this might be because of Vsync being turned on, but I have it disabled, along with shadows, AA and everything else that absolutely kills mobile performance. What else can be the problem? My game relies heavily on good performance for gameplay so this needs to be resolved ASAP.

Edit: I also noticed that the GPU stays at 0 ms which is really odd as well.

# Answer
> 1 votes
Disabling "multithreaded rendering" from Player Settings \> Other settings might work (As these guys have pointed out)

My own experience was some postprocess effect was horribly conflicting with the hardware I was developing on (though mine was PC). I found out the culprit by deactivating everything (gameobjects and components) in the scene one by one. (I had noted down other people's solutions here)

Hope this helps.

# Answer
> 1 votes
well I can tell you from my experience that for me the SpeedTree's caused that. what the profiler is saying to you is "I have to wait for rendering to end before i call for the next frame update" therefor you get this bottle neck that chokes your application and that's why it uses 0 ms. there is a tutorial made by Unity regarding the Profiler and at the middle approx. he is talking about this issue and name a few things that might cause it.

Live Training June. 22, 2015: Profiler Overview for Beginners

by the way its weird that its unity 5.3.5 cause on my profiler that Gfx.WaitForPresent is inside the Camera.Render and I can try and analyze it in a way.

good luck identifying the source of that. hope my answer helps.

# Answer
> 1 votes
In the profiler capture it looks like `SetPass` and `Triangles` increase rapidly. Multiple cameras and render textures indeed can cause that because the scene has to be rendered multiple times.

# Answer
> 0 votes
I finally figured out what was causing my Gfx.WaitForPresent spikes . . . for me it was the Inspector inside the Unity Editor that was causing it. If I closed the Inspector tab, or switch to say the Lighting tab so the Inspector is not visible, my Gfx.WaitForPresent issues go away.

I could also control the frequency and amount of lag of Gfx.WaitForPresent depending on what I had selected while the Inspector tab was visible. I think the Profiler is taking the complexity of whatever the Inspector is drawing into account and that's when Gfx.WaitForPresent spikes.

At least on my system that is, I would try it and see if it does anything on your machine.

My specs: Win 7 x64 Unity 5.5.0f3, profiling from the Editor window (not external profiling) also profiling with Maximize on Play = Off.

# Answer
> 0 votes
My problem was a high resolution texture I used for terrain (8192 x 8192). It wasn't an all time lag, more like occasional spikes of 40-60 ms. It didn't matter if I'm zoomed in on terrain, or completely zoomed out scrolling camera around, spikes were the same. After that, I split the terrain into 1024 x 1024 chunks and spikes went down to 5 - 10 ms max.

# Answer
> -1 votes
For me, a simple Unity restart worked out, lol.

---
Tags: unity, performance, frame-rate, profiler
---


# Question
Title: Rotating kinematic object around a moving point Box2D
I'm new at Box2D and I am making a simple game where you control the rotation of the maze and the gravity leads the ball to the exit.

**The game looks like:**

**The problem:** I want to rotate the maze, and I'm doing it well. It is a kinematic object, so it will only move when I want. But it always rotate on a static pivot, I think that's it's center of mass. Rotating the maze, the ball hits the walls and when too further to the center, it becomes hard to control the movement of the ball by rotating the maze as the centrifugue force is too high for the ball.

**What I want:** I want to change the maze's rotation pivot to the ball's position, every game loop/frame, so it will rotate around the ball always and I will be able to use only gravity, not centrifuge forces, to lead the ball to the exit.

**What I tried:** I already tried to find a function to change the pivot center, or the center of mass, but I only found to change the mass proprieties. It changes the center of mass only if it was a dynamic body. Even the kinematic body having the same localCenter.x and localCenter.y proprieties as the dynamic body, it remains on (0.0 ,0.0) when trying to change it. And when changing the localCenter on the dynamic body, it doesn't rotate at this point anyway, so I'm not sure what to do.

Is there any possibility to change the center of the kinematic body all the time? I'm using Box2D Vestion 2.3.2, as you can see on the picture, and Visual Studio 2013 with OpenGL.

Thanks!

# Answer
> 1 votes
As you realized, changing the gravity can work for you.

It sounds like you may also be looking for a function that rotates a body around a point in world coordinates. I wrote a function for this in my fork of Box2D (`RotateAboutWorldPoint`) that I have translated to Box2D 2.3.2 for you as the following code:

```
void b2RotateAboutWorldPoint(b2Body& body, float32 amount, b2Vec2 worldPoint)
{
    const b2Transform xfm = body.GetTransform();
    const b2Vec2 p = xfm.p - worldPoint;
    const float32 c = cos(amount);
    const float32 s = sin(amount);
    const float32 x = p.x * c - p.y * s;
    const float32 y = p.x * s + p.y * c;
    const b2Vec2 pos = b2Vec2(x, y) + worldPoint;
    const float32 angle = xfm.q.GetAngle() + amount;
    body.SetTransform(pos, angle);
}

```

This can be used then to rotate the kinematic body that is your maze, around the position of the ball.

Also, in case you haven't done this already, you'll probably want to make your ball be a bullet object. That'd at least help with avoiding seeing as much non-physical behavior if you're rotating your maze using the `SetTransform` method. I believe an alternative (to using `SetTransform`) would be to make your maze be a dynamic object and use a revolute joint on it. Seems it'd still be a good idea though to make the ball be a bullet object.

---
Tags: box2d, rotation, kinematic
---


title: Source code of Minecraft servers?

text:
# Question
Title: Source code of Minecraft servers?
Is there any way to get the source code of Minecraft servers? I tried decompiling but I get very obfuscated arguments, classes, and methods.

If the answer is no, how did services like Bukkit and Spigot create their 'servers'?

# Answer
There is the modcoderpack. It contains the minecraft client and server code: http://www.modcoderpack.com/website/releases
> 3 votes

# Answer
As far as I'm aware, your only option is to decompile the `.jar` and cope with the fact that the results are obfuscated, just like everybody else. In the past, there were tools to help deobfuscate the decompiled Minecraft code, as discussed here. I have no idea if such tools are still maintained, and as such can't make recommendations.

In theory you could obtain a source license from Microsoft, and get the raw source that way, but only if they were even willing to entertain such a deal in general and with you in the specific.
> 0 votes

---
Tags: minecraft-modding
---


# Question
Title: How can you procedurally dismember a character model?
For example in the new Doom, you can use a chain saw and slash an enemy apart, the enemy actually splits in half in the path of the chain saw. I know how to do the cheap effects where you store a copy of an already chopped up model and then when you kill the enemy it's replaced with the chopped up model. But the real good ones, like in Doom or Shadow Warrior, split depending on how you slash it. How do they do that? I've been searching this on google for the past year, and I haven't found many tutorials or articles on it. Please help!

Example: https://www.youtube.com/watch?v=96LInqKNCHY

# Answer
I do believe Doom uses a set of pre-build slicing animation for where the chainsaw hits the enemy. After that you can use some sort of mesh slicer to slice the target mesh according to the chainsaw impact. The blood spray could be made with a combination of a particle system and decals. This is a really good mesh slicing system for unity to get you started.
> 1 votes

---
Tags: unity, 3d, rendering, software-engineering, graphics-programming
---


title: How to reuse frames in a 2D animation?

text:
# Question
Title: How to reuse frames in a 2D animation?
This is my sprite sheet, when I select the frames and drag them into the scene view to create the animation, it just creates an animation with the selected frames in sequence and I can't figure out how to change that sequence.
If we numbered the frames from left to right and top to botom, I'd need the sequence to be: 2-3-5-2-4-6- and loop.

I can just repeat the frames in the intended sequence, but there must be a smarter way to do this.

# Answer
Look at the Animation Panel (Window \> Animation). Your animation frames are there. From there you can simply drag one frame to another position in animation to change its place. You can also add other frames, or copy some.
> 1 votes

---
Tags: unity, 2d, animation, sprites
---


title: Simple Line Formation

text:
# Question
Title: Simple Line Formation
I'm working on the first formation for my game's troops. These should simply stand on land, facing the same direction.

To achieve this, I tried to create offsets towards a pivot-unit, that is approximately the unit in the center of the formation. The units are (temporary) elements of a squad list withing the Squad class. I divide the List by 2 and get the closest integer, that should be the pivot point of the formation. Now I generate offsets for all units on the left side (Unit 1 to pivot-1) and right (pivot+1 to last unit) based on the distance/gaps.

This is the code for the line formation. Sadly, the units are only forming a very stange line with no visually detectable system:

```
int count = (int)(squadMembers.Count / 2);
pivot = squadMembers[count];
center = pivot.transform.position;
switch (type) {
    case FormationType.Line:
        int space = 5;
        for (int i = 0; i < squadMembers.Count; i++) {
            Unit tmp = squadMembers[i];
            int dist = 0;
            if (i > count) {
                dist = (count + 1) * space;
                center.x -= dist;
            }
            if (i < count) {
                dist = (count - 1) * space;
                center.x += dist;
            }
            tmp.StartMove(center);
        }
        break;
}

```

It also appears that this only works along the x axis, any idea how i can realize this with the walking/facing direction ov the pivot?

Is there any (obvious) error? How can I improve this script?

PS: Any idea, how I can transform this into a double line (2 Lines behind with half spacing)

# Answer
> 2 votes
Well I hope I understood your question correctly: you want your squad members at the same distance from one to another, facing the same direction and forming a line.

First I'd tackle the direction issue. Let's say there is a point in world called `destination` they are aiming to. You may want to create a `Vector3` describing the difference between `destination` and the position of the first member. This will give you the orientation to be aligned to. Once you got that you just have to normalize this vector and multiply it by the distance you want between squad members. This will give you an offset to apply from a member to another. So... adding this offset to the first member position will give you the second member position... and so on.

Once the alignement is not a problem anymore, making your unit members look in the same direction (means, looking at `destination` point), you can simply use LookAt method on their `Transform`.

Something like this (edited to use the pivot):

```
public class Aligned : MonoBehaviour
{
    [SerializeField]
    private List<Transform> units;
    [SerializeField]
    private GameObject destination;
    [SerializeField]
    private float distance = 5;

    private void Start()
    {
        // Find the ID of the pivot
        // ie: unit at the center of the line / list
        int pivot_id = units.Count / 2;
        Transform pivot = units[pivot_id];
        // Make the pivot look at the destination and save the rotation
        pivot.LookAt(destination.transform);
        Quaternion look_rot = pivot.rotation;

        // Create the offset between units
        Vector3 offset = pivot.position - destination.transform.position;
        offset = offset.normalized * distance;
        for (int i = 0; i < units.Count; ++i)
        {
            // Apply position offset
            units[i].position = pivot.position + offset * (i - pivot_id);
            // Make the unit look at the destination point
            units[i].rotation = look_rot;
        }
    }
}

```

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


title: Long distance walking and fast travel

text:
# Question
Title: Long distance walking and fast travel
I'm developing a sort of ’social mmmo’ where people build an avatar and chat with people around them, carryout tasks together, and play team games.

At the moment I have a product I want to release to beta testers but I only have 2 locations ready and they are quite far apart.

I have a fast travel system in place where people can pay to ride the bus making any journey take a short period of time.

If people run out of money they either have to earn more or make the walk themselves.

In the beta would it be better to make the bus free, or have people walk the empty land to get to the other town if they run out of money?

At the moment the land is just plain grass, hills, a river, and the odd tree with nothing of interest.

The journey currently takes around 10-15 minutes to walk if you know the way.

# Answer
First: **Why should you have fast-travel in the first place?**

Because fast travel has an important function: It prevents boredom.

Traversing a well-designed area for the first time is interesting because there is lots of new stuff to discover for the player. The player is exploring, which is one of the four major appeals of MMOs. But when traversing it again, the novelty has worn off and it becomes boring. You don't want the players to experience boredom, so you shouldn't force them to make the same hike multiple times. That's why many games have fast-travel systems which get unlocked for each route after the player has traversed it manually for the first time.

So now **why make it cost money**? When fast-travel is costly, you encourage players to walk instead. That's a bad design decision! You should never encourage players to do boring stuff. Your encouragement should always be towards the most fun aspects of your game.

But then why do so many games still do it? Because it is a money sink. Typical MMO economies have a problem with inflation. Players constantly generate wealth in form of money and items when they play the game. To fight that inflation, you need to remove money from the economy. The best way to do that is through NPC services which cost money. Fast-travel services are a good opportunity for such a service.

But you need to balance the cost properly so that it is enough to remove a non-negligible amount of money from the game but not so high that any player thinks twice about spending their money on it. A good logic to come up with a good price is to consider how much money players make per minute traveling and how much when they are making while playing in the (for them) most lucrative location. When a player saves 10 minutes travel-time with fast-traveling, makes 100 gold per minute while walking and 1000 gold per minute while at their destination, it is economically better for players to pay up to `(1000 - 100) * 10 =` 900 gold for fast-traveling to their destination immediately.

But unless you are a very experienced game analyst who has figured out every progression curve just from the game formulas before even writing the first line of code, you likely don't have a good idea yet of how much money players will make in what location. But you can easily figure that out when you have actual data from test players. So my recommendation would be to keep fast-travel free for now and then add a cost after you figured out how much money exactly you should take for it.

For further watching I recommend the video MMO Economies - How to Manage Inflation in Virtual Economies by our game design gurus Extra Credits.
> 1 votes

# Answer
When you talk about beta testing, I don't know if you mean **closed beta**. If that is the case, you can focus testing on particular parts of the game, which also means you may ask the testers to do certain things (such as use the bus). In this enviroment it would be ok to give them the money for the bus.

Otherwise, we are talking about **open beta**, and people will do whatever. Including going to the empty land even when they have money for the bus.

---

If you are considering making the bus free to give a better experience to beta testers, you should also consider make the bus free in the final game. After all, the purpose of the test is to find ways to improve the final game. An improvement for the test should be an improvement for the final game.

Evidently, the game is subject to change. Consider if that if you are planning to make temporary changes to ease beta testers, perhaps the game is not ready for beta.

On the other hand, testing is useful at every stage of the game, you should not be ashamed※ of an incomplete game when evidently that is what beta tester have signed for.

※: It is impossible to fix everything; every video game company has released games with bugs. And testing can be ridiculous, even tedious... but without it, things would be worst.

**You know that this empty land is a problem**. It is a known issue. You will be fixing it before or after testing. Do not hide it. Think that even if you make the bus free, a good tester will try every option, and thus will wander into the empty land.

*Aside: I am guessing you have grand plans for the empty land. That sounds too ambitious! You could have created the game without the empty land, being the bus the only option... and then, when you have created whatever plans you have for the empty land (which would no longer be empty), you can introduce it to the game. Regardless, you have the empty land there. Let the feedback come.*

---

So, I suggest to not introducing temporary changes. That includes making the bus free or giving free money. Instead, be clear with the beta testers about what they are going into. That may include telling them what the route is in the long walk. In fact, it is a good idea to provide manuals for an open beta, where you explain the game.

As an alternative to beta testing, you can do blind alpha tests. In that case, you have people in a controlled environment where you can supervise them. The idea is to see how the player reacts to the situation first hand (that is much more reliable than their account of what happened). This kind of testing is great for discoverability. Consider that perhaps players will not know that they have to take the bus, or that the empty land only takes them to the same place the bus does.

As per beta testing. People will probably provide feedback about the empty land. Be ready to receive that feedback. The mitigation is including it in manuals as mentioned above.
> 0 votes

---
Tags: game-design, mmo, economy, beta, open-world
---