# Question
Title: Setting a uniform float in a fragment shader results in strange values, is this a type conversion? How can it be fixed?
First, some details:

In a fragment shader, I'm trying to make an image do a sort of "flipping mirroring" animation (lines 44-57):

```
#version 450 core
in vec3 Color
in vec2 Texcoord;
out vec4 outColor;
uniform sampler2D tex;
uniform float factor;
void main() {
 if (Texcoord.y < factor) {
    outColor = texture(tex, Texcoord) * vec4(Color, 1.0);
  } else {
    outColor = texture(tex, vec2(Texcoord.x, 1.0 - Texcoord.y));
  }
}

```

When factor is 1, the image should be right-side up and has some color on it. When factor is 0, the image should be upside down and has no color added to it. When factor is 0.5, the top half should be right-side up and the bottom half should be upside down.

Currently, that is only the case if I replace `factor` with the number.

When I set the uniform factor with `glUniform1f()`, I'm getting very strange results. To illistrate, I added some debug code to lines 188-197 that sets the uniform with one number, retrieves the number from the uniform, and outputs both values to try and see what's going on.

Here's the code:

```
GLfloat factorToSet = 1.0f;
GLfloat setFactor = 0.0f;
GLint uniFactor = glGetUniformLocation(shader_program, "factor");

while (factorToSet > -0.1f) {
  glUniform1f(uniFactor, factorToSet);
  glGetUniformfv(shader_program, uniFactor, &setFactor);
  printf("Factor of %.1f becomes %f\n", factorToSet, setFactor);
  factorToSet -= 0.1;
}

```

And here are the results:

```
Factor of 1.0 becomes 0.000000
Factor of 0.9 becomes -2.000000
Factor of 0.8 becomes -0.000000
Factor of 0.7 becomes 2.000000
Factor of 0.6 becomes 0.000000
Factor of 0.5 becomes -0.000000
Factor of 0.4 becomes 2.000000
Factor of 0.3 becomes -36893488147419103232.000000
Factor of 0.2 becomes 0.000000
Factor of 0.1 becomes 36893488147419103232.000000
Factor of -0.0 becomes -0.000000

```

So with what little I understand about OpenGL and the way scalar types are stored in binary, I'm thinking that this issue is caused my GLfloat getting converted into something else on the way to the shader's uniform float. But I'm grasping at straws.

What could be causing this strange conversion between the number I send to the uniform float and the value that the uniform float becomes? What could I do to fix it if it's possible to fix?

Thanks in advanced for any help and leads, I really appreciate it :)

---

*An additional note after receiving a working answer*

George Hanna provided a link to a post where someone had a similar issue. I read over the comments and someone said to use `-DGL_GLEXT_PROTOTYPES` as a CFLAG. So I rolled back my local code to use `glUniform1f()` again, added `-DGL_GLEXT_PROTOTYPES` to the Makefile, and everything worked! Even crazier, all the compiler warnings I had for implicit declarations of OpenGL functions were gone!

So in addition to the answer below, if you have this issue, try adding `-DGL_GLEXT_PROTOTYPES` to your CFLAGS.

(You can also get this affect by adding `#define GL_GLEXT_PROTOTYPES` before any OpenGL `#include`s)

# Answer
You can try solving the issue by using `glUniform1fv(uniFactor, 1, &factorToSet);` instead of `glUniform1f` as this has worked for others.

Similar problem and possible fix
> 2 votes

# Answer
You need to either use

```
glProgramUniform1f(shader_program, uniFactor, factorToSet);

```

if you have either at least GL 4.1 or the `ARB_separate_shader_objects` extension or use

```
glUseProgram(shader_program); // CALL THIS FIRST

glUniform1f(uniFactor, factorToSet);

```

to select which shader you want to "work on" before you can change the uniforms.

Uniform values are conceptually stored "inside" the shader program (actual implementation may vary but act as-if the same), each individual programs have their own uniforms so you must select the shader program first or use `glProgramUniform1f` to set uniforms on a specific program without selecting it first.

For completeness: If you want to share uniform values between shader programs you can use **Uniform Buffer Object**s.
> 1 votes

---
Tags: opengl, c, floating-point
---


# Question
Title: Steering behaviors: how to flee then go back towards the hunter?
I have implemented a Wander and Flee steering behavior and it works like this:

When the entity is not hunted by anything it wanders around. But when it is hunted by the player it will flee away from the player at growing speed. This is like a butterfly that flees quickly.

But now I want to change its behavior. So that when the entity is hunted by the player, it flees away at the beginning. But if the player keeps chasing the entity it will go back towards the player at a slower speed so that the player can catch the entity. In my previous implementation the player cannot catch the entity because the entity always has a fleeing force if the player comes closer.

Can I just decrease the fleeing force over time? But this still cannot guarantee the entity is catchable and it will make player feel the entity is not moving.

# Answer
You could start decreasing the fleeing force as soon as it exceeds a set value and then reset it when the distance from the player starts increasing.

pseudo-code

```
if(fleeingforce greater than X)
   beingchased is true
   previousdistance from player = length(player.xyz - self.xyz)

if(beingchased is true)
   if fleeingforce > minfleeingforce
      decrease fleeingforce
   if(distance from player is greater than previousdistance)
      beingchased is false

```
> 1 votes

---
Tags: steering-behaviors
---


# Question
Title: Unity: Blender's Armature messes up Faces
The Model itself is fine when imported but when I activate the Animation all Normals and lighting get Inverted from the Bones.

Result:

Import Settings:

Import Settings:

Blender Armature Settings:

Blender Export Settings:

# Answer
There's probably a transformation on the rig in blender, that is being applied to the mesh upon export (or upon animating). In the 3D view port open the properties window with 'N', and check if there is a un-applied transform. i.e rotation != (0, 0, 0) or scale != (1, 1, 1)

To apply the transformation, select the rig (in object mode) then hit ctrl-A, do the same with the mesh (just in case). If that doesn't help, try clearing the transformation(s) with alt-R, alt-G, and alt-S, for rotation, translate and scale respectively. Blender docs

If this doesn't fix your issue, then just hack around the bug. Invert all the normals with Ctrl-N and export it like that haha
> 1 votes

---
Tags: unity, blender, skeletal-animation, normals
---


# Question
Title: How are Uniform Layout Qualifiers in GLSL spaced out
So for attributes the spacing between indexes is vec4, so if I had 2 matrix as an attribute, they'd be **layout (location = 0) in mat4 a** and **layout (location = 4) in mat4 b**

If I did the same for 2 uniform matix, what would the index of matrix b be?

Side note: with OpenGL 4, are VBOs also attributes, there isn't a key word for vertex?

# Answer
> 1 votes
Uniform locations don't work like attribute locations.

Every basic type in OpenGL takes up 1 uniform location. So a `float` and a `mat4` both take up 1 location. The only time multiple locations are consumed is if you're using an aggregate (aka: struct or array) of basic types. Each basic type element of the aggregate, recursively, takes up one location.

---
Tags: opengl, glsl
---


# Question
Title: Most efficient way to detect and act upon collision (Specific for my 2d game)
Currently, mainly just for fun, I'm working on a 2d game where I have all collide-able blocks (background) assorted into an array when its loading, along with the player put into a different part of the 3d array. The player object gets put in with the AI array. It looks like this --\>

```
    var world_objects = [
  [], //All 'background' collide-able objects. Such as stones and the border ~~ Code name: bg
  [], //All AI ~~ code name: ai
  []  //Projectiles ~~ Code name: ps
];

```

The map is set up into a bitmap that I've made using another 3d array, that currently is made into a 15x15, but that is subject to change. The brown border is included in the bitmap and world\_objects array. And when the blocks/ai/projectiles are inserted, they all will have a basic object properties of:

x, y(2 variations, one with just normal x,y according to the exact pixel in the canvas, and the other is according to which cell its in for the bitmap)

Width, height (Both width and height for ai and projectiles are recorded as percentages according to the size of each cell, because the size is made to change depending on screen size)

Along with other properties not related to collision. What would be the most efficient way of detecting all objects and whether they collide or not? If needed, I could add additional properties to each object if that would make it easier and more efficient.

# Click to see all of the code

# Answer
As long as your game stays in a 15x15 grid, the naïve way of just checking collisions by comparing every object position with every other object position is likely a "good enough" solution. I would recommend you to just stick to this until you actually run into measurable performance problems.

Those problems might show up when the number of objects in your game increases a lot, because the computational cost of this solution increases quadratically with the number of objects you check for collisions with each other.

When you need to improve the performance, you can use a data-structure which allows you to quickly get all objects in a given area. Possible candidates for this are spatial hashing or the various variants of 2d-trees. There is no "best" solution, because all solutions have cases where they work good and cases where they work bad. For example, spatial hashing isn't very useful when objects cluster a lot in individual boxes and keeping 2d trees up-to-date becomes expensive when objects move around a lot. There is only the best solution for your game.
> 0 votes

---
Tags: collision-detection, javascript, html-canvas, efficiency
---


title: What is original Pong ball behaviour?

text:
# Question
Title: What is original Pong ball behaviour?
I am building a Pong clone to learn interactive programming and I've stumbled in getting the ball movement and bouncing on the paddles right.

If I play the original game I can't really understand how the "spin" and the paddle bounce works.

I've been searching a bit on the internet and all I got was just more confusion.

Can anybody explain me how the bounce is handled? If the paddle stands perfectly still and the ball, just moving on x, hits the paddle at the center I simply get -x, that is clear.

What happens if you hit the paddle on the sides? What changes if when the ball hits the paddle the paddle is also moving?

I did an Arkanoid-like implementation but it is far from the real Pong feeling.

# Answer
> 3 votes
What i understand in the pong implementation (or other brick breackers) is that the most you hit the side of the paddle the more the ball will go in that direction.

Here is a small picture of what i mean:

So you just have to calculate the center of the paddle then you calculate the ration from the side of it and determine the angle from that ratio. I do not think that they use the speed of the paddle to compute the angle.

Tell me if i am clear enough i can improve the answer little bit.

---
Tags: physics, pong
---


# Question
Title: C++ Thread, structuring thread so Gameloop can continue
I want my thread to run seperately, but I want to be able to keep executing the game loop without killing the thread scope, If I remove the join there is a crash ?

What can I do ?

My desired result is for the unit just to wait while the path is being calculated, but I don't want the game loop to pause, now while it is alot quicker, there are freezes of atleast 1 second over long distances while its stuck in the pl and hpl threads.

thread pl

thread hpl

are my seperate pathfinding threads.

path requester--- only execute path for selected unit if there is a unit requesting in the pathingrequester vector, this is stored in an abstract class. The units waypoints get pushed onto its waypoint queue when its done.

```
void pathingrequester()
{
    // executes the requested paths for A* pathing
    if (AWorld.RequestingPath.empty() != true)
    {
        AWorld.RequestingPath.front();
        //cout << "Completed "<< AWorld.RequestingPath.front()->pf_Source->warpPointNO<<"to:"<< AWorld.RequestingPath.front()->UltimateDestination->warpPointNO<<endl;
        astarpathfinder(AWorld.HiFiWaypoints, AWorld.RequestingPath.front()->pf_Source->ret_posX(), AWorld.RequestingPath.front()->pf_Source->ret_posY(),
        AWorld.RequestingPath.front()->UltimateDestination->ret_posX(), AWorld.RequestingPath.front()->UltimateDestination->ret_posY(), AWorld.RequestingPath.front(), AWorld.lines, AWorld.pointsInLine, MainAB.Path);
        AWorld.RequestingPath.pop_front();
    }
}

```

------------------------------- program execution loop

```
while (ConqEngine->IsRunning())
{
    bool running = ConqEngine->IsRunning();
    // Draw the scene
    ConqEngine->DrawScene();
    updateTime = ConqEngine->Timer(); // Frame Timer

    thread pl(pathingrequester);
    thread hpl(hpa_pathin_requester);

    if (MainAB.bmenuloop)
    {
        initial_menu_loop(MainAB.loaded_men_interface, MainAB.bmenuloop, MainAB.bloadloop, MainAB.binfoloop ,textControl);
    }
    else if (MainAB.bloadloop)
    {
        preconqload(MainAB.bloadloop, MainAB.bgameloop, MainAB.startingx, MainAB.pipnumber);
    }
    else if (MainAB.binfoloop)
    {
        if (ConqEngine->AnyKeyHit())
        {
            ConqEngine->RemoveSprite(MainAB.LoadingSprite);
            MainAB.binfoloop = false;
            MainAB.bmenuloop = true;

        }
    }
    else if (MainAB.bgameloop)
    {

        thread gl(gameloop, ref(myFont), ref(myFont2), ref(textControl));
        gl.join();

    }

    hpl.join();
    pl.join();

```

Can anyone give me good example code how to set this up ? or a library that helps handle this?

# Answer
Disclaimer; I am not a C++/gaming dev expert, but happened to run across your question, and think I understand the problem..

Every single loop you call this every every thread;

```
thread.join();

```

This design of your program pretty much results in the entire loop taking as long as the longest running thread.

I would recommend making the threads all run completely independently and joining **after** the game loop is done. Sharing of information and joining can be two different things.

Additionally, you're intializing the threads inside the game loop, also address this; the threads that help the 'main'loop which also draws, should not block it; they should just 'feed' it the info it needs to render the state of the program.

The data into which the other threads feed, and the reading of the data should be mutexed (with the same mutex) - Not the best design possible; but it should significantly help your problem.

Update: In Pseudo; I would refactor your code to look roughly like this:

```
std::mutex stateMutex;
GameState state;
thread pl(pathingrequester); //updates 'the state' (should use stateMutex also)
while (ConqEngine->IsRunning())
{
    GameState copyOfGameState;
     {
      //lays a lock only for the duration lock_guard is in scope, always releases, even when exceptions occur, thanks to RAII
      std::lock_guard<std::mutex> lock(stateMutex);
      copyOfGameState = state;
     }
    ... code here that renders using state ...
}

```

Note; making a copy is not useful if it is highly costly (i.e. moreso than rendering, if the main loop does this; I am not sure it does.)
> 2 votes

---
Tags: c++, multithreading
---


# Question
Title: Implement Hearthstone disenchant extra cards particles
How would you implement the hearthstone flying particles? like you can see here These are not just simple particles flying from a to b... I think that they are flying in some random spline, and stretched...

Any information, even to something similar that you can point me to would help! Thanks

# Answer
> 1 votes
It certainly looks like you could use splines to get similar paths. I fired up Krita & made a few to help illustrate some things that might help get you going.

The spline above goes from one corner to the opposite, passes through a somewhat central middle node. Note that the control handles that node are less than 45 degrees off from the angle between the end points, are symmetric in length & have lengths that fall within the bounding box of the end points.

Let's experiment with those parameters a bit. Here's what happens when we push the angle to about 135 degrees. Note that the shape gets a bit more of a pronounced S curve:

Next, let's push the controls outside the bounding box. Not that the S curve becomes even more exaggerated.

Finally, let's break the symmetry. In this final example, the lower handle barely escapes the bounding box, but the upper handle is about twice the length of the lower one. Of the four, this one probably has the most personality.

I recommend that you grab whatever graphics software you want that supports spline editing, make copies of a 'default' spline & edit them in different ways. You'll probably hit upon a couple of things that looks reasonable much faster than if you were going directly to your code. After you have a few promising recipes, try them out. Maybe try a few 'bad' ideas as well - sometimes things look different when animated. Either you'll happen upon some hidden gems, or you'll refine your sense of what's not going to work out.

---
Tags: particles
---


# Question
Title: Why is my camera movement not working as expected?
I'm doing a 2D Tile Game in Java. It should be the right calculations to make the camera following the player only if it is located at a distance from the center of the window, but this only works the first time the player overcame it, not all of them later. (I'm trying to do it like the snippet)

What is my mistake? Can anyone help me please?

```
// all this code is in the game loop
int cx = width/2;
int cy = height/2;

int dx = Math.abs(player.x - cx);
int dy = Math.abs(player.y - cy);

int xoff = 0;
int yoff = 0;

if(dx > 100){
    if(dx < player.x){
        xoff += player.speed;
    }else{
        xoff -= player.speed;
    }
}
if(dy > 100){
    if(dy < player.y){
        yoff += player.speed;
    }else{
        yoff -= player.speed;
    }
}

level.render(xoff, yoff, screen);

```

```
const RUN_SPEED = 5.5;

  var camPanX = 0.0;
  var camPanY = 0.0;
  const PLAYER_DIST_FROM_CENTER_BEFORE_CAMERA_PAN_X = 150;
  const PLAYER_DIST_FROM_CENTER_BEFORE_CAMERA_PAN_Y = 100;

  const KEY_LEFT_ARROW = 37;
  const KEY_UP_ARROW = 38;
  const KEY_RIGHT_ARROW = 39;
  const KEY_DOWN_ARROW = 40;
  var holdLeft = false;
  var holdRight = false;
  var holdUp = false;
  var holdDown = false;

  function initInput() {
    document.addEventListener("keydown", keyPressed);
    document.addEventListener("keyup", keyReleased);
  }

  function setKeyHoldState(thisKey, setTo) {
    if(thisKey == KEY_LEFT_ARROW) {
      holdLeft = setTo;
    }
    if(thisKey == KEY_RIGHT_ARROW) {
      holdRight = setTo;
    }
    if(thisKey == KEY_UP_ARROW) {
      holdUp = setTo;
    }
    if(thisKey == KEY_DOWN_ARROW) {
      holdDown = setTo;
    }
  }

  function keyPressed(evt) {
    setKeyHoldState(evt.keyCode, true);
    evt.preventDefault(); // without this, arrow keys scroll the browser!
  }

  function keyReleased(evt) {
    setKeyHoldState(evt.keyCode, false);
  }

  const BRICK_W = 60;
  const BRICK_H = 60;
  const BRICK_GAP = 1;
  const BRICK_COLS = 20;
  const BRICK_ROWS = 15;
  var brickGrid =
      [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
        1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
        1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1,
        1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1,
        1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1,
        1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1,
        1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1,
        1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1,
        1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1,
        1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1,
        1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1,
        1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];;

  var canvas, canvasContext;

  function brickTileToIndex(tileCol, tileRow) {
    return (tileCol + BRICK_COLS*tileRow);
  }

  function isBrickAtTileCoord(brickTileCol, brickTileRow) {
    var brickIndex = brickTileToIndex(brickTileCol, brickTileRow);
    return (brickGrid[brickIndex] == 1);
  }

  function isBrickAtPixelCoord(hitPixelX, hitPixelY) {
    var tileCol = hitPixelX / BRICK_W;
    var tileRow = hitPixelY / BRICK_H;

    // using Math.floor to round down to the nearest whole number
    tileCol = Math.floor( tileCol );
    tileRow = Math.floor( tileRow );

    // first check whether the slider is within any part of the brick wall
    if(tileCol < 0 || tileCol >= BRICK_COLS ||
       tileRow < 0 || tileRow >= BRICK_ROWS) {
       return false;
    }

    var brickIndex = brickTileToIndex(tileCol, tileRow);
    return (brickGrid[brickIndex] == 1);
  }

  function sliderMove() {
    var nextX = sliderX;
    var nextY = sliderY;

    if(holdLeft) {
      nextX += -RUN_SPEED;
    }
    if(holdRight) {
      nextX += RUN_SPEED;
    }
    if(holdUp) {
      nextY += -RUN_SPEED;
    }
    if(holdDown) {
      nextY += RUN_SPEED;
    }

    if(isBrickAtPixelCoord(nextX,nextY) == false) {
      sliderX = nextX;
      sliderY = nextY;
    }
  }

  window.onload = function() {
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    initInput();

    // these next few lines set up our game logic and render to happen 30 times per second
    var framesPerSecond = 30;
    setInterval(function() {
        moveEverything();
        drawEverything();
      }, 1000/framesPerSecond);

    sliderReset();
  }

  function sliderReset() {
    // center slider on screen
    sliderX = canvas.width/2;
    sliderY = canvas.height/2;
  }

  function instantCamFollow() {
    camPanX = sliderX - canvas.width/2;
    camPanY = sliderY - canvas.height/2;
  }

  function cameraFollow() {
    var cameraFocusCenterX = camPanX + canvas.width/2;
    var cameraFocusCenterY = camPanY + canvas.height/2;

    var playerDistFromCameraFocusX = Math.abs(sliderX-cameraFocusCenterX);
    var playerDistFromCameraFocusY = Math.abs(sliderY-cameraFocusCenterY);

    if(playerDistFromCameraFocusX > PLAYER_DIST_FROM_CENTER_BEFORE_CAMERA_PAN_X) {
      if(cameraFocusCenterX < sliderX)  {
        camPanX += RUN_SPEED;
      } else {
        camPanX -= RUN_SPEED;
      }
    }
    if(playerDistFromCameraFocusY > PLAYER_DIST_FROM_CENTER_BEFORE_CAMERA_PAN_Y) {
      if(cameraFocusCenterY < sliderY)  {
        camPanY += RUN_SPEED;
      } else {
        camPanY -= RUN_SPEED;
      }
    }

    // instantCamFollow();

    // this next code blocks the game from showing out of bounds
    // (this isn't required, if you don't mind seeing beyond edges)
    if(camPanX < 0) {
      camPanX = 0;
    }
    if(camPanY < 0) {
      camPanY = 0;
    }
    var maxPanRight = BRICK_COLS * BRICK_W - canvas.width;
    var maxPanTop = BRICK_ROWS * BRICK_H - canvas.height;
    if(camPanX > maxPanRight) {
      camPanX = maxPanRight;
    }
    if(camPanY > maxPanTop) {
      camPanY = maxPanTop;
    }
  }

  function moveEverything() {
    sliderMove();
    cameraFollow();
  }

  function colorRect(topLeftX, topLeftY, boxWidth, boxHeight, fillColor) {
    canvasContext.fillStyle = fillColor;
    canvasContext.fillRect(topLeftX, topLeftY, boxWidth, boxHeight);
  }

  function colorCircle(centerX, centerY, radius, fillColor) {
    canvasContext.fillStyle = fillColor;
    canvasContext.beginPath();
    canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
    canvasContext.fill();
  }

  function drawBricks() {
    for(var eachCol=0; eachCol<BRICK_COLS; eachCol++) { // in each column...
      for(var eachRow=0; eachRow<BRICK_ROWS; eachRow++) { // in each row within that col

        if( isBrickAtTileCoord(eachCol, eachRow) ) {
          var brickLeftEdgeX = eachCol * BRICK_W;
          var brickTopEdgeY = eachRow * BRICK_H;
          colorRect(brickLeftEdgeX, brickTopEdgeY,
                   BRICK_W - BRICK_GAP, BRICK_H - BRICK_GAP, 'blue' );
        } // end of isBrickAtTileCoord()
      } // end of for eachRow
    } // end of for eachCol
  } // end of drawBricks()

  function drawOnlyBricksOnScreen() {
    // what are the top-left most col and row visible on canvas?
    var cameraLeftMostCol = Math.floor(camPanX / BRICK_W);
    var cameraTopMostRow = Math.floor(camPanY / BRICK_H);

    // how many columns and rows of tiles fit on one screenful of area?
    var colsThatFitOnScreen = Math.floor(canvas.width / BRICK_W);
    var rowsThatFitOnScreen = Math.floor(canvas.height / BRICK_H);

    // finding the rightmost and bottommost tiles to draw.
    // the +1 and + 2 on each pushes the new tile popping in off visible area
    // +2 for columns since BRICK_W doesn't divide evenly into canvas.width
    var cameraRightMostCol = cameraLeftMostCol + colsThatFitOnScreen + 2;
    var cameraBottomMostRow = cameraTopMostRow + rowsThatFitOnScreen + 1;

    for(var eachCol=cameraLeftMostCol; eachCol<cameraRightMostCol; eachCol++) {
      for(var eachRow=cameraTopMostRow; eachRow<cameraBottomMostRow; eachRow++) {

        if( isBrickAtTileCoord(eachCol, eachRow) ) {
          var brickLeftEdgeX = eachCol * BRICK_W;
          var brickTopEdgeY = eachRow * BRICK_H;
          colorRect(brickLeftEdgeX, brickTopEdgeY,
                   BRICK_W - BRICK_GAP, BRICK_H - BRICK_GAP, 'blue' );
        } // end of isBrickAtTileCoord()
      } // end of for eachRow
    } // end of for eachCol
  } // end of drawBricks()

  function drawEverything() {
    // drawing black to erase previous frame, doing before .translate() since
    // its coordinates are not supposed to scroll when the camera view does
    colorRect(0, 0, canvas.width, canvas.height, 'black');

    canvasContext.save(); // needed to undo this .translate() used for scroll

    // this next line is like subtracting camPanX and camPanY from every
    // canvasContext draw operation up until we call canvasContext.restore
    // this way we can just draw them at their "actual" position coordinates
    canvasContext.translate(-camPanX,-camPanY);

    //drawBricks();
    drawOnlyBricksOnScreen();

    colorCircle(sliderX, sliderY, 10, 'white');

    canvasContext.restore(); // undoes the .translate() used for cam scroll

    // doing this after .restore() so it won't scroll with the camera pan
    canvasContext.fillStyle = 'white';
    canvasContext.fillText("Arrow keys to slide, scrolling demo",8,14);
  }
```

```
<canvas id="gameCanvas" width="800" height="600"></canvas>
```

# Answer
> 0 votes
I happen to be making a 2D game with a camera that follows the player right now. My camera is quite a bit more sophisticated than yours. The movement of the camera is smooth and springy. Anyway, here's your code

```
int cx = width/2;
int cy = height/2;

int dx = Math.abs(player.x - cx);
int dy = Math.abs(player.y - cy);

int xoff = 0;
int yoff = 0;

if(dx > 100){
    if(dx < player.x){
        xoff += player.speed;
    }else{
        xoff -= player.speed;
    }
}
if(dy > 100){
    if(dy < player.y){
        yoff += player.speed;
    }else{
        yoff -= player.speed;
    }
}

level.render(xoff, yoff, screen);

```

I'm guessing that `off` is added to all the positions of the game objects before they are rendered and `c` is the center of the window. `d` is the distance the player is from the center of the screen. You want to move `off` when the distance is less than `100` to keep the player on the screen. To do that you might want to do something like this.

```
const int centerRadius = 100;

int dx = player.x - cx;
int dy = player.y - cy;

if (Math.abs(dx) > centerRadius) {
  xoff -= dx > 0 ? dx - centerRadius : dx + centerRadius;
}
if (Math.abs(dy) > centerRadius) {
  yoff -= dy > 0 ? dy - centerRadius : dy + centerRadius;
}

```

Here I'm calculating the distance the player is from the edge of the square in the center of the screen. Then I'm moving the camera by that distance to keep the player within the rectangle.

This kind of code is very easy to get wrong and I'm not able to properly test my code. You might need to flip the signs somewhere to this to work right. If you want a more complicated camera, I'd be happy to help you out.

---
Tags: java, camera
---


# Question
Title: How to get Google Play to suggest my app?
I uploaded a game to Play and obviously it isn't the very first suggestion on the list. I uploaded it 3 days ago.

As somehow new games do get played, I assume people start to know about them.

I would like to ask that how does Play start suggesting an app? Is it by download count/download frequency? Or does it show new apps by itself?

# Answer
> 3 votes
Google won't release the exact algorithm used for getting featured or getting listed on the store front, probably because they want to minimize the amount people try game the system.

Having said that it is safe to assume that number of downloads and ratings are key to get featured.

At Google I/O there was a talk on this a few years ago: https://youtu.be/5Od2SuL2igA

---
Tags: google-play
---


title: Get 2D mouse delta along 2D angle?

text:
# Question
Title: Get 2D mouse delta along 2D angle?
I'm trying to develop my own transformation gizmo (with x, y & z handles/arrows the user can grab and move, like in game engines), however, I'm not sure how I should calculate the 2D mouse delta along the 2D angle of the grabbed handle axis. I already have converted the base and tip of the handle/arrow to screen-space, and have calculated the screen-space points' angle between the screen-space base and tip. I'm just stuck on taking the X & Y mouse delta and getting the acceleration of the delta along that 2D angle. I've made a little visualization;

# Answer
What you want is projecting the mouse vector to the axis vector.

First, subtract the base position vector from the tip position vector to get the axis as a vector, next subtract the base position from the position of the mouse to get the vector pointing to the position of the mouse.

Use the following formula with these vectors:

```
projected = mouse ⋅ (axis / |axis|)

```

where  means dot product and `|v|` is the magnitude of **v**. This should result in a scalar.
> 0 votes

---
Tags: 2d, mathematics
---


title: ECS -- Textures and Game Objects

text:
# Question
Title: ECS -- Textures and Game Objects
I'm developing a game using an entity-component system, and had a question about storing, using and linking textures to entities.

I have a `GraphicsSystem` that is responsible for storing and registering textures. Each entity has a `GraphicsComponent` including a `textureID`, which is just an integer used to look up the stored texture in the `GraphicsSystem`.

This works well for textures that are only used by one entity, for example player textures. In this case, I can create new `GraphicsComponent`s by something like:

`GraphicsComponent(graphicsSystem.addTexture("Player1.png"));`

`graphicsSystem.addTexture()` adds a texture to the graphics system and returns an integer to its position, which is then stored in the component for later use.

My problem is that this approach doesn't work for textures that are registered once and then used across multiple entities. Examples are textures for bullets and world terrain.

My temporary solution to this problem is to register the texture once, and store the texture id centrally. Whenever I need to (for example) create a new bullet, I just need to remember that the bullet is texture id of (say) 1, and then pass this to the `GraphicsComponent` constructor for the bullet.

Similarly for my terrains, I currently just need to remember which texture ID is for which terrain type:

```
World::World() :    floorTerrain(1),
                    wallTerrain(2),
                    ...

```

I did think about storing these IDs somewhere, for example in the `GraphicsSystem` itself, but my `world` instance doesn't have direct access to the graphics system.

Anyway, as you can probably tell I am new to ECS game design and would appreciate any pointers!

Thanks, Rich.

# Answer
You could have a map in `graphicsSystem` where the key is the name of the texture file and the value is a reference to the loaded texture object.

When adding textures by calling `graphicsSystem.addTexture("TextureName.png")` you return the texture pointer.

In `graphicsSystem.addTexture(string s)` you then check if the hash contains a value with the key `s` and return the texture. if it doesnt contain the key, load the texture and add the key-valuepair to the map.
> 2 votes

---
Tags: c++, entity-component
---


# Question
Title: How do you draw a straight line between two points in a bitmap?
I'm playing around with height maps (bitmaps), trying to create some of my own in my game, and for that I need to implement some basic drawing methods. I've quickly realized that drawing straight lines isn't as basic as I thought.

It simple's if your points share an X or Y coordinate, or if they are aligned so you can draw a perfectly diagonal line. But in all other cases its trickier.

What algorithm do you use to determine what pixels need to be coloured for it to become a "straight" line ?

# Answer
> 27 votes
I think what you need is Bresenham's line algorithm.

From what I remember it is used to determine *what* point should be coloured, not *how much* each point should be coloured.

# Answer
> 21 votes
Bresenham's line algorithm can be used to determine which points in a raster grid to plot in order to achieve a appropriate visual approximation of a line segment.

The algorithm covers the rasterization of a line defined by the origin and endpoints in a coordinate space where the origin is in the upper left. Integer coordinates are presumed to map to pixel centers. Notably, the basic form of the algorithm only covers one octant of the circle: the one where the line has increasing X and Y coordinates but a negative slope with an absolute value less than 1. All other octants can be derived as simple transformations of this basic octant.

In psuedocode, this basic form looks like:

```
void DrawLine(Point origin, Point endpoint, Bitmap surface) {
    deltaX = endpoint.X - origin.X
    deltaY = endpoint.Y - origin.Y
    error = 0

    // Note the below fails for completely vertical lines.
    deltaError = absoluteValue(deltaY / deltaX)

    Y = origin.Y
    for (X from origin.X to endpoint.X) {
        surface.PlotPixel(X, Y)
        error = error + deltaError
        if (error >= 0.5) {
            ++Y;
            error -= 1.0
        }
    }
}

```

The Rosetta Code website has a collection of concrete implementations in a variety of languages.

You may also be interested in Wu's line algorithm, which allows for anti-aliasing.

# Answer
> 2 votes
Here is an extremely simple way of drawing lines. The function can easily be changed to be used in projects.

```
void draw_line(float x0, float y0, const float& x1, const float& y1)
{
    float x{x1 - x0}, y{y1 - y0};
    const float max{std::max(std::fabs(x), std::fabs(y))};
    x /= max; y /= max;
    for (float n{0}; n < max; ++n)
    {
        // draw pixel at ( x0, y0 )
        x0 += x; y0 += y;
    }
}

```

---
Tags: c++, rasterization
---


title: Cloning Prefabs with Unity not working

text:
# Question
Title: Cloning Prefabs with Unity not working
Ok so ive created a prefab of an obstacle avoidance bot and am attempting to clone it. Problem is, only one of the instances works correctly, the rest just sit there. The bots are supposed to turn left when right sensor is triggered and vice versa. The instantiation code:

```
public int populationSize = 10;
public GameObject carPrefab;
public Vector2 spawnPosition;
public static float speed = 2f;

private GameObject[] cars;

// Use this for initialization
void Start () {
    cars = new GameObject[populationSize];
    for (int i = 0; i < populationSize; i++) {
        spawnPosition = new Vector2((1.0f*i)-2,3.83f);
        cars [i] = GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
    }

}

// Update is called once per frame
void Update () {

}

```

The prefab scripts: (Left Sensor and Right Sensor are children of CarMovement)

```
public float speed = 2f;
public static Rigidbody2D rb2d;

// Use this for initialization
void Start () {
    rb2d = GetComponent<Rigidbody2D> ();

}

// Update is called once per frame
void Update () {
    rb2d.transform.Translate (Population.speed * Time.deltaTime, 0, 0);
}

```

Left Sensor:

```
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnTriggerStay2D (Collider2D other){
    Debug.Log ("LEFT");
    CarMovement.rb2d.rotation -= 5;
}

```

Right sensor:

Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine;

public class RightSensor : MonoBehaviour {

```
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {

}

void OnTriggerStay2D (Collider2D other){
    Debug.Log ("RIGHT");
    CarMovement.rb2d.rotation += 5;
}

```

Any help would be greatly appreciated. I have no idea whats going on.

# Answer
> 1 votes
Why did you choose to define `rb2d` as `static`?

```
public static Rigidbody2D rb2d;

```

This tells the compiler to allocate only one memory location for this variable, no matter how many instances of the class you have. So they all end up sharing a single `Rigidbody2D` variable.

Whichever instance happens to run its `Start()` method last will assign *its* `Rigidbody2D` to this shared variable, overwriting whatever the other instances had tried to store there.

From that point onward, every reference to `CarMovement.rb2d` will refer to only this last instance's `Rigidbody2D`, moving it and ignoring everyone else.

If you're looking for a way for one instance of a script to influence just one instance of another, a static variable is not an appropriate solution.

It looks like what you really want is for your sensor class to look like this:

```
public class Sensor : MonoBehaviour {

    // Give each one an instance variable you can wire up in the Inspector
    // to point to the CarMovement or Rigidbody2D you want this sensor to affect.
    public Rigidbody2D body;

    // While we're at it, store the rotation rate as an instance property too, so
    // we can do both left and right movement with the same script, and tune the speed.
    public float avoidance = 5f * 50f;

    void OnTriggerStay2D (Collider2D other){
        Debug.Log (avoidance < 0f ? "LEFT" : "RIGHT");
        // Storing avoidance in degrees per second and scaling by deltaTime
        // means you won't have to re-tune all your behaviours if you ever
        // change your FixedUpdate timestep.
        body.rotation += avoidance * Time.deltaTime;
    }
}

```

When you spawn an instance of this sensor as part of the prefab containing the `Rigidbody2D` it points to, the `body` variable above will automatically point to the `Rigidbody2D` spawned as part of *this instance*.

If the sensors aren't part of the same prefab as the body they modify, then you can wire up these dependencies dynamically on spawn using the strategies discussed in this answer.

---
Tags: unity
---


# Question
Title: I'm still not get it about the difference between playing Animator State and/or playing AnimationClip?
The states and animations not my own.

I have a prefab of a character that have Animator component attached to it. The character in the Hierarchy have Animator with some states and blends and also have some animation clips.

Now when i play/run a State of the Animator is that meaning i'm playing animation? Or the animation clips is something else ?

And why i can't playing the animation clips ? I'm not getting errors or exceptions it's just not playing it.

Here is a script that attached to this character and i also added to this character a Animation component. So now the character object have both Animator and Animation components.

```
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class SwitchAnimations : MonoBehaviour
{
    private Animator animator;
    private int index = 0;
    private static UnityEditor.Animations.AnimatorController controller;
    private UnityEditor.Animations.AnimatorState[] an;

    // Use this for initialization
    void Start()
    {
        animator = GetComponent<Animator>();
        an = GetStateNames(animator);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            animator.Play(an[index].name);
            if (++index == an.Length)
                index = 0;
        }
    }

    private static UnityEditor.Animations.AnimatorState[] GetStateNames(Animator animator)
    {
        controller = animator ? animator.runtimeAnimatorController as UnityEditor.Animations.AnimatorController : null;
        return controller == null ? null : controller.layers.SelectMany(l => l.stateMachine.states).Select(s => s.state).ToArray();
    }

    private void RollSound()
    {

    }

    private void CantRotate()
    {

    }

    private void EndRoll()
    {

    }

    private void EndPickup()
    {

    }
}

```

Inside the variable an there are 9 states:

```
Aiming
Death_A
Use
Grounded
Roll
PickupObject
Reload_Rifle
Shoot_Rifle
Empty

```

When i click on A key it's playing the states one by one each time i click on A Everything is working fine i can play the 9 states by clicking on A.

what i don't understand with the States is inside the editor when i'm in the hierarchy selecting the character and in the menu make: Window \> Animator i see the 9 states on the LegsLayer:

But then if i click on state Grounded double click i see a blend tree and i'm not sure if this is also states or maybe this is animation clips ? Then how can i get access to them ?

Ok this is one part i don't understand yet about the Animator and what and how i can play with it.

The second part is related to AnimationClip/s and why i can't play them ?

The script for animations clips:

```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.Animations;
using UnityEngine;

public class SwitchAnimations : MonoBehaviour
{
    private Animation animation;
    private AnimationClip[] animationClips;

    // Use this for initialization
    void Start()
    {
        animation = GetComponent<Animation>();
        animationClips = AnimationUtility.GetAnimationClips(gameObject);

        foreach (AnimationClip clip in animationClips)
        {
            animation.AddClip(clip, clip.name);
        }
    }
    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.A))
        {
            animation.clip = animationClips[6];
            animation.Play(animationClips[6].name);
        }
    }

    private void RollSound()
    {

    }

    private void CantRotate()
    {

    }

    private void EndRoll()
    {

    }

    private void EndPickup()
    {

    }

    private void FootStep()
    {

    }
}

```

And in the variable animationClips i have 9 animations:

```
Rifle_Aiming_Idle
Rifle_Aiming_Walk_F_RM
Rifle_Aiming_Walk_B_RM
Rifle_Aiming_Walk_L_RM
Rifle_Aiming_Walk_R_RM
Rifle_Idle
Rifle_Walk_F_RM
Rifle_Run_F_RM
Rifle_Sprint_F_RM

```

When i'm running the game and clicking on A this time i see in the Inspector inside the Animation component all the animation clips and in Animation i see the animation clip to play.

I'm not getting any errors or exceptions but it's just not playing it. The character stay still idle. Even if i choose another animation clip index to play 5 or 3 or 1 nothing is playing.

I wonder why it's not playing the animations when i click A. In this case animation number 6 from the List but still not playing.

# Answer
An **Animation Component** is good for when you want just one or a handful of animations on an object, with very simple transitions you're happy to control entirely in code. Things like:

* A spinning coin
* A UI element sliding onto the screen, pulsing, and reacting to a click
* An animated prop like a machine that just runs in a loop, or can be turned on & off
* A firing animation on a weapon that doesn't need precise coordination with a character's hands

It acts like a tape player: You load up the cassette (AnimationClip) that you want it to play, and tell it when to play, pause, stop, or change to a different source. It doesn't do anything particularly clever on its own, just plays the animation start to finish (or optionally looping).

---

An **Animator Component** is good for when you have complex layered animation with many states and transitions that would be fussy to wire up entirely through code. Things like an animated character who:

* Can move in multiple directions according to player input
* Needs to blend between forward, turning, and strafing animations
* Needs to blend between different movement speeds (idle, walk, run...)
* In multiple movement modes (crouched, upright, climbing...)
* While transitioning in & out of ability animations (throwing, aiming, firing...)
* And layering with character states (injured, carrying something...)

Controlling all of this manually in your own code would get brittle and repetitive, and it would make it hard for an animator on your team to tune the blend weights and timings for the right look.

So instead the Animator Component wraps all of this transition and blending logic in something called an Animation Controller state machine. This expresses all of these details as data in the form of flow charts, so it's quicker to iterate on, and already contains reusable patterns for common animation tasks like blending, layering, and masking.

This makes working with an Animator Component different than the tape cassette model described above. One of the great things it does for us is abstract away the individual animation clips into *states*, so our code doesn't need to know about the individual clips at all or micro-manage when to play each one. That frees the animators on your team to completely change the look of a character's animations, and do fancy things like blending multiple clips, or playing a different run clip when the character is hurt or encumbered, without breaking or creating new dependencies in your code.

So instead of telling the Animator Component *what clip* to play, the usual approach is to tell it *what's happening*, by setting state and trigger variables on it. From there its internal state transition logic will find the right animation or blend of animations to serve that state.

This will usually look something like:

```
myAnimator.SetFloat("Forward", Input.GetAxis("Vertical"));
myAnimator.SetTrigger("Die");

```

(You can of course cache those strings as integer IDs for better efficiency)

---

You rarely, if ever, want to use both an Animation Component and an Animator Component on the same object. Unless you're very careful to divide their activity and responsibilities, they're likely to fight for control of the same objects and you might get nonsensical results or no animated movement at all.

---

To fix your specific case:

1. Remove the Animation component so the two don't fight
2. Re-import your animations - it looks like you set them to legacy animations when trying to get the Animation component to work, and that animation type is not supported by the Animator, as the warnings in your screenshots are telling you
3. Try controlling your Animator component using the variables and signals on the Parameters tab of its controller graph.
> 1 votes

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


# Question
Title: Can I force a manually created texture to not be divided with low quality?
I have a texture that I have created that looks something like this:

.

This is a very low texture map, but it helps me in a shader that I'm making that distinguishes between land and ocean, the ocean tiles do different things than the land. To try and figure out what was going on, I used the shader to turn the ocean, as defined by the mask, black. Note that this image doesn't match the ocean texture example from above, but it's the best I had...

The ocean is a binary color, either it is ocean or isn't, and is set appropriately. But what I'm actually seeing is that if the 2x2 tile area has mixed land/ ocean, the value is averaged.

What I've noticed is that the pixels were combining together, a 2x2 pixel area was averaged. After tracing through this for some time, I discovered that the issue was a quality setting that reduced the resolution of certain images.

There are some images that I don't mind lowering the resolution of, but images such as this one I absolutely don't want to lower the resolution. Is there a setting that I can add to a runtime generated texture to tell it not to reduce it's resolution if requested to by the quality settings?

EDIT: Code fragments to produce the results above. It's kind of hard to pull just the fragments that produce this code and not produce an overwhelming bit, but hopefully this will do.

Code to generate textures:

```
Color32[] windMask=new Color32[world.width*world.height];
for (int x = 0; x < world.width; x++)
{
    for (int y = 0; y < world.height; y++)
    {
        windMask[x + world.width * y] = world.Tiles(x, y).baseType == Tile.BaseType.Ocean?new Color32(255,255,255,255):new Color32(0,0,0,255);
    }
}

sharedMaterial.SetTexture("_WindMask", TextureUtilities.TextureFromColors(world.width, world.height, windMask, FilterMode.Point));

public static Texture2D TextureFromColors(int width, int height, Color[] colors, FilterMode filterMode = FilterMode.Trilinear)
{
    Texture2D texture = new Texture2D(width, height);
    texture.SetPixels(colors);
    texture.filterMode = filterMode;
    texture.Apply();
    return texture;
}

```

The Shader code:

```
o.Albedo *= 1 - tex2D(_WindMask, IN.uv_MainTex).r;

```

The "Fastest" quality settings that show the issue:

The "Fantastic" quality, which correctly isolates the ocean.

Image of the correctly isolated ocean:

The issue is the "Texture Quality", which you will note for the fastest setting is half resolution. I would really like to keep the ability to use lower resolution in the game, but have a few textures that do not use the lower resolution if the quality settings change.

# Answer
> 2 votes
Can you try replacing your creation line with this?

```
var texture = Texture2D(width, height, TextureFormat.R8, false);

```

This forces the texture to a non-compressed format with no mipmaps. (You can also try TextureFormat.RGBA8, but I noticed you're only using the red channel so we can save some bytes)

You'll also want to ensure that width and height are powers of 2, otherwise on some graphics hardware Unity will be forced to scale your image, resulting in pixel values other than the ones you want.

# Answer
> 1 votes
On the import setting of the image, you could try changing the setting, that by default says "Bilinear" (hope it is spelt correct), to "Point (no filter)". Also, there should be a setting that, by default, says "Compressed", to something else.

---
Tags: unity, shaders, textures
---


# Question
Title: Unity runs custom AssetPostProcessor every time on save
I've written a AssetPostProcessor script that make some changes to prefabs and materials on import in some specific folders. I'm using this method to do that:

```
private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromPath)
{
   // if the importedAsset is a prefab
   GameObject obj = (GameObject)AssetDatabase.LoadAssetAtPath(objName, typeof(GameObject));
   if (obj) {
        if (AssetDatabase.GetAssetPath(obj).Contains("Assets/Tiled2Unity/Prefabs")) {
            // Here's some code that changes the asset
        }
    }
}

```

For some reason, every time I save this AssetPostProcessor is run which is something I don't want because this is lost time for something that isn't needed. What can I do to stop this?

# Answer
> 0 votes
The asset postprocessor point of existence is to be actually executed each time any asset in the project structure changes.

In order to prevent a post-processor from taking too much time while it executes, you need to change your logic in a way that rejects unneeded assets as quickly as possible. For example, in your code you could verify the path of the asset examining the `objName` and not go and load the entire asset. For instance:

```
if (objectName.Contains("Assets/Tiled2Unity/Prefabs")) {
   // Now you can load the actual asset.
}

```

The above check is way less expensive than loading the asset itself (which means reading it from the disk, and creating the respective Unity Object which represents it).

You may also refer to Sarprer Soher's example of an asset post-processor. He utilises some of the built-in methods in the post-processor which address specific asset types, such as:

* `void OnPreprocessTexture()` \- called for images
* `void OnPreprocessModel()` \- the one you need for working with FBX-es
* `void OnPreprocessAudio()` \- for sounds/music

The above methods have a post-process counterpart:

* `void OnPostprocessTexture()`
* `void OnPostprocessModel()`
* `void OnPostprocessAudio()`

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


# Question
Title: Cannot implicitly convert type 'T' to 'UnityEngine.Vector3'
**I'm trying to use C# generics on a method in order to send a Vector3 (position) as a parameter. I can print the value correctly but can't store it on a local variable. I also can't access its x, y or z attributes separately.**

I'm implementing a state machine. My intention is to use generics for allowing sending different parameters to the different states. The value will be sent to an "Enter" method which will be called once on each state every time that state is set to active or current. So for example: the player will be on the DefaultState-\>something happens-\>change state to HeroTeleportingState while sending it it's new position

This is my Enter method on the HeroTeleportingState class:

```
void IState.Enter<T>(T newPosition)
{
    //The following line prints the correct value
    Debug.Log("move this hero to " + newPosition);

    //The following lines don't work
    //pos = newPosition
    //pos.x = newPosition.x;
}

```

The method call is just something like: `currentlyRunningState.Enter(Vector3.one);`

`pos = newPosition` gives me the following error on Visual studio (I'm paraphrasing cause my visual studio is in spanish):

> Cannot implicitly convert type 'T' to 'UnityEngine.Vector3'

And `pos.x = newPosition.x` gives me something like:

> 'T' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type 'T' could be found

---

**EDIT:** IState interface:

```
public interface IState
{
    void Enter<T>(T value);

    void Execute();

    void Exit();
}

```

# Answer
> 4 votes
Generics in C# don't work this way. It looks like you're using them the way you'd use templates in C++, but there are notable differences between C++ templates and C# generics. The biggest is that generics are instantiated at runtime.

That means that if you are going to use methods or properties of a generic type within a generic method, you need to tell the compiler what interfaces provide those methods and properties first. You do this with constraints. You can constrain on interfaces, base (reference) types, and a few other things not entirely relevant to your issue here.

Unity's `Vector3` is a value type, and so cannot be used as a base type constraint. Even if it could, the practical upshot of doing that is to effectively make you "generic" method equivalent to the non-generic version, `void IState.Enter(Vector3 newPosition)`.

You can't directly do what you're trying to do at the low level here. But you can still accomplish the high level goal:

> My intention is to use generics for allowing sending different parameters to the different states. The value will be sent to an "Enter" method which will be called once at the beginning of every new state.

There are two ways, offhand, you might want to go about this. The simple solution is to write `Enter` as: `void Enter(Dictionary<string, object> parameters)`, using a generic dictionary mapping from parameters names to parameter values, and letting each state subclass that implements `Enter` "know" which named keys to extract and how to cast them from `object` to do what is needed.

The second way is to write `Enter` as `void Enter(StateEntryParameters parameters)` where `StateEntryParameters` is a base class containing the appropriate parameters for the state. `Enter` implementations in each state subclass will still need to cast `parameters` to the correct subclass they expect. For example, the parameters for a state that takes a vector for a new position might look like:

```
class InitialStateParameters : StateEntryParameters {
    public Vector3 NewPosition;
}

```

You could also use an interface instead of a base class, since `StateEntryParameters` isn't (at least in this example) actually adding any value. Note that this approach also allows you to use generics with constraints on `StateEntryParameters`, but that's still effectively pointless.

A third option (and honestly, the one I'd prefer, but which may not work for you in the larger context of your design) is to simply pass the parameters you need to each state subclass in it's own constructor, and don't actually *do* anything with them in those constructors except store them for later, when you eventually call `Enter()`. This requires that you know what the parameters to each state will be when you create it, and so may not fit into your larger design, but it keeps the `IState` interface much simpler; `Enter` can be just as boring of a function as `Execute()` is.

# Answer
> 1 votes
Currently `T` can be anything, you don't want that. Instead, try making `T` extend Vector3:

```
void IState.Enter<T>(T newPosition) where T : Vector3

```

This way you can only pass something to this method, if it extends Vector3

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


# Question
Title: Is it possible (and practical) to dynamically create normal maps from graphics in Pixi.js?
I am building a tile game using Pixi.js. The game features dynamically-generated terrain and a day/night cycle. I'd like to use a normal map to give the sense of sloping hills or mountains.

Luckily pixi.js supports normals. I've recreated a demo app from their examples here:

```
var viewWidth = 1024 // /2;
 var viewHeight = 1024 //512 /2;

  // Create a pixi renderer
 var renderer = PIXI.autoDetectRenderer(viewWidth, viewHeight);
 renderer.view.className = "rendererView";

  // add render view to DOM
 document.body.appendChild(renderer.view);

  // create an new instance of a pixi stage
 var stage = new PIXI.Stage(0xFFFFFF);

  //EXPERIMENTAL: Trying to dynamically create textures. Doesn't work.
  //If using this method, comment out line 24.
 /*var rect = new PIXI.Graphics();
 rect.beginFill(0xFFFFFF);
 rect.drawRect(0,0,600,600);
 rect.endFill();
 var pondFloorTexture = rect.generateTexture();*/

  // create a background texture
  var pondFloorTexture = PIXI.Texture.fromImage("http://www.goodboydigital.com/pixijs/examples/20/counch_norm.jpg");

  // create a new background sprite
  //var pondFloorSprite = new PIXI.Sprite(pondFloorTexture);
  //stage.addChild(pondFloorSprite);

 var filter = new PIXI.NormalMapFilter(pondFloorTexture);

 var sprite = PIXI.Sprite.fromImage("http://www.goodboydigital.com/pixijs/examples/20/couch.jpg"); //(pondFloorTexture);

 sprite.filters = [filter];
 stage.addChild(sprite);

 var tick = 0;
 requestAnimationFrame(animate);

 function animate() {

   // increment the ticker
   tick += 0.1;

   var mouse = stage.interactionManager.mouse;

   if (mouse.global.x < 0) mouse.global.x = 0;
   else if (mouse.global.x > viewWidth) mouse.global.x = viewWidth;

   if (mouse.global.y < 0) mouse.global.y = 0;
   else if (mouse.global.y > viewHeight) mouse.global.y = viewHeight;

   filter.uniforms.LightPos.value[0] = mouse.global.x;
   filter.uniforms.LightPos.value[1] = mouse.global.y;
   // time to render the state!
   renderer.render(stage);

   // request another animation frame..
   requestAnimationFrame(animate);
 }
```

```
<script src="http://www.goodboydigital.com/pixijs/examples/20/pixi.js"></script>
<script src="http://www.goodboydigital.com/pixijs/examples/20/NormalMapFilter.js"></script>
```

Note that at line 15 I've added a bit of code that attempts to replace the normal map with a dynamically created rectangle. But for some reason this results in everything appearing black. Am I doing something wrong? Is there a better way to do this?

But more importantly, *should* I be creating normal maps dynamically? Obviously generating them on the fly will be computationally expensive, but how else would I get a normal map for something I won't know the shape of until last minute?

# Answer
> 1 votes
I'm confused by your question; I think you're going about this all wrong.

Let's first consider that it would have to be an advanced algorithm indeed that could (accurately) reconstruct surface normals given no more than a texture implying surface geometry.

If I had to tackle that problem myself, I'd try getting at it by treating every pixel as a height within a heightmap. But there would be all kinds of factors required to determine a pixel's actual height from its shading, everything from it's albedo colour to whether it is in shade due to overhangs. Non-trivial. Then you'd need to use the heightmap to determine surface gradients and thus normals at various points. I've seen similar problems solved... by computational geometry specialists in doctors' level theses. I'm not even sure this probably could actually be solved for all cases, because an object could have albedo colours that confuse the geometry reconstruction algorithm (most notably: full black).

So back down to planet Earth: if you're dynamically generating the terrain, you should be extracting spatial data during generation, then implementing proper lighting therewith, whether via normal maps or any other approach.

# Answer
> 0 votes
Apparently the NormalMapFilter extension is very limited and doesn't even work with Pixi.js v3. NormalMapFilter might just be buggy and may never be fixed. Instead, the preferred method of lighting and normal maps in Pixi.js is currently to use the pixi-lights extension.

Now I've played around with it, and I'm still having some serious problems with texture swapping when including pixi-lights with my project (I'm almost certain this is a bug with the library since it breaks my code just by being included, but I will report it or suggest a fix once I discover why it breaks texture swapping in my application). Nevertheless, I expect that this extension will not be limited by the quirks of NormalMapFliter.

As for dynamically creating normal maps, I've decided that while it may be possible, there is a better way. I'll just create a simple program to create several variations of a normal map in advance and include them in the texture atlas. Without getting into specifics, the normal map for a tile that is facing east then might look like this:

The normal map for a tile on a cliff facing south-west and plateaus might look like this:

And so on. So that I'll have a relatively small number of these to choose from. Suppose that each of the four sides has three possibilities: slope up, slope down, or plateau. Then there are at most 3x3x3x3 = 81 of these to generate - many of them being mirror images of each other (but you get the idea).

# Answer
> 0 votes
The purpose of normal maps is to contain some detail that is used to calculate how much light will contribute lighting up parts of a polygon.

If all your tiles are flat squares there isnt a need of a normal map. Just apply the inverse transform matrix of your modelview.

In your case you would probably need to calculate the normals of the entire mesh terrain. This would give you a position and normal per vertex. If the terrain doesnt rotate or scale then there is also no need to apply any matrix to the vertices

---
Tags: graphics-programming, normal-mapping
---


# Question
Title: Rendering to framebuffer / multiple rendering in a frame makes geometry black
I'm trying to adapt the shadow-mapping process given on this microbasic guide into my game, it's made with LibGDX. I've run into a blocking point with the creation of the shadow buffer via rendering to a texture.

When I just use my normal shader, the game looks fine:

When I render using my depth shader, it renders as I expect it should:

But when I try to render to a FrameBuffer with the depth shader, and then normally with the normal shader, all geometry rendered with that normal shader appears black:

Debug geometry, which is rendered with Libgdx's default shaders, actually renders fine though. I'd appreciate suggestions as to what could be causing this, since I've spent a few hours searching through the code I could find and I couldn't find anything that I obviously wasn't doing or was doing wrong.

I'll post the relevant code, which is written in Scala.

In the render function:

```
val provider: RenderableProvider = (the provider for all geometry)

lightBuffer.begin()
Gdx.gl.glClearColor(0, 0, 0, 1)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT)
lightBatch.begin(lightCam)
lightBatch.render(provider)
lightBatch.end()
lightBuffer.end()

Gdx.gl.glClearColor(0.5089f, 0.6941f, 1f, 1f)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT)
Gdx.gl.glEnable(GL20.GL_TEXTURE_2D)
modelBatch.begin(cam)
modelBatch.render(provider, environment)
modelBatch.end()

```

In the initialization logic:

```
private var modelBatch: ModelBatch = _
private var lightCam: PerspectiveCamera = _
private var lightBuffer: FrameBuffer = _
private var lightBatch: ModelBatch = _
private var depthShader: DepthShader = _
private var sceneShader: TestShader = _
private var environment: Environment = _

```

...

```
modelBatch = new ModelBatch(new BaseShaderProvider {

  shaders.add(sceneShader)

  override def createShader(renderable: Renderable): Shader =
    new DefaultShader(renderable, new DefaultShader.Config())

})

environment = new Environment
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.4f, 0.4f, 0.4f, 1))
environment.add(new DirectionalLight().set(1, 1, 1, 0, -1, 0))

lightCam = new PerspectiveCamera(120f, 1024, 1024)
lightCam.near = 0.1f
lightCam.far = 100f
lightCam.position.set(0, 10, 0)
lightCam.lookAt(1, 10, 1)
lightCam.update()

lightBuffer = new FrameBuffer(Format.RGBA8888, 1024, 1024, true)
depthShader = new DepthShader()
depthShader.init()
lightBatch = new ModelBatch(new ShaderProvider {
  override def getShader(renderable: Renderable): Shader =
    depthShader

  override def dispose(): Unit =
    depthShader.dispose()
})

```

The Scala shader classes:

```
class DepthShader extends Shader {

  var program: ShaderProgram = _
  var cam: Camera = _
  var context: RenderContext = _

  var u_projViewTrans: Int = _
  var u_worldTrans: Int = _
  var u_cameraFar: Int = _
  var u_lightPosition: Int = _

  override def canRender(instance: Renderable): Boolean = true

  override def init(): Unit = {
    val vert = Gdx.files.internal("shaders/depth_v.glsl").readString()
    val frag = Gdx.files.internal("shaders/depth_f.glsl").readString()
    program = new ShaderProgram(vert, frag)

    if (!(program isCompiled))
      throw new GdxRuntimeException(program.getLog)

    u_projViewTrans = program.getUniformLocation("u_projViewTrans")
    u_worldTrans = program.getUniformLocation("u_worldTrans")
    u_cameraFar = program.getUniformLocation("u_cameraFar")
    u_lightPosition = program.getUniformLocation("u_lightPosition")
  }

  override def compareTo(other: Shader): Int = 0

  override def begin(camera: Camera, context: RenderContext): Unit = {
    this.cam = camera
    this.context = context
    program.begin()

    program.setUniformMatrix(u_projViewTrans, camera.combined)
    program.setUniformf(u_cameraFar, camera.far)
    program.setUniform3fv(u_lightPosition, Array(camera.position.x, camera.position.y, camera.position.z), 0, 3)

    context.setDepthTest(GL20.GL_LEQUAL)
    context.setCullFace(GL20.GL_BACK)
  }

  override def render(renderable: Renderable): Unit = {
    program.setUniformMatrix(u_worldTrans, renderable.worldTransform)
    renderable.meshPart.render(program)
  }

  override def end(): Unit = {
    program.end()
  }

  override def dispose(): Unit = {
    program.dispose()
  }
}

class TestShader(sheet: Texture) extends Shader {

  var program: ShaderProgram = _
  var cam: Camera = _
  var context: RenderContext = _
  var u_projViewTrans: Int = _
  var u_worldTrans: Int = _

  override def canRender(instance: Renderable): Boolean = {
    instance.meshPart.primitiveType == GL20.GL_TRIANGLES
  }

  override def init(): Unit = {
    val vert = Gdx.files.internal("shaders/test_v.glsl").readString()
    val frag = Gdx.files.internal("shaders/test_f.glsl").readString()
    program = new ShaderProgram(vert, frag)
    if (!(program isCompiled))
      throw new GdxRuntimeException(program.getLog)
    u_projViewTrans = program.getUniformLocation("u_projViewTrans")
    u_worldTrans = program.getUniformLocation("u_worldTrans")
  }

  override def compareTo(other: Shader): Int = 0

  override def begin(camera: Camera, context: RenderContext): Unit = {
    this.cam = camera
    this.context = context
    program.begin()
    program.setUniformMatrix(u_projViewTrans, camera.combined)
    sheet.bind()
    program.setUniformi("u_texture", 0)
    context.setDepthTest(GL20.GL_LEQUAL)
    context.setCullFace(GL20.GL_BACK)
  }

  override def render(renderable: Renderable): Unit = {
    program.setUniformMatrix(u_worldTrans, renderable.worldTransform)
    renderable.meshPart.render(program)
  }

  override def end(): Unit = {
    program.end()
  }

  override def dispose(): Unit = {
    program.dispose()
  }

}

```

The GLSL shaders:

```
#version 120

attribute vec3 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_worldTrans;
uniform mat4 u_projViewTrans;

varying vec2 v_texCoord0;
varying vec4 v_color;

// scene vertex shader
void main() {
    v_texCoord0 = a_texCoord0;
    v_color = a_color;
    gl_Position = u_projViewTrans * u_worldTrans * vec4(a_position, 1.0);
}

#version 120

varying vec2 v_texCoord0;
varying vec4 v_color;

uniform sampler2D u_texture;

// scene fragment shader
void main() {
    gl_FragColor = texture2D(u_texture, v_texCoord0);

    //gl_FragColor = v_color;
}
#version 120

attribute vec3 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;

uniform mat4 u_worldTrans;
uniform mat4 u_projViewTrans;

varying vec4 v_position;

// depth vertex shader
void main() {
    v_position = u_worldTrans * vec4(a_position, 1.0);
    gl_Position = u_projViewTrans * v_position;
}

#version 120

uniform float u_cameraFar;
uniform vec3 u_lightPosition;

varying vec4 v_position;

// depth fragment shader
void main() {
    gl_FragColor = vec4(length(v_position.xyz - u_lightPosition) / u_cameraFar);
}

```

Thank you for your time.

# Answer
> 1 votes
The problem was that I was using multiple shader providers, and references to the shaders were cached into the renderables. Instead of extending BaseShaderProvider, I just directly implemented ShaderProvider to only cache models if they should be rendered with the LibGDX default shader. (If you do this, remember that the shader provider is responsible for initializing shaders).

---
Tags: opengl, libgdx, lwjgl, scala
---


# Question
Title: Handling incoming packets immediately or queuing them
I'm using Golang to write a game server. I was wondering what the advantages of queuing the incoming packets for processing over processing them immediately.

For example (processing immediately) each new connection/client a new goroutine/coroutine is created and within that goroutine a loop that reads from the network socket and has a switch statement that routes and handles each packet.

Or (queuing) each new connection/client a new goroutine is created and within that goroutine a loop that reads from the network socket and passes it to a queue. A second dedicated goroutine for this connection/client has a loop that process the packets in the queue.

Is this a pre-optimization? How are MMORPG's (server side) packet recv/handling handled in principle?

I'm using TCP.

# Answer
> 1 votes
Since you clarified in the comments that you really want to know about TCP, the answer is simple: At this level of performance, it usually does not really matter.

If you aim for a higher level of performance, you'll want to use a different approach with far fewer threads than the ones you suggested.

* Use 1 thread per NIC, handling every single client connected to that NIC. Because of the large number of clients you only do parsing, followed by the minimal preprocessing of the messages necessary to enqueue messages on the appropriate target thread. If you use UDP, this thread will likely also implement heartbeat and some retransmission request functionality as necessary.
* Use multiple threads based on the game's design. Easy targets to split off into independent threads are chat and dungeon instances (if they aren't already on different servers), most everything else depends on the specifics of the game, although inventory is often a candidate for getting its own thread.

The primary benefit of a pre-processing thread for all incoming messages (per NIC) is scaling. Additionally, by moving the parsing and sorting to a different thread this is something you no longer need to worry about.

The downside of a pre-processing thread for all incoming messages is complexity if compared to the single threaded mega-application.

Using multiple threads for the initial processing of incoming messages is undesirable. First, it offers no benefit: A single thread is fast enough to parse everything the NIC and the OS can deliver, unless the parsing function is poorly designed (solution: optimize the parsing function). Second, it does introduce unnecessary race conditions: If 2 players want to pick up the same item, player A's packet may arrive at the server first, but player B's request may end up being processed first. Third, using multiple threads to parse and sort incoming messages ends up requiring more performance, primarily due to light synchronization overhead.

Using a thread per player is undesirable, because it leads to large synchronization overhead.

# Answer
> 2 votes
You will probably want to handle packets as they become available. As mentioned in the comments, OS and network drivers will queue packets, but as soon as your code knows about them you'll want to consume them.

However, processing the effect of a specific message may depend on the purpose of it. If it's a simple ping or other synchronizing message, you may want to respond right away.

But if it's a player action, that needs to be reconciled against other player actions, you may want to queue it temporarily and process all such messages at one time.

This is because of general latency. If Player A performs some task and Player B performs a counter to that, it's possible that the messages will come in in a different order than they actually happened.

So you may consider holding all messages during a given frame (some small period of time to allow for normal lag, maybe 100ms) and process them. Or holding the message to be resolved once you have all messages that came in 50ms before and 50ms after are available.

In the end my recommendation is to receive each packet as it comes in, and respond to it if needed, or put the event it represents into a queue to be processed.

---
Tags: networking, mmo, server
---


# Question
Title: Object array in unity not instantiating properly
I'm trying to instantiate my CarMovement class with my population class for a Genetic Algorithm, but when i run the project, the car prefab doesnt spawn.

Everything is wired up in the inspector correctly. Anyone know whats going on?

Here's the population class:

```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Population : MonoBehaviour {

    public int populationSize = 10;
    private CarMovement[] cars;

    // Use this for initialization
    void Start () {
        cars =  new CarMovement[populationSize];
        for (int i = 0; i < populationSize; i++) {
            cars [i] = new CarMovement ();
            cars [i].score = 1+i;
            Debug.Log (cars [i].score);
        }
        //cars[0].Start();
    }

    // Update is called once per frame
    void Update () {
    }
}

```

Here's the CarMovement/Individual class:

```
public class CarMovement : MonoBehaviour {

    public float speed = 2f;
    public Rigidbody2D rb2d;
    public Vector2 spawnPosition = new Vector2((1.0f)*0.1f,3.83f);
    public int score;
    public GameObject carPrefab;

    // Use this for initialization
    public void Start () {
        rb2d = GetComponent<Rigidbody2D> ();
        GameObject.Instantiate (carPrefab,spawnPosition,Quaternion.identity);
        Debug.Log ("YAAAA");

    }

    // Update is called once per frame
    public void Update() {
        rb2d.transform.Translate (speed * Time.deltaTime, 0, 0);

    }
}

```

# Answer
It looks like you want something like this:

```
public class Population : MonoBehaviour {

    // Assign this Inspector variable to point at your prefab.
    public CarMovement carPrefab;

    public int populationSize = 10;

    // The Population class does the spawning now, so it can hold the spawn position.
    public Vector2 spawnPosition = new Vector2(0.1f, 3.83f);

    private CarMovement[] cars;

    void Start () {
        cars =  new CarMovement[populationSize];
        for (int i = 0; i < populationSize; i++) {
            cars [i] = (CarMovement)Instantiate(
                           carPrefab,
                           spawnPosition,
                           Quaternion.identity);
            cars [i].score = 1+i;
        }
    }
}

```

This Instantiates your cars and grabs a handle to the `CarMovement` script instance already on them (assuming your prefab has a `CarMovement` on it), rather than trying to create an instance of the component free-floating without a GameObject attached.
> 1 votes

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


title: Convertion from 3D to 2D openGL

text:
# Question
Title: Convertion from 3D to 2D openGL
Few days ago , we learned about Homogeneous Matrices in OpenGL class. From what I have understood , using these matrices we can convert 3D objects to 2D. However , I am facing some difficulties answering a simple question like : "Which of those matrices answering to the definition of converting from 3D to 2D (Homogeneous)" :

```
           A                         B                      C               D

```

I'm not asking you to do my homework, I know the answer it's D and C and this is all I need for this section. I just want to understand why? how it works? why A,B not and C,D yes.
Thank you.

# Answer
In matrix C you have an X scale factor of 1 at position (0, 0). You have a Y scale factor of 1 at position (1, 1). The Z scale factor is at position (2, 2) and it is set to 0. If you take any coordinate and multiply it by the matrix, the Z-component ends up as 0. No matter what x and y are, Z will always be 0, so you've essentially flattened (or more accurately projected) all coordinates onto the XY plane. All 3D points become 2D points in the XY plane.

For matrix D, again, think about multiplying a point by the matrix. Since the first row is the same as the second row, the resulting x and y coordinates will always be the same. Therefore, every resulting coordinate will be on the x=y plane.

Whenever you create a matrix that, when multiplied by any point results in points that are on the same plane, you've converted from 3D to 2D.
> 2 votes

---
Tags: opengl, 3d, matrix
---


title: Implementing Jump in pygame

text:
# Question
Title: Implementing Jump in pygame
I have come across a problem in my code for my game. Currently i am developing a 2D platformer game in pygame. I have gotten the character to move left and right, although i haven't been able to get him to jump. I have experimented with a number of possibilities that all haven't worked.

```
while True:
    #handles user input
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == KEYDOWN:
            if (event.key == K_LEFT or event.key == K_a) and player.direction != RIGHT:  #if the left key is pressed
                player.direction = LEFT  #change the direction to left
                player.playerPicture = player.runLeft
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif (event.key == K_RIGHT or event.key == K_d) and player.direction != LEFT:  #if the right key is pressed
                player.direction = RIGHT #change the directions to right
                player.playerPicture = player.runRight
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif (event.key == K_UP or event.key == K_w) and player.direction != LEFT and player.direction != RIGHT:
                player.direction = UP
                player.playerPicture = player.jump
                player.playerPicture = player.playerPicture.convert_alpha()
                DISPLAYSURF.blit(player.playerPicture, (player.playerx, player.playery))

            elif event.key == K_ESCAPE: #if the escape key is pressed
                 terminate()  #quit the game

        else:
            player.playerPicture = player.standingStill
            player.playerPicture = player.playerPicture.convert_alpha()
            player.direction = None

    DISPLAYSURF.fill(Black)

    #update game state

    if player.direction == LEFT:
         #if the players position is greater than the left boundary
        if (player.playerx > boundaryLeft):
            player.playerx -= 8 #move the player to the left

        #if the direction is right
    elif player.direction == RIGHT:
        if (player.playerx < boundaryRight): #player is less than the right boundary
            player.playerx += 8  #move the player to the right

    elif player.direction == UP:

```

This code is in the mainloop of the game. It pretty much checks what key has been pressed, applies the appropriate image for the character and changes the direction. Afterwards the character is manipulated based on the direction that he is facing. If he is facing right, he will walk right etc.

```
class Player(pygame.sprite.Sprite):
def __init__(self): #constructor
    pygame.sprite.Sprite.__init__(self) #constructor for the sprite
    self.playerPicture = pygame.image.load('JumpLeft.png')
    self.runRight = pygame.image.load('RunRight2.png')
    self.runLeft = pygame.image.load('RunLeft2.png')
    self.jump = pygame.image.load('Jump.png')
    self.playerPicture = self.playerPicture.convert_alpha()
    self.rect = self.playerPicture.get_rect()

    self.standingStill = pygame.image.load('JumpLeft.png')
    self.playerx = windowWidth / 2
    self.playery = windowHeight - 200
    self.direction = None
    self.onGround = False
    self.isJumping = False;
    self.gravity = 1.2
    self.velocity = 0

    self.rect.center = (self.playerx, self.playery)

```

Current attempts: So far i've tried

```
if direction == 'UP':
   player.playery -= 2

```

which the character pretty much just continuously moves up until the user releases the space button

# Answer
It's actually pretty simple!

When you jump, you have upwards velocity that is greater than the force of gravity. As time progresses this upwards velocity starts to decrease because of gravity! After a while it becomes negative and you start heading towards the ground. Finally, when you hit the ground your velocity becomes zero.

(I am not a physicist so if their is a mistake please don't kill me!)

Same goes with games:

1. When the user presses space you set the player's velocity to a number greater than the force of gravity
2. Then, each time the game updates, you change the players velocity based on the force of gravity and the time passed since the last update (`delta`)
3. When the player hits the ground, you set the players velocity to 0

Here is an example in code:

**When the user presses jump:**

```
player.isJumping = true
player.velocity = x

```

**When the game updates:**

```
if (player.isJumping):
   player.velocity -= player.gravity * delta

player.playery += player.velocity

```

**When the player hits the ground:**

```
player.isJumping = False
player.velocity = 0

```

(`x` is the upwards velocity you want the player to have when the user presses jump)
> 2 votes

---
Tags: python, pygame
---


title: Perspective View using Spritesheets

text:
# Question
Title: Perspective View using Spritesheets
I am creating a Top-View 2D game. However, the only way i can get a good view of the objects, such as houses, trees, is to make the game in orthographic view. The same way games such as Pokemon games in GameBoy Advances used. Until i found out that, GTA 1 and 2 are originally in top-view. Whenever the car (your focus) passes a building, the view of the building changes, specifically, the "Skewness" of the building.

Is it possible to do this using SpriteSheets? or atleast a single image and just dynamically change its attributes? or GTA 2 is already using a 3D game engine.

# Answer
It's perfectly possible to do this. Most game engines (it's harder with graphics APIs, but it's possible) allow you to supply matrices, and these can represent skewing.

So, first of all, let's say you have a house (or a block of something) defined as the bottom polygon and the player's position:

First, for each line in the polygon you get the vectors pointing from the player's position to the ends of the lines, multiply them by two and add them to the player's position to get a "shadow" of the lines:

This gives you 4 points, which describe a quad.

If you have a way to draw custom quads, then just use this and texture it correctly. If you don't, then a line by line solution should work instead.

First, calculate the angle of the bottom line (the line you used to create the "shadow") and create a rotation matrix that transforms the line to a horizontal position. If the line is defined by the two points `A` and `B`, then this would be:

```
angle = atan2(B.y - A.y, B-x - A.x)

matrix = | cos -angle, -sin -angle |
         | sin -angle,  cos -angle |

```

Then multiply every point of the quad with this matrix, this should result in the following effect:

This is necessary to make the base of every quad aligned with the x axis. Now the line-by-line part. Get the distance on the y axis between the bottom and top lines of the quad (the base line and the "shadow") in pixels and loop through between 0 and this distance. The endpoints of the line parallel to the x axis, that's going across the quad at a specific y position are:

```
P1 = A + y / height * (D - A)
P2 = B + y / height * (C - B)

```

using the naming from the image above. For an example look at this image:

Now, loop through this line pixel by pixel to get an x position. Now you have an x and y position in the quad's coordinate system. To convert this to uv coordinates, use the following formula:

```
u = (x - P1.x) / (P2.x - P1.x)
v = y / height

```
> 0 votes

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


# Question
Title: How to draw a NavMesh Path to a destination without traversing the path in Unity3d?
I have a set of pre-determined destinations. When the user chooses any one of those destinations, the path to the destination should be drawn, similiar to google maps. I am trying to do this in unity, but not able to figure out just how.

# Answer
> 0 votes
You can use **LineRenderer** component that Unity provides. Attach it to the the appropriate GameObject, set the parameters of it in order to visualise the line however you desire and use the following code:

```
private Vector3[] wayPoints; //You have to set these waypoints before you start to use LineRenderer.
private LineRenderer lineRenderer;

void Start()
{
    lineRenderer = GetComponent<LineRenderer>();
    lineRenderer.positionCount = wayPoints.Length;
    for (int i = 0; i < wayPoints.Length; i++)
    {
        lineRenderer.SetPosition(i, wayPoints[i]);
    }
}

```

You might want to check the manual out as well.

---
Tags: unity, path-finding, navmesh, path
---


title: Tank avoid other objects?

text:
# Question
Title: Tank avoid other objects?
My tanks working good except one thing, they not avoid each other in good way. they not generate the path to find new good position. My tank follow it own agent position and direction. I add NavMeshObstacle fit the tank size. After all this, still I get some bad things. tanks hit each other, tank moving above other tank, some time get stuck between two tanks which lead to strange movement(shaking). example this tank on the middle.

what can I do to improve tank avoiding ?

# Answer
> 1 votes
First Move the tanks off the terrain and rebake the nav mesh so the whole terrain bakes properly. Then hit control z and they should move back where you had them before the bake.

Couple things to check are :

Click on the Tank and in your Navigation Tab click OBJECT and check Navigation Static then check the Not Walkable Option and they should path around each other.

*note: The object must be in the scene to set the 'not walkable' option so if it's a prefab drop it to the scene and set it.*

Also on the nav agent there is a stopping distance setting that you can increase so a group of objects would not all try to pile up at the same point

---
Tags: unity, navmesh
---


# Question
Title: Why can changing a camera's position prevent it from rotating?
I am going through the official introductory series "Roll a Ball" by the Unity team, and am on part 3 (youtube link.

There is a ball with mouse controls attached, and a Camera set as a descendant of the ball so that it follows it around. As the tutorial mentions, the Camera at this stage "rolls" along with the ball and is unusable.

The fix, as shown in the video, is the following added to Camera:

```
public GameObject player; # added through GUI
private Vector3 offset;
void Start () {
  offset = transform.position - player.transform.position;
}
void Update () {
  transform.position = player.transform.position + offset;
}

```

I understand in terms of C# syntax what this does, but I don't understand why it stops the camera from rotating. Isn't position controlled separately from rotation?

# Answer
> 1 votes
The tranform of the GameObject has the properties "position" and "rotation"

These properties inherit their values from their parent unless you assign them different values.

But if the camera has no father and you only change its position, the value of its rotation is always constant

Good luck!

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


# Question
Title: How can I fix the vibration in my Player movement?
Edit: solved my issue, but look at the other answer

I am stuck with a problem that I cant quite figure out.

When I move my Player to a new point, it does get there, but it vibrates. I can't seem to get it to stop.

I've used an Entity Component System.

This is a function in my `Component_Transform` class

```
void direction(float x_pos_str, float y_pos_str, float x_pos_end, float y_pos_end)
    {
        if (x_pos_str < x_pos_end)
        {
            if (x_pos_str != x_pos_end) { velocity.x = 1; }
        }
        if (y_pos_str < y_pos_end)
        {
            if (y_pos_str != y_pos_end) { velocity.y = 1; }
        }
        if (x_pos_str > x_pos_end)
        {
            if (x_pos_str != x_pos_end) { velocity.x = -1; }
        }
        if (y_pos_str > y_pos_end)
        {
            if (y_pos_str != y_pos_end) { velocity.y = -1; }
        }
        if (x_pos_str == x_pos_end)
        {
            velocity.x = 0;
        }
        if (y_pos_str == y_pos_end)
        {
            velocity.y = 0;
        }

```

This is apart of my `Controller_Mouse` class

```
void update() override
    {
        if (Game::event.type == SDL_MOUSEBUTTONDOWN)
        {
            if (SDL_BUTTON_LEFT)
            {

                std::cout << "transform vals: " << transform->position.x <<", " <<transform->position.y << std::endl;
                std::cout << "click vals:     " << Game::event.motion.x << ", " << Game::event.motion.y << std::endl;

                transform->target.x = Game::event.motion.x; transform->target.y = Game::event.motion.y;

            }

        }
        if (Game::event.type == SDL_MOUSEBUTTONUP, SDL_BUTTON_LEFT)
        {
            transform->direction(transform->position.x, transform->position.y, transform->target.x, transform->target.y);

        }

```

# Answer
I solved it by doing this

I should note that I use speed, which was not apart of the original post. It is separate from velocity. It is so I can control the individual pacing of things that have the Transform Component

Here is the update function,which explains the relationship

```
void update() override
    {
        position.x += velocity.x * speed;
        position.y += velocity.y * speed;
    }

```

And here is the revised Direction function

```
        if (x_pos_str == x_pos_end || x_pos_str >= x_pos_end - speed || x_pos_str <= x_pos_end + speed)
        {
            velocity.x = 0;
        }
        if (y_pos_str == y_pos_end || y_pos_str >= y_pos_end - speed || y_pos_str <= y_pos_end + speed)
        {
            velocity.y = 0;
        }

        if (x_pos_str < x_pos_end - speed)
        {
            velocity.x = 1;
        }
        if (y_pos_str < y_pos_end - speed)
        {
            velocity.y = 1;
        }

        if (x_pos_str > x_pos_end + speed)
        {
            velocity.x = -1;
        }
        if (y_pos_str > y_pos_end + speed)
        {
            velocity.y = -1;
        }

```
> 0 votes

# Answer
This is a quite easy problem to solve.

This happens, because your player overshoots the target. Let's think in a single axis. The player is on the 49.5 point and the target is at 50. The next step you make the player move a unit, so they'll land on 50.5. 50.5 is greater than 50, so it goes back. This repeats forever and makes the player "vibrate".

You shouldn't make the player land exactly at that position, a "close enough" should work well. Continuing with our 1D example, let' make the player only go towards the point, if the distance os greater than pr equal to 1. This way, it'll stop at 49.5.

In 2D you'd solve this by getting the distance between the player's pos and the target, and only move if it's greater than the velocity (I'm abusing the fact, that if `√x > √y`, then `x > y`, because the latter is less intensive on the CPU):

```
    if (x_pos_str < x_pos_end && pow(x_pos_end - x_pos_str, 2) + pow(y_pos_end - y_pos_str, 2) < 1)
    {
        velocity.x = 1;
    }

```

Additional notes:

1.) You don't need to check if `x_pos_str` equals `x_pos_end` after checking if the former is lower than the latter. If x is smaller than y, then x =/= y.

2.) You should probably look up code conventions. People usually use camelcase (camelCase) instead of underscores (under\_scores) for variables. The variables should also habe a more descriptive name.
> 1 votes

---
Tags: c++, architecture, sdl
---