title: Version Control for Save Data

text:
# Question
Title: Version Control for Save Data
So I have this tile-based game (something like Farmville). As "tile-based" implies, the save data could potentially become very large. Game saves are stored on cloud, and any change to the save data forces me to send the whole save file to the game client, which you can imagine is terribly inefficient if the changes are very small (changing even a single tile will trigger sending of all the save data).

I'm looking at the possibility of version control to mitigate the network load. In this solution, I imagine that:

1. The client sends the server a version number.
2. The server matches the number to an older version of the savefile and compares it with the latest version.
3. The server sends a diff file back to the client, which uses it to interpret and re-produce the latest version, along with the latest version number for future reference.

How can I implement this?

# Answer
> 1 votes
Instead of sending the whole map on every load and save, divide your game map into rectangular blocks of tiles (chunks) and implement a network protocol to save/load individual chunks.

When a client connects, it requests only the chunks around the player. When the player moves, the client requests additional chunks around their new location. That way the client won't download any parts of the map it won't need anyway.

When a client saves, it only uploads those chunks to the server which it changed since the last save.

Further, in most games the map information is quite suitable for compression with stock compression algorithms. So you might shave off some traffic by compressing the map chunks with an algorithm like LZMA, DEFLATE, bzip etc. before sending them over the network.

# Answer
> 0 votes
In addition to storing the whole map on the server, store a *journal* of the map. This is a list of structures with 3 fields:

* x-coordinate
* y-coordinate
* tile state

The list index is the version number.

Whenever a map tile is changed, add a new entry for that tile to the journal.

When a client requests to be updated from version `n`, then:

* Create a temporary empty map (empty as in "no tile at all", not "empty grass tile")
* Traverse the journal from `n` to end updating that temporary map in order of journal entries.
* The result will be a mostly empty map with only those tiles set which changed since version `n`. Run this map through a compression algorithm like LZMA, DEFLATE or bzip. They will reduce the space which is taken up by empty sections considerably.
* Send this compressed delta-map to the client
* On the client-side, uncompress the map
* Iterate the map from the network and copy it to the local map, while skipping those tiles which are empty.

To avoid running out of storage for the journal, you might want to limits its maximum size to a few hundred to a few thousand versions by discarding older versions. When a client requests to be updated from a version which was already discarded, just send them the current map.

# Answer
> 0 votes
This sounds like a very odd use case. Are you sure you're not looking for a more all-encompassing solution than you actually need? There are several approaches you could apply to a map to make it possible to have it be expansive and yet still small:

1. **Sparse data structures** E.g. if your world is mostly grass that the player has to traverse, with a few "islands" or terrain actually modified by a player, you can save only the parts the player actually modified, and whenever the game is asked to show an area that isn't in your save game, you just return a default tile (in our example, grass).
2. **Palettes** Many maps contain repeating patterns. E.g. long stretches that are only grass, or maybe a building's roof is always made up of two start tiles, an arbitrary number of pairs of middle tiles, and then two end tiles. When you transfer it, instead of sending these tiles individually, what you can instead do is just have a "palette" stored locally that contains the two start tiles in the right arrangement, a pair of middle tiles, and the two end tiles, each given a number, and transmit 3 special codes that say "palette entry 1", "palette entry 2", "palette entry 3".
3. **Run-Length Encoding** Often maps also contain long stretches of identical information. A common mechanism to reduce that is to just send a number with every tile. So instead of "roof start", "roof middle", "roof middle", "roof middle", "roof end", you transfer 1x "roof start", 3x "roof middle", 1x "roof end". Now while maps that have few repeating items may use more room to represent this information, repetitive maps collapse so much that they'll usually balance things out again.
4. **Repeat codes** Similarly, you can add a buffer in which you remember the last row (or whatever unit you choose) you received, and then add a simple "repeat last row" code. So if you have a stretch that is all the same tile, you transfer one row of that tile, and then 10 short codes saying "again". There are even more complex ways to do this.

E.g. HyperCard had a B/W graphic format where they even XORed together the previous row with another one. That way, they were able to re-transmit only the different parts of a row, and generate three repeating patterns out of two repeats interrupted by a different one.

E.g. a checkerboard pattern is every other pixel is black, but among three rows, every other row is the reverse. If you then just say "512x black XORed onto the previous white/black row", you get black/white row instead. with much less information. Basically, a checkerboard turns from uncompressable into one row of black/white pixels followed by a bunch of "repeat inverted" codes.
5. **Selective Updates** By remembering the size and position (in tile coordinates) of a block of tiles, you can re-transmit arbitrary subsections of a map. If a single tile changes, you only transmit that one tile's new value and tell your app "insert that at position 100,100. Or insert this 4x3 block of tiles at position 17,2 (effectively overwriting the tiles from 17,2 to 21,2 and 17,3 to 21,3 and 17,4 to 21,4).
6. **Information Reduction** This is like Mipmapping in computer games: If you know your player will be zoomed out very far, try to transmit less information first that looks the same. E.g. if a user is zoomed at 1/4th, you could transmit only 1/4th of the tiles. If there are squares of the same tiles, just transmit the one larger tile. And then only transmit more detailed information for areas that contain more information, or even that you know the user is working with.

This could e.g. mean that you show certain houses slightly wrong in the zoomed-out version, and as you zoom in make them look more right. What you can do here depends heavily on the tiles you have and what is important in your game.

Only when the user actually clicks a certain tile in a huge, zoomed-out map, you could then load the information you need to let them manipulate those tiles in detail, and render it with more precision, scaled down. And you could of course do like progressive loading of images in older browsers used to work, where you first get the low-res version of the map, and then slowly you load more detail. The low-res version lets the user orient themselves and move the mouse to where they want to manipulate, and by that time the high-res version may have been loaded in the background.
7. **Generation Numbers** Whenever something on the map is changed, you increment a "generation" counter you have, and you remember that number on each tile when you change it. It is like a "last changed" timestamp on a file, just that we don't use wall time, because we don't really care about the seconds it took to make the actual change on our server, or the time that goes by while the user is logged out. Now, when your user logs into the server, they can tell you "this is the last time stamp I've seen" and you can just collect all tiles that have a bigger generation number than that and send them back.

You're not really saying much about your game and how it'll actually work, and why maps can be this large that transferring this data would be a problem.

---
Tags: networking, version-control
---


# Question
Title: Bounding box collision handling makes player glitch to the other side of the wall
The way I handle simple collision detection causes a really frequent and easy to reproduce glitch, which affects gameplay severely. Here's my code (Python 3.5):

```
 def move(self, _map):
    self.col = False
    for y in _map.actors:
        for actor in y:
            if actor[1]:
                if not (((self.y + self.h) < (actor[1].y - self.cam.y)) or (self.y > ((actor[1].y - self.cam.y) + actor[1].h)) or (self.x > ((actor[1].x - self.cam.x) + actor[1].w)) or ((self.x + self.w) < (actor[1].x - self.cam.x))):
                    print(self.col)
                    self.col = True
    if not self.col:
        if self.directions[0]:
            self.cam.y -= self.speed
        if self.directions[1]:
            self.cam.y += self.speed
        if self.directions[2]:
            self.cam.x -= self.speed
        if self.directions[3]:
            self.cam.x += self.speed
    else:
        if self.directions[0]:
            self.cam.y += self.speed
        if self.directions[1]:
            self.cam.y -= self.speed
        if self.directions[2]:
            self.cam.x += self.speed
        if self.directions[3]:
            self.cam.x -= self.speed
    if self.running:
        self.speed = system.RUNNING_PLAYER_SPEED
    else:
        self.speed = system.NORMAL_PLAYER_SPEED
    self.x = ((self.cam.w / 2) - (self.w / 2))
    self.y = ((self.cam.h / 2) - (self.h / 2))

```

As you can see, I'm detecting collision against walls and whatever (Any actor in the map) in the player's "move" method. The logic is pretty straightforward, a basic bounding box collision test (I consider the position of the player relative to the camera, since the player is always in the center (It's the camera that moves)). If I just stop the player if there's a collision, the player gets stuck inside the wall, thus creating the necessity of "teleporting" the player to its former position, as you can see in this other question. The problem with that solution is that it leads to this glitch, which I need to illustrate in order to make myself clear.

In this first example, I'm going up (pressing W) towards the wall.

The collision works fine just pressing W, it gets teleported in the opposite direction at each collision. The problem is when I start pressing S (Down) at the same time. The player goes **to the opposite** direction, glitching up towards the other side of the wall, since the collision test always returns true when the player is "inside" the wall, just like this:

This would severely compromise the gameplay, since players would be able to play outside the boundaries of the map in multiplayer. How can I avoid this using bounding box collision or other method?

# Answer
> 1 votes
I've finally realized how to solve the problem perfectly. I came to the conclusion that it's not a matter of detecting the collision in the present, but rather a matter of foreseeing the collision **in the future**. It's a matter of **time**! Either you record the positions of the player and then teleport him to his past in the event of a collision instead of moving him in the opposite direction in the present, or you check for a possible collision **in the future**. It works perfectly! The player can't get stuck inside the wall, or glitch through it, because the player **never gets there**! So that's the answer, future viewers: Accurate collision detection is all about **time**! (Not considering pixel-perfect detection, of course. That's not always necessary).

```
def move(self, _map):
    def check_collision(future_pos):
        for y in _map.actors:
            for actor in y:
                if actor[1]:
                    if not (((self.y + self.h) < (actor[1].y - future_pos[1])) or (self.y > ((actor[1].y - future_pos[1]) + actor[1].h)) or (self.x > ((actor[1].x - future_pos[0]) + actor[1].w)) or ((self.x + self.w) < (actor[1].x - future_pos[0]))):
                        return True
        return False
    if self.directions[0] and not check_collision((self.cam.x, self.cam.y - self.speed)):
        self.cam.y -= self.speed
    if self.directions[1] and not check_collision((self.cam.x, self.cam.y + self.speed)):
        self.cam.y += self.speed
    if self.directions[2] and not check_collision((self.cam.x - self.speed, self.cam.y)):
        self.cam.x -= self.speed
    if self.directions[3] and not check_collision((self.cam.x + self.speed, self.cam.y)):
        self.cam.x += self.speed
    if self.running:
        self.speed = system.RUNNING_PLAYER_SPEED
    else:
        self.speed = system.NORMAL_PLAYER_SPEED
    self.x = ((self.cam.w / 2) - (self.w / 2))
    self.y = ((self.cam.h / 2) - (self.h / 2))

```

---
Tags: collision-detection, python, pygame
---


# Question
Title: What is a good approach to dynamically change actor Position?
In my card game there are 2 players with each player having a `hand`(a ListArray of of `Card`s.In this case its `handPlayer1`). The `Card` class extends `Actor`.This is the code I use to deal the cards to the first player(I call this in the `show()` method) :

```
 for (int i = 0; i < 6; i++) {
        handPlayer1.get(i).setPosition(20 + i * 35, TABLE_HEIGHT - CARD_HEIGHT - 30);
    }

```

For now whenever a player plays a card it is removed from their hand and moved to the table.If the player draws a card it is added to the hand of the player like so :

```
deck.get(deck.size() - 1).addAction(Actions.moveTo(handPlayer1.get(handPlayer1.size() - 1).getX() + 20, 30, 0.1f));

```

But the problem is that sometimes the cards go out of screen bounds when the player has too much cards and are not visible.

.What is a good way to manipulate the positioning of `Actors` so that the `hand` stays in the center and all cards are a set distance from one another? I have read up on `Groups` but I don't know if adding the cards to a Group would change anything.(Picture below for reference)

# Answer
> 0 votes
*Warning* \- this is not the best approach, but it's for `UI` learning purposes.

As I can see you keep your 'deck' in a `Table`.

First of all, make a wrapper `Table` which will fill the whole screen (it will be invisible don't worry):

`final Table fullScreenTable = new Table();`

Set it's size to full screen w/h and add it to the stage:

```
stage.add(fullScreenTable);
fullScreenTable.setSize(Gdx.graphics.getWidth, Gdx.graphics.getHeight());
fullScreenTable.bottom(); // remember about this, it will force adding components to the bottom of the table.

```

Now for the player, also make a `Table`, like this:

`final Table playersTable = new Table();`

now, add the table to the screen Table like this:

```
fullScreenTable.add(playersTable).size(Gdx.graphics.getWidth(), 250);
playersTable.debug(); // calling debug will enable debug lines so you'll see where your table is (cause it's invisible D:)

```

Your `playersTable` is now on the bottom of the screen. If you add an element to it, it will be placed on the center of the table and the next element will be placed on the right of the previous.

Now, when you have your list with the cards:

```
public void rebuildHand(){
    playersTable.clear(); // it will clear the table from previous cards
    for (int i = 0; i < handPlayer1.size(); i++) {
        Card card = handPlayer1.get(i);
        // we will have to 'pad' the card to the left, cause otherwise they'll stick to each other
        final float cardPadding = card.getWidth() - 10;
        playersTable.add(card).size(card.getWidth(), card.getHeight()).padLeft(-cardPadding);
        // or if it doesn't work call .padRight(cardPadding);
    }
}

```

The code above clears the table (it doesn't remove your cards from the memory, don't worry). If you 'draw a card' or 'play a card' you need to call the function above and it will rebuild the whole table, bringing all cards together (but remember that when you draw a card, you need to add it to the `handPlayer1` list and if you play a card, you have to remove it from the list.

This way, there will be no spaces between cards if you play one and you can draw more cards now cause they'll stick to each other with every draw.

If it's still not enought - you could set a MAX\_CARDS\_IN\_HAND variable or make a new row() in the Table if your cards is too big and place next cards beneath them (two rows).

Read about Table UI here: https://github.com/libgdx/libgdx/wiki/Table

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


title: AS3 move object to a point

text:
# Question
Title: AS3 move object to a point
I'm trying to make a room full of monster each side and the player stay in the middle. I have a problem, I don't know how I move each monster to the player and rotate each of them to face the player, all object is clip (in the library)... Can someone help me.

here the code of the game (Game - in english):

```
package cem {

import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;

public class Game extends MovieClip {
    private var _myPlayer: Player = new Player,
                _myTimer: Timer,
                _limitTime: uint = 1000,
                _containerMonster: MovieClip = new MovieClip;

    public function Jeu() {
        // constructor code
        addChild(_myPlayer);
        addChild(_containerMonster);

        _myPlayer.x = 500;
        _myPlayer.y = 450;

        _myTimer = new Timer(_limitTime);
        _myTimer.addEventListener(TimerEvent.TIMER, _createMonster);
        _myTimer.start();
    }

    private function _createMonster(e: TimerEvent){
        var a:Monster = new Monster;
        var b:Monster = new Monster;
        var c:Monster = new Monster;
        var d:Monster = new Monster;
        var placeMonsterTop: Array = ["178", "302", "426", "550", "674", "798", "922", "1046"];
        var placeMonsterRight: Array = ["118", "248", "372", "496", "620"];
        var placeMonsterDown: Array = ["178", "302", "426", "550", "674", "798", "922", "1046"];
        var placeMonsterLeft: Array = ["118", "248", "372", "496", "620"];
        _containerMonster.addChild(a);
        _containerMonster.addChild(b);
        _containerMonster.addChild(c);
        _containerMonster.addChild(d);
        a.x = placeMonsterTop[Math.floor(Math.random() * placeMonsterTop.length)];
        a.y = 0;
        b.x = 1222;
        b.y = placeMonsterRight[Math.floor(Math.random() * placeMonsterRight.length)];
        c.x = placeMonsterDown[Math.floor(Math.random() * placeMonsterDown.length)];
        c.y = 760;
        d.x = -46;
        d.y = placeMonsterLeft[Math.floor(Math.random() * placeMonsterLeft.length)];
}}}

```

My hierarchy is like: main folder - into the main folder I have the .fla and a folder name cem - into cem I have two .as files one name: Jeu.as an the other name Monstre.as.

I use OOP for my school.

In my cem/Monstre.as code I have nothing for the moment, but I would like to put the moving code in it.

Here the picture of my .swf (like the entire game)

The blue circle is my player and the blue squares are all my monsters. They pop each 1 sec. They pick a random value in the assignment array (like for the monster a they pick inn the top array...) and they pop. Now I only need to move it to the player, rotate it when they move or at the start (to face the player) and stop it when they reach the player.

# Answer
So here is what I would do:

1. In the Monster class constructor, you need to pass the player instance and store it, this way each monster will be able to know its target and chase it.
2. Add an event receiver for enter frame event in Monster class
3. In the enter frame function, you need to calculate the angle to the player similar to this post, and rotate the sprite to face the player.
> 1 votes

---
Tags: rotation, movement, flash, actionscript-3
---


# Question
Title: AS3 Client not sending movement to server
I am having trouble with multiplayer player movement in my game.

The client is in AS3 and the server is in C#.

Here is my problem: When I first launch the game, it connects to the server, and everything works fine. But... when I try to move my player, it isn't sending the UTF8 bytes over to the server. I even have it trace output after the socket sends the bytes. I sent the exact same bytes to the server when the game started just to see if the server recognized it, and it did.

I am not sure why it isn't even sending it at all. This is very frustrating.

```
private function keyDown(event:KeyboardEvent):void
    {
        switch(event.keyCode)
        {
            case Keyboard.W:
                up = true;
                break;

            case Keyboard.S:
                down = true;
                break;

            case Keyboard.A:
                left = true;
                break;

            case Keyboard.D:
                right = true;
                break;
        }
    }

    private function keyUp(event:KeyboardEvent):void
    {
        switch(event.keyCode)
        {
            case Keyboard.W:
                up = false;

                break;

            case Keyboard.S:
                down = false;
                break;

            case Keyboard.A:
                left = false;
                break;

            case Keyboard.D:
                right = false;
                break;
        }
    }

    private var playerSpdTemp:int = 5;

    private function enterFrame(e:Event):void{
        if (up){
            archer.y -= playerSpdTemp;
            socket.writeUTFBytes("move--"+archer.x+":"+archer.y);
            trace("Sent...");
        }
        if (left){
            archer.x -= playerSpdTemp;
        }
        if (down){
            archer.y += playerSpdTemp;
        }
        if (right){
            archer.x += playerSpdTemp;
        }
    }

```

I tried putting the `socket.writeUTFBytes()` in the keyDown and keyUp functions but nothing happens either...

And yes, I have the correct event listeners set up. The player moves correctly but not the socket.

# Answer
> 1 votes
Have you tried calling `Socket.flush()`? According to the documentation:

> Flushes any accumulated data in the socket's output buffer.
>
> On some operating systems, flush() is called automatically between execution frames, but on other operating systems, such as Windows, the data is never sent unless you call flush() explicitly. To ensure your application behaves reliably across all operating systems, it is a good practice to call the flush() method after writing each message (or related group of data) to the socket.

---
Tags: actionscript-3
---


# Question
Title: Perlin noise terrain issue when scrolling
I am generating a terrain in Javascript canvas using this js project for the Perlin noise. I have an array of points, and when one point leaves the left-hand-side of the window, it is removed, and a new point is added to the right.

For the first few points (before any point moves out of the LHS of the window), it works fine, but once I start removing points from the start of the array and adding them to the end the Perlin stops working.

JSFiddle

Does anyone know why this would happen?

# Answer
You seem to be adding and removing points with inconsistent logic. At first, you create 1 point per step in your loop (because there is room left in the points array). Then you wait for point removals in order to add more points. This results in inconsistent "count-spacing" between your points (0.1 at first and larger later). In other words, you're querying Perlin noise with different resolutions.

The following logic seems to solve the problem:

```
if (points.length === 0 || points[points.length - 1].x <= width - sectionWidth) {
  var x = width;
  var yTemp = noise.perlin2(count, count);
  count += 0.1;
  var y = (yTemp * 50) + (height / 2);
  points.push(new Point(x, y));
  if (points.length > numPoints) {
    points.shift();
  }
}

```

It will force the algorithm to wait until there is enough spacing for the next point, thus resulting in uniform spacing (in the count space).

Fiddle

Since your problem is just that you use different count intervals at different times, another solution would be simply to move your `count += 0.1` to the line after the push. Then, it will only get incremented when a point is added.
> 2 votes

---
Tags: javascript, html-canvas, terrain, perlin-noise, scrolling
---


# Question
Title: Dynamically setting parent causing strange object scaling
**TL;DR: How could one fix scaling skew caused by a parent object assigned at run-time where the parent object's scaling perpendicular to its surface is not a 1:1 ratio, thereby turning the circular child into an oval, and the child's rotation is not guaranteed to line up with any axis other than the surface normal?**

**The Problem:**

I am making a projectile that, when it strikes a collider, sticks to that collider. Originally, this was being done by setting the object to be Kinematic, and attaching a joint between it and the struck object if that object had a rigidbody.

The joints began causing issues when multiple projectiles were attached to one object, so I opted to change the system over to remove the projectile's rigidbody and set the projectile's parent to be the struck object. This worked wonderfully, except that some objects had strange scaling after "sticking."

I found the issue to be caused by non-1:1 ratios of the axes perpendicular to the axis of "sticking" of the projectile, and I have only observed this for box colliders. To elaborate, if a projectile strikes at an angle where its Z or Y axis line up with the Z or X axis of the target, there is no skew. If the projectile hits at an angle, I experience skew.

I am now stuck, so I come to the SE again hoping for other approaches. Please note that this uses the Unity3D engine and C#.

---

**Assumptions:**

1. The surface normal of the box collider is always (approximately) parallel to one of its axes (usually Y but not always), and is **always** (approximately) parallel to the X-axis of the projectile.
2. I cannot resize the parent object, as the environment is full of these objects and there is no way for me to change them all to use unit dimensions with the colliders resized. (I could, but it could take days or even weeks.)
3. Multiple projectiles can and will stick to one target.
4. Performance is important here as the game is fairly heavy on a system as is.
5. Assume objects can be moved by the player. If a solution cannot be found that allows the projectiles to follow the object's position and rotation (I've tried, but Quaternions are hard), I can detach them.

---

**Previous Attempts:**

1. Setting the parent of the projectile to an intermediate game object with (1,1,1) scale and setting its parent to the target. Also doing this with two such intermediate game objects.
2. Attempting to directly set the object's scale to the inverse of the parent's.
3. Using `Transform.SetParent(other.transform, false)` and setting the position and/or scale directly.
4. Rotating the projectile with two quaternions, to line up the surface normal as described in assumptions, and to line up the other axes. This caused problems with the surface normal line up, which is essential to the solution.
5. Determining which axis is parallel to the surface normal and trying to rotate appropriately, as shown below. This attempt was less than successful for the desired surfaces, and actually caused problems with the surface normal detection for mesh colliders, of which there are many.

Current rotation & parenting code for the projectiles:

```
private void RotateToSurface(RaycastHit hitInfo, Vector3 contactPoint, GameObject other)
{
    Vector3 surfaceNormal = hitInfo.normal;
    Vector3 thisVector;
    Vector3 targetVector;
    if (Mathf.Abs(Vector3.Dot(surfaceNormal, other.transform.up)) == 1f)
    {
        thisVector = Vector3.Cross(RightVector, ForwardVector);
        targetVector = Vector3.Cross(other.transform.forward, surfaceNormal);
    }
    else if (Mathf.Abs(Vector3.Dot(surfaceNormal, other.transform.right)) == 1f)
    {
        thisVector = Vector3.Cross(UpVector, ForwardVector);
        targetVector = Vector3.Cross(other.transform.up, surfaceNormal);
    }
    else if (Mathf.Abs(Vector3.Dot(surfaceNormal, other.transform.forward)) == 1f)
    {
        thisVector = Vector3.Cross(RightVector, ForwardVector);
        targetVector = Vector3.Cross(other.transform.right, surfaceNormal);
    }
    else
    {
        thisVector = ForwardVector;
        targetVector = -surfaceNormal;
    }
    Quaternion q = Quaternion.FromToRotation(thisVector, targetVector);
    transform.rotation = q * transform.rotation;
    transform.position = q * (transform.position - contactPoint) + contactPoint;
}

```

{...}

```
Destroy(thisRB);
this.transform.SetParent(other.transform, true);

```

Note: `ForwardVector` and the like are my sanity getters, as the darts are rotated to have their `Transform.right` vectors pointing backwards for some reason.

# Answer
> 0 votes
Due to the complexities of the system I was working in, since the player could interact with objects, but only those with rigidbodies attached, I had to get a bit creative.

First of all, I started with the object to attach and the projectile:

```
> Target
> Projectile

```

A pool of `Projectile Parent` objects was created, one for each projectile. These objects were grabbed by projectiles on impact *if and only if* there did not exist already such a parent on the target object. Then, the target and projectile were both parented to this object.

```
> Projectile Parent (1)
    > Target (1)
    > Projectile (1)
> Projectile Parent (2)
    > Target (2)
    > Projectile (2)
    > Projectile (3)

```

Once a projectile reached the end of its life time, it was returned to the object pool, and the hierarchy was reset if no projectiles remained attached.

```
> Target (1)
> Projectile Parent (2)
    > Target (2)
    > Projectile (3)

```

Finally, for the player-manipulated objects, since these were set to be kinematic and had their transforms modified directly, the `Projectile Parent` objects modified their own transforms in `Update` to match the parent's world-space. The projectiles had their rigidbodies removed entirely, and were set to exist entirely in the `Ignore Raycast` layer to prevent funny effects from the overlapping colliders between the projectile and the target object.

The solution wasn't ideal, but it's what I had to work with to accomplish the desired effect in a VR game where player's can pick up a large portion of the scene.

---
Tags: unity, 3d, virtual-reality
---


# Question
Title: Technical Design Document and PNG filesizes
I am writing a Technical Design Document and starting to list assets and their file sizes.

The formula for calculating the file size of a PNG is easy: width x height x bit depth.

I am having a problem with the file size windows shows in the file properties for some of my png's.

Background image:

The dimensions are 1280 x 720 32bit and filesize ought to be 3,686,400B. Windows Properties shows 3.6KB. Shouldn't this be 3600KB?

Now I have a cursor image:

32 x 32 32bit ought to be 4,096B. Why does the file properties in windows say the file size is 304B?

As you can see the size on disk is correct for the cursor but the size is off. With the background image the size is correct but the size on disk is bigger.

I am using GIMP to create the images and exporting with none of the tick boxes checked, so no comments or background colour saved etc.

Can anyone explain why windows does this? Thank you.

# Answer
We know that a disk is made up of Tracks and Sectors. In Windows that means the OS allocates space for files in "clusters" or "allocation units".

The size of a cluster can vary, but typical ranges are from 512 bytes to 32K or more. For example, on my C:\ drive, the allocation unit is 4096 bytes. This means that Windows will allocate 4096 bytes for any file or portion of a file that is from 1 to 4096 bytes in length.

If I have a file that is 17KB (kilo bytes), then the Size on disk would be 20.48 KB (or 20480 bytes). The calculation would be 4096 (1 allocation unit) x 5 = 20480 bytes. It takes 5 allocation units to hold a 17KB file.

Another example would be if I have a file that is 2000 bytes in size. The file size on disk would be 4096 bytes. The reason is, because even though the entire file can fit inside one allocation unit, it still takes up 4096 of space (one allocation unit) on disk (only one file can use an allocation unit and cannot be shared with other files).

So the size on disk is the space of all those sectors in which the file is saved. That means,usually, the size on disk is always greater than the actual size.

So the actual size of a file(s) or folder(s) should always be taken from the Size value when viewing the properties window.
> 3 votes

# Answer
PNG is an image format which uses the lossless DEFLATE algorithm to compress the image data. For that reason PNG files are usually far smaller than the sum of their pixels. Especially when you have images with large areas of the same color, because these are very easy to compress.

Image format compression only reduces the size on disk. When you load the image, your graphics framework will usually uncompress the image data. The memory consumption of the texture in the running game will be indeed width x height x bit depth. That means unless your graphics framework uses texture compression, which means that it will recompress the image data to reduce the data in VRAM again. But that will very likely be a different algorithm with different parameters than the one used by your image editor, so the PNG filesize isn't reliable in this regard either.

Windows shows both files as consuming 4 KB on disk because that's the cluster size of your Windows filesystem. By default, NTFS always allocates space in clusters of 4 KB (you can set a different cluster size when you create a new hard drive partition). So the "space on disk" gets rounded up to 4KB increments. However, this is likely not relevant in your case. When you are that worried about a few KB of filesize, you are either developing for the web or for smartphones. In the first case the HTTP protocol will only transfer the actual file, not the padding needed to get it to 4KB. In the second case all your assets will be bundled into a single file with the executable, so they will appear as one file on disc.
> 3 votes

---
Tags: sprites, image, png, gimp
---


# Question
Title: What is the most efficient way to access resources?
I have a resource manager that loads and returns resources. Currently, I just return `shared_ptrs` for the resources I create, but I'm thinking about going over to using something like simple handles, whereby you get an ID you use to access the resource. The reasons are more explicit ownership, and also less overhead, rather than using `smart_ptrs`.

Are resource handles the most efficient way to access resources, should I stick with shared\_ptrs or are there other alternatives?

The reason I am asking is that I was reading this article, which made me wonder if I should implement something like that, instead.

# Answer
> 4 votes
I disagree with Vittorio about not needing shared ownership of resources and, while I dislike the implementation of `shared_ptr`, it can be made to work just fine.

You want shared ownership because, of course, multiple game objects might be using the same resource. More importantly, if you have multiple levels and want to minimum level loading, you need some way to compute the union and intersection of resources needed by both.

One way to do this, which does require something more than just a `shared_ptr`, is to allow "loading" a level without resources and letting it take shared ownership of resources it needs. Then unload the old level, removing its ownership. Then, for any resource that still has ownership active but isn't loaded, load the resource.

For a resource A needed by levels 1 and 2, the reference count goes something like:

```
load level 1
ref=1
load A
load level 2
ref=2
unload level 1
ref=1

```

For a resource B used by only level 1, it goes like:

```
load level 1
ref=1
load B
load level 2
ref=1
unload level 1
ref=0 (removed)

```

And a resource C used by only level 2, it goes like:

```
load level 1
ref=0 (implicit, as no resource C exists)
load level 2
ref=1
unload level 1
load C

```

One method might be to have a layer of indirection. You store `shared_ptr` to a `ResourceHolder`. These holders are also in a list of some kind. When loading a level, you create and hold on to these `ResourceHolder` objects. They contain a `unique_ptr` to the actual resource (initially `nullptr`) and the path or other information needed to eventually load the item.

After loading the new level and unloading the old, you can then iterate through the list of live `ResourceHolder` objects, find any that have a `nullptr` handle to the actual resource, and then load it. When the `shared_ptr` to a `ResourceHolder` hits a ref count of 0 and unloads it, it also naturally frees the resource, and you should ensure that it removes itself from the list of live resources.

You can do much better than `shared_ptr` but it's a perfectly fine place to start to get up and running. Optimize it into something better later on once you have a working game.

# Answer
> 0 votes
No, they are not the most efficient way to access resources. The same Sean Middleditch who gave you an answer wrote an article "Dangers of std::shared\_ptr" against using `shared_ptr` about one year later. You might consider using handles again. As he wrote himself:

> Game engines have long supported this kind of borrowed reference using things like unique ID handles. Instead of storing a pointer (smart or otherwise) to an object, store a numeric ID instead (possibly wrapped in a templated type to ensure type safety).

Please review the section **Efficiency** in his article for more explanations on how to be much more efficient when using handles in contrast to `shared_ptr`.

For more advantages of IDs you can read the short **Entity Component System Pattern** article.

---
Tags: c++, resource-management
---


# Question
Title: Introduction to game engines for children
My friend's 10 years old kid is very interested in programming and video game development. The little guy has already finished CodinGame, so I directed him to other learning games I know of in the meantime. However, I haven't found anything of the sort for game engines

I'm looking for a **child friendly introduction to game engines**, in the same spirit as CodinGame. It can be about Unity 3D, Unreal Engine or anything of that sort

I've always been interested in teaching Computer Science, and I'd love to be able to use something like that as material

# Answer
I found the good old rpg maker quite good when I was at that age myself. It's not that powerful compared to the big name engines but for a plain game it is more than enough. And it focuses more on working with the engine rather than writing code.

You have to take as well into consideration how long it takes for your child to see a result. While I was construction some nice battle logic, my friend was happy to smash a big fireball on a tree in a corner. The faster your child can see a result on what he was working on, the more motivated he will get. Don't over complicate things and just let him/ her play with it.
> 10 votes

# Answer
Scratch can be something you search for:

https://scratch.mit.edu/
> 5 votes

# Answer
If one of your goals in doing this is not just entertainment and showing how things can work, but also teaching your child how the real games out there are made, instead of the "coding for kids" stuff which often doesn't look much like the actual game code, I suggest finding a simple enough platformer, a small RPG or a puzzle game with open source. Figure it out on your own first, set up some popular and easy to learn IDEs, like Visual Studio Community, and sit down with the kid and show them how changing variables and code affects the existing game. Then show each piece which makes that game work and together try to create a new game with these pieces. Add some custom mechanics to the game, explain how they would work in theory and in code. It should be more fun and educating than just letting the child be on their own with something that you wouldn't see in the real game stores.

Finding open source games of course is the biggest challenge here :p But here's some options:

Basically, you're the child friendly introduction in this scenario, and extra quality interaction time with your kid is worth it.
> 4 votes

# Answer
Kodu by Microsoft is a very good tool to learn game development. I believe you can even run the games you create on Xbox.
> 3 votes

# Answer
While not specifically an engine, a game with a heavy modding community and a well documented API might be a great start, especially considering he/she learned on CodinGame. You get the intro to game development without worrying about all the nitty gritty engine stuff but still learn useful techniques on how to work with an engine and standard game patterns and stuff.

My suggestion might be Garry's Mod which has a great LUA API reference and runs on the Source Engine.
> 3 votes

# Answer
I would recommend looking at any games the child currently enjoys *playing* and seeing if those games have level editors. Basically, find something the child already likes and is familiar with and use that as a starting point.

It can be frustrating for a kid (and an adult programmer) to spend a lot of time learning a new environment and new programming language and end up with a program that only draws a few ugly boxes bumping around. A level editor will allow the child to produce an impressive looking end product, in a game engine they already know. You could also try creating levels yourself and trading them with the child; let them play and look at your code and vice versa.
> 3 votes

# Answer
Minecraft. Some Tech-based FTB pack can be a best solution at my look.

**Play game, and keep programming inside.**

https://www.feed-the-beast.com/modpacks/ftb-official-pack (I suggest Direwolf20 packs - you can find lot's of videos about it)

Factor 1: **each time when you confusing - you should look at google** "how to craft something" or "why my turtle not working". Just like true programmer, always doing the same.

Factor 2: **in-game programming** \- many mod-packs contain some tricky computer-mods. Mining turtles for example using Lua Programming language for AI scripting. Some computers works just like little linux, even with package managers.

Factor 3: **Automatic** \- you can find lot's of videos and manualr how to automate things, fabrics, mining, processing with other devices and computers. This is really perfect brain-training.

Factor 4: **When you game crash** or you need to add install some specific mod, you need to look up for solution (just right here, on stackexchange) - you involuntarily start to understand how the game is arranged inside, and why.

After all - it's really interesting. And funny. And you definitely should play with your friend. :3

*UPDATE:* Twitch Client allow you to make custom mod packs quickly with any mod you want.
> 2 votes

# Answer
Not an expert on kids, but Processing is a pretty good language to start with for coding. At least if the kid want to try something different then playing with a GUI.

Processing is built on top of Java and let you abstract away a lot of the hard stuff, so it's easy to make geometry figures move and similar things. They also has a lot of tutorials to get you going.

An example to draw an rectangle on the screen:

```
rect(250, 200, 150, 100);

```

And then you press play, and you will get a window with your rectangle.

Check out https://processing.org/
> 1 votes

---
Tags: software-engineering, teaching
---


title: Unity Movement Help

text:
# Question
Title: Unity Movement Help
i am making script something like in swing copters when player moves to Left to right when you touch the screen , but its on X asis , i made my script on Y Axis , But it only goes down when i touch screen , it just doesnt go up at all , Please help

```
void MovePlayerOnYAxis()
    {

        foreach (Touch touch in Input.touches)
        {

            WasTouched = !WasTouched;

            if (WasTouched)
            {
                if (Input.touchCount == 0)
                {
                    WasTouched = false;

                    transform.localScale = new Vector3(1, 1, 1);
                }
            }
            else
            {
                if (Input.touchCount > 0)
                {
                    WasTouched = true;
                    transform.localScale = new Vector3(1,-1, 1);
                }

            }
            huongbay = transform.localScale.y;

        }
        transform.root.Translate(Vector3.up * speed * huongbay * Time.deltaTime);
    }

```

Input script

```
bool WasTouchedOrClicked()
    {
        if(Input.GetButtonUp("Jump") || Input.GetMouseButtonDown(0) ||
         (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
            return true;
        else
            return false;
        }

```

# Answer
> 1 votes
I would say it's because you always toggle the `WasTouched` flag. Try removing the line:

```
WasTouched = !WasTouched;

```

# Answer
> 0 votes
This looks like a copy-paste error from an earlier answer. What the other user intended you to write was something more like this:

```
bool wasTouched = false;
float direction = 1f;

void MovePlayerOnYAxis()
{

    if (wasTouched)
    {
        if (Input.touchCount == 0)
        {
            WasTouched = false;
            direction = 1f; // up
        }
    }
    else
    {
         if (Input.touchCount > 0)
         {
             WasTouched = true;
             direction = -1f; // down
         }
     }

    transform.root.Translate(
           Vector3.up * speed * direction * Time.deltaTime,
           Space.World);
}

```

As discussed in the comments above, the behaviour you've described should only depend on *whether* the screen was touched - not *how many* touches there are. So, you don't want to loop over every touch with a `foreach` \- running this logic just once is enough.

In fact, if all you want to do is go down when there's at least one touch, you can simplify this massively to:

```
void MovePlayerOnYAxis()
{
    float direction = Input.touchCount > 0 ? -1f : 1f;

    transform.root.Translate(
       Vector3.up * speed * direction * Time.deltaTime,
       Space.World);
 }

```

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


# Question
Title: Java OpenGL Perspective matrix not working
I'm trying to render a simple triangle with OpenGL in Java using LWJGL3. Everything is working great, but the projection matrix (perspective) is not working. In C++ I just used to apply the `glm::perspective()` method which works just great. But in Java, I implemented it myself since there are no libraries like GLM handling it. So here the code for the perspective in Java :

```
public mat4 perspective(float fov, float aspectRatio, float zNear, float zFar){
    mat4 perspective = new mat4();

    float halfTanFov = (float) Math.tan(Math.toRadians(fov/2));
    float range = zNear - zFar;

    perspective.m00 = 1f / halfTanFov * aspectRatio;
    perspective.m11 = 1f / halfTanFov ;
    perspective.m22 = - (zFar - zNear) / range;
    perspective.m23 = -1;
    perspective.m32 = (2f * zFar * zNear) / range;

    return perspective;
}

```

Of course I tested this multiplication and a compared a result with my TI output, and it worked great. Other information, the default `constructor` for the `mat4` class is putting all the values to 0. here is the code :

```
public void setZero(){
    m00 = 0; m01 = 0; m02 = 0; m03 = 0;
    m10 = 0; m11 = 0; m12 = 0; m13 = 0;
    m20 = 0; m21 = 0; m22 = 0; m23 = 0;
    m30 = 0; m31 = 0; m32 = 0; m33 = 0;
}

```

the `viewMatrix()` in the other hand is working great. It's a simple implementation of the `lookAt()` method. So when it's `lookAtMatrix * modelMatrix * position` where the `position` is a `vec4` the result is good. But when I try to add the projection matrix for the MVP : `perspective * lookatMatrix * model * position` the result is nothing. Here where I do it in the code :

```
public mat4 getViewProjection() {
    mViewProjection = MatrixTransform.getInstance().lookAt(mPosition, mPosition.add(mDirection), mUp);
    return mViewProjection;
}
public mat4 getMVP(mat4 model){
    return mPerspective.mult(getViewProjection()).mult(model);
}

```

And here is my simple GLSL shader (for the vertex shader ) :

```
#version 430

layout(location=0) in vec3 position;
uniform mat4 MVP;

void main(void){
    gl_Position = MVP * vec4(position, 1);
}

```

I tried other implementation of the perspective without success, so I guess my mistake is somewhere else, but sadly enough, I can't figure out where. If someone could help, it'd be great ! thank you. If you other informations, please ask me and I'll post it.

**EDIT :** Here is how I put a mat4 into a uniform :

```
    public void uniform(String variableName, mat4 matrix){
            int loc = glGetUniformLocation(mId, variableName);
            FloatBuffer buffer = BufferUtils.createFloatBuffer(16);
            matrix.putIntoBuffer(buffer);
            buffer.flip();
            glUniformMatrix4(loc, false, buffer);
    }

```

and the method `putIntoBuffer()` :

```
public void putIntoBuffer(FloatBuffer buffer){
    buffer.put(m00);
    buffer.put(m01);
    buffer.put(m02);
    buffer.put(m03);

    buffer.put(m10);
    buffer.put(m11);
    buffer.put(m12);
    buffer.put(m13);

    buffer.put(m20);
    buffer.put(m21);
    buffer.put(m22);
    buffer.put(m23);

    buffer.put(m30);
    buffer.put(m31);
    buffer.put(m32);
    buffer.put(m33);
 }

```

# Answer
> 1 votes
> Other information, the default constructor for the mat4 class is putting all the values to 0

This is incorrect. Your default matrix should be the identity matrix instead; i.e:

```
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

```

# Answer
> 0 votes
Take a look at LWJGL examples.

This one could help you: https://github.com/LWJGL/lwjgl3-demos/blob/master/src/org/lwjgl/demo/opengl/shadow/ShadowMappingDemo.java

---
Tags: opengl, java, matrix, perspective
---


# Question
Title: vuforia how do I force objects into a 2D plane
I'm working on a game in which cards are placed on a table and then rendered in augmented reality. These objects have 3D physics attached to them which doesn't work as well if they are either rotated or if the system mistakes them for being higher or lower then they really are.

Is there a good method to force Vuforia/Unity to place all items in the same 2D plane and keep all of them upright compared to that plane?

I currently have the following code:

```
using UnityEngine;
using System.Collections;

public class projectioncode : MonoBehaviour {
    Vector3 p1;
    Vector3 p2;
    Vector3 p3;
    Vector3 v1;
    Vector3 v2;
    Vector3 normal;

    /*
     *use a plane with the following 3 coordinates
     */
    public void setPlaneByPoints(Vector3 point1,Vector3 point2, Vector3 point3){
        p1 = point1;
        p2 = point2;
        p3 = point3;

        v1=p2-p1;
        v2=p3-p1;
        normal=getNormal(v1,v2);
    }

    public Transform projectTransform(Transform input){
        input.position = projectPoint (input.position);
        return input;
    }
    /*
     *  projects a 3d point into space;
     */
    Vector3 projectPoint(Vector3 point){
        Vector3 vOToPoint = point - p1;//vector between origin and point
        float dist = Vector3.Dot (vOToPoint, normal); //distance plane to point
        return point - dist * normal;
    }

    /*
     * caclulates the normal of 2 vectors
     */
    Vector3 getNormal(Vector3 v1,Vector3 v2){
        Vector3 res= (Vector3.Cross (v1, v2));
        res.Normalize();
        return res;
    }
}

```

This seems to project objects onto a plane but the results tend to be inaccurate and result in weird movements, particularly when moving the camera around.

This is what it looks like:

# Answer
I manage to get this to work by separating the target and the model so that the model is NOT a child of the target in the scene. I let Vuforia handle the calculation of where the target is located, and then created a script to calculate the transform of the model based upon the transform of the target. In this script, I forced the y-position, x-rotation, and z-rotation to zero.

**Note:** This script assumes the xz-plane is aligned with the tabletop. You could also determine this by placing a "stationary target" on the tabletop and setting everything in the scene relative to the x and z components of the stationary target's transform.

```
using UnityEngine;
using System.Collections;

public class VuforiaFixToPlane : MonoBehaviour  {
    public Transform target;

    private Rigidbody rb;

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

    void FixedUpdate()  {
        Vector3 positionInPlane = target.position;
        positionInPlane.y = 0.0f;
        rb.position = positionInPlane;

        Vector3 rotInPlane = target.rotation.eulerAngles;
        rotInPlane.x = 0.0f;
        rotInPlane.z = 0.0f;
        rb.rotation = Quaternion.Euler(rotInPlane);
    }
}

```
> 1 votes

# Answer
you can "lock" the axis for a rigidbody so it cannot move/rotate/whatever around/along specific axis. Check the inspector options for the rigidbody component.

http://docs.unity3d.com/Manual/class-Rigidbody.html
> -1 votes

---
Tags: unity, graphics, vuforia, augmented-reality
---


# Question
Title: How to properly differentiate single-clicks and double-click in Unity3D using C#?
What I am trying to understand and learn here is a very basic thing: what is the most general and most polished way to *properly* differentiate single-clicks and double-clicks for the 3 main mouse buttons in Unity, using C#?

My emphasis on the word *properly* is not for nothing. Although I was surprised that this seems to have never been asked in this website before, of course I have searched and found numerous similar questions on Unity's forums and Unity's own question-answer pages. However, as it is often the case with answers posted in these resources, they all seemed to be either plain wrong or at least a bit too amateurish.

Let me explain. Proposed solutions always had either of the two approaches and their corresponding flaws:

1. every time a click happens, calculate time delta since last click and if it was smaller than a given threshold, a double click would be detected. However, this solution results in that a quick single click is detected before the double-click is detected, which is undesirable in most situations because then it activates both single and double click actions.

Rough example:

```
float dclick_threshold = 0.25f;
double timerdclick = 0;

if (Input.GetMouseButtonDown(0)
{
   if (Time.time - timerdclick) > dclick_threshold)
   {
       Debug.Log("single click");
       //call the SingleClick() function, not shown
   } else {
       Debug.Log("double click");
       //call the DoubleClick() function, not shown
   }
   timerdclick = Time.time;
}

```
2. set a wait-for delay for the single-click to be activated, which means, at every click, only activate single click actions if the time delay since last click is above a given threshold. However, this gives sluggish results, since a waiting before it is possible to notice the waiting before single-clicks are detected. Worse than that, this kind of solution suffers from discrepancies across machines, since it does not take into account how slow or how fast is the user's double-click speed setting at the OS level.

Rough example:

```
   float one_click = false;
   float dclick_threshold = 0.25f;
   double timerdclick = 0;

   if (one_click && ((Time.time - timerdclick) > dclick_threshold))
   {
       Debug.Log("single click");
       //call the SingleClick() function, not shown
       one_click = false;
   }

   if (Input.GetMouseButtonDown(0))
   {

       if (!one_click)
       {
           dclick = -1;
           timerdclick = Time.time;
           one_click = true;
       }

       else if (one_click && ((Time.time - timerdclick) < dclick_threshold))
       {
           Debug.Log("double click");
           //call the DoubleClick() function, not shown
           one_click = false;
       }

   }

```

Therefore, my questions becomes the following. Is there a more polished and reliable way of detecting double clicks in Unity using C#, other than these solutions, and one that handles the problems aforementioned?

# Answer
> 13 votes
Coroutines are fun:

```
using UnityEngine;
using System.Collections;

public class DoubleClickTest : MonoBehaviour
{
private float doubleClickTimeLimit = 0.25f;

protected void Start()
{
    StartCoroutine(InputListener());
}

// Update is called once per frame
private IEnumerator InputListener()
{
    while(enabled)
    { //Run as long as this is activ

        if(Input.GetMouseButtonDown(0))
            yield return ClickEvent();

        yield return null;
    }
}

private IEnumerator ClickEvent()
{
    //pause a frame so you don't pick up the same mouse down event.
    yield return new WaitForEndOfFrame();

    float count = 0f;
    while(count < doubleClickTimeLimit)
    {
        if(Input.GetMouseButtonDown(0))
        {
            DoubleClick();
            yield break;
        }
        count += Time.deltaTime;// increment counter by change in time between frames
        yield return null; // wait for the next frame
    }
    SingleClick();
}

private void SingleClick()
{
    Debug.Log("Single Click");
}

private void DoubleClick()
{
    Debug.Log("Double Click");
}

}

```

# Answer
> 5 votes
I can't read English. But UniRx may be able to help you.

https://github.com/neuecc/UniRx#introduction

```
void Start () {

    var clickStream = Observable.EveryUpdate().Where(_ => Input.GetMouseButtonDown(0));
    var bufferStream = clickStream.Buffer (clickStream.Throttle (TimeSpan.FromMilliseconds (250))).Publish ().RefCount ();
    bufferStream.Where (xs => xs.Count == 1).Subscribe (_ => Debug.Log ("single click"));
    bufferStream.Where (xs => xs.Count >= 2).Subscribe (_ => Debug.Log ("double click"));
}

```

# Answer
> 2 votes
Windows default double click delay is 500ms = 0.5 seconds.

Generally in a game it's much easier to handle double click on the control that's being clicked, not globally. If you decide to handle double clicks globally, you have to implement workarounds to avoid 2 very undesirable side effects:

1. Every single click could be delayed by 0.5 seconds.
2. A single click on one control followed quickly by a single click on another control could be misinterpreted as a double-click on the second control.

If you have to use a global implementation, you'll need to look at the location of the click as well - if the mouse moved too far it's not a double click. You would normally implement a focus tracker that resets the double click counter whenever the focus changes.

To the question if you should wait until the double-click timeout passes, this needs to be handled differently for each control. You have 4 different events:

1. Hover.
2. Single click, which may or may not become a double click.
3. Double click.
4. Double click timeout, single click confirmed to not be a double click.

Whenever possible, you try to design the GUI interactions such that the last event will not be used: Windows File Explorer will select an item on a single click immediately, and will open it on a double click, and will do nothing on a confirmed single click.

In other words: You use both options you suggested, depending on what the desired behavior of the control is.

# Answer
> 2 votes
The above solutions work for clicks done on the whole screen. If you want to detect double-clicks on individual buttons, I've found this modification to an above answer is working well:

```
using UnityEngine;
using System.Collections;

public class DoubleClickTest : MonoBehaviour
{
    private float doubleClickTimeLimit = 0.35f;
    bool clickedOnce = false;
    public string singleTapMove;
    public string doubleTapMove;
    float count = 0f;

    public void startClick(){
        StartCoroutine (ClickEvent ());
    }

    public IEnumerator ClickEvent()
    {
        if (!clickedOnce && count < doubleClickTimeLimit) {
            clickedOnce = true;
        } else {
            clickedOnce = false;
            yield break;  //If the button is pressed twice, don't allow the second function call to fully execute.
        }
        yield return new WaitForEndOfFrame();

        while(count < doubleClickTimeLimit)
        {
            if(!clickedOnce)
            {
                DoubleClick();
                count = 0f;
                clickedOnce = false;
                yield break;
            }
            count += Time.deltaTime;// increment counter by change in time between frames
            yield return null; // wait for the next frame
        }
        SingleClick();
        count = 0f;
        clickedOnce = false;
    }
    private void SingleClick()
    {
        Debug.Log("Single Click");
    }

    private void DoubleClick()
    {
        Debug.Log("Double Click");
    }
}

```

Attach this script to as many buttons as you want. Then in the On Click section of the editor (for each button you attach this to), click '+', add the button to itself as the game object, and then select "DoubleClickTest -\> startClick()' as the function to call when the button is pressed.

# Answer
> 2 votes
I was looking for a proper single-double click handler. I've found this topic and gathered some really good ideas. So finally I've came up with the following solution and I want to share it with you. I hope you find this method helpful.

I think it's a great approach to use Unity's inspector, because this way your code is more flexible as you can reference any of your game objects visually and safely.

First add the **Event System** component to any of your game objects. This will also add the **Standalone Input Module** component. This will take care of the input events like mouse clicks and touches. I recommend to do this on an individual game object.

Next add the **Event Trigger** component to any of your **raycast enabled** game object. Like a UI element **or** a sprite, a 3D object **with a collider**. This will deliver the click event to our script. Add the **Pointer Click event type** and set the receiver game object which has the **Click Controller** script component on it and finally select its **onClick()** method. (Also you can alter the script to receive all clicks in an Update() and skip this step.)

So the receiver game object, which of course can be the one with the event trigger, will do anything with the single or doudle click events.

You can set the **time limit** for double click, the desired **button** and the **custom events** for single and double click. The only **limitation** is that you can choose **only one button** at a time **for one game object**.

The script itself starts a coroutine on every first clicks with two timers. The firstClickTime and the currentTime in sync with the first.

This coroutine loops once at the end of every frame till the time limit expires. Meanwhile the onClick() method continues counting the clicks.

When the time limit expires it calls the single- or doubleclick event according to the clickCounter. Then it sets this counter to zero so that the coroutine can finish and the whole process starts from the beginning.

```
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

public class ClickController : MonoBehaviour
{
    public float timeLimit = 0.25f;
    public PointerEventData.InputButton button;

    [System.Serializable]
    public class OnSingleClick : UnityEvent {};
    public OnSingleClick onSingleClick;

    [System.Serializable]
    public class OnDoubleClick : UnityEvent {};
    public OnDoubleClick onDoubleClick;

    private int clickCount;
    private float firstClickTime;
    private float currentTime;

    private ClickController () {
        clickCount = 0;
    }

    public void onClick (BaseEventData data) {

        PointerEventData pointerData = data as PointerEventData;

        if (this.button != pointerData.button) {
            return;
        }

        this.clickCount++;

        if (this.clickCount == 1) {
            firstClickTime = pointerData.clickTime;
            currentTime = firstClickTime;
            StartCoroutine (ClickRoutine ());
        }
    }

    private IEnumerator ClickRoutine () {

        while (clickCount != 0)
        {
            yield return new WaitForEndOfFrame();

            currentTime += Time.deltaTime;

            if (currentTime >= firstClickTime + timeLimit) {
                if (clickCount == 1) {
                    onSingleClick.Invoke ();
                } else {
                    onDoubleClick.Invoke ();
                }
                clickCount = 0;
            }
        }
    }
}

```

# Answer
> 0 votes
I think there is no way to read user's mind either he is gonna click single or double, after all we have to wait for the input. Although you can set wait of 0.01 seconds (low as much) for the second click. In this regard I'd go for the waiting option.

And YES `Coroutines` are fun...

An alternative

```
float _threshold = 0.25f;

void Start ()
{
    StartCoroutine ("DetectTouchInput");
}

IEnumerator DetectTouchInput ()
{
    while (true) {
        float duration = 0;
        bool doubleClicked = false;
        if (Input.GetMouseButtonDown (0)) {
            while (duration < _threshold) {
                duration += Time.deltaTime;
                yield return new WaitForSeconds (0.005f);
                if (Input.GetMouseButtonDown (0)) {
                    doubleClicked = true;
                    duration = _threshold;
                    // Double click/tap
                    print ("Double Click detected");
                }
            }
            if (!doubleClicked) {
                // Single click/tap
                print ("Single Click detected");
            }
        }
        yield return null;
    }
}

```

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


# Question
Title: Using LibGDX, is it necessary to clip what I'm rendering for efficiency?
So I am working on a game, and I've noticed that everything in the world is sent to be rendered. Of course with the camera, only some of the world is rendered.

Does this mean there is there any expense for when I send all those extra vertices to OpenGL that don't show up on screen? Will OpenGL/LibGDX do it automatically?

If I should clip it, is ScissorStack the way to go?

# Answer
> 2 votes
I'm not sure if this will help but the fastest thing to render is nothing at all.

Make sure to cull as much unseen data out as you can.

On the CPU use an octree or something and cull with view frustum, that get you everything in front of the camera, then cull that some more with occlusion query's to get only the objects that you can see.

Once this is done you will have a very small but visible set of objects to draw.

I have done this bit by bit as I need to get more and more drawn on screen I had to cull more and more.

For a long time I was just using the view frustum but that will only get you so far.

If you have shadows then use cascaded shadow maps because you can update the cascades at different intervals, also you only need to render everything in to one or two cascades the last two in my case get less and less drawn into them.

I do the same with water reflections, I skip grass and any small plants and undergrowth.

Just sit back and think to your self what do I really need to draw, think out side the box and just try stuff

# Answer
> 0 votes
Yes, if there's extra data/rendering being performed that's outside the bounds (frustum) of your camera, it would be more efficient to not attempt to render the geometry that can't be seen. How you actually do this depends on how your game is structured - tile-based 2D games can simply figure out what bounds of the world to draw, whereas 2D and 3D games not on a grid tend to use a space partitioning algorithm such as Binary Space Partitioning

---
Tags: libgdx
---


# Question
Title: What are the advantages of tangent space normals over object space normals?
What are the advantages of normals in tangent space to normals in object space for calculation of bump mapping?

# Answer
> 29 votes
Everything, really.

The only benefit to object-space normals is simplicity. They're easier to use.

Tangent-space normals require a tangent-space basis, but offer:

1. The ability to use the same texture for different surfaces. Object-space normal maps can only ever be used on the surface for which they were created. By regularizing normals in tangent-space, you gain the freedom to use the same bump texture for different surfaces. As long as the surface has a tangent-space basis, you'll get reasonable results.
2. The ability to modify the texture mapping, with UV animation for example. Since object-space normal maps store normals in object-space, you can't just add 0.5 to all of the texture coordinates and expect to get proper normals from the texture. You can with tangent-space bump mapping.
3. Smaller component representation. Object-space normal maps must have 3 components; you can't drop one and reconstitute it in the shader. Tangent-space normals will always have a positive Z component, so you can only store the XY of the normal. So you can either get greater precision by using a `GL_RG16_SNORM` or `GL_RG16F` formats (32-bits per texel), or employ compression by using an RG-compressed image format (`GL_COMPRESSED_SIGNED_RG_RGTC1`, 8-bits per texel) format. You can try to use S3TC on an object-space normal map, but good luck with what you get back.

The absolute most you get with object-space normal maps is less computation time (not having to transform the light direction into tangent space, or alternatively, transforming the normal from tangent space into model space). But that's not a big deal, especially nowadays with deferred renderers running around.

# Answer
> 1 votes
A partial answer, to append to Nicol's answer.

Lots of advantages. According to an article I found (which is also linked in the comments), there are still some slight disadvantages. However, with artists that are used to dealing with these problems, or objects that are somehow less prone to these challenges, this disadvantage may not be very impactful.

From an article on tangent space normal mapping:

> Although a good implementation can limit problems, the fundamental idea of normal mapping has its flaws. Unwrapping complex models and putting seams in less exposed areas can be tricky for artists. The following images show object space normal maps (left) and tangent space normal maps (right). Here object space normal maps cause a lot less problems because bilinear filtering softens the edges and flat surfaces have simply one normal and are therefore perfectly flat. Seams on the left side are much less visible as the shading is independent from the UV layout and the triangle distortions.
>
> Object space normal maps:
>
> Tangent space normal maps:

---
Tags: graphics-programming
---


# Question
Title: In a large space simulation, why is my sun light not reaching the planets?
I want to create a space simulation, but I'm facing some difficulties when I try to create a realistic sun.

Currently, I've a simple ***Point Light*** inside a sphere. But for some reasons, no matter the intensity and the attenuation radius of this light, the other objects in the scene (the planets, for instance) aren't lit any more if their centre are separated by more than 1.5 kilometres approximatively.

*(Top) Lit planet, 1.4 km away from the sun.*
*(Bottom) Unlit planet, 1.5 km away from the sun.*

Do you know what can cause this phenomenon? Is there a way to bypass it? If not, how can I create a realistic sun light in a large space simulation?

# Answer
It is definitely the size of your scene and the culling of light that is causing your light to 'disappear' from the planet at that distance. There were a lot of suggestions that are good and answer your question of bypassing it.

Another one would be to actually tweak the shaders in UE4 to accomodate lighting such a large simulation space as suggested by a UE4 staffer:

> *"If you actually need planets or objects to render with the correct light angle that are far enough away from you to get a different light direction, you'd have to do some shader tweaks. Thankfully, round objects like planets will usually look good without casting shadows just using an NdotL lighting term."* \- RaynB "Creating a massive point-light, has anyone tackled the issues with this?" (forums.unrealengine.com)

One that I have also heard of is the potential of using Light Propagation Volumes that are built into the UE4 engine... but it seemed like a concern that such a large space could still prove to be problematic.

Another suggestion would be to just turn off the Inverse Square Fall-off of your light to see if that works in your un-scaled simulation.

> *"...have you tried disabling exponential light falloff? You may have to expand the light properties a bit to see that option. Then the radius and exponent values should be literal and you can get as much light as you need. You might have quality issues with dynamic shadows in that situation however."* \- RyanB

If you are making a single player game with only one sun (they cannot travel between solar systems) the suggestion of rotating the angle of your Directional Light based on the player's position between the sun and view is another way to go about it.

> *"Pointlights are not really intended to work as a sunlight for a huge scene, \>directional lights were created to solve many of the problems you will get by doing that. What I would probably do is use a directional light but use the level blueprint to rotate the directional light according to the player's orientation around the sun."*-RyanB

Personally, If you want 1:1 scale simulations and need the lighting to work for that, I would suggest altering the culling of the UE4 shaders for this. Just remember that this may have a performance impact.

If you are intimidated by modifying your shaders or creating an new one for your specific needs, and have access to the forums, I suggest giving this a good read: https://forums.unrealengine.com/showthread.php?27766-Odessey-Creating-my-own-G-Buffer-in-UE4&highlight=custom+depth+buffer+shader even though it is just about a custom G-Buffer, it will help teach you about writing and binding your own shaders for pointlights.

Or you could find the code that clamps your culling distance and edit that.

If scaling your world, keep in mind that if you are using PhysX, the mass of the object is calculated from the size and you may run into issues if micro-scaling.
> 3 votes

# Answer
You should remove the fall off because the sun from a planets point of view is a directional light and does not have fall off.

If it was me I would just use a directional light instead of a point light, I guess if you want to fly around the sun then one could use 6 directional or a point light with no fall off.

Also I have a limit set for may lighting because I don't need it to go all the way to farclip so maybe you need to make the size of the light biger?
> 0 votes

---
Tags: lighting, unreal-4
---


# Question
Title: Monogames Most efficient way of checking intersections between multiple objects
I've created a top-down shooter with multiple objects such as enemy AI (tanks), walls, power-ups etc.

At first I was able to create about 300 AI units which aims to move the player character, checks for collision and shoot a bullet. This bullet also checks for collision on each frame until it encounters an intersection to be destroyed.

I wasn't long after I encountered massive performance issues. I immediately identified that the main performance drop was caused by the collision detection.

Each object's bounds is represented by a rectangle. If this rectangle intersects with any other rectangle the collision event is raised.

I'm currently unsuccessful in deciding what to do to reduce performance, but still maintain all the characters' capabilities. I want to check if the player or AI will collide with any object before it moves to the given location. I also want to check when the bullet collides with any other object.

I'm currently flagging all my objects by using different interfaces. I then created a Dictionary\>\> (GroupedObjects) Dictionary that filters the objects into different flags where the first type represents the interfaces the object inherited and the second type identifies the object's type. For e.g. I check only the Hostile tanks of type AITank for collision with the bullet. GroupObjects\[Hostile\]\[AITank\].

I've read that I need to create trees where collision is only checked with all the objects in the current tree.

After a few benchmarks I identified that checking collision between 1 million rectangles uses 38ms on the CPU and checking the distance from a fixed point to 1 million other points take 136ms.

## QUESTION

1. With the benchmarks above in mind, how would I group objects by their range (for e.g. within the screen size) if calculating the distance takes more processing than checking the intersection with a rectangle representing the screen?
2. What will be the most efficient way to check for collision between objects, meaning the player checks for collision AND the AI tank checks for collision since both of them can't move through the walls? Keep in mind that the AI isn't static and moves on each frame. Also, object A checks for collision between itself and object B and object B checks for collision between itself and object A.
3. I created an object called CollisionMap that contains points, that represent collision, generated by an image with a specified colour as collision. These points need to be updated every time an object moves and an other object needs to check for collision with this object's CollisionMap (that can contain hundreds of points). I've created this CollisionMap to represent shapes that isn't rectangular or circular so that colliding object will treat each intersection according the shape of the shape. Does this sound possible to process if you have hundreds of objects with hundreds of points representing collision?

I'm new to game dev and I have no idea on what's the most efficient way to check for collision between multiple objects. And for all the algorithms (AABB, Rays) I've seen: it's only for one object or it's still too inefficient...

P.S. I know I typed allot, but I'm trying to explain my problem so that I don't get referenced back to sources I already examined and show what I've tried.

Thanks in advance!

# Answer
> 1 votes
**Implementing a Quadtree**

The following was converted to C# from a Java tutorial by Steven Lambert, Quick Tip: Use Quad Trees to Detect Collisions in 2D Space.

A quadtree starts as a single node. Objects added to the quadtree are added to the single node.

When more objects are added to the quadtree, it will eventually split into four subnodes. Each object will then be put into one of these subnodes according to where it lies in the 2D space. Any object that cannot fully fit inside a node’s boundary will be placed in the parent node.

Each subnode can continue subdividing as more objects are added.

We’ll start off by creating the main Quadtree class.

```
public class Quadtree {

  private int MAX_OBJECTS = 10;
  private int MAX_LEVELS = 5;

  private int level;
  private List<myGameObject> objects; //convert to your object type
  private Rectangle bounds;
  private Quadtree[] nodes;

 /*
  * Constructor
  */
  public Quadtree(int pLevel, Rectangle pBounds) {
   level = pLevel;
   objects = new List<myGameObject>;
   bounds = pBounds;
   nodes = new Quadtree[4];
  }
}

```

The Quadtree class is straightforward. MAX\_OBJECTS defines how many objects a node can hold before it splits and MAX\_LEVELS defines the deepest level subnode. Level is the current node level (0 being the topmost node), bounds represents the 2D space that the node occupies, and nodes are the four subnodes.

In this example, the objects the quadtree will hold are Rectangles, but for your own quadtree it can be whatever you want.

Next, we’ll implement the five methods of a quadtree: clear, split, getIndex, insert, and retrieve.

```
/*
 * Clears the quadtree
 */
 public void Clear() {
   objects.Clear();

   for (int i = 0; i < nodes.Count; i++) {
     if (nodes[i] != null) {
       nodes[i].Clear();
       nodes[i] = null;
     }
   }
 }

```

The clear method clears the quadtree by recursively clearing all objects from all nodes.

```
/*
 * Splits the node into 4 subnodes
 */
 private void Split() {
   int subWidth = (int)(bounds.Width / 2);
   int subHeight = (int)(bounds.Height / 2);
   int x = (int)bounds.X;
   int y = (int)bounds.Y;

   nodes[0] = new Quadtree(level+1, new Rectangle(x + subWidth, y, subWidth, subHeight));
   nodes[1] = new Quadtree(level+1, new Rectangle(x, y, subWidth, subHeight));
   nodes[2] = new Quadtree(level+1, new Rectangle(x, y + subHeight, subWidth, subHeight));
   nodes[3] = new Quadtree(level+1, new Rectangle(x + subWidth, y + subHeight, subWidth, subHeight));
 }

```

The split method splits the node into four subnodes by dividing the node into four equal parts and initializing the four subnodes with the new bounds.

```
    /*
     * Determine which node the object belongs to. -1 means
     * object cannot completely fit within a child node and is part
     * of the parent node
     */
  private int GetIndex(Rectangle pRect) {
   int index = -1;
   double verticalMidpoint = bounds.X + (bounds.Width / 2);
   double horizontalMidpoint = bounds.Y + (bounds.Height / 2);

   // Object can completely fit within the top quadrants
   boolean topQuadrant = (pRect.Y < horizontalMidpoint && pRect.Y + pRect.Height < horizontalMidpoint);
   // Object can completely fit within the bottom quadrants
   boolean bottomQuadrant = (pRect.Y > horizontalMidpoint);

   // Object can completely fit within the left quadrants
   if (pRect.X < verticalMidpoint && pRect.X + pRect.Width < verticalMidpoint) {
      if (topQuadrant) {
        index = 1;
      }
      else if (bottomQuadrant) {
        index = 2;
      }
    }
    // Object can completely fit within the right quadrants
    else if (pRect.X > verticalMidpoint) {
     if (topQuadrant) {
       index = 0;
     }
     else if (bottomQuadrant) {
       index = 3;
     }
   }

   return index;
 }

```

The getIndex method is a helper function of the quadtree. It determines where an object belongs in the quadtree by determining which node the object can fit into.

```
    public void insert(Rectangle pRect) {
       if (nodes[0] != null) {
         int index = getIndex(pRect);

         if (index != -1) {
           nodes[index].Insert(pRect);

           return;
         }
        }

       objects.Add(pRect);

       if (objects.Count > MAX_OBJECTS && level < MAX_LEVELS) {
          if (nodes[0] == null) {
             Split();
          }

         int i = 0;
         while (i < objects.Count) {
           int index = GetIndex(objects[i]);
           if (index != -1) {
             nodes[index].Insert(objects.Remove(i));
           }
           else {
             i++;
           }
         }
       }
    }

```

The insert method is where everything comes together. The method first determines whether the node has any child nodes and tries to add the object there. If there are no child nodes or the object doesn’t fit in a child node, it adds the object to the parent node.

Once the object is added, it determines whether the node needs to split by checking if the current number of objects exceeds the max allowed objects. Splitting will cause the node to insert any object that can fit in a child node to be added to the child node; otherwise the object will stay in the parent node.

```
/*
 * Return all objects that could collide with the given object (recursive)
 */
 public List<myGameObject> Retrieve(List<myGameObject> returnObjects, Rectangle pRect) {
   int index = GetIndex(pRect);
   if (index != -1 && nodes[0] != null) {
     nodes[index].Retrieve(returnObjects, pRect);
   }

   returnObjects.AddRange(objects);

   return returnObjects;
 }

```

The final method of the quadtree is the retrieve method. It returns all objects in all nodes that the given object could potentially collide with. This method is what helps to reduce the number of pairs to check collision against.

**Using This for 2D Collision Detection**

Now that we have a fully functional quadtree, it’s time to use it to help reduce the checks needed for collision detection.

In a typical game, you’ll start by creating the quadtree and passing the bounds of the screen.

```
Quadtree quad = new Quadtree(0, new Rectangle(0,0,600,600));

```

At every frame, you’ll insert all objects into the quadtree by first clearing the quadtree then using the insert method for every object.

```
quad.Clear();
for (int i = 0; i < allObjects.Count; i++) {
  quad.Insert(allObjects[i]);
}

```

Once all objects have been inserted, you’ll go through each object and retrieve a list of objects it could possibly collide with. You'll then check for collisions between each object in the list and the initial object, using a collision detection algorithm.

```
List<myGameObject> returnObjects = new List<myGameObject>();
for (int i = 0; i < allObjects.Count; i++) {
  returnObjects.clear();
  quad.Retrieve(returnObjects, objects[i]);

  for (int x = 0; x < returnObjects.Count; x++) {
    // Run collision detection algorithm between objects
    // i.e. your Rectangle.IntersectsWith(x)
  }
}
Note: Collision detection algorithms are beyond the scope of this tutorial. See this article for an example.

```

Conclusion

Collision detection can be an expensive operation and can slow down the performance of your game. Quadtrees are one way you can help speed up collision detection and keep your game running at top speeds.

# Answer
> 0 votes
On creation, each wall should be assigned to a region (maybe an array or list or chunk). These sections are part of the world map as opposed to being part of the camera.

As each moving object (tanks and bullets) moves, they should each determine which region they are in. There are many ways to do this and lots of room for optimization... but don't get focused on that too early, just get the system working first.

When each moving object knows what region it is in, now do your collision check against all the objects (moving and stationary) in that region as well as the neighboring regions.

For example, tank 1 knows it is in region 134 (how it knows this will depend on your design... maybe it's camera position plus tank position or maybe your tanks have real world coordinates), and knowing that, it then checks for collision against walls in and tanks in regions 133, 134, 135, 212, 211, 210, and the 3 regions north as well. No need to check 213's walls and tank 4, or the hundreds of other regions' tanks and walls and bullets. Tweak and optimize region sizes and even regions within regions until your performance goals are met.

That's the idea. The specifics will depend on your particular case and since I don't know c# or whatever it was you said you are using I can't offer any specific help anyway.

---
Tags: c#, collision-detection, monogame, efficiency
---


# Question
Title: Why is my Direct3D 9 floating point texture clamping values 0–1?
I'm using Direct3D 9 to draw some primitives into a texture. The format used at texture creation is D3DFMT\_A16B16G16R16F, and the primitives are drawn using additive blending. The additive blending works as expected provided the result is \<= 1. If it is greater than 1 then it seems to be clamped to 1.

This question includes a comment stating that COLOR0 output semantics for a pixel shader automatically clamp the output values. I can't ask for elaboration there due to low SE rep. Is there anything else that I need to do on top of changing the texture format that I pass in to CreateTexture, in order to use the full range of 16-bit floats? Given that I can otherwise draw primitives with shading (aside from the clamping issue) fine, is there any other setup that needs to be done?

To illustrate my issue, I'm doing two passes of the following shader (ping-ponging between two textures in the aforementioned format):

```
texture tex;

sampler2D sam = sampler_state {
    texture = <tex>;
    minfilter = none;
    magfilter = none;
    mipfilter = none;
};

float4 main(float2 uv : TEXCOORD) : COLOR0 {
    float4 cin = tex2D(sam, uv);
    float4 cout = cin;

    cout.g = 10;
    if (cin.g > 1)
        cout.b = 1;

    return cout;
}

```

The output (starting from black) is a green screen. If I change:

```
cin.g > 1

```

To:

```
cin.g >= 1

```

Then I get a cyan screen.

I'm working from a modified version of SDL2's Direct3D 9 driver if that helps.

# Answer
I am the author of the comment referred to in this question.

Unfortunately since Microsoft have pulled all of the old DirectX SDKs it's no longer possible to cite a reference to one of those for the clamping behaviour; instead I'll cite The Complete Effect and HLSL Guide by Sebastien St-Laurent; Table 6-4 Pixel Output Semantics (this should also be searchable on Google Books):

> Any pixel shader prior to version 3.0 should clamp a parameter that uses this semantic between 0 and 1. For pixel shaders beyond 3.0 shaders, the data range is dependent on the render target format.

(It should be immediately obvious that this citation omits what happens with PS\_3\_0, which is regrettable).

A possible workaround for you is to scale your pixel shader output down during your main rendering pass(es), then scale it back up again as a post-processing pass. Doom 3 used a similar technique to likewise achieve a higher dynamic range (in it's case, at the expense of some bits of precision).
> 1 votes

# Answer
From my understanding (of GLSL though), those values are always clamped between 0.0 and 1.0. You don't get it any darker than black and any lighter than white. With more memory for color, all you get is more precision between zero and one. So setting "green" to 10.0 in your shader just sets it to 1.0. I do not actually understand what you mean by "...in order to use the full range of 16-bit floats". You ARE already using the increased precision. There is just no point of going above 1.0 if you are not intending to implement HDR or similar techniques...

P.s: maybe this is rather a comment than an answer...
> 0 votes

---
Tags: directx, hlsl, directx9, hdr
---


# Question
Title: Detect camera collision in OpenGL without using bounding box
Is there any way to detect collisions in `OpenGL` without using any kind of bounding box?

I have created a maze/labyrinth and I want to move the camera/player inside the maze, such that the movement of camera is restricted by the walls of the maze.

# Answer
> 3 votes
OpenGL is a graphics API, whose sole purpose is shoving triangles to your screen. It does not do collision detection, at all.

If your maze has orthogonal walls, an axis-aligned bounding box is definitely the easiest collision detection you can code.

---
Tags: opengl, c++, visual-studio
---


title: Texture coordinates projection

text:
# Question
Title: Texture coordinates projection
I have some classic texture coordinates and as a normal behaviour they follow the mesh's transformations.

I am trying to use the same texture coordinates behaviour but without being affected by the mesh rotation transformation. The results would be a sort of texture coordinates projection.

I don't know if my explanations are well explained but how could I achieve such effect.

Thanks a lot.

# Answer
> 0 votes
I think that I got a solution but I would gladly know if there are some optimizations possible.

My UVs and local coordinates values are corresponding. I mean that they are in the same range value. That said, I can use my XY vertices values for sampling the occlusion texture. The main problem is that the local coordinates are dependent to the rotation of my object which doesn't solve anything...

To solve that I am converting my local coordinates into world space using a objectToWorld matrix (inverse of current world matrix). Then I am converting it back into object space using the inverse TRS matrix but without taking into account the rotation of the object.

It's a bit hacky and I think that I could avoid some steps but this is working. Any advice is welcome :)

---
Tags: opengl, shaders, directx, glsl, hlsl
---


title: Eye Parallax Refraction Shader

text:
# Question
Title: Eye Parallax Refraction Shader
I am trying to implement the Parallax Refraction effect explained by **Jorge Jimenez** on this presentation: http://www.iryoku.com/downloads/Next-Generation-Character-Rendering-v6.pptx and I am facing some difficulties. Here is a screenshot of the interesting part.

But this document lacks a bit of explanations especially the second part with the **Physically based Refraction**.

Here is what I've achieved for the moment.
This is the simple **Parallax Refraction** effect and, as you might notice in the screenshot, there is small glitch at grazing angles in the iris when the Parallax Scale value is too high.

This seems to be caused by the parallax calculation but are there some tricks to avoid or minimize such issue ?

I don't want to go deeper with parallax mapping for the moment, so I don't want to use Steep Parallax Mapping or Parallax Occlusion Mapping.

This is the simple Parallax Refraction part.

```
// height value comes from a texture
float2 offset = height * viewDir;
offset.y = -offset.y;
texcoord -= ParallaxScale * offset;
// Next there is the texture sampling with the texcoord value

```

Here is the way I calculate the refraction vector according to Snell's law.

```
float cosine = dot(viewDir, worldNormal);
float sine = sqrt(1 - cosine * cosine);

float sine2 = (_IOR * sine);
float cosine2 = sqrt(1 - sine2 * sine2);

float3 x = -worldNormal;
float3 y = normalize(cross(cross(viewDir, worldNormal), worldNormal));
float3 refractedW = x * cosine2 + y * sine2;

```

This is integrated with the Physically based Refraction and it gives interesting results but I still don't know how to get rid of the high parallax scale issue which appear at grazing angles...

Any idea how to get rig of that ?
Thanks a lot.

# Answer
As I am working with Unity, I found an interesting way of calculating the parallax offset inside the engine. It's not physically based but it gives better results than the classic parallax refraction.

```
float2 ParallaxOffset(half h, half height, half3 viewDir)
{
    h = h * height - height / 2.0;
    float3 v = normalize(viewDir);
    v.z += 0.42;
    return h * (v.xy / v.z);
}

```
> 0 votes

---
Tags: opengl, shaders, directx, pbr
---


# Question
Title: GameStudio : How to remove object after delay
When you pick an item in the inventory and drop it to `obj_item_ground`, this item is send to the ground. That's fine. I want to add a delay to this item to destroy it, but if I drop 2 items to the ground, only the last is destroy.
Question : How can I create one timer by item dropped ?
**Step :**
`obj_inventory` : on Create event

```
 instance_create(0, 0, obj_item_ground);

```

`obj_item_ground` : on Create event

```
initialTime = 5;
time = 5;
ground = -1;

```

on Alarm\[0\] event; if timer is less than 0, object is destroy.

```
if (time > 0) {
    time -= 1;
    alarm[0] = 30;
} else {
    with (ground) {
        instance_destroy();
    }
}

```

on Left Pressed event :

```
if (mouseItem != -1) {
    scr_item_ground_timer();
}

```

*mouseItem is item I drag to the obj\_item\_ground.*

`scr_item_ground_timer()` :

Here I create the instance of object dropped to the ground and start the alarm\[0\] timer.

```
scr_inventory_item_drop(mouseItem);

for (i = 0; i < mouseQuantity; i++) {
 ground = instance_create(obj_player.x + random_range(-30, 4), obj_player.y + random_range(-12, 0), mouseItem);
}
alarm[0] = 30;
mouseItem = -1;

```

*scr\_inventory\_item\_drop is just to clear the array which contains the object dropped.*

# Answer
As you noticed, if you handle the destruction of items dropped to the ground in the inventor object, you won't be able to handle multiple items.

Make sure to let the responsibility of destroying the items on ground for themselves, that's it, each object will have it's own alarm. It's not a bad design, and it doesn't cause lag as well because it's just a single counter that gets decreased every step.

So, for every possible `mouse_item` I recommend that you create a parent object, let's call it `obj_droppable`. In This `obj_droppable` you should set the alarm.

`obj_droppable` Create:

```
alarm[0] = 60; //or whatever time you need for it to stay on ground

```

`obj_droppable` Alarm 0:

```
instance_destroy();

```
> 0 votes

---
Tags: game-maker, timer, objects
---