# Question
Title: In Unreal, what are the differences between C++'s float and FFloat32?
I have been trying to learn some deeper aspects of UE4 and while reading many examples codes and also the source base of the engine, I noticed that sometimes people (and the very source code) use the standard C++ `float` primitive, but sometimes use UE4's custom implementation `FFloat32`.

Then I got curious: when programming a game with Unreal, what are the differences between using those 2 options and possibly what are the main cases when one should drop the standard C++ primitive in favor of the engine's implementation?

# Answer
> 17 votes
`float`, is well, a C++ floating point. `FFloat32` is a structure that represents a float as well as (via a union) the decomposed bitfields for that float's sign, mantissa and exponent parts.

You should generally *never* use `FFloat32` except when:

* you're using some API that expects a `FFloat32` (these are very rare) or
* you need to do some kind of low-level bit hackery with a floating point value (also fairly rare these days)

It's not that `FFloat32` is *bad*, per se, it's just that it doesn't really offer you anything you'd need for general-purpose floating point usage.

It is less common than a plain old `float`, which has some minor readability impact (others may not know immediately what it is for at a glance). It also doesn't implicitly convert to `float` so you'll be typing `something.FloatValue` a lot, which is also not a big deal, but could get tedious.

Finally, its use of unions and bitfields is non-portable, and implementation-defined (see below). This is not *your* problem, it is Epic's job to make sure the type is structured so that it's usable for all supported implementations, but it's a potential source of bugs if they fail to catch an issue with the implementation of the type when a new compiler version is released or added to the list of supported compilers.

So unless you have a need to play with the individual bits in the floating point representation, you should probably just avoid `FFloat32` (its cousin, `FFloat16`, may have slightly more utility as there is no standard 16-bit C++ floating point type).

It used to be common to manipulate floats via integer representations of their components for "speed." Modern computers obviate much of that need for many platforms, and the various type-punning techniques that could be used to do this sort of thing can actually be detrimental to performance or correctness in any event.

It should be telling that a search of Unreal's GitHub repository reveals very few uses of the `FFloat32` type. All of them are in the the definition of `FFloat32` itself or in the definition of `FFloat16`.

---

Specifically, `FFloat32` does two things which the C++ standard calls out. It:

* allows you to act as if more than one member of the union is active at one time; you are expected to write to the floating point members and read from one of the integer members (9.5.1, \[class.union\])
* expects the bitfield allocation within the union to match that of the bit allocation of an IEEE floating point value; however, allocation and alignment of bitfield members within a class type is implementation defined (9.6.1, \[class.bit\])

---
Tags: c++, unreal-4, floating-point
---


# Question
Title: Unity: Z-position issue on gameobject with subcomponents
I'm following this tutorial from Ryan Miller on how to create a rig of sorts from a sprite atlas sheet.

My intention was to put the panda behind a bamboo, but this is what happened:

The bamboo's Z-position has been set to 2, whilst the Panda's has been set to 6.

Here's a 3D look at the problem:

How do I fix this?

# Answer
Because modifying the Z-position of the children of the Panda GameObject, I decided to mess with the **Sorting Layers**, as they were all set to `default`.

I decided to leave the Panda as is, and created a new Sorting Layer for the bamboo by selecting `Add Sorting Layer` from the list, and creating my own. It seemed to have solved the issue.
> 1 votes

---
Tags: unity
---


# Question
Title: Computing how fast a vector should go toward certain direction
I have two object in space, one has velocity (object A) with fixed magnitude, and one is static (object B).
every timestep, I add to object A's velocity a vector which direction is object A to object B, and then make the length of velocity back again (so after this addition, only angle changed), then I move object A using this new velocity (with its magnitude multiplied by fixed timestep), so at the next timestep, the additive vector will have different angle because object A had moved.
If I keep doing it every timestep, the angle between velocity vector of A and vector that goes from A to B will go toward (small enough) zero.
How do I calculate the magnitude of the additive vector so that the angle will go to zero after x seconds?

# Answer
> 1 votes
I think you can't. With this approach your object A will always have a velocity with a small component in the original direction. Why don't you calculate the angle between the A's velocity and the direction vector towards B (via scalar product). You can then lower this angle each time step (fast enough so that it becomes 0 after X seconds) and calculate the new velocities and positions.

---
Tags: vector
---


title: Best Way to Create A Map for a 2D Game?

text:
# Question
Title: Best Way to Create A Map for a 2D Game?
I apologize for the subjective "best" keyword.

My friend and I have started creation of a 2D adventure game. It will be top-down in the style of pokemon or zelda (just the perspective). We have been discussing methods of creating a large world-map that the player can traverse without straining the memory capabilities of our machine.

Our first impulse was to create a large map and a circle around the player in which content will be loaded. We figured this won't hold for long and decided to partition the map into sections. First we had four large sections, but realized we could simply break it down into many tiny sections.

I played some Zelda from the SNES and saw that, during the shift of a map, the content could be loaded just then. What I mean is, instead of just checking a rectangular area for data to load, we simply section the map into many tiny chunks that load and de-load data as we move from map-portion to map-portion.

Today, he told me he wanted to create a simply 2D array map\[WIDTH\]\[HEIGHT\] that contains data about every grid in the game and is a constant save-to-disk operation for data that we don't need.

I'm not sure about these ideas and thought that I might as it here. Any links, resources or tutorials on the subject would be greatly appreciated as well as direct answers to our question on how to do it efficiently.

# Answer
First off, estimate your map size. Don't just assume that a "big world" is not going to fit in memory. Nowadays, a map taking upwards of 10 mb in memory is absolutely acceptable, and you can stuff a LOT in 10 mb in a simple tile-based 2D world.

If you have a *really* large world, the most robust solution is indeed use map chunks. Split your world into fixed-size chunks (say, 64x64). Load chunks on-the-fly as player moves around, keeping at least one chunk loaded in all directions (i.e. load the chunk the player is in and all its neighbors).

As for unloading chunks, you can choose between several strategies. Eagerly unloading means you unload and save to disk all chunks the moment player moves sufficiently far away; but you can also delay unloading to improve performance (saving chunk, as any disk access, is a costly operation).
> 28 votes

# Answer
Personally, I'd build the map using a designated tile-editor like TileEd. This approach yields several benefits:

* Uses less resources. You just have to load a tile-sheet and data-file with indexes to build a potentially endless map.
* Since you'll have your map divided into really small chunks (depending on your tile-size), you can easily add/remove rows/columns while the character is moving through the world.
* Having a data-file that describes your map also allows you to add terrain-information easily. This allows for different tile-types like walls or lakes (i.e. obstacles) or a swamp where movement of the character could be slowed down...
* Last but not least, a tile-based map is also much easier to edit and tweak later on because you can always fire up the editor, change some things and save a new data-file.

I suggest you avoid loading bits of the map during gameplay to prevent lag. As mentioned previously, this should not be necessary as you'll probably be able to keep the tile-sheet in memory. When the character enters another part of the "world" you could swap the tile-sheet with a different one (eg. snow-tiles replaced with desert-tiles).

Blitting the tiles to screen is probably the fastest way to render your map. I don't know SFML, but from the docs on their site you should be looking into the `Sprite` class or use the `Copy` function of the `Image` class.

**Update:** I just read some of the SFML docs and you should definitely use `Drawable` or `Sprite` instead of manipulating images for the sake of performance. Apparently there's a Tiled SFML loader out there. That's probably a good way to get something up and running fast.
> 5 votes

# Answer
Start by making the map the size required to tell the story you wish the game to tell. Test on the machine with the minimum spec required for people to play your game. If it is too slow, profile and optimize.
> 1 votes

# Answer
Using a 2D array of individual tiles is best in my opinion. You can have the whole entire large map as one 2D array and only draw the part of it that needs to be displayed at any given time. The top down rpg example (found here https://www.tabageos.com/examples) uses several small maps and switches quickly between them without a transition, giving the feeling of a large open world while not being a performance drain.
> 0 votes

# Answer
Unless you're planing on re-building ultima-online (Fallout 3, or Oblivion), there's no reason the world needs to be seamless. Baldur's Gate and Icewind Dale are two games that come to mind that implement effective maps that do not detract from gameplay.

Granted, you've got a lot more computing horsepower than they did so loading screens should be minimal, but even Fallout and Oblivion have loading screens for some things.

All I can tell you is that for me, I'm writing a small Obj-C lib for the iPhone that takes a 32x32 tileset and draws it into an NSImage. I get about 10fps this way, and I probably should be using OpenGL, but I only need to re-draw if the character moves out of the rect.

You should split the map up into 9 screen-sizes (for me it's 960x640 blocks) so if the character moves out of the center block, I re-draw the 9-screens into a large image (about 1.2MB - gives a lot of room under the 20MB limit on iPhone 3G). That happens fairly slowly (much slower than 10fps) so the re-drawing is not noticeable during play.

I'll likely move to OpenGL ES at some point, but for now it works fine.

---

\[EDIT\]

Allow me to clarify.

The drawing algorithm for the 9-screen background takes 0.1 seconds (10fps flat-out). Unless your player can traverse an entire screen in less than a tenth of a second, the redrawing should be imperceptible during play.
> -3 votes

---
Tags: game-design, 2d, tiles, maps
---


title: What to do with empty space?

text:
# Question
Title: What to do with empty space?
On the game I am developing, I have a very small amount of left-over space on each level screen (but on no other screens.) It is a little less than 5 millimeters (~1/5in) on the left side and bottom. It is caused by the size of blocks, etc. and a few other factors. I could center the level, but still then there would still be dead space. By the way, the player cannot go past the edge of the screen or into the whitespace, so having the level appear to extend past the screen would be misleading. What should I do?

# Answer
> 1 votes
Center the level and then use the remaining pixels to add a decorative border which fits the style of your game interface.

You could also leave it black. Most screens have a black border anyway, so most people won't notice when it's a tiny bit wider than usual.

---
Tags: levels
---


# Question
Title: Character from downloaded AssetBundle renders as magenta in Unity
I'm currently using Unity 5.3.5f1 free edition.

I have a character in an assetbundle that I load from my server at runtime. The target platform for the asset bundle is Android. The default shader that I use for all the materials in the character is `Mobile/Diffuse`.

My problem is that when I download and instantiate the character, the whole character appears solid magenta. Please see the below screenshot:

Interestingly, if I open the scene window and switch the shader to something else (anything) the material starts to display correctly even when I switch it back to `Mobile/Diffuse`. Obviously, doing this in game isn't a choice so what causes this behavior and how can I fix this? Is this a bug?

# Answer
> 1 votes
This issue only happens when using a mobile shader. When I shifted to the Standard shader, this issue disappeared. Perhaps this is a bug in Unity.

So if you're having a similar problem, just shift to the Standard shader if possible.

---
Tags: unity, assets, asset-management
---


# Question
Title: Anti-Aliasing + Atlas Texture + VBO = nasty looking artifact
With my research I have found that using a VBO to render graphics is much faster than using depreciated OpenGL. I've found with this that you can't switch textures mid VBO render, so if I have multiple objects in a single VBO, they all have to use the same texture. I solved this problem by using a texture atlas to combine multiple textures together into one texture used throughout the whole VBO.

Now all this works perfectly. It's fast, it's efficient, and it looks good until you turn on SFML's anti-aliasing. If you look at the pictures, it appears that it's merging textures in the texture atlas at a distance. These pictures should help clear up what that means.

Without Anti-Aliasing:

With Anti-Aliasing:

The Atlas Map as it looks in memory:

Also if it helps, I experimented with adding blank space between these individual textures to see if that would hide the problem. The problem persists, only it makes objects far away appear translucent because of the alpha between the textures.

# Answer
> 1 votes
Sure took long enough to solve this, but the cause of the problem was SFML's anti-aliasing shader script. I kind of knew that was the problem all along, but didn't know how to fix it. The solution was to simply write my own shader script for anti-aliasing (which is designed to work with an atlas map) and disable mip-maps.

I got the general idea of how to do it from here: How do I implement anti-aliasing in OpenGL?

---
Tags: sfml, vbo, texture-atlas
---


# Question
Title: Updating bots/AI behavior after a fixed elapsed timestamp in game loop?
I am developing a HTML5 game in javascript. Now I have created a few bots and they should be able to change their orientation after a few seconds/a fixed timestamp in the game loop.

Suppose my game loop is like this:

```
function loop() {
    bots.updateOrientation();
    bots.render();
    player.update();
    player.render();
    requestAnimationFrame(loop);
}

```

How can I make that happen in my game loop?

# Answer
> 2 votes
The easiest way is to use counters.

If you want your bots to do something in X frames, you'll have:

```
class Bot {
  constructor() {
    this.doSomethingCounter = 0;
  }

  doSomethingInFrames(n) {
    this.doSomethingCounter = n;
  }

  update() {
    if (this.doSomethingCounter > 0) {
      this.doSomethingCounter--;
      if (this.doSomethingCounter === 0) {
        this.doSomething();
      }
    }
  }
}

```

If you want your bots to do something after X milliseconds, have the counter track the number of milliseconds left:

```
  update(ms) {
    if (this.doSomethingMs > 0) {
      this.doSomethingMs -= ms;
      if (this.doSomethingMs <= 0) {
        this.doSomething();
      }
    }
  }

```

Once you have a large collection of counters, it may be better to use a programming pattern. In the context of AI, you may want to look at a pattern like a behavior tree or FSM. Here's some places to start: New to creating AI - where to start?

# Answer
> 0 votes
Implement a que system, it gives lots of possibilities and freedom, and you'll be able to make chains of actions.

1. Maintain a que with 2 columns: 1) Timestamp and 2) Action

Add to this que new rows at any time. Apparently it's timestamps will be "now + a few milliseconds ... seconds, even hundreds of seconds in future". Each time a row is added, sort the table by timestamp, ascending; ie. the topmost row always holds the closest upcoming action.

2. During each game loop cycle, look at the topmost row. If it's timestamp is passed by teh games internal clock "now" (which ofc grows all time, as the application's internal clock advances), execute the action described it's column 2 and remove that row from the que table. If "now" is still smaller than the topmost timestamp, do nothing. Look only at the topmost row -\> potentially each game cycle removes one row, and you'll get up to fps actions at most.

An action that gets executed can add one or several further action(s) to the que, to be executed in say 2 seconds. That action again can add a further one, etc.

To for example move the sun over the sky during an entire day, insert a que entry to happen in for example 10 minutes (action timestamp is Tnow + 600 seconds). As it finally executes (in 10 minutes), let the executed function insert "itself" into the que, with timestamp "now" + 600 seconds -\> the sun will move all day.

Actions can be simple integer numbers, like: 1 = re-calc sun position 2 = refresh that guy that blacked out 2 seconds ago, etc.

Then just call the appropriate functionality based on action number. Plus have all the good housekeeping data handy :-).

---
Tags: javascript, html5, game-loop
---


title: AddForceAtPosition

text:
# Question
Title: AddForceAtPosition
I'm trying to lift the front wheel of my bike, and I got it, applying this:

```
GetComponent.<Rigidbody>().AddForceAtPosition(Vector3(0,300,0),
        Vector3(GetComponent.<Rigidbody>().position.x,
        (GetComponent.<Rigidbody>().position.y)+5,(GetComponent.<Rigidbody>().position.z)+10));

```

Works perfect, but only when the bike is on start position, when I turn it to different position the force is applied on incorrect axis.

How I can do this applying the force on local object and ALWAYS on the same position and up direction??

Thank you.

-- EDIT --

As usual, problem solved, thank you to this amazing site and amazing people. Here is the working code:

```
public var force : Vector3;
public var forcePosition : Transform;
private var rbody : Rigidbody;

(on Start function)
rbody = GetComponent<Rigidbody>();

(on update function)
if(Input.GetKey(KeyCode.F) && Input.GetKey(KeyCode.UpArrow) && curGear >0  && WheelR.isGrounded)
{
var setPositionForce = Vector3(forcePosition.position.x,forcePosition.position.y,
forcePosition.position.z);
rbody.AddForceAtPosition (force, setPositionForce);
}

```

Well, I added on if the "F" key just for test and is necessary to move the wheel and to move the wheel first gear is nedded, and minium, the rear wheel is on floor. The bike is stable when the wheel is going up and works perfectly on all directions.

# Answer
The problem is that you are applying an absolute offset. You need it to be relative to the bike's transform. Have a look at

```
transform.forward

```

Etc.

As a simple alternative, you could just create an empty object as a child of the bike, position it on the front wheel and add it as a Transform reference to your script. You can then just use the child object's position to add force.

```
public Vector3 force;
public Transform forcePosition;
private Rigidbody rbody;

private void Start()
{
    rbody = GetComponent<Rigidbody>();
}
public void TriggerForce()
{
    rbody.AddForceAtPosition(force, forcePosition.position);
}

```
> 1 votes

# Answer
Try this.

```
public Rigidbody rig;
public float force = 5f;
public Vector3 forcePositionOffset;

void Start () {

    rig = GetComponent <Rigidbody> ();
}

void Update () {

    rig.AddForceAtPosition (Vector3.up*force,transform.position+forcePositionOffset);
}

```

I recommend using this method (OnDrawGizmos or OnDrawGizmosSelected) to help you visualize in the editor where the force will be applied

```
public float gizmoSize;
void OnDrawGizmos(){

    Gizmos.DrawWireSphere (transform.position+forcePositionOffset,gizmoSize);
}

```
> 0 votes

---
Tags: unity
---


# Question
Title: Unity - Get list of gameobjects close to object clicked?
I have a stack of balls of 4 colors some touching some not. When you click on one color ball I want to destroy that ball and any other balls of that color that are close. They may not be touching so collision wont work.

How do I detect gameobjects close but not touching that are the same color? Say half a radius away from the edge of the ball clicked.

Here are the two scripts I'm working with to create and touch the game objects.

```
public class SpawnBalls : MonoBehaviour {
public Rigidbody ball;
public float waittime = 0.5f;

// Use this for initialization
void Start () {
    spawn ();
}

// Update is called once per frame
void Update () {
    //Instantiate (ball);

}
public void spawn(){
    //yield WaitForSeconds(waittime);

        for (var i = 0; i < 10; i++) {
            Instantiate (ball);
        }
}

```

}

Selecting the balls

```
public class Ball : MonoBehaviour {

public Color[] colors;
private Color ballpicked;

// Use this for initialization
void Start () {
    GetComponent<Renderer>().material.color = colors[Random.Range (0, 4)];
}

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

}
 void OnMouseDown(){
    if (Input.GetKey("mouse 0")){

        ballpicked = GetComponent<Renderer> ().material.color;

        //if (ballpicked == "Any other balls within a half a ball width") {

        //}

        Destroy (gameObject);
    }
}

```

# Answer
There's a few physics methods you may be interested in:

* OverlapSphere \- Returns an array with all colliders touching or inside the sphere.
* OverlapBox \- Find all colliders touching or inside of the given box.

You can utilize one of the above to select all the objects within a specified area. Then you can iterate through them and just keep the ones you're interested in.
> 3 votes

---
Tags: unity, collision-detection
---


# Question
Title: flip horizontaly (X) a ParticleEffect [Libgdx]
i got a particle effect thats is inside a group

```
 shellParticle = new ParticleEffect();
    shellParticle.load(Gdx.files.internal("shell13"),Gdx.files.internal(""));
    shellParticle.getEmitters().first().setPosition(0,0);
    shellParticle.scaleEffect(0.3f);

```

i need it to flip horizontaly but it just have the function `flipY` and `setFlip(bool X, bool Y)`

```
setFlip(true,false)

```

just do nothing. flipY() actualy flip it verticaly. Also i cant substract its own width\*2 beause it dosent have so please help me

# Answer
> 0 votes
This seems to be a lack of infrmation from part of libgx api. The `setFlip` method is flipping the particle sprites (for particles which have already been emitted and future particles). `flipY()` modify propieties of emmiter setting everithing to negative but setting to negative just some of properties i get the `flipX()` method. Acctualy every change you wanna do with particules you shoud do it with emmiters properties exeptiong for the x and y position.

```
   private void flipX(){

    emmiter.getAngle().setHigh(emmiter.getAngle().getHighMin(),emmiter.getAngle().getHighMax());
    emmiter.getAngle().setLow(emmiter.getAngle().getLowMin(),emmiter.getAngle().getLowMax());

    emmiter.getGravity().setHigh(emmiter.getGravity().getHighMin(),emmiter.getGravity().getHighMax());
    emmiter.getGravity().setLow(emmiter.getGravity().getLowMin(),emmiter.getGravity().getLowMax());

    emmiter.getWind().setHigh(-emmiter.getWind().getHighMin(),-emmiter.getWind().getHighMax());
    emmiter.getWind().setLow(-emmiter.getWind().getLowMin(),-emmiter.getWind().getLowMax());

    emmiter.getRotation().setHigh(-emmiter.getRotation().getHighMin(),-emmiter.getRotation().getHighMax());
    emmiter.getRotation().setLow(-emmiter.getRotation().getLowMin(),-emmiter.getRotation().getLowMax());

    emmiter.getYOffsetValue().setLow(emmiter.getYOffsetValue().getLowMin(),emmiter.getYOffsetValue().getLowMax());

    emmiter.getXOffsetValue().setLow(emmiter.getXOffsetValue().getLowMin(),emmiter.getXOffsetValue().getLowMax());

}

```

I hope it helps someone.

---
Tags: java, libgdx, particles
---


# Question
Title: Using Gimp and clone tool. Source selection selects center of four pixels
I am using gimp to make tilesets. When I use the clone tool and hold ctrl to select the source, the selection is in the center of four pixels instead of just one pixel. I don't know if I am doing something wrong or if there is a setting to change this. Any help would be greatly appreciated. Here is a pic.

# Answer
Problem solved! It is just a glitch. After you ctrl click and start cloning, the source mask stays on a single pixel.
> 0 votes

---
Tags: pixel, selection, gimp
---


# Question
Title: Render BitmapFont with size < 1 in Libgdx
My ingame camera has units that 25 times less than screen units so when I render BitmapFont generated for camera which used in non-game screens (settings, level choose etc.) it's even doesn't fit in camera.

I came up with some solutions:

1. Generate font with right size, but `No cap character found in font` exception caught.
2. Scale font with `font.getData().setScale(float scaleXY)` but got this:
3. Increase camera units but I'll need to rewrite a lot of code depending on camera combined matrix.

Is there any easier way to do this?

# Answer
> 0 votes
You could create a second 'overlay' camera that is sized differently than the main camera and draw text using that camera.

```
batch.setProjectionMatrix(sceneCamera.combined);
batch.begin();
drawSceneThings(batch);
batch.end();

batch.setProjectionMatrix(uiCamera.combined);
batch.begin();
drawUIThings(batch);
batch.end();

```

Otherwise, using distance field fonts might give you better results than bitmap fonts since they scale much better, although this will require some work to get the shaders set up and rendering properly.

---
Tags: libgdx
---


# Question
Title: Pygame wall collision is acting very odd
I've been playing around with python for a while, but I only did basic functional programming. Lately, I've been teaching myself about classes. I've been using pygame *(instead of tk, because let's face it, it's much more fun)*

So I have a simple script, with a player class, a wall class, and a game class. When the player hits the wall, it stops in it's place like it should, but only if it's moving in one direction, that is - x\>0 and only x. if y is \>0 too, I'm getting really odd behaviors as the player just flies out of the screen :( I shall post the script below, I realize it's not as orderly as an object-oriented game should be, please take into consideration that I am new to OO.

```
import pygame
pygame.init()

BLACK = 0, 0, 0
RED = 255,0,0
GREEN = 0,255,0
BLUE = 0,0,255
WHITE = 255,255,255

class Player(pygame.sprite.Sprite):

    def __init__(self, color, width, height, x, y, speed):
        super(pygame.sprite.Sprite, self).__init__()

        self.move_x = 0
        self.move_y = 0
        self.speed = speed
        self.width = width
        self.height = height
        self.image = pygame.Surface([self.width, self.height])
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def move(self):
        self.rect.x += self.move_x
        self.rect.y += self.move_y

class Wall(pygame.sprite.Sprite):

    def __init__(self, width, height, x, y):
        super(pygame.sprite.Sprite, self).__init__()

        self.width = width
        self.height = height
        self.image = pygame.Surface([self.width, self.height])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def collision(self, player):

        if self.rect.colliderect(player.rect):

            if player.move_x > 0:
                # moving right
                player.rect.right = self.rect.left

            elif player.move_x < 0:
                #moving left
                player.rect.left = self.rect.right

            elif player.move_y < 0:
                # moving up
                player.rect.top = self.rect.bottom

            elif player.move_y >0:
                #moving down
                player.rect.bottom = self.rect.top

class Game():

    def __init__( self, x, y, fps ):

        #initialize
        self.x = x
        self.y = y

        self.screen = pygame.display.set_mode( ( x,y ) )
        self.running = True

        self.clock = pygame.time.Clock()
        self.fps = fps
        self.fpsFont = pygame.font.SysFont('mono', 22)

        self.player = Player(BLUE, 50, 50, 400, 400, 5)
        self.wall = wall = Wall(1220,40,0,0)

    def on_event(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.running = False

            # Get keydowns and adjust player speed
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    self.player.move_x += self.player.speed
                if event.key == pygame.K_LEFT:
                    self.player.move_x -= self.player.speed
                if event.key == pygame.K_UP:
                    self.player.move_y -= self.player.speed
                if event.key == pygame.K_DOWN:
                    self.player.move_y += self.player.speed

            # Get keyups and resets vector
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    self.player.move_x = 0
                if event.key == pygame.K_LEFT:
                    self.player.move_x = 0
                if event.key == pygame.K_UP:
                    self.player.move_y = 0
                if event.key == pygame.K_DOWN:
                    self.player.move_y = 0

    def draw_rects(self):
        # draw all the images to the screen
        self.screen.blit(self.player.image, (self.player.rect.x, self.player.rect.y))
        self.screen.blit(self.wall.image, (self.wall.rect.x, self.wall.rect.y))

    def draw_fps(self):
        #Displays an fps counter
        text = "FPS: " + str(round(self.clock.get_fps()))
        self.renderedFPS = self.fpsFont.render(text, True, BLACK)
        self.screen.blit(self.renderedFPS, (0 , self.y - self.y / 20))

    def mainloop(self):
        #Game loop
        while self.running == True:

            # Event loop
            self.on_event()

            # Game Logic
            self.player.move()
            self.wall.collision(self.player)

            # Draw everything
            self.screen.fill( WHITE )
            self.draw_fps()
            self.draw_rects()
            pygame.display.flip()

            # Limit FPS to 60
            self.clock.tick(self.fps)

if __name__ == "__main__":

    game = Game(1220, 720, 60)
    game.mainloop()

```

# Answer
> 2 votes
You might need to look into axis separation. When it comes to collision detection in 2d with rects, you need to split up your movement and collision detection into separate x- and y-axis.

In other words, you should try moving your player on the x-axis first, then check for collision on that axis. If there is a collision, adjust on the x-axis only.

After that, do the same for the y-axis. Move the player on the y-axis and then check and correct movement against the rect on the y-axis.

This prevents the object from jumping around and it makes it easier to detect the position as you're only dealing with one axis at a time.

So add separate functions for moving your character on the x- and y-axis.

Do the same for the collision function and I think this could improve your collision detection. Look up axis separation if you need further information. I believe that is what it is called.

I had similar issues way back when I was first starting out with game programming in pygame. Axis separation as I have described it has become an essential tool for player collision detection, even in 3D.

# Answer
> 0 votes
The problem happens because when you are pressing both the up key and either the left or right key, lets use right in this case, your player.move\_y is negative, and that moved the player.rect.top to the wall.rect.bottom as you want, but the player.move\_x is also possative, or negative if moving left, so the function not only moves your player to the bottom of the wall but it also teleports him/her/it to the left of the wall as well because the player.rect.left = wall.rect.left argument is also being called.

To fix this issue, you may be able to put something like this bit of code before your first if statement after if "self.rect.colliderect(player.rect):" in Wall.collisions() function:

```
if player.move_x > 0 and player.move_y < 0:
# moving up and right
    player.rect.top = self.rect.bottom
    return
elif player.move_x < 0 and player.move_y < 0:
# moving up and left
    player.rect.top = self.rect.bottom
    return

```

The return is meant to return the function before it has a chance to hit the rest of the statement and cause the bug if you are moving up right/up left.

This bit of code only fixes it for the bottom of the wall, but from this, I'm sure you can work out how to get the rest of the wall covered if you need it.

I hope this helps. :)

---
Tags: python, pygame
---


# Question
Title: Use depth bias for shadows in deferred shading
We are building a deferred shading engine and we have a problem with shadows.

To add shadows we use two maps: the first one stores the depth of the scene captured by the player's camera and the second one stores the depth of the scene captured by the light's camera. We then ran a shader that analyzes the two maps and outputs the third one with the ready shadow areas for the current frame.

The problem we face is a classic one: Self-Shadowing:
<sub>(source: microsoft.com)</sub>

A standard way to solve this is to use the slope-scale depth bias and depth offsets, however as we are doing things in a deferred way we cannot employ this algorithm. Any attempts to set depth bias when capturing light's view depth produced no or unsatisfying results.

So here is my question: MSDN article has a convoluted explanation of the slope-scale:

```
bias = (m × SlopeScaleDepthBias) + DepthBias
Where m is the maximum depth slope of the triangle being rendered, defined as:
m = max( abs(delta z / delta x), abs(delta z / delta y) )

```

Could you explain how I can implement this algorithm manually in a shader? Maybe there are better ways to fix this problem for deferred shadows?

Update: trying to implement normal-offset shadows. Current state:

Image with no bias applied:

Normal offset bias applied, it works with the teapot, but look what it does with all the other shadows:

I even tried adding the NDotL term, it does not help:

```
float4 worldPosition = mul(input.Position, World);
float nDotL = dot(input.Normal,(shadowCameraPosition - worldPosition));
worldPosition.xyz += input.Normal*NormalBias*(1-nDotL);

```

# Answer
The hardware slope-scaled depth bias should work fine with deferred shading. It only affects the depth values written into the shadow map, so you generate the same shadow map regardless of whether you're using forward or deferred shading. Is it possible you're not reconstructing position from (camera) depth correctly when you do your lighting passes? That would throw off the points where you're sampling the shadow map, which could cause issues like this.

In general, though, I prefer normal-offset shadows instead of using depth bias. When drawing the shadow map, you use the vertex shader to offset each vertex inward a small distance along its normal. This helps shadow acne without introducing the light leaking artifacts typical of slope-scaled depth bias.
> 2 votes

# Answer
I encounter the same problem when using R32Float as shadow depth, here's my code:

```
float dx = ddx(depth);
float dy = ddy(depth);
const float bias = max(abs(dx), abs(dy)) * YOUR_SLOPE_SCALED_BIAS;
return depth + bias;

```

My recommendation is to use hardware depth instead of color buffer, and the depth bias / polygon offset will work correctly; I use R32Float just to workaround a bug of some game engine.
> 0 votes

---
Tags: depth-buffer, shadow-mapping
---


# Question
Title: Radiance arriving at or leaving a surface
I was reading this text about radiance and according to the next figure, both leaving and arriving radiances' solid angles are anchored on the surface point?

My logic tells me that the solid angle of the radiance arriving at a surface is supposed to be anchored somewhere in the "air" (say at the light bulb position). Something like this:

This way the radiance formula makes sense too, no? (irradiance per solid angle, meaning when the solid angle gets bigger the radiance at point gets smaller)

Can someone shed some light on this?

# Answer
> 2 votes
I think that both ways of looking at radiance are valid; it just depends on what you are trying to determine.

Their diagram shows the radiance arriving at a point from a particular direction. If you wanted to determine the *total radiance* arriving at that point from all directions then you would add up the radiance arriving from *all* light sources visible from that point.

Your diagram shows the radiance leaving your light source in a particular direction. The *total radiance* leaving your light source would determine how much light arrives at *each* of the many points visible from the light source.

---
Tags: shading
---


title: deprecated unity networking system

text:
# Question
Title: deprecated unity networking system
I have pretty old half done unity multiplayer project. I made it with the old unity multiplayer system that now has deprecated.

now can I complete it with the old unity network? or i need to learn new networking system?

# Answer
> 0 votes
This entirely depends on if your migrating to the new engine? if you are then you may encounter some problems, as i did. But that being said it is dependent on how your doing. The old unity networking was built on a client side server hosting - The idea that, during testing, you would host client side i.e the player hosts. This is still sort of the case now, but unity offer hosting etc, for no fee up to 100 users at one time *I think*

> (For new projects, you should use the new networking system introduced in 5.1. This information is for legacy projects using the old networking system.)

this is from unity's website regarding the legacy networking, they do advise against using the old system if your going to use the new engine.

*To sum it up*

Yes and no, but yes being the harder route, and no being the easier one (Learning the new networking)

If your going to use the new unity networking, most of it is done in similar ways, if not the same. Unity just has built in modules now to help, so its not so bad i guess.

although this is going to be very opinion based, and i expect downvotes, i want to help :)

# Answer
> 0 votes
In general, changing technology mid-way in a far progressed project is usually more costly than it is worth. It's not just the work of replacing those parts which directly interact with the technology. It's also the cost of learning the technology, learning to use it *well* (which is usually easier on a green-field project where you have less moving parts around it) and fixing all the *indirect* dependencies on the old technology (parts of your overall software architecture which were designed around the old technology handling specific things in specific ways, even though they appear quite far away from it). So we developers tend to grossly underestimate the short-term and long-term cost of such a move. Usually it is the more economical decision to just finish the project the way we started.

But on the other hand, introducing new technology can sometimes solve some as of yet unsolved problems in your project.

So my recommendation would be to teach yourself what the new technology has to offer. Then see if there is anything which solves a problem you haven't solved yet and is easier to do than with the old technology.

When your multiplayer system is already working well and your game just needs some polish in other areas, stay with what you have and focus on getting it shipped. But when your multiplayer system is still just partly done, buggy, slow and generally makes you feel miserable when you look at it, trashing it and redoing it from scratch with the new technology *might* give a payoff.

Just remember the old wisdom in software development: When it sounds easy to do, you aren't aware of all the details yet.

---
Tags: unity, networking
---


# Question
Title: My game's title is similar to other game's title. Will I get sued?
I have a game called '**Shapes Dodge**' which is still in development. I figured out the name back in February when I began developing it. Since then I've been checking monthly the Google Play Store for games with similar titles and today I saw my worst nightmare coming true - there are a few games with a similar name: https://play.google.com/store/search?q=shapes%20dodge&c=apps

I am worried about the first two games which both have the name '*Shape Dodge*'. So will I get sued if I publish my game with the name '**Shapes Dodge**' ('***shapes***' with '***S***' at its end) on the Google Play Store?

I want to emphasize that the content of my game is very different from these games' (different controlls, gameplay, graphics, music, etc), only the title is similar.

Please answer me as simple as possible because I am not very familiar with legislation, laws, copyright, trademark and so on. Thank you! :)

**Edit**

So after serios consideration and brainstorming I figured out a new name for my app: **'Dodgy Shapes'**. Obvously the amount of similarity with the other apps which contain these keywords (https://play.google.com/store/searchq=shapes%20dodge&c=apps) is much less. But do you think it is enough difference so that I won't have any problems in the future?

Again, thanks to all who responded. :)

# Answer
> 1 votes
There are few possible scenarios:

1. Games have different names and different gameplay.
2. Games have same name, but differ when it comes to their actual content and gameplay.
3. Games have different names, but are nearly identical in gameplay.
4. Games are identical both in names and gameplay.
5. Game is a rip-off of some other proprietary thing.

Now it easier to say that 1 and 2 are safe, 4 and 5 are totally not safe, and 3 could be controversial. Of course the other author can try to sue you in every scenario, but when the game is based on simple and rather common principles, then it would be hard for him to prove his claims.

Scenario #5 would be if you make game based on, e.g. Game of Thrones.

---
Tags: publishing, google-play
---


# Question
Title: How to transform a spherically-projected render into a perspective projection?
Suppose that you have a projection obtained by mapping spherical coordinates to a texture; example:

1. What is that projection called?
2. Is it possible to "fix" such texture so that it becomes a regular perspective projection?

# Answer
1. That specific projection is called an equirectangular projection.
2. Your second question is much harder to answer. The short answer is "no" there isn't a "simple" way to fix this projection to a perspective projection. You can easily map it to a cube, but that's just due to how it's defined (you can find out more about this with a quick google search). As for a more difficult answer, if you need to create a perspective image from one of these projections, you'll have to do some more advanced edge and line detection. I found paper that talks about some methods, but it's still quite tricky.

Face and Straight Line Detection in Equirectangular Images

Edit:

After a bit more research, I found that you can make a perspective projection by projecting each point on the sphere onto a cube that contains the sphere. Paul Bourke has a quick tutorial for photoshop which can probably be converted to pseudocode fairly easily.

Paul Bourke - Spherical Panoramas
> 1 votes

---
Tags: 3d, projection
---


# Question
Title: Simple Collision Resolution between 2 moving objects
I have two circles. And they can move in any direction. Their movement is based on these values:

```
circle1.xSpeed & circle1.ySpeed

```

And the same for the second circle. Now I know when they collide with eachother:

```
var dx = this.x - other.x;
var dy = this.y - other.y;
var intersectDist = (this.scale + other.scale) - Math.sqrt(dx * dx + dy * dy);
if (intersectDist >= 0) {
    // MOVE OBJECTS APART:
    intersectDist /= 2;
    this.x -= intersectDist * Math.cos(this.dir);
    this.y -= intersectDist * Math.sin(this.dir);
    other.x -= intersectDist * Math.cos(other.dir);
    other.y -= intersectDist * Math.sin(other.dir);

    // ADJUST VELOCITY: (STUCK HERE)

}

```

Im not sure if that is the best way to move the objects apart, but the main issue is the resulting x and y speeds for each object. How can I calculate those?

# Answer
A way I would usually handle this is: assuming that your objects have assigned masses which could be their dimensions or material or type base metrics. take both objects and calculate the force by multiplying their mass\*acceleration "look up the acceleration formula"! after you have the force just check which has the greater force.

Example:

One = object one;

Two = object two;

XVelocity One = 4 pixels per frame;

XVelocity Two = 8 pixels per frame;

Mass One = Radius of Circle One which is = 20;

Mass two = Radius of Circle Two which is 16;

Force One = 4 * 20; use Velocity if no accelaration!!

Force Two = 8 * 16; use velocity if no accelaration!!

Force One = 80;

Force Two = 128;

EnergyLoss One = (Force One / Force Two)\*XVelocity One = 2.5 = 0.25 "Put a zero in front"

EnergyLoss Two = (Force Two / Force One)\*Xvelocity two = 12.8 = 0.12 "Put a zero in front"

New XVelocity One = XVelocityOne\*Energyloss;

New XVelocity Two = XVelocityTwo\*Energyloss;

New XVelocity One = (0.8/1.28)-4; New XVelocity two = (1.28/0.8)-8;

This process is not complete and the formulas could be adjusted but I hope this puts you on the right path for collision ressolution!

I usually use something like this to resolve my collisions! I hope this helps!
> 1 votes

---
Tags: physics, movement
---


# Question
Title: Dynamic items in Scrollable Vertical Layout overlap Unity
I have followed steps from this tutorial site to create dynamic scrollable vertical layout. I am trying to show 10 prefab buttons in a scrollview dynamically. I can see buttons at runtime, but they are overlapped.

**ScrollPanel:**

**Content Container**

I am probably missing some components tweaks. Or problem is due to anchors? Please guide me to resolve this issue. Thanks.

# Answer
Set `ContentContainer` as the item's parent instead of `ScrollPanel`. Make sure your `Scroll Rect` has its `Content` property set to `ContentContainer`

Most likely you'll want a line like this one after instantiation:

```
LevelListItem.transform.SetParent(ContentContainer.transform, false);

```

See another post I wrote about setting up items dynamically.
> 1 votes

# Answer
The panel with the VerticalLayoutGroup has to be the parent of the objects you want to arrange within it. In your object tree it appears to be their sibling.

When you instantiate the LevelListItem buttons, make them children of the ContentContainer, not the ScrollPannel.

It also appears like you deleted the horizontal and vertical scrollbars of the standard ScrollView (or never had them in the first place because you created the ScrollView manually instead of from the "create new object" context menu. You shouldn't do that unless you know what you are doing). Without these there is no way to actually scroll it. When you want to hide them (always or only when they are unnecessary), then there is a property for that on the scrollbars.
> 3 votes

---
Tags: unity, scrolling
---


# Question
Title: What type of rotation is this and how do I apply it?
I'm developing a 3D game in Java using LWJGL and JOML. In order to simplify player and NPC coding, I'm representing their orientation as two scalar quantities: "direction" and "angle" (maybe not the best names). "Direction" is the compass direction that the object is facing, and "angle" is the angle of the object relative to a horizontal plane. So for example if a player has a direction of 180 and an angle of 45, it will be looking south at a point halfway between the horizon and the zenith.

**First question: what is this kind of rotation called officially?**

I've already written code to handle calculations on points/positions represented in this manner, but I don't know how to include the rotation in a transformation matrix for OpenGL. I have the following code to produce a transformation matrix for an object:

```
Matrix4f world_matrix = new Matrix4f().identity().translate((float) position.x, (float) position.z, (float) -position.y).rotateY((float) Math.toRadians(-direction));

```

(same code, more readable)

```
Matrix4f world_matrix = new Matrix4f()
    .identity()
    .translate((float) position.x, (float) position.z, (float) -position.y)
    .rotateY((float) Math.toRadians(-direction));

```

where `position` is the location of the object and `direction` is the aforedescribed "direction" of the object.

**Second question: how do I include `angle` in `world_matrix`?**

# Answer
> 1 votes
What you're using are called Euler angles. Euler angles can tell the direction of a vector (in your case the direction that an object is facing) with 2 angles, one around the Y axis (yaw) and 1 around the X axis (pitch).

A common misconception is that Euler angles consist of angles around the X, Y and Z axes, but what those are really called are Tait-Bryan angles.

You can include your "angle" in the world matrix by rotating around the X axis after the rotation around the Y axis (using the `rotateX` method at the end of your transformation chain). Note that the transformation methods in JOML act after any existing transformations already applied to the matrix, so `rotateX` will rotate the object about its local X axis (to set the object's rotation relative to the global coordinate space use one of the "setRotation" methods).

---
Tags: opengl, java, rotation, lwjgl
---


# Question
Title: Why do I have render problems happening frequently in my Unity scene?
I am making vertical endless runner. My platforms are moving down, and the camera and players are remaining in the same location, resulting in the effect of player movement. The obstacles are generated and move in same direction as platforms.

The problem is obstacles rendered by the camera is not right. I mean that the obstacles are in camera's FOV but are still visible after some time when they reach the player to close.

# Answer
> -1 votes
I am not entirely sure I am understanding your question. But if it is what I think it is, then you should make it so when the item hits the bottom/leaves the field of view it self destructs. If this is not the answer you are looking for then you should consider rewording your question or posting a screen shot.

http://answers.unity3d.com/questions/610537/best-practice-for-destroying-objects-that-are-out-1.html

---
Tags: unity
---


# Question
Title: Different methods of item implementation - what are the differences?
More often that not, when I see how item systems have been implemented in games, the items are retrieved using either a string or ID. Eg, GetItem("Sword") or GetItem(ID.Sword). Is there some advantage to this method that I am missing?

When I have made item systems in my games, I create a class for the item and get a new one that way - eg, new Item(Sword). At times I have also stored the items in a list of some kind, and retrieved them that way, eg GetItem(Sword).

So my question is - why do most of the systems I see use a name tag or id system? What's the problem with getting them directly by reference?

# Answer
Both has advantages and disadvantages.

`GetItem("HolySwordOfAwesomness")` is more readable. But did you notice I misspelled "Awesomeness"? The compiler can't catch that error, so it will result in a runtime error which will need to be debugged.

`GetItem(1337)` won't throw a runtime error. It will create the wrong item instead. This bug might be even harder to catch than an explicit error. But the advantage is that this passes just 4 byte to the function instead of a 21 character string. Also, a lookup by integer can be implemented much faster than a lookup by string. So this method has performance advantages. But it is completely unreadable unless you have your whole item database in your head (you won't).

But you get the best of both worlds when you use integers, but also define a constant for each item: `GetItem(ITEMID_HOLY_SWORD_OF_AWESOMNESS)`. This is readable, can be caught by the compiler because you are referring to an undefined identifier and it might offer you auto-complete help from your IDE. But the drawback is that you now need to define a constant for each item you create, which slightly increases the maintenance overhead for creating new items.

You can of course also go the object-oriented route and only refer to items by reference: `player.GiveItem(new HolySwordOfAwesomeness())`. But this only works as long as your game is completely contained within your program. References can not be passed via network, can not be read from a config file and can not be written to a savegame files. This means you will need some serialization/deserialization scheme for your items. Yes, some programming languages can serialize/deserialize objects to strings out-of-the-box, but most of these schemes tend to break after the slightest change to the class definition. IDs (no matter if integers or strings) make this much more convenient, robust and often far more compact. Also, the referencing approach can be difficult or impossible when you want to use a scripting engine (depending on the API for the engine).
> 4 votes

# Answer
In order to separate an engine from the game, you often referred to objects by a string. Especially in a scripted logic layer. Even if that name is hashed for an ID within the get method for optimization.

This way, script writers don't have to worry about how int based IDs might be changed from build to build after you learn that neither hardcoding IDs, nor looking up the ID you want from some intermediate manifest everytime are good options.
> 0 votes

---
Tags: inventory
---


title: What's the benefit of packaging assets?

text:
# Question
Title: What's the benefit of packaging assets?
So, I often see assets being packaged in some sort of custom container format.

World of Warcraft uses a bunch of files called "data.xxx" where xxx is a number (but they used something like MPQ files in the past. Not sure about the extension).

Warhammer Online used MYP files.

GW2 just had a giant .dat file (I think) with literally everything in it. Like, the whole game is one executable and then a giant file and that's it.

But is there a benefit apart from encryption? The only thing I can think of is that I can give assets something like an identifier which the engine then looks up in some sort of index that contains size and offset and then it reads from a giant file.

A few examples: I load texture "skybox-dessert-world" and it loads the texture. I don't have to worry about the format or the path. I just convert to the format I want in my packager.

Maybe something that makes more sense: I reference textures and height maps in my terrain file format. Using identifiers, I can reduce the length of the file name. Especially if I'd have to use the same texture file multiple times.

Or maybe something like this: I have multiple version of a model for discrete level of detail and just loading "model-npc-elf-male" would load the appropriate models.

But is that worth it? Or am I making a big deal out of nothing and loading files straight from disk is just as good? I've heard it's a good thing in the context of encryption and compression but that's about it.

# Answer
Only you can answer if it is worth it for your own projects. It is more work to build a container file format yourself, although you could just use `.zip` (maybe renaming the extension) and one of the many available APIs to access zip-compressed files.

Some reasons you might want to create an archive or container file are:

* obfuscation of your data (as you already pointed out) to help defeat, somewhat, casual hacking or inspection
* size optimization; one (or few) big files can take up less space than the same data split across many small files because there is a minimize file size representable by the filesystem (which includes header and metadata information about the files, which scales up in total with the number of distinct files)
* performance optimization; in a custom archive format you can lay out the subfiles however you like, grouping related files near each other so as to minimize disk seeks during IO operations
* simplicity; it can be easier to install and manage one file versus many

For all of these potential benefits, you pay a cost in complexity (which really means that that "simplicity" point is about moving the simplicity around, not necessarily increasing net simplicity) to design or at least implement such a format. So you need to weigh the value of the specific advantages you want to leverage against the cost of building and maintaining the feature to provide them for your own projects.
> 3 votes

---
Tags: assets
---


# Question
Title: How to stop diagonally in an event driven input system?
Example scenario:

Assume 2 dimensional top down movement system.

Given that I have 4 directional keys ( UP / DOWN / LEFT / RIGHT ), I am able to move in 8 different directions 4 perpendicular and 4 diagonal.

As long as a directional key is pressed there exists an assumed movement, if all directional keys are released then movement is assumed to have stopped.

If I have an event driven input system in place (instead of polling for key states every frame there is an observer which receives and acts upon events based on which keys are pressed and released) **is it possible to stop movement in a diagonal direction given that the events received will be sequential?**

In a polling driven input system, as long as I would be able to release both keys fast enough for them both to register as released at the same time on the next frame there would be no need to change the direction and the movement would conclude in a diagonal state.

# Answer
> 3 votes
If you want this kind of interaction, you'll have to introduce some sort of delay into your controls because it is very unlikely that the player will be able to release both keys in the same frame. That's most likely 16-33ms depending on your frame rate.

If you add the delay (maybe just on release and on diagonals as a special case), your direction won't change when releasing a key off a diagonal movement for a small margin of time. If both keys are released in that margin, your movement would stop in the original diagonal direction.

A lot of games will have some key press/release queue with a generous delay for diagonal controls. A good example is dashing on the diagonal by double-pressing two arrow keys.

---
Tags: architecture, algorithm, input, events, control
---


# Question
Title: How to read rendered textures back without killing performance
I have an application where I need to render some OpenGL based dlls, read the rendered textures back, and send them to another directx based application that will render them in directx.

Right now, I am rendering them using FBOs, reading them back, and then sending the data across the network. However, the "reading them back" step is killing the performance.

My basic loop is as follows:

```
while(true)
   ... render 5 to 10 textures ...
   foreach( texture in renderedTextures )
      bind texture
      glGetTexImage( data )
      push data onto a queue to send asyncronously

```

Commenting out the `glGetTextImage` call causes performance to improve drastically. What techniques can I use to read the data back faster?

# Answer
> 4 votes
So, fundamentally, the problem here is that to coerce from OpenGL to Direct3D requires bouncing from GPU memory back to system memory and back to GPU memory once more. You might seriously consider porting the OpenGL DLLs to Direct3D, or the Direct3D application to OpenGL. **Ooops**, missed that this was over the network anyways.

If you do not, there are two aspects to this performance problem to consider:

1) This is fundamentally going to eat up a lot of bandwidth. You've already discovered the only real technique to help with that: Only call glGetTexImage if you really, really need that data. If the texture didn't change, reuse the result of your last read. If you don't need the texture this frame, wait until the next. Etc.

2) This is fundamentally going to introduce some latency. Worse, your current code introduces a "sync point". GPUs operate asynchronously, a little behind where the CPU is at in terms of drawing your scene - the GPU may very well still be drawing e.g. the previous frame when your CPU is issuing draw commands for the 'current' frame. "glGetTexImage" demands the results for the current frame immediately - forcing the CPU to wait for the GPU to catch up, "synchronizing" with where the CPU is at (hence the term.)

You can reduce this problem by making the readback "asynchronous" - that is, you tell the GPU/driver to start reading the texture back into CPU memory *once it's ready*, instead of blocking the CPU, and then check the results a frame or two later. This lets you keep the CPU and GPU busy simultaneously. With OpenGL, you can use glReadPixels with a Pixel Buffer Object (PBO) that you copied the texture into (directly from GPU memory to GPU memory) to do this.

Straight from the horse's mouth, here's an article from nVidia on doing this, containing some code snippets, performance benchmarks across GPUs and texture formats, etc.:

http://http.download.nvidia.com/developer/Papers/2005/Fast\_Texture\_Transfers/Fast\_Texture\_Transfers.pdf

# Answer
> 1 votes
Try to change to location of the readback in the loop cycle. Potentially place it *right before* the "render 5 to 10 textures" (may cause a small overall sync lag).

If the loop cycle contains CPU execution, try to place that directly after "render 5 to 10 textures", as the GPU will probably release the CPU while it executes the render batch.

Try to make the render part of the loop cycle as compact as possible, do CPU right after that. You will have to experiment.

Copying from video memory to CPU memory at least used to be slow.

---
Tags: opengl, directx, graphics, performance
---


# Question
Title: Is it feasible to stream your game when the screen is small?
My game consists of a very small screen (256x256). Behind that screen, though, there is a lot of very, very expensive ray tracing going on, which requires a very powerful GPU. Moreover, all clients see a variation of the same scene, so, a single GPU could render the whole scene for everyone.

Given that scenario, I had the idea of just rendering the screen on the server and streaming it to the clients. This way, one could run my game even on very weak machines. But I guess the bandwidth use could make it unpractical; is it possible to stream a 256x256 screen at 30 fps without delay and in a lossless format?

# Answer
> 2 votes
Sure. Services like OnLive did this for games that *weren't* small (resolution-wise), and you can stream 1080p60 videos on YouTube if you go looking for them. And although both of those examples may have accepted some tradeoffs (compression and an initial buffering delay), it certain seems feasible for your reduced data set to fit within the constraints.

Assuming an uncompressed 3 bytes per pixel, a 256x256 image is 196,608 bytes. You want to send *at least* 30 of these in a second, so that's 5,898,240 bytes per second, or about 5.7 megabytes per second. A 50 Mbps broadband internet connection is 6.25 megabytes per second. So yes, it is theoretically possible for people who have an appropriately fast (but not uncommonly so) connection.

In practice, of course, a customer doesn't get the full bandwidth of their connection 100% of the time, and even if they did, other things on their network might be competing for portions of it, and other nodes in the wider internet might bottleneck your packets sometimes. So you always have to account for that kind of thing, but a 256x256@30 stream seems quite doable for a reasonable portion of the user base.

---
Tags: rendering, performance
---


# Question
Title: How could I implement programming as a mechanic?
I am wondering how I could manage to execute programs made by players in my game via some sort of in-game computer. I have been trying to figure it out but I have no idea how it is even possible.

Examples of other games that do this are:

I just need a basic explanation of how I could do it so I can start making my own games with in-game coding as a mechanic.

# Answer
There's two basic approaches:

* you host a scripting language like Lua in your game, and you have your game's "computer" be "programmed" in Lua. Simulating this computer is simply running the user's Lua scripts after setting up a Lua environment that contains the variables and other state you want your computer to represent.
* you do the same thing as above, except instead of using Lua you invent your own language or abstraction around a language (such as by placing blocks with certain functionality in the world which interact with blocks nearby them, as in Minecraft).

Really they're basically the same thing, it comes down to how much you want the experience of programming the virtual computer to be like programming a real one or like interacting with your world. And also down to how much effort you want to put into it.

In both cases you need to design what a "computer" in your game looks like. Usually they're quite simple, things that have a small amount of memory and some very basic IO functions. In your game you set aside a block of memory in a variable and you call that your "computer"'s memory. Similarly you write a bunch of functions to manipulate that memory -- to get a value from it, to add a value to it, to print it to the screen, et cetera -- and you hook them up in some fashion to the rest of your gameplay via whatever interface is appropriate for your game design.
> 3 votes

---
Tags: architecture, software-engineering
---


# Question
Title: LibGDX - button change image on hover over time
As we all know, LibGDX has a `TextButton`class which has a `TextButtonStyle` and `ButtonStyle`. The style has some parameters:

* up - an image which is shown normally as a button background
* down - shown when the button is being 'pressed'
* over - on hover

**My question is:** Is there any way to implement the 'hovering' / changing the background image IN TIME? So for example it takes 2 seconds and it's smooth?

I tried with actions and tween engine, but honestly, I really have no idea how I should implement this. Maybe some alpha operations?

If you have any ideas, I would be grateful :)

# Answer
> 2 votes
1. Extend a `TextButton`
2. Override a `draw()` method
3. Make a 'fake actor' in this new class which you'll use to a hover action
4. In `draw()` don't call super and draw the button on your own
5. Draw the 'hover' background with the 'fake actor's' alpha
6. Add alpha action to the fake actor on hover/click
7. Profit

Example:

```
public class SomeTextButton extends TextButton{

    private Actor hoverActor;

    public SomeTextButton(//some code){
    // some code
    hoverActor = new Actor();
    hoverActor.getColor().a = 0f;
}

@Override
public void draw(Batch batch, float parentalpha){
    //super.draw() // don't! you want to draw on your own

    hoverActor.act(Gdx.graphics.getDeltaTime());

    // there are two backgrounds in a textfield - normal and hover
    batch.begin();

    // we draw the hover background with the fake actor's alpha
    Color oldBatchColor = batch.getColor();
    Color newColor = new Color(batch.getColor());
    newColor.a = hoverActor.a;

    hoverbackground.draw(batch, this.getX(), this.getY(), this.getWidth(), this.getHeight());

    batch.setColor(oldBatchColor);

    // we draw the normalbackground normally, without any alpha magic
    normalBackground.draw(batch, this.getX(), this.getY(), this.getWidth(), this.getHeight());

    batch.end();
}

public Actor getHoverActor(){
    return hoverActor;
}

```

}

To fire it:

```
SomeTextButton button = new SomeTextButton(// some params);
stage.add(button);

button.addListener(new HoverListener(){
    onHover(){
        button.getHoverActor().addAction(Actions.alpha(1f,1f)); // profit
    }
});

```

---
Tags: libgdx, ui-design
---


title: Can OpenAL be used with Python?

text:
# Question
Title: Can OpenAL be used with Python?
I'm from a background of using OpenAL with other languages; and I'm on a project that benefits very much from Python. I remember PyAL, but it hasn't been updated since 2013 and my computer can't even find a copy of the package to download. I'm also aware of such relative-fringe packages as alpy and python-openal; but I'm hesitant to pick them up if they are also unmaintained. (Can't be sure yet.)

Is there a library that provides a Python binding to OpenAL? Or do I simply need to either write my own or make due with one of the other, non-3D-sound, packages? If getting it is more complicated than pip, how would I go about doing so?

Thanks.

# Answer
> 1 votes
OpenAL being cross-plattform, C and open source can most probably be used with Python. However, indeed there seems to be curently no actively supported Python binding available.

Some current attempts I could find:

They all do not look very good (you can try them out though) and none is easily installable with pip.

I'm afraid but if you want a working Python binding for OpenAL you probably have to wait or start writing your own, maybe based on one of the approaches above.

As for the alternatives, they all have advantages and disadvantages too (PyGlet, PyAudio, PyDub, PyMedia, PyGame, PyQt). Support might vary.

---
Tags: python, sound, openal
---


title: Unity trigger problem

text:
# Question
Title: Unity trigger problem
I have been making my first game but I have encountered a small problem. To show the text when you win, you have to go into a block with the OnTriggerEnter line. I cannot get to this block however, because when I put my player (a sphere) as a trigger it just passes through the ground. How do I fix this?

# Answer
Don't make the player a trigger, make the ending block a trigger.
> 5 votes

# Answer
You need to set your player as a rigid body, and set the ending block as a trigger. Although you could also put in a box trigger and have it invisible, so when you pass through that area your trigger will allow the end text to appear, and maybe go to a different scene i.e, the menu.
> 1 votes

---
Tags: unity
---


title: How scroll camera smoothly?

text:
# Question
Title: How scroll camera smoothly?
I have such screen: very long world which I draw on stage and I need to scroll it. Now I move my camera in `touchDrag()` method. But I want to move my camera like I scroll it. E.g. I fling screen fast and my camera smoothly fly for some distance on y-axis. Just like it works in ScrollPane. How can I do this?

# Answer
Yes, you understood me exactly. The question is not already actual. But thank you very much for your answer, this is another implementation of one idea. I did probably the same things, now I show my realization

```
public class CameraScroller extends InputAdapter implements GestureListener {
    public static final String TAG = "SCROLL_TAG";
    public static final float TIME_TO_SCROLL = 2.0f;

    private Camera mCamera;
    private final float mLowerPosition;
    private final float mUpperPosition;

    private GestureDetector mGestureDetector;
    private float mTimer;
    private float mVelocityY;

    /**
     * @param camera        {@link Camera} that have to be scrolled
     * @param upperPosition the upper limit position of camera
     * @param lowerPosition the lower limit position of camera
     */
    public CameraScroller(Camera camera, float lowerPosition, float upperPosition) {
        mUpperPosition = upperPosition;
        mLowerPosition = lowerPosition;
        mGestureDetector = new GestureDetector(this);
        mCamera = camera;
    }

    /**
     * Call in Screen.render()
     */
    public void act(float deltaTime) {
        if (mTimer > 0) {// if timer is not 0
            float acceleration_y = mVelocityY * deltaTime;// calculate acceleration (the rate of change of velocity)
            mTimer -= deltaTime;// decreasing timer
            mVelocityY -= acceleration_y;// decreasing velocity

          mCamera.position.y += mVelocityY;
          checkCameraPosition();// check if camera position is in not less or more than some value else stop camera (mTimer = 0)
        }
    }

    private void checkCameraPosition() {
        if (mCamera.position.y > mUpperPosition) {
            mCamera.position.y = mUpperPosition;
            mTimer = 0;
        }
        if (mCamera.position.y < mLowerPosition) {
            mCamera.position.y = mLowerPosition;
            mTimer = 0;
        }
    }

    @Override
    public boolean fling(float velocityX, float velocityY, int button) {
        mTimer = TIME_TO_SCROLL;
        mVelocityY = velocityY * Gdx.graphics.getDeltaTime();

        return true;
    }

    @Override
    public boolean pan(float x, float y, float deltaX, float deltaY) {
        float cam_y = mCamera.position.y;
        System.out.println();
        if (cam_y >= mLowerPosition && cam_y <= mUpperPosition) {
            mCamera.position.y += deltaY;
        }
        if (mCamera.position.y > mUpperPosition) mCamera.position.y = mUpperPosition;
        if (mCamera.position.y < mLowerPosition) mCamera.position.y = mLowerPosition;

        return false;
    }

    @Override
    public boolean panStop(float x, float y, int pointer, int button) {
        mVelocityY = 0;
        return true;
    }

    @Override
    public boolean touchDown(float x, float y, int pointer, int button) {
        mTimer = 0;
        return true;
    }

    public GestureDetector getGestureDetector() {
        return mGestureDetector;
    }

    @Override
    public boolean zoom(float initialDistance, float distance) {
        return false;
    }

    @Override
    public boolean pinch(Vector2 initialPointer1, Vector2 initialPointer2, Vector2 pointer1, Vector2 pointer2) {
        return false;
    }

    @Override
    public boolean tap(float x, float y, int count, int button) {
        return false;
    }

    @Override
    public boolean longPress(float x, float y) {
        return false;
    }
}

```
> 2 votes

# Answer
I'm having a bit of trouble understanding the exact question, but I think your solution is to add some basic physics to your camera:

If you're looking for a way to have your camera keep moving after you drag it, have it record the velocity you drag it with as a vector. To make it slowly come to a stop, you modify the velocity after release with posNew = posOld + finalVelocity\*t + 1/2 * a * t^2, where "a" is a (negative!) constant of friction (you'll have to experiment to find a good value for this) and t is the time between frames or updates.

Now I'll get a bit more specific:

1. Recording final velocity:

When you drag the screen, you will record positions over time. To get a velocity, you simply find v = (posEnd - posStart)/t, where t is the time between frames. If you want to be able to scroll on just the x-axis, you only need to put x-values into the position variables. If you want x and y scrolling, you need to compute separate final velocities for both x and y and use them independently.

2. Movement of camera after you release:

If you need to move in both the x and y directions, record a final velocity for both x and y and use the same formula as above to compute the next frame's velocity. To find the frame position, use the formula above.

3. Movement after finalVelocity * t = -a\*t^2:

You will get to a point eventually where this equation becomes true. This is the point where your camera stops moving. This is also the point you want to stop using physics. If you continue after this point, t^2 will increase faster than just t, and you will end up moving your camera in the opposite direction. I would suggest using an if-statement with a simple inequality wrapping the whole drag method.

4. About using vectors:

If you must move in both the x and y directions, I would suggest using some sort of vector class. I'm not quite sure what language you're using or what libgdx is, but vectors should work in the same ways for any programming language, and they sometimes have built in functions for what I described above. If you use vectors, it might be helpful to get some background understanding of vector math when it comes to physics, which can be done through even a simple Wikipedia search.

I hope this answers your question, but if it doesn't, please comment and let me know what needs to be specified.
> 1 votes

---
Tags: libgdx, camera, scrolling
---


# Question
Title: Center of Image whose height, width and position are known
I have been struggling to find the center of an image(rectangle). I have following data with me:

```
width: w,
height: h,
position: (x,y)

```

My image is an object on canvas. I am using KonvaJS framework. My concern is not specific to image it's with `Rect`, `Square` as well but cause images are actually rectangle or squares and I believe that solution will be common for all. What I want to do is I need to find the center of the shape so that I can perform the desired operation. eg. I want to place the connector between a circle and image. End point of the connectors should be at the center like the way I have displayed it in image. Please let me know what should I do to achieve this. I believe it will be done by `Math.atan()` and `Math.atan2()` but don't know how can I use them. I am new to this bizarre.

# Answer
> 2 votes
If the `(X,Y)` is at the top-left corner of the rectangle as you have drawn in the picture in your question, then the center is simply:

```
(X + W*0.5 , Y - H*0.5 )

```

Note that it is always a good practice to multiply by 0.5 instead of dividing by 2, since multiplications are much less computationaly expensive than divisions.

# Answer
> 0 votes
`width: w,
height: h,
position: (x,y),
centre: (x + w/2, y + h/2)`

Hope it helps.

---
Tags: mathematics, javascript, html-canvas
---


title: Mac OSX GLFW Fullscreen Crash

text:
# Question
Title: Mac OSX GLFW Fullscreen Crash
Whenever I run my code to make a fullscreen GLFW window, it crashes.

Here is the code:

```
package ext.tpz.test;

import static org.lwjgl.glfw.GLFW.*;

public class Main {

    public Main() {
    }

    public static void main(String[] args) {
        if (glfwInit() == false) {
            System.out.println("GLFW failed to init.");
            System.exit(1);
        }
        long fullscreen = 0;
        if(args.length >= 1) {
            if (args[0].equals("-fullscreen")) {
                fullscreen = 1;
            }
        }
        long win = glfwCreateWindow(640,480, "Test", fullscreen, 0);

        glfwShowWindow(win);
        while(glfwWindowShouldClose(win) == false ) {
            glfwPollEvents();
        }

        glfwTerminate();
    }
}

```

Here is the crash report:

> A fatal error has been detected by the Java Runtime Environment:
>
> SIGSEGV (0xb) at pc=0x000000012dd11841, pid=13565, tid=1811
>
> JRE version: Java(TM) SE Runtime Environment (8.0\_65-b17) (build 1.8.0\_65-b17) Java VM: Java HotSpot(TM) 64-Bit Server VM (25.65-b01 mixed mode bsd-amd64 compressed oops) Problematic frame: C \[libglfw.dylib+0x9841\]
>
> Failed to write core dump. Core dumps have been disabled. To enable core dumping, try "ulimit -c unlimited" before starting Java again
>
> An error report file with more information is saved as: /Users/a677c774/IdeaProjects/LWJGL 3 Tests/hs\_err\_pid13565.log
>
> If you would like to submit a bug report, please visit: http://bugreport.java.com/bugreport/crash.jsp The crash happened outside the Java Virtual Machine in native code. See problematic frame for where to report the bug.
>
> Process finished with exit code 134 (interrupted by signal 6: SIGABRT)

# Answer
> 1 votes
The problem was that you set the `fullscreen` variable to 1, instead this variable should be set to a monitor value.

To retrieve the default monitor's value you can call glfw's method `glfwGetPrimaryMonitor()`.

This should solve the main issue, besides of that I have also added the context creation, window update and window clearing function calls.

You can find a documentation on how to use glfw at
http://www.glfw.org/docs/latest/

```
import org.lwjgl.opengl.GL;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryUtil.NULL;

public static void main(String[] args) {
    if (!glfwInit()) {
        System.out.println("Failed to initialize GLFW.");
        System.exit(1);
    }

    long fullscreen = NULL;
    if(args.length >= 1) {
        if (args[0].equals("-fullscreen")) {
            fullscreen = glfwGetPrimaryMonitor();
        }
    }

    long window = glfwCreateWindow(640, 480, "Test", fullscreen, NULL);
    if (window == NULL) {
        System.out.println("Failed to create the window.");
        glfwTerminate();
        System.exit(1);
    }

    glfwMakeContextCurrent(window);
    GL.createCapabilities();

    while(!glfwWindowShouldClose(window)) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwTerminate();
}

```

---
Tags: glfw, lwjgl3
---


# Question
Title: Formula for model matrix with mouse coordinates
I'm trying to create a simple OpenGL app where I can drag objects with the mouse.

The code below is based on a raycasting algorithm covered here.

I'm using the diff between the current mouse coord and an anchor point. The anchor point is initially where the mouse was originally clicked, and then later the last current coord after the frame is rendered.

I'm missing the proper formula to use against the distance. I believe it has something to do with the viewport to world space frustum. As a result, the object being dragged either moves too fast or too slow.

```
// Hold mouse coords
struct mstate {
    double x = 0;
    double y = 0;
    double lastX = 0;
    double lastY = 0;
    double deltaX = 0;
    double deltaY = 0;
    bool pressed = FALSE;
    glm::vec3 worldAnchor;
    glm::vec3 worldAnchorTranslated;
} MouseState;

// Initialize OpenGL window/scene
Application::Application() {
    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
    }

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Map Editor", NULL, NULL);
    if (window == NULL)
    {
        fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible.");
        glfwTerminate();
        return;
    }
    glfwMakeContextCurrent(window);

    glewExperimental = true;
    if (glewInit() != GLEW_OK)
    {
        fprintf(stderr, "Failed to initialize GLEW\n");
        return;
    }

    glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

    glClearColor(0.0f, 0.0f, 0.4f, 0.0f);

    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);

    //
    // Initialize GL program
    //
    //GLuint VertexArrayID;
    glGenVertexArrays(1, &GlobalVertexArrayID);
    glBindVertexArray(GlobalVertexArrayID);

    ProgramID = LoadShaders("SimpleVertexShader.vertexshader", "TextureFragmentShader.fragmentshader");
    GlobalProgramID = ProgramID;

    // Model Matrix stuff
    MatrixID = glGetUniformLocation(ProgramID, "MVP");

    Projection = glm::perspective(1.0f, 4.0f / 3.0f, 0.1f, 1500.0f);
    GlobalProjection = Projection;

    View = glm::lookAt(
        glm::vec3(0, 0, 500), // Camera location
        glm::vec3(0, 0, 0), // Where camera is looking
        glm::vec3(0, 1, 0) // Camera head is facing up
    );
    GlobalView = View;

    Model = glm::mat4(1.0f);
    GlobalModel = Model;

    MVP = Projection * View * Model; // Matrix multiplication

    TextureSampler = glGetUniformLocation(ProgramID, "myTextureSampler"); // Corresponds with fragment shader

    glfwSetMouseButtonCallback(window, buttonDownCallback);
    glfwSetCursorPosCallback(window, cursorPositionCallback);

    init_font();
}

// Handle mouse events, keep track of coords
void Application::buttonDownCallback(GLFWwindow* window, int button, int action, int mods)
{
    int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT);
    if (state == GLFW_PRESS)
    {
        MouseState.pressed = TRUE;

        MouseState.lastX = MouseState.x;
        MouseState.lastY = MouseState.y;

        OutputDebugString("Pressed");
    } else {
        MouseState.pressed = FALSE;
        MouseState.lastX = 0.0;
        MouseState.lastY = 0.0;

        OutputDebugString("Not-Pressed");
    }

    glm::vec3 pos = glm::vec3(MouseState.x, MouseState.y, 0.0f);

    vec3 un = Application::viewToWorldCoordTransform(MouseState.x, MouseState.y);

    MouseState.worldAnchor = glm::vec3(MouseState.x, MouseState.y, 1.0);
    MouseState.worldAnchorTranslated = glm::vec3(un[0], un[1], un[2]);
}

// Convert cords from viewport to world view
vec3 Application::viewToWorldCoordTransform(int mouse_x, int mouse_y) {
    // NORMALISED DEVICE COORDINATES
    float x = (2.0f * mouse_x) / WINDOW_WIDTH - 1.0f;
    //Debugger::LogLn("Normalised X: " + std::to_string(x));

    float y = 1.0f - (2.0f * mouse_y / WINDOW_HEIGHT);
    float z = 1.0f;
    vec3 ray_nds = vec3(x, y, z);

    // HOMOGENEOUS CLIP COORDINATES
    vec4 ray_clip = vec4(ray_nds.x, ray_nds.y, -1.0, 1.0);
    //Debugger::LogLn("Homogeneous X: " + std::to_string(ray_nds.x));

    // EYE (CAMERA) COORDINATES
    vec4 ray_eye = inverse(GlobalProjection) * ray_clip;
    ray_eye = vec4(ray_eye.x, ray_eye.y, -1.0, 0.0);
    //Debugger::LogLn("Eye Coordinates: " + std::to_string(ray_eye.x));

    // WORLD COORDINATES
    vec4 ray_wor_temp = (inverse(GlobalView) * ray_eye);
    //Debugger::LogLn("ray temp x: " + std::to_string(ray_wor_temp.x));
    vec3 un = vec3(ray_wor_temp.x, ray_wor_temp.y, ray_wor_temp.z);
    un = normalize(un);
    //Debugger::LogLn("World Coordinates: " + std::to_string(un[0]));
    return un;
}

// Main loop, moves object according to mouse distance
void Application::loop() {
    glfwPollEvents();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(ProgramID);

    if (MouseState.pressed)
    {
        Debugger::LogLn("====================");

        vec3 delta_transformed1 = Application::viewToWorldCoordTransform(MouseState.lastX, MouseState.lastY);
        vec3 delta_transformed2 = Application::viewToWorldCoordTransform(MouseState.x, MouseState.y);
        glm::vec3 transformed_diff_vec = glm::vec3(delta_transformed1.x - delta_transformed2.x, 0.0, 0.0);

        Debugger::LogLn("Last X: " + std::to_string(MouseState.lastX));
        Debugger::LogLn("X: " + std::to_string(MouseState.x));
        Debugger::LogLn("Transformed Delta X: " + std::to_string(transformed_diff_vec.x));

        Tiles[0]._x -= transformed_diff_vec.x * 500; // <-- Uses camera distance. Close, too little distance
        //Tiles[0]._x -= MouseState.lastX - MouseState.x; // <-- Too much distance
        Debugger::LogLn("Tiles[0]._x: " + std::to_string(Tiles[0]._x));
    }

    Model = glm::translate(glm::mat4(1.0f), glm::vec3(Tiles[0]._x, Tiles[0]._y, 0.0));

    MVP = Projection * View * Model;
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

    Tiles[0].draw();
    Debugger::LogOpenGLError("Tile draw");
    glfwSwapBuffers(window);

    MouseState.worldAnchor = glm::vec3(MouseState.x, MouseState.y, 1.0);
    MouseState.worldAnchorTranslated = glm::vec3(0.0, 0.0, 1.0);
    MouseState.deltaX = 0;
    MouseState.deltaY = 0;
    MouseState.lastX = MouseState.x;
    MouseState.lastY = MouseState.y;
    loopNum++;
}

```

My questions are:

1. What is the correct algorithm to calculate the correct distance in world space?
2. Are there any suggestions on articles/documentations to give a better basic and in depth understanding of 3D space calculations?

# Answer
The problem I was running into was essentially of the view to matrix algorithm being incorrect.

**Key Problems**

1.) I was normalizing the return value:

`un = normalize(un); // Removed from new code`

2.) I was transforming view coords to screen coords as a point and not a vector:

```
// Old
vec4 ray_clip = vec4(ray_nds.x, ray_nds.y, -1.0, 1.0);

// New
glm::vec4 screenPos = glm::vec4(x, -y, -0.0f, 0.0f);

```

**Code**

Here's the key areas of code that were modified:

*viewToWorldCoordTransform*

```
glm::vec3 Application::viewToWorldCoordTransform(int mouse_x, int mouse_y) {
    double x = 2.0 * mouse_x / WINDOW_WIDTH - 1;
    double y = 2.0 * mouse_y / WINDOW_HEIGHT - 1;

    glm::mat4 ProjectView = GlobalProjection * GlobalView;
    glm::mat4 viewProjectionInverse = inverse(ProjectView);
    glm::vec4 screenPos = glm::vec4(x, -y, -0.0f, 0.0f);
    glm::vec4 worldPos = viewProjectionInverse * screenPos;

    return glm::vec3(worldPos);
}

```

*Main Loop*

```
void Application::loop() {
    glfwPollEvents();
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(ProgramID);

    if (MouseState.pressed)
    {
        totalXMovement += MouseState.lastX - MouseState.x;

        vec3 delta_transformed1 = Application::viewToWorldCoordTransform(MouseState.lastX, MouseState.lastY);
        vec3 delta_transformed2 = Application::viewToWorldCoordTransform(MouseState.x, MouseState.y);

        glm::vec3 transformed_diff_vec = glm::vec3(delta_transformed1.x - delta_transformed2.x, 0.0, 0.0);

        Tiles[0]._x = static_cast<float>(delta_transformed2.x) *CameraDistance;
        Tiles[0]._y = static_cast<float>(delta_transformed2.y) *CameraDistance;
        Tiles[0]._z = static_cast<float>(delta_transformed2.z);// *CameraDistance;

        Model = glm::translate(glm::mat4(1.0f), glm::vec3(Tiles[0]._x, Tiles[0]._y, 0));
    }

    MVP = Projection * View * Model;
    glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]);

    Tiles[0].draw();
    glfwSwapBuffers(window);

    MouseState.worldAnchor = glm::vec3(MouseState.x, MouseState.y, 1.0);
    MouseState.worldAnchorTranslated = glm::vec3(0.0, 0.0, 1.0);
    MouseState.deltaX = 0;
    MouseState.deltaY = 0;
    MouseState.lastX = MouseState.x;
    MouseState.lastY = MouseState.y;
    loopNum++;
}

```
> 0 votes

---
Tags: opengl, glm
---


# Question
Title: How can I make it so the baller/ball does not keep moving after it bounces?
I am pretty new to Unity so how I did it may not be the best way, but when the character jumps it is inconsistent. When I press the up arrow key really quickly and then stop the jump will be further than it is supposed to be and it starts to glide. I want all the jumps to be the same size and the player can't bounce again until it is on the ground. Also if I start playing to quickly within the first second or two the ball jumps really far but if I wait a couple seconds it bounce like normal.

Here is my code:

```
    using UnityEngine;
    using System.Collections;

    public class MovePlayer : MonoBehaviour {

    public float distance;
    public float fspeed;
    public float uspeed;
    public float addToDistance;
    bool jumping = false;

    //PRIVATE
    private Rigidbody rigidBody;

    void Awake()
    {
        rigidBody = GetComponent<Rigidbody>();
        rigidBody.freezeRotation = true;
    }

    void FixedUpdate()
    {
        if (!jumping)
        {
                if (Input.GetButtonDown ("up")) {
                    rigidBody.AddForce (new Vector3 (0, uspeed, fspeed));
                }

                if (Input.GetButtonDown ("down")) {
                    rigidBody.AddForce (new Vector3 (0, uspeed, -fspeed));
                }

                if (Input.GetButtonDown ("right")) {
                    rigidBody.AddForce (new Vector3 (fspeed, uspeed, 0));
                }

                if (Input.GetButtonDown ("left")) {
                    rigidBody.AddForce (new Vector3 (-fspeed, uspeed, 0));
                }
         }

     }

    void OnCollisionEnter(Collision other)
    {
    if (other.gameObject.CompareTag("Ground"))
        jumping = false;
    }

    void OnCollisionExit(Collision other)
    {
    if (other.gameObject.CompareTag("Ground"))
        jumping = true;
    }
}

```

# Answer
> 3 votes
Use a `ForceMode`. `Impulse` is great for a jumping character, looks realistic as uses mass. And it's not continuous. Also requires a lower value for more effect.

```
if (Input.GetKey(KeyCode.UpArrow))
{
   rigidBody.AddForce(new Vector3(0, uspeed, fspeed), ForceMode.Impulse);
}

```

Leaving the force mode parameter empty causes `Force` to be default as `ForceMode` which is continuous. Which causes sliding more than inertia does.

For ignoring inertial sliding nullify velocity when touching ground.

```
void OnCollisionEnter(Collision other)
{
    if (other.gameObject.tag == "Ground")
    {
        jumping = false;

        rigidBody.velocity = Vector3.zero;
    }
}

```

Checking `!jumping` before input already rules out jumping on air.

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