# Question
Title: Calculating vertex_normals (vn) causes ugly lines C++/openGL
Im trying to procedurally generate planets for a project I'm working on. By adding noise to each vertex, I'm able to generate elevation, but without having updated vertice normals for my shader. It originally looked something like the picture below.

When I tried to recalculate the vertex normals, I got some ugly sharp lines, most likely as a result from the way I was parsing the model.

this is the code Im using to recalculate the normals:

```
for (auto &x : normals)x = vec3(0);  //zero normals
vec3 facenormal; //buffer

//indices is the faces/triangles indexed, in pairs of 3.
for (size_t i = 0; i<indices.size();)
{
    facenormal = cross(
        (shape[indices[i + 1]] - shape[indices[i]]),
        (shape[indices[i + 2]] - shape[indices[i]])
        );

    normals[indices[i++]] += facenormal;
    normals[indices[i++]] += facenormal;
    normals[indices[i++]] += facenormal;
}

for (auto &x : normals)x = normalize(x); //normalize adjacent faces

```

Basically I add up the adjacent faces to the vertices they belong to, then normalize the value they have.

Then, based on suggestions, I took a look at the parsing and made sure it doesnt share vertices in the indexing. This seems to remove the lines, but im still stuck flat shading?

But according to this, it should be accurate. So I'm still not fixing the problem. What is the correct formula to do the vertex calculation, if its not what I'm already doing.

Like user Kolenda suggests, I was not modifying values at the base-mesh level. but rather, doing them after loading the indexed copies. So, what I end up with is a combination of flat shading faces "shading" ghost vertice normals. Iterating over the faces on a mesh level, with the same formula, solves the problem.

# Answer
You didn't tell us how do you create this mesh but it seems it's made of a few chunks that don't share any vertices. It's similar to the situation when you create a cube with 6 separate sides, then tesselate and normalize those sides separately.

As a result you have visible seams. The normal on one side is an average of triangle normals at that side, but ignores triangles on the other side.

To fix this you could fix the creation of a base sphere mesh - if you have any vertices that have the same position then leave just one of them and remove the rest, updating triangles indices.
> 1 votes

---
Tags: opengl, c++, glm
---


# Question
Title: How can I open the map in Skyrim using Papyrus or SKSE?
While making a mod for Skyrim, I'd like to allow a player to chose a location to teleport to.

Essentially, I'll be:

* enabling Fast Travel if disabled
* changing fast travel speed so that the travel happens near instantly in game time
* opening the map to allow player to select destination
* resetting fast travel speed, disabling fast travel if appropriate

It's the third dot point I need help with. I can work out the others with Papyrus script, but is there a way to open the Map using Papyrus or SKSE?

# Answer
> 1 votes
OK, I found the answer myself:

It can't be done with Papyrus, but can with SKSE using the Input function:

```
    int MapKey = Input.GetMappedKey("Quick Map")
    Input.TapKey(MapKey)

```

Needed to extract the SKSE script sources to Skyrim Data Script Source folder to get access to the SKSE functions.

---
Tags: modding, skyrim-modding
---


title: Simple cartoon water shader shoreline

text:
# Question
Title: Simple cartoon water shader shoreline
I'm currently attempting to create a cartoon-ish water shader with a shoreline. After looking around trying to find out how other games do it i figured out it has something to do with getting the distance from the depth map (which doesn't include the water when it's render queue is set to transparent) and the and the world position of the current pixel.

From certain angles i'm actually getting very close to the desired result as show here:

The topmost island almost has the desired result, but as you can tell, the closer it gets to the camera, the more out of place the effect becomes.

here's a zoomed out top down view illustrating the problem

as per request, here's what the terrain looks like beneath the water surface (animated gif)  and of course, here is my shader code:

```
Shader "Custom/CartoonWater" {
 Properties {
     _Color ("Color", Color) = (1,1,1,1)
     _Glossiness("Smoothness", Range(0,1)) = 0.5
     _ShoreFade("Shoreline Distance", Float) = 1
 }
 SubShader {
         Tags{ "Queue" = "Transparent" "RenderType" = "Transparent" }
     LOD 200

     CGPROGRAM
     // Physically based Standard lighting model, and enable shadows on all light types
     #pragma surface surf StandardSpecular

     // Use shader model 3.0 target, to get nicer looking lighting
     #pragma target 3.0

     sampler2D _CameraDepthTexture;

     struct Input {
         float3 worldPos;
         float4 screenPos;
     };

     half _Glossiness;
     fixed4 _Color;
     float _ShoreFade;

     void surf (Input IN, inout SurfaceOutputStandardSpecular o) {

         o.Albedo = _Color.rgb;
         o.Smoothness = _Glossiness;

         fixed4 depth = tex2Dproj(_CameraDepthTexture, UNITY_PROJ_COORD(IN.screenPos));

         o.Albedo = _Color;
         if (distance(LinearEyeDepth(depth), distance(_WorldSpaceCameraPos, IN.worldPos)) < _ShoreFade) {
             o.Albedo = fixed4(1, 1, 1, 1);
         }

     }
     ENDCG
 }
 FallBack "Diffuse"
 }

```

any help is greatly appreciated :) thanks in advance.

# Answer
> 2 votes
After much trial and error and Google-fu, I've come across a texture blend shader that gave a similar effect to what you wanted. After a bit of tinkering I've achieved a satisfactory result.

What this shader does, is that it blends the mesh right below itself and it'd normally add some sort of transparency effect to the material. I've modified the values of the result and instead of making it more transparent as it got closer to the object, I've increased its colors. You could just set the colors to white instead too.

Here's the shader I've used:

```
Shader "Custom/SurfaceDepthTextureColorized" {
    Properties{
        _Color("Color", Color) = (1,1,1,1)
        _BlendColor("Blend Color", Color) = (1,1,1,1)
        _MainTex("Albedo (RGB)", 2D) = "white" {}
    _Glossiness("Smoothness", Range(0,1)) = 0.5
        _Metallic("Metallic", Range(0,1)) = 0.0
        _InvFade("Soft Factor", Range(0.01,3.0)) = 1.0
        _FadeLimit("Fade Limit", Range(0.00,1.0)) = 0.3
    }
        SubShader{
        Tags{ "Queue" = "Transparent" "RenderType" = "Transparent" }
        LOD 200

        CGPROGRAM
        // Physically based Standard lighting model, and enable shadows on all light types
#pragma surface surf Standard vertex:vert alpha:fade nolightmap

        // Use shader model 3.0 target, to get nicer looking lighting
#pragma target 3.0

        sampler2D _MainTex;

    struct Input {
        float2 uv_MainTex;
        float4 screenPos;
        float eyeDepth;
    };

    half _Glossiness;
    half _Metallic;
    fixed4 _Color;
    fixed4 _BlendColor;
    sampler2D_float _CameraDepthTexture;
    float4 _CameraDepthTexture_TexelSize;

    float _FadeLimit;
    float _InvFade;

    void vert(inout appdata_full v, out Input o)
    {
        UNITY_INITIALIZE_OUTPUT(Input, o);
        COMPUTE_EYEDEPTH(o.eyeDepth);
    }

    void surf(Input IN, inout SurfaceOutputStandard o) {
        // Albedo comes from a texture tinted by color
        fixed4 c = tex2D(_MainTex, IN.uv_MainTex) * _Color;
        o.Albedo = c.rgb;
        // Metallic and smoothness come from slider variables
        o.Metallic = _Metallic;
        o.Smoothness = _Glossiness;

        float rawZ = SAMPLE_DEPTH_TEXTURE_PROJ(_CameraDepthTexture, UNITY_PROJ_COORD(IN.screenPos));
        float sceneZ = LinearEyeDepth(rawZ);
        float partZ = IN.eyeDepth;

        float fade = 1.0;
        if (rawZ > 0.0) // Make sure the depth texture exists
            fade = saturate(_InvFade * (sceneZ - partZ));
        //o.Alpha = c.a * fade; //(original line)
        //the rest are lines I've input
        o.Alpha = 1;
        if(fade<_FadeLimit)
        o.Albedo = c.rgb * fade + _BlendColor * (1 - fade);
    }
    ENDCG
    }
}

```

Here are the results; soft factor 0.15, fade limit 1:

soft factor 0.05, fade limit 0.05:

Finally, thanks to @DanielHolst for chatting with me on the matter, I would've just gotten bored at some point if he didn't work with me on this.

---
Tags: unity, shaders, depth-buffer, water
---


# Question
Title: Where and how to store players collection in a computer card game?
I am developing a trading card game ( something like Hearthstone but not as complex) and I am faced with the following problem: I don't know what is the optimal way to store players collections and decks (the cards that they have available).

I thought of storing their collections on a local file on their device, but that seems bad, as they could probably modify that file and get themselves cards that they shouldn't have.

The second idea is that i could save all their decks and collection in a database. But having one table for each player isn't possible. Having one table with all that data something like `PlayerCards(id, cardId, playerName, deckName)` seems like it might work, but the table would be huge, and containg quite a bit of redundant data (cards that are in the same collection but are in multiple decks).

What would be the proper way to do it?

# Answer
> 3 votes
The **relational-database-by-the-book solution** would have a table `players`, a table `cards_owned_by_players`, a table `decks` a table `cards_in_deck` and a table `cards`.

Here is an entity-relationship diagram of the whole schema. If you are wondering where `cards_in_deck` and `cards_owned_by_players` went: note that an N:M relationship needs to be represented with a separate relation-table.

* A `player` owns m `cards`
* A `card` is owned by n `players`
* A `player` has n `deck`s
* A `deck` is always owned by one `player`
* A `deck` has n `cards`
* A `card` is in m `decks`

The table `players` would have the primary key `playerId`. It contains all the information about the player themselves (like the player name).

The table `cards_owned_by_players` manages the ownership relation of individual cards. Its primary key would be `cardId` and `playerId`. If a player can own more than one copy of a card, it would have a value-field `count`. To get all cards owned by a player, you can do `SELECT cardId FROM cards_owned_by_players WHERE playerId = [id]`. If you also need additional information about these cards, like their artwork or name, you would add a `JOIN` with `cards` to this query. More about the table `cards` later.

The table `decks` would have the primary key `deckId`. It includes all the information about the deck itself (name of the deck and the Id of the player who owns it).

The table `cards` would have the primary key `cardId` and include the information about the cards themselves (name, description, artwork, functionality). You have one entry per type of card. I.e. if you have a card "Goblin Warrior" which is owned by 1752125 players and is in 2357689 decks, you would still only have one row for it in `cards`.

The table `cards_in_deck` would have a compound primary key of `deckId` and `cardId`. If your game allows multiple copies of a card in one deck, the value field would be `count`. When it doesn't, that table might not actually need any fields at all except the primary key.

As an example query, let's say you want the deck names and card names of all cards in all decks by a specific player which you only know by name "Bob". You would then do the query:

```
SELECT decks.name, cards.name, cards_in_deck.count
       FROM players
       JOIN decks ON players.playerId = decks.playerId
       JOIN cards_in_deck ON decks.deckId = cards_in_deck.deckId
       JOIN cards ON cards_in_deck.cardId = cards.cardId
       WHERE players.name = "Bob"

```

A JOIN over 4 tables *looks* like it could be a lot of work for the database, but notice that they are all JOINs on primary keys. Most database management systems optimize heavily for primary key access. The slowest parts of this query will likely be `WHERE players.name = "Bob"`, because that will require a full table scan of the `players` table, unless you have an index on the `name` field.

Also, don't be afraid of your `cards_in_deck` table growing too large. We are living in the age of big data. Many database management systems are capable of handling tables with *billions* of rows and *terabytes* of data... as long as all queries on them are using primary key or index access.

---

**An optimized solution:**

If you ever meet the ghost of Edgar F. Codd, please don't tell him I wrote this.

If you are sure you will always query only for the complete content of a deck and never query for individual cards in a deck, you can remove the table `cards_in_deck` and instead serialize the deck content into a binary representation and put it into one BLOB field of the table `deck`. You will no longer be able to do queries like "all players which have card X in their deck". Also, making a change to a deck will now require to get the whole BLOB, deserialize it, change it, serialize it, and write it back. But it will be a lot faster to get the whole deck of a specific player.

You can now of course no longer do a JOIN with `cards`. But you might not have to do that. You won't have that many different cards (even Hearthstone only has about 2000), your game mechanics will constantly need them, and your card information will only change when you make a major update to your game. So it might be better to keep the card information constantly in the game server's memory instead of re-reading it from the database all the time.

# Answer
> 1 votes
> I thought of storing their collections on a local file on their device, but that seems bad, as they could probably modify that file and get themselves cards that they shouldn't have.

Correct; if you care about the player being able to tamper with their collection of cards, you don't want the authoritative collection of cards stored on their device. If their devices are computers, it's pretty easy to access that data for modification. If their devices are phones or tablets, it's a little harder, but still possible.

> The second idea is that i could save all their decks and collection in a database.

This seems like the ideal solution, especially if your game already has a multiplayer component where you might want to stand up a central database for match scores or tournaments.

Assuming you have a `Cards` table (describing every card in the game) indexed by `CardId` and a `Players` (describing every player in the game) table indexed by `PlayerId`, you only need a two- or three- column additional table to represent who owns what.

This `Inventory` table describes which cards every player has by using a player ID column and a card ID column, such that one row of this table is indicating that (for example) player 90 has card 43. If a player can possess multiple cards you can add a third column for `Count`.

You *will* have a large number of rows in this table if you have a large number of players and a large number of cards. It *won't* be redundant data though; it's the minimum amount of data you need. The "larger" chunks of data, stuff like the player's name, the card's name or stats, all of that lives in the `Players` or `Cards` tables where it isn't duplicated.

---
Tags: data-structure, databases, card-game
---


title: Smooth Camera Movement Java

text:
# Question
Title: Smooth Camera Movement Java
So, I'm making a platformer game from scratch in Java and I am trying to make the camera movement smoother. Here is what it currently is

```
public class Camera {
    private int x, y;

    public Camera(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public void tick (GameObject player) {
        setX((int) (-player.getX() + Reference.WIDTH / 2 + 16));
        setY((int) (-player.getY() + Reference.HEIGHT / 2 + 64));
    }
}

```

It moves too strictly and it always centres the player to the screen, I don't like it.

I tried watching this video, but it's in GameMaker. Any way to translate this to Java? https://youtu.be/6cIN6iW5ois

Any help would be appreciated, thanks! :)

# Answer
> 4 votes
Currently you have:

```
setX((int) (-player.getX() + Reference.WIDTH / 2 + 16));
setY((int) (-player.getY() + Reference.HEIGHT / 2 + 64));

```

This should be placing the player in the center of the view (perhaps offset by some constant... I do not know if the coordinates are from the center or the corner, I do not know how big the player is either... it does not really matters).

We will take these values you have and store them as tweening easing target:

```
int targetX = (int) (-player.getX() + Reference.WIDTH / 2 + 16);
int targetY = (int) (-player.getY() + Reference.HEIGHT / 2 + 64);
setX(targetX);
setY(targetY);

```

Yes, that does the same as before, it is just refactoring. We know have to apply the tweening algorithm linear interpolation (a.k.a. lerp):

```
x += (target - x) * CONSTANT

```

That is the same as:

```
x = x + (target - x) * CONSTANT

```

Using the value `0.1` for the constant in your code, it ends up as follows (since we have to use the current value twice, I will take it as local variables too):

```
int targetX = (int) (-player.getX() + Reference.WIDTH / 2 + 16);
int targetY = (int) (-player.getY() + Reference.HEIGHT / 2 + 64);
int x = getX();
int y = getY();
setX(x + (targetX - x) * 0.1);
setY(y + (targetY - y) * 0.1);

```

Alternatively, you can tell java to stop being in the way:

```
int targetX = (int) (-player.getX() + Reference.WIDTH / 2 + 16);
int targetY = (int) (-player.getY() + Reference.HEIGHT / 2 + 64);
x += (targetX - x) * 0.1;
y += (targetY - y) * 0.1;

```

The result is what Itay Karen calls lerp-smoothing in the article Scroll Back: The Theory and Practice of Cameras in Side-Scrollers.

As suggested in the video you linked, experiment with the constant factor to get the effect you want. If you decide to change the constant for a function of the difference of target and the current value... then it is no longer a linear interpolation, but it is still easing.

I will also suggest looking into edge-snapping, it may fit your game. It is implemented as a clamp that prevent the camera to show beyond the edge of the world.

---

Demo without edge-snapping:

```
var time = (new Date()).getTime(); // time in milliseconds
var speed = 50;
var player = {x: 8, y:50, width:16, height:64};
var camera = {x: 0, y:32, width:100, height:100};
var world = {width: 200, height:200};

function update()
{
  // get current time
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;

  // moving the player

  player.x = player.x + speed * elapsed;
  if (player.x < 0)
  {
    player.x = 0
    speed = -speed;
  }
  if (player.x > world.width - player.width)
  {
    player.x = world.width - player.width;
    speed = -speed;
  }
  player.y = 50;

  // move the camera

  // note: since I'm moving a "camera" object, instead of computing a transformation
  // the target has reversed sign.

  var targetX = player.x - camera.width/2 + player.width/2;
  var targetY = player.y - camera.height/2 + player.height/2;
  camera.x += (targetX - camera.x) * 0.1;
  camera.y += (targetY - camera.y) * 0.1;

  // update the elements
  var playerElement = document.getElementById('player');
  playerElement.style.left = player.x + "px";
  playerElement.style.top = player.y + "px";
  var cameraElement = document.getElementById('camera');
  cameraElement.style.left = camera.x + "px";
  cameraElement.style.top = camera.y + "px";

  // update time

  time = new_time;
}
setInterval(update, 40);
```

```
body,div{margin:0px}
#camera{border:1px solid blue; position:absolute; top:32px; width:100px;height:100px;}
#player{background:green; position:absolute; top:50px; width:16px;height:64px;}
#world{border:1px solid red; position:absolute; width:200px;height:200px;}
```

```
<div id="camera"></div>
<div id="player"></div>
<div id="world"></div>
```

---

Demo with with-snapping on target:

```
var time = (new Date()).getTime(); // time in milliseconds
var speed = 50;
var player = {x: 8, y:50, width:16, height:64};
var camera = {x: 0, y:32, width:100, height:100};
var world = {width: 200, height:200};

function update()
{
  // get current time
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;

  // moving the player

  player.x = player.x + speed * elapsed;
  if (player.x < 0)
  {
    player.x = 0;
    speed = -speed;
  }
  if (player.x > world.width - player.width)
  {
    player.x = world.width - player.width;
    speed = -speed;
  }
  player.y = 50;

  // move the camera

  // note: since I'm moving a "camera" object, instead of computing a transformation
  // the target has reversed sign.

  var targetX = player.x - camera.width/2 + player.width/2;
  var targetY = player.y - camera.height/2 + player.height/2;

  targetX = Math.min(world.width - camera.width, Math.max(0, targetX));
  targetY = Math.min(world.height - camera.height, Math.max(0, targetY));

  camera.x += (targetX - camera.x) * 0.1;
  camera.y += (targetY - camera.y) * 0.1;

  // update the elements
  var playerElement = document.getElementById('player');
  playerElement.style.left = player.x + "px";
  playerElement.style.top = player.y + "px";
  var cameraElement = document.getElementById('camera');
  cameraElement.style.left = camera.x + "px";
  cameraElement.style.top = camera.y + "px";

  // update time

  time = new_time;
}
setInterval(update, 40);
```

```
body,div{margin:0px}
#camera{border:1px solid blue; position:absolute; top:32px; width:100px;height:100px;}
#player{background:green; position:absolute; top:50px; width:16px;height:64px;}
#world{border:1px solid red; position:absolute; width:200px;height:200px;}
```

```
<div id="camera"></div>
<div id="player"></div>
<div id="world"></div>
```

---

Demo with with-snapping on camera:

```
var time = (new Date()).getTime(); // time in milliseconds
var speed = 50;
var player = {x: 8, y:50, width:16, height:64};
var camera = {x: 0, y:32, width:100, height:100};
var world = {width: 200, height:200};

function update()
{
  // get current time
  let new_time = (new Date()).getTime();
  let elapsed = (new_time - time) / 1000.0;

  // moving the player

  player.x = player.x + speed * elapsed;
  if (player.x < 0)
  {
    player.x = 0;
    speed = -speed;
  }
  if (player.x > world.width - player.width)
  {
    player.x = world.width - player.width;
    speed = -speed;
  }
  player.y = 50;

  // move the camera

  // note: since I'm moving a "camera" object, instead of computing a transformation
  // the target has reversed sign.

  var targetX = player.x - camera.width/2 + player.width/2;
  var targetY = player.y - camera.height/2 + player.height/2;
  camera.x += (targetX - camera.x) * 0.1;
  camera.y += (targetY - camera.y) * 0.1;

  camera.x = Math.min(world.width - camera.width, Math.max(0, camera.x));
  camera.y = Math.min(world.height - camera.height, Math.max(0, camera.y));

  // update the elements
  var playerElement = document.getElementById('player');
  playerElement.style.left = player.x + "px";
  playerElement.style.top = player.y + "px";
  var cameraElement = document.getElementById('camera');
  cameraElement.style.left = camera.x + "px";
  cameraElement.style.top = camera.y + "px";

  // update time

  time = new_time;
}
setInterval(update, 40);
```

```
body,div{margin:0px}
#camera{border:1px solid blue; position:absolute; top:32px; width:100px;height:100px;}
#player{background:green; position:absolute; top:50px; width:16px;height:64px;}
#world{border:1px solid red; position:absolute; width:200px;height:200px;}
```

```
<div id="camera"></div>
<div id="player"></div>
<div id="world"></div>
```

---

*Note on terminology*

The terms "position-locking", "edge-snapping", "lerp-smoothing" are from Itay Karen and are described in the linked article Scroll Back: The Theory and Practice of Cameras in Side-Scrollers.

Referring to this as tweening is not wrong per-se. Yet tweening is a term used in key frame animation, and if you look for how to do tweening, you will get tutorials on using animation tools. So, instead look for how to implement easing.

However, avoid quantitative easing, that is economy / finance / monetary policy lingo meaning that the central bank will buy financial assets in such way that it causes a smooth inscrease in money supply and the prices of financial assets (see: yield curve)... while that is also easing, you will not get code from articles on monetary policy.

---
Tags: java, tweening
---


# Question
Title: I have a question about 3D game models and copyright
I am making a game that is like a combination of minecraft and unturned. It is like minecraft as it is very block based. It is like unturned because it has vehicles and other unturned functionalities. This is what the player model would probably look like:

The player model is very similar to minecraft's Steve. It does however have some major differences that make it unique. For instance the eyes are not stationary and can actually look around. The mouth has two sets of teeth which act as the jaw line and lips that represent the mouth. Both the teeth and the lips can be animated for a "Talking" animation. The eyes also have eyelids which can close and open with proper animating skill. The player model can also be customized in game, as the hair style, beard style, eye color, skin color, hair and beard color, can be changed during game play. Unlike minecraft's character, It is not restricted to just helmet, chest plate, leggings and boots for armor. This model can change its shirt, pants, helmet, hat, pants, leg armor, armor boots, chest plate, backpack (If he equips one), gloves, shoulder pads, elbow pads, and any other piece of armor and clothing that can be used in game.

My problem is, even with the major differences in the model, will it still be too similar to Steve? Or is this model too different to have me sued for copyright/IP infringement?

Thanks for any input.

I just started working on the model again, This time the player can hold things and also wears shoes:

# Answer
> 1 votes
It's very hard to tell, because we aren't lawyers, but some things can be said about it.

1.: Mojang was pretty generous when it came to stuff like this. Just look at the amount of games that are very similar to Minecraft. However, Minecraft was recently bought by Microsoft, so it's not 100% that this is the case anymore. (Thanks @Philipp for reminding)

2.: Law never completely adapted to the current technology. Currently, you only infringe copyright rules if you either stole code or game assets. Whether this counts as stoling game asset is hard to tell.

3.: We're just recently started seeing cases where game companies sued other game companies succesfully for copying games. The other companies didn't steal code nor game assets though, which could mean my 2nd statement is starting to fade.

You should definitely get a lawyer and ask him about this, or change the model completely. The latter one is orders of magniude cheaper.

One thing is certain. If you use any assets that you got from the game (like the grass texture), then you're in an illegal area.

You also don't want to make a game that looks like Minecraft, because people will put it down saying it's another Minecraft clone.

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


# Question
Title: Single pass separable gaussian blur problem
I created a single pass gaussian blur using HLSL compute shader. I also want it to be separable, which means, that first I perform blur along the horizontal direction, write out the result to the texture, then perform the vertical blur with the horizontally blurred data.

I do this by creating **DeviceMemoryBarriers** before and after writing out the blur results to the **globallycoherent** Texture2D.

This is my shader:

```
Texture2D<float4> input:register(t0);
globallycoherent RWTexture2D<float4> input_output:register(u0);

// Note: Shader requires feature: Typed UAV additional format loads!
[numthreads(16, 16, 1)]
void main(uint3 DTid : SV_DispatchThreadID)
{
    // Query the texture dimensions (width, height):
    uint2 dim;
    input_output.GetDimensions(dim.x, dim.y);

    // Determine if the thread is alive (it is alive when the dispatchthreadID can directly index a pixel)
    if (DTid.x < dim.x && DTid.y < dim.y)
    {
        // Do bilinear downsampling first and write it out:
        input_output[DTid.xy] = input.SampleLevel(sampler_linear_clamp, ((float2)DTid + 0.5f) / (float2)dim, 0);
        DeviceMemoryBarrier();

        uint i = 0;
        float4 sum = 0;

        // Gather samples in the X (horizontal) direction:
        [unroll]
        for (i = 0; i < 9; ++i)
        {
            sum += input_output[DTid.xy + uint2(gaussianOffsets[i], 0)] * gaussianWeightsNormalized[i];
        }
        // Write out the result of the horizontal blur:
        DeviceMemoryBarrier();
        input_output[DTid.xy] = sum;
        DeviceMemoryBarrier();
        sum = 0;

        // Gather samples in the Y (vertical) direction:
        [unroll]
        for (i = 0; i < 9; ++i)
        {
            sum += input_output[DTid.xy + uint2(0, gaussianOffsets[i])] * gaussianWeightsNormalized[i];
        }
        // Write out the result of the vertical blur:
        DeviceMemoryBarrier();
        input_output[DTid.xy] = sum;
    }
}

```

The problem is that the result flickers a bit, and has some errors in the image, too. Seems a bit like a thread group can't see writes by other groups.

But there is a globallycoherent modifier before the RWTexture2D which should flush the entire resource so that writes are visible in every thread group (MSDN). Indeed, if I remove that modifier, then the flickering becomes a whole lot worse than if I leave it there.

Here is a screenshot of the problem:

(Notice the lines on the windmill, and it also flickers on the whole image from time to time which is not visible on a still shot)

Anyone here has an idea what I can do about it? (PS. the blur is performed when creating mipmaps, so I very much want to avoid multiple passes because it is already one pass for each mip)

# Answer
> 3 votes
I'm not an expert in compute shaders, but it looks like the memory barriers you're using there say:

> "Ensure all *current writes in progress* finish before proceeding to the next step"

...while I think what you mean/want is:

> "Ensure all writes ***to the texels I'm about to try to read*** finish before proceeding to the next step"

Those writes might not have even been *attempted* by another thread group yet, so even after all *current* writes complete and you proceed to the vertical blur, you can end up sampling texels from `input_output` that haven't been written yet this frame.

Here it looks like you're getting last frame's blurred result in these samples instead, which would explain why you see the lines trailing behind the moving vanes of the windmill along the borders separating vertically stacked threadgroup chunks.

You could avoid this by performing the blur in two passes, fully populating the intermediate buffer before trying to read from it. You'd likely want to output to another buffer yet, rather than stuffing the result into the same buffer you're reading - otherwise you can hit a similar but more subtle issue where your second pass samples pick up a mix of texels that have been blurred only horizontally and those that have already gotten both the horizontal and vertical passes.

If you need to do this in a single pass, you could have each threadgroup maintain its own local strip of horizontally-blurred intermediates, half the kernel size larger than the thread group's span above & below, then read from that - but you compute some intermediates twice that way.

---
Tags: directx11, hlsl
---


# Question
Title: How do I get antialiasing in LibGDX with the LWJGL3 backend?
Updated to the LWJGL3 backend for LibGDX to for controller connect / disconnect functionality and access to geometry shaders and I'd rather not go back. There used to be a "samples" field in the LWJGLApplicationConfiguration object for setting antialiasing, but it no longer exists in LWJGL3ApplicationConfiguration. (Oh, and I'm only targeting Desktop)

# Answer
> 3 votes
Use `setBackBufferConfig` on the LWJGL3ApplicationConfig. The last parameter is the amount of samples.

```
public void setBackBufferConfig(int r, int g, int b, int a, int depth, int stencil, int samples)

```

---
Tags: java, libgdx, lwjgl3
---


# Question
Title: Is there a way how to handle multiple SDL_PollEvent loops without clearing the event queue?
Is there a way how can I handle more `SDL_PollEvent` while loops for one `SDL Event`, without taking the events off from the event queue?

---

Let us say I have something like this:

```
void Game::processInput() {

    SDL_Event event;
    SDL_PollEvent(&e);

    Engine::InputManager::processInput(&e)

    GUI_Library::InputManager::processInput(&e);
}

```

And then the engine processes the input in function like this:

```
    void Engine::InputManager::processInput(SDL_Event* e) {

    _mainEvent = *e;

    while (SDL_PollEvent(&_mainEvent)) {

        switch (_mainEvent.type) {

            case SDL_KEYDOWN : {

                Engine::InputManager::pressKey(_mainEvent.key.keysym.sym);
                break;
            }
            case SDL_KEYUP : {

                Engine::InputManager::releaseKey(_mainEvent.key.keysym.sym);
                break;
            }
        }
    }
}

```

However, this while loop clears the whole event queue, and another input manager (my GUI, for example) does nothing because it no longer has events in the queue.

Is there a possible way to handle this situation?

# Answer
> 1 votes
I've had similar; not a huge fan of how SDL does this but nothing stops you from storing the inputs in a secondary vector. Move the loop from out of your `InputManager` upward into your `Game`, call it `Game::Loop` or `Game::ProcessEvents`. Now, as you poll/pop all events there, act on what you can (like Window-related events), but store the inputs on a public (static) vector on your own `InputManager`. Then when you call the `InputManager` to run, you can process the inputs.

---
Tags: sdl, game-loop, sdl2
---


# Question
Title: What's the difference between Alpha and PreMulAlpha?
I've seen videos comparing the two but it looks like there's no difference and they don't explain what's the difference

# Answer
> 10 votes
**Standard Alpha blending** uses this formula:

```
result = foreground.alpha * foreground + (1 - foreground.alpha) * background

```

This is a linear interpolation between the foreground and background colours, using the foreground's alpha as the interpolation weight, effectively the same as:

```
result = lerp(background, foreground, foreground.alpha)

```

This means the colour of a texel is treated entirely independently from its transparency, which is intuitively simple, but has some perplexing implications: it's possible for an object to simultaneously be both "purple" and "invisible" (ie. `rgba(0.5, 0, 1, 0)`), as odd as that may sound.

**Pre-multiplied Alpha blending** uses a different formula:

```
result = foreground + (1 - foreground.alpha) * background

```

It's so-named because the multiplication of the first term by foreground.alpha has been baked-in ahead of time.

So you can see, **anything we can do with conventional alpha blending, we can do with pre-multiplied alpha blending**. You can take any texture set up for "standard" alpha blending, multiply the rgb channels by the alpha channel, and now you have an equivalent texture ready for pre-multiplied blending.

But pre-multiplied blending has some extra super-powers...

**Super-Power #1: Pre-Multiplied Alpha can combine layer and additive blending**

This is because the pre-multiplication means we're storing data in terms of:

* how much colour to *add* to the background (rgb), and
* how much to *obscure* the background (alpha).

By leaving the obscuring alpha factor at zero, any values in the RGB channels get applied additively on top of the background, without being dimmed themselves - a classic "ADD" blend mode. By setting alpha to something between zero and one, we can get blend modes that are intermediate between additive and "standard/layer" blending.

This can be used, for instance, to combine multiple different sprites into a single batched draw call, even when they want different blend modes that would ordinarily force us to separate the batches.

We can even make a single effect that combines both blending modes, like a fire particle system that transitions from bright additive flames to opaque obscuring smoke with a single material/texture sheet:

Rendering this same spritesheet with standard alpha blending makes the flames disappear entirely (since they have zero alpha in the texture sheet above). Changing the texture sheet to assign an alpha to the flames makes them look too solid under alpha blending, without the characteristic brightness of an additive effect:

**Super-Power #2: Pre-Multiplied Alpha blending works cheaply in either direction**

Let's say we wanted to pre-compose some layered sprites - like a character made of several body part and clothing layers - into a sprite sheet with a transparent background, so we can later just stamp that pre-composed character into our scene as a single unit.

Here we don't yet know the colour of the background we're drawing over, so applying the standard blending formula using the simple lerp style will actually give us the wrong result when we later layer it onto the background.

To get the same result with standard blending as if we'd layered the image from bottom up, we have to use a slightly more complicated version of the formula:

```
result.rgb = ( foreground.rgb * foreground.alpha
              + middle.rgb * (1 - foreground.alpha) * middle.alpha)
              / (foreground.alpha * middle.alpha * (1 - foreground.alpha));

result.alpha = foreground.alpha + middle.alpha * (1 - foreground.alpha);

```

Note the division there, making the blend substantially more expensive to calculate, not natively supported in the GPU's blend stage, forcing us to implement the composition in our shader. When we can assume the background is opaque, the denominator comes out to 1 and we can skip it, but we can't do that and maintain correctness when blending transparency with transparency.

With pre-multiplied alpha though, there's no division required, and we can do this pre-composition directly in the native blending pipeline:

```
result.rgb = foreground.rgb + middle.rgb * (1 - foreground.alpha);

result.alpha = foreground.alpha + middle.alpha * (1 - foreground.alpha);

```

Much simpler - and the same formula for both the RGB and alpha channels! And the same formula works whether we're blending onto an opaque background or a transparent one.

**Super-Power #3: No discoloured fringes**

With regular alpha blending can suffer from discoloured fringes at the edges between opaque and transparent regions - particularly if it's drawn with bilinear filtering, or mipmapped to lower resolutions.

This is caused by the lack of weighted blending that Roy T. explains in detail in the other answer.

Look closely at the edges of this sprite: you'll notice in all but the top-left version, the colour shifts just at the fall-off from opaque to transparent - getting a dark shadow or a light whispy halo.

(Gem sprite by Kenney)

The reason is that many authoring programs will output fully-transparent texels as back or white, or some other colour chosen by the compressor. When blending between two texels along this edge, the alpha results are correct, but the colour results are wrong: the adjacent texel we're blending with isn't a colour the artist painted there (they left it transparent/empty), but one the tool filled in.

This is where the "simultaneously invisible and purple" issue comes back to bite us. There are dragons lurking in those unseen regions!

We can often fix this by bleeding out the colour we want to average with into the transparent regions, which is what I did to remove the artifact in the top-left case.

Because this is a widespread problem, game engines can often fix this automatically - for example, in Unity checking the "Alpha is Transparency" box in a texture's import settings will usually eliminate fringing artifacts, doing this colour bleed or something like it under the hood. (I left the box unchecked for the example above, so Unity was forced to take the PNG's saved colour values literally)

But if you use pre-multiplied alpha, storing plain black in the transparent regions, this problem goes away. Now instead of meaning "an invisible black monster lurks here" a black transparent pixel means "absorb no light, add no light," exactly what we want from a transparent region. And it blends correctly with adjacent texels - a 50% blend of "absorb all light, add 100% green light" with transparent black yields "absorb 50% of light, add 50% green light," a correct reduction of opacity without distorting the colour.

This is of particular significance for texture formats like DXT1, which can only store 1 bit of alpha as transparent black. So you get perfectly correct blending if you interpret the texture as premultiplied alpha, but you have dark fringes with standard alpha blending that you can't fix with colour bleeding - since there's no way to store colour and transparency in the same texel in such a format.

# Answer
> 3 votes
Both normal (post-multiplied) alpha blending and pre-multiplied alpha blending work perfectly... That is until you start blending adjacent colors within the texture or cross-fading between textures inside your shader.

See the below images. In the first column we have a square which is filled with red and semi-transparent green. In the second column we see the result if the colors are averaged (for example, if we're using bilinear texture filtering to draw a sample halfway between these two differently-colored texels). The first row uses post-multiplied-alpha while the second row uses pre-multiplied alpha.

Why does this happen? In post-multiplied alpha blending, the alpha component is only taken into account after blending. This means that we computed the average of the RGB of the left and the RGB of the right values regardless of how transparent the image is. After that we take the average of the alpha channels to compute the translucency.

So a red image and a green image combined will result in a green-brown image, even if the green image was so faint as to be nearly transparent.

In pre-multiplied alpha blending, the RGB channels are always multiplied with the alpha channel. This means that the RGB channels in an almost transparent image weigh less than the RGB channels of an opaque image. This results in the correct weighted blending as seen in the second row.

Note that this blending artifact does not apply to *layering* a sprite over a background, pre-multiplied or no. In that case, the blending function correctly takes alpha into account either way for a correct weighted blend. It's just the naive interpolation between RGB channels in texture filtering / mipmapping that needs the extra weighted blending correction offered by pre-multiplication.

I recommend reading this article for a more in-depth answer and how to use pre-multiplied alpha (you need to make some changes to your graphics pipeline).

---
Tags: graphics
---


# Question
Title: Make one object rotate to face another object in 2D
In my 2D project, I have an object that is sometimes above or below another object.

Once the primary object comes in close proximity with the secondary object, I want the object to rotate on the z axis so that the front of the primary object is facing the secondary object.

(Here, following Unity's default setup, the z axis is the axis pointing into the screen)

# Answer
> 4 votes
I can see this question is old, but it's a fairly common issue worth a standard answer.

Quaternion.LookRotation gives us a convenient way to say "point this way" but the problem is that it wants to point the z+ axis in the given direction - usually not what we want in 2D.

Fortunately we can correct for this, taking advantage of the second argument (usually used to control the "up" vector or twist of the resulting rotation)

**To point the local y+ axis toward something**, keeping z+ pointing into the screen:

```
Vector3 offset = target.position - transform.position;

transform.rotation = Quaternion.LookRotation(
                       Vector3.forward, // Keep z+ pointing straight into the screen.
                       offset           // Point y+ toward the target.
                     );

```

**To point the local x+ axis toward something**, keeping z+ pointing into the screen:

```
Vector3 offset = target.position - transform.position;

// Construct a rotation as in the y+ case.
Quaternion rotation = Quaternion.LookRotation(
                          Vector3.forward,
                          offset
                      );

// Apply a compensating rotation that twists x+ to y+ before the rotation above.
transform.rotation = rotation * Quaternion.Euler(0, 0, 90);

```

Of course in both cases, instead of setting `transform.rotation` directly, you can store the target rotation and blend (Lerp/Slerp/RotateTowards) this value over multiple frames for a smoother/more controllable result.

---
Tags: unity, 2d, transformation
---


title: vector subscript out of range

text:
# Question
Title: vector subscript out of range
I'm trying to setup a 2d game and have been thrown up an error on vector subscript out of range. I've been trying to look up about it, but have not seen anything that helps. If someone could help and take the time to look at my code and help me fix my error i'd be very grateful. I think it's got something to do with something about that it can't handle more then 0-9 or something but my knowledge/understanding of it is not great and would appreciate the help. I'll paste my code below so you can see what i'm trying to do.

```
//tile setup
level.loadTexture("gfx/Maptiles.png");
Tile tile;
vector<Tile> tiles;
for (int i = 0; i < 10; i++)
{
    tile.setSize(sf::Vector2f(32, 32));
    tile.setAlive(true);
    tiles.push_back(tile);
}

//sky tile set to false so we don't collide
tiles[0].setAlive(false);
//    X   Y   W   H  of the sprite sheet
/*tiles[0].setTextureRect(sf::IntRect(187, 51, 70, 70));
tiles[1].setTextureRect(sf::IntRect(0, 0, 70, 70));*/
tiles[0].setTextureRect(sf::IntRect(864, 221, 70, 70));
tiles[1].setTextureRect(sf::IntRect(73, 2, 70, 70));
tiles[2].setTextureRect(sf::IntRect(140, 2, 70, 70));
tiles[3].setTextureRect(sf::IntRect(210, 2, 70, 70));
tiles[4].setTextureRect(sf::IntRect(280, 2, 70, 70));
tiles[5].setTextureRect(sf::IntRect(350, 2, 70, 70));
tiles[6].setTextureRect(sf::IntRect(420, 2, 70, 70));
tiles[7].setTextureRect(sf::IntRect(506, 577, 70, 70)); //ground block
tiles[8].setTextureRect(sf::IntRect(560, 2, 70, 70));
tiles[9].setTextureRect(sf::IntRect(630, 2, 70, 70));
//tiles[].setTextureRect(sf::IntRect(630, 0, 70, 70));
//tiles[11].setTextureRect(sf::IntRect(770, 34, 70, 70));
//tiles[12].setTextureRect(sf::IntRect(840, 51, 70, 70));
//tiles[13].setTextureRect(sf::IntRect(910, 0, 70, 70)); //^^ 1st row
/*tiles[14].setTextureRect(sf::IntRect(0, 0, 70, 70));
tiles[15].setTextureRect(sf::IntRect(70, 0, 70, 70));
tiles[16].setTextureRect(sf::IntRect(140, 0, 70, 70));
tiles[17].setTextureRect(sf::IntRect(17, 34, 70, 70));
tiles[18].setTextureRect(sf::IntRect(34, 34, 70, 70));*/
level.setTileSet(tiles);
// Map dimensions
    sf::Vector2u mapSize(25, 19);
// build map
std::vector<int> map = {
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, //25 X 19
    2, 2, 3, 4, 5, 6, 7, 8, 9, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
};
//fix tile layout
level.setTileMap(map, mapSize);
level.setPosition(sf::Vector2f(0, 0));
level.buildLevel();

level.render(window);

```

# Answer
> 0 votes
You haven't made your vector big enough.

You `push_back` 10 elements in a loop so the vector's size is 10. If you want the vector to be bigger, call `.resize()` on it, or use `push_back`/`emplace_back` instead of assigning the indices directly.

Your commented-out code uses indices up to 18. Since you can access indices `[0,size)` in a vector, that means the size would need to be at least 19 for all your indices to be legal. You could assign these in several ways:

```
// automatically increases size (and capacity, when needed)
for (int i = 0; i != 19; ++i)
  tiles.push_back(tile);

// explicit size/capacity
tiles.resize(19);
tiles[0] = ...;
tiles[1] = ...;
...
tiles[18] = ...;

```

Remember that it is always illegal to access indices outside the bounds `[0,size)`, so you want to *check the bounds* anywhere you might have untrusted user data. For instance, with a tilemap, you will generally want to check the values of any tile indices in your 2D grid before looking them up in the `tiles` array, since a user may conceivably put a bogus tile index into the level.

```
for (int y = 0; y < height; ++y)
  for (int x = 0; x < width; ++x)
    if (map[y * width + x] < tiles.size()) // check tile validity
      draw(map[y * width + x]);

```

Note that checking the bounds repeatedly is generally poor form, and may be a big performance sink. In this example, it's likely better to check all the indices at the time the map is created (or whenever a map location is changed) so that it's guaranteed that its indices are always safe to use everywhere else.

While very atypical, you can also use the `.at()` member function to "safely" access a vector's elements at runtime. The `at()` member is just like `operator[]` but it will check the bounds automatically and throw a C++ exception if the index is illegal, which can be caught and handled by your code. This usage is uncommon, especially in games, due to the performance overhead of checking bounds along with the unpopularity of C++ exceptions in the game industry.

```
vector<int> example;
example.resize(10); // explicit size of 10

example[0] = 1;
example.at(0) = 1; // same as above

example[20] = 2; // ILLEGAL - will crash or corrupt memory!
try {
  example.at(20) = 2; // legal and safe - throws an exception
} catch (std::out_of_range e) {
  // handle out-of-bounds access here
}

```

See the cppreference documentation for vector for more information.

---
Tags: c++, sfml
---


# Question
Title: Fundamental Questions: Building vs Compiling vs Rendering vs Coding vs Running?
I'm using Urho3D on Raspberry Pi, but the following questions apply to all platforms.

What should I do in order to reduce the load of online real-time rendering of the game? Does building/compiling/rendering the game (before running it) makes it easier and lighter to be run afterwards?

When making animations with 3dsmax, we use high-end computers to design the animation and render it. After that, any low-end and simple computer can play the animation. Now can we use a similar approach? Can I build/compile/render the game in a high-end machine and run the game in a low-end machine?

What is exactly the difference between building/compiling/rendering when designing a game, and running/real-time-rendering when playing the game?

Does a game needs rendering when after designing? Or all the renderings all left to the playing time!?

# Answer
> What should I do in order to reduce the load of online real-time rendering of the game? Does building/compiling/rendering the game (before running it) makes it easier and lighter to be run afterwards?

Building/compiling are always required... or you would have no game to run!

> Does a game needs rendering when after designing? Or all the renderings all left to the playing time!?

You've confused pre-rendering with rendering. *Pre*-rendering generates images which are rendered (i.e. drawn to screen) at runtime. You always have to render at runtime or the player will see nothing!

For a pre-rendered 2D game, here is the process:

* (Produce model assets) Designer builds models, texture, setup materials, rig, animate etc.
* (Produce image assets) Designer pre-renders (NOTE: not the same as "renders", see end of this list) models from all desired angles & positions, and under all desired lighting conditions, to images/textures, according to designer/developer specs.
* (Produce code) Developer writes all code required to load & display images. This can be done in software or hardware-accelerated mode. Also all other game code is written / updated.
* (Build) Developer builds code, which includes tasks like code linting, generating files and directories, *compilation*, formatting of Max assets, and many others.
* (Run) loads images/textures (via software or hardware-accelerated renderer, underlying mechanisms may vary). (startup)
* (Run) advances the simulation and and updates all positions / animation frames. (repeats)
* (Run) renders what player must see this frame. (repeats)

Once you've run the game, if you don't like what you see, then you typically go back to design and coding, rebuild the game, then try again.

Some games, like the original Starcraft, Command & Conquer, or Diablo, used pre-renderings for the reason you mention - they are cheap to display at runtime. All the calculations needed to arrive at those pixels has already been done. Essentially, it's cached data that you just load and display. OTOH, true 3D games without pre-rendering can display any object in any orientation / lighting etc. at any time - but it must calculate a lot of factors before it can do that, and that is costly / may be slow. HTH.
> 2 votes

---
Tags: rendering, build-process
---


title: How can I optimize my flocking script?

text:
# Question
Title: How can I optimize my flocking script?
I have a flocking script for some ducks based on a youtube video I watched. The script works really well and I added my own basic obstacle avoidance system. However, performance is shocking! On average, every bird seems to take away 1 fps. That doesn't sound too bad but it scales really poorly. I have a 4km x 4km map, and I want a lot of birds. With no birds, I have about 130-140fps. With 100 birds, that drops to 40-50fps. I would really like to be able to increase the number of birds to at least 200 and still have around 100fps. I know my code isn't very well optimized but I just don't how to do that. Below is are my two flocking scripts. I know for a fact that it is these scripts because the profiler has the flock.update() at about 20-30%. Each bird also has a ragdoll system so the player can shoot them and they will fall out of the sky. This means that each bird has a rigidbody and collider on each joint. I've also added an LOD system so the birds are culled outside a certain distance. Could someone please take a quick look at them and see if I'm doing something particularly expensive that could be done better?

**GlobalFlock.cs**

```
public class GlobalFlock : MonoBehaviour
{
    [SerializeField]
    private GameObject birdPrefab;
    [SerializeField]
    private Transform parent;

    [SerializeField]
    private int tankSize = 200;
    private float yOffset = 10;

    private static int numBirds = 100;
    public static GameObject[] allBirds = new GameObject[numBirds];

    void Start()
    {
        for (int i = 0; i < numBirds; i++)
        {
            //creating a random position within a 'tank' to spawn each bird
            Vector3 pos = new Vector3(Random.Range(-tankSize, tankSize), Random.Range(yOffset, yOffset + 1), Random.Range(-tankSize, tankSize));

            //makes the tanks position reletive to this transform
            pos += transform.position;

            //instantiating birds and parenting them to an empty to reduce clutter in the heirachy
            allBirds[i] = (GameObject)Instantiate(birdPrefab, pos, Quaternion.Euler(0, Random.Range(-360, 360), 0));
            allBirds[i].transform.parent = parent;
        }
    }
}

```

**Flock.cs**

```
public class Flock : MonoBehaviour
{
    private float speed;
    private float startSpeed;
    private float rotationSpeed = 4.0f;
    private Vector3 averageHeading;
    private Vector3 averagePosition;
    private float neighbourDistance = 4.0f;
    private bool flee;
    private Vector3 fleePos;
    private float fleeDistance = 100.0f;
    private float fleeRotationSpeed = 6.0f;
    private Transform[] rayTransforms;
    private int layer = 16;
    private int layerMask;
    private Vector3 goalPos;
    private Vector3 childPos;

    [SerializeField]
    private float rayLength;

    [HideInInspector]
    public bool ragdoll;

    private States states;

    void Start()
    {
        speed = Random.Range(4, 6);
        startSpeed = speed;
        states = FindObjectOfType<States>();

        rayTransforms = transform.GetChild(1).GetComponentsInChildren<Transform>();

        childPos = transform.GetChild(1).position;

        layerMask = ~(1 << layer);
    }

    void Update()
    {
        if (!ragdoll)
        {
            //randomly changing the goal position 5 times out of 10000
            if (Random.Range(0, 10000) < 3)
            {
                goalPos = new Vector3(Random.Range(-2000, 2000),
                                      Random.Range(0, 200),
                                      Random.Range(-2000, 2000));
            }

            //scare the birds - flee
            if (states.shoot)
            {
                fleePos = states.transform.GetChild(0).position;

                if (Vector3.Distance(fleePos, this.transform.position) < fleeDistance)
                {
                    flee = true;
                }
            }
            else
            {
                if (Vector3.Distance(fleePos, this.transform.position) >= fleeDistance)
                {
                    flee = false;
                }
            }

            if (Random.Range(0, 5) < 1)
                ApplyRules();

            transform.Translate(0, 0, Time.deltaTime * speed);
        }
    }

    void ApplyRules()
    {
        GameObject[] gos;
        gos = GlobalFlock.allBirds;

        Vector3 vCenter = Vector3.zero;
        Vector3 vAvoid = Vector3.zero;
        float gSpeed = 0.1f;

        float dist = 0;

        int groupSize = 0;

        foreach (GameObject go in gos)
        {
            if (go != this.gameObject && go)
            {
                dist = Vector3.Distance(go.transform.position, this.transform.position);
                if (dist <= neighbourDistance)
                {
                    vCenter += go.transform.position;
                    groupSize++;

                    if (dist < 1.0f)
                    {
                        vAvoid += this.transform.position - go.transform.position;
                    }

                    Flock anotherFlock = go.GetComponent<Flock>();
                    gSpeed += anotherFlock.speed;
                }
            }
        }

        Ray lRay = new Ray(childPos, rayTransforms[1].forward * rayLength);
        Ray rRay = new Ray(childPos, rayTransforms[2].forward * rayLength);
        Ray uRay = new Ray(childPos, rayTransforms[3].forward * rayLength);
        Ray dRay = new Ray(childPos, rayTransforms[4].forward * rayLength);

        if (Physics.Raycast(dRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(-1, 0, 0);
        }
        else if (Physics.Raycast(uRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(1, 0, 0);
        }
        else if (Physics.Raycast(lRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(0, 1, 0);
        }
        else if (Physics.Raycast(rRay, rayLength, layerMask))
        {
            transform.localEulerAngles += new Vector3(0, -1, 0);
        }

        if (flee)
        {
            Vector3 newFleePos = new Vector3(fleePos.x, transform.position.y, fleePos.z);
            Vector3 direction = transform.position - newFleePos;

            speed = Mathf.Lerp(speed, 9.0f, Time.deltaTime * 2);

            transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * fleeRotationSpeed);
        }
        else
        {
            if (groupSize > 0)
            {
                vCenter = vCenter / groupSize + (goalPos - this.transform.position);
                speed = (speed == startSpeed) ? (gSpeed / groupSize) : Mathf.Lerp(speed, startSpeed, Time.deltaTime);

                Vector3 direction = (vCenter + vAvoid) - transform.position;

                if (direction != Vector3.zero)
                {
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * rotationSpeed);
                }
            }
            else
            {
                speed = Mathf.Lerp(speed, startSpeed, Time.deltaTime);

                Vector3 direction = goalPos - this.transform.position;

                if (direction != Vector3.zero)
                {
                    transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * rotationSpeed);
                }
            }
        }
    }
}

```

# Answer
I can't speak directly for your solution, but here are some general flocking performance tips that apply.

**Probably the biggest thing:**

For every duck, you're checking every other duck. This is a complexity problem as well as a duplication problem. If you moved these checks to a manager class, you could do half as many distance checks.

Think of it like this. The distance between ducks A-\>B is the same as the distance of ducks B-\>A. So save the distance somewhere and use it twice.

If you really want this to scale, look into spatial partitioning like Oct/quadtrees or a grid system. That way you only compare against objects that actually matter.

Also, do you need proper distance? Or can squared distance work? Right now you're doing n^2 square roots, which is a big time sink.

**More general stuff:**

Rather than constantly using transform.position and transform.rotation, use a Vector for pos and a Quat for rotation, then assign them once at the end of the update. Every assign to transform has additional overhead as it does other unnecessary calculations under the hood.

Are they raycasts for obstacle avoidance? If so, do you really need casts in any direction other than forward?

You should try to avoid Quaternion.Slerp. Try using something like Lerp instead. Not the huuuugest deal, but slerp requires a trig while lerp does not.

Not sure how you're handling the ragdoll, but it doesn't need to be on all the time. Have it disabled, then get enabled on death.

**Other options**

Try parallelism. If you want thousands of ducks you'll probably need to go to the gpu with compute shaders, but for something that scales decently well, if you create some worker threads to do all your math in parallel you can cut down on time.

Use a coroutine to separate your calculations over several frames. You don't need to update your flocking behavior every frame. 3-4 times a second should be fine. This means you can spread the performance cost over 20ish frames rather than one, this is a BIG improvement.
> 1 votes

# Answer
Zebraman already gave a great overview of the biggest wins you're likely to get.

In particular, the suggestion of using a manager class to update the whole flock will also save the engine overhead of calling each bird's Update() separately, which can become significant over hundreds of instances.

If you keep your live birds in a set order, then the manager won't need to check for null or self-interactions in its inner loop, the way your code does now with its `if (go != this.gameObject && go)`

A few other considerations to go along with what's already been said:

* You're storing a list of all bird `GameObjects`, then using `GetComponent<Flock>` O(n^2) times every frame to get at the components you need. Instead, store this as an array of `Flock` components so you can access them directly. Unity has optimized reaching from arbitrary components to the parent gameObject/transform, going the other way requires a search, which is pretty redundant.
* If your birds have a collider and rigidbody for processing hits, you may want to move them using velocity / impulses / forces / torques, rather than setting their transform position & rotation directly. When you do that, from the the physics engine's point of view the object has just teleported, and this can sometimes incur extra processing to make sure it hasn't jumped into a position intersecting other colliders. (In older versions of Unity, this caused noticeable performance hits for static colliders and large trigger colliders in particular)
* Rather than running your ApplyRules logic randomly (which could lead to performance spikes where occasionally many birds decide to raycast on the same frame because of bad die rolls), try time-slicing it. As your manager runs its tick, choose one block of the birds array to get their rules updated in this pass - then next frame, move onto the next block of birds. This saves random branching that can frustrate modern processor optimizations.

Now, you might find groups of birds all changing direction in synch doing it this way. If you keep your update budget similar to what you have now, where each bird gets an update every 5 frames, then this synchronization shouldn't be very noticeable. You can also blend the resulting rotation and speed changes over the following frames. Another trick is to make your update block size relatively prime with the length of your birds array - that way birds that update together once won't update together every time, making any synchronicity fleeting & more coincidental-looking.
> 0 votes

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


# Question
Title: Pygame array; keeping list items constant
I have an array in python(pygame):

```
Grid=[[0,0,0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,0,0]]

```

I have written a program that changes some of the values of the array to 1 if certain variables are true. How can I ensure that the first item and the last item in all 3 lists will always remain as 0?

# Answer
> 2 votes
```
def ensureZeros(grid):
    for row in grid:
        row[0] = row[-1] = 0

```

You just need a function that sets the first and last item of each row to zero. Call this whenever you need to ensure that there are zeros in the correct places.

---
Tags: python
---


title: Damage indicator move in an arc

text:
# Question
Title: Damage indicator move in an arc
I'm trying to imitate the damage indicator in Ragnarok online (moving in an arc): sample here. But I can only do this

I have this code below. I'm not sure how to make it go faster. If I do `pos.y += 2 * yOffset;`, it will just go higher.

```
public void update(float delta) {
    if(xOffset < Math.PI) {
        xOffset += delta;
        pos.x += xOffset;
    }
    if(xOffset >= Math.PI) {
        xOffset = Math.PI;
    }
    yOffset = (float)(3 * -Math.sin(2*xOffset));
    if(xOffset < Math.PI) {
        pos.y += yOffset;
    }
}

```

# Answer
You probably want "gravity physics" instead of a sine wave. So you'll need to give your damage indicator a velocity and an acceleration. The acceleration is what creates the nice curved parabola path for your object.

```
public void update(float delta)
{
    speed += <your_gravity_strength>;

    pos.x += delta;
    pos.y += speed;
}

```

Now, when you create your damage indicator, set `speed` to something negative, so that the text moves up for a while first. The gravity number will then start to slow the movement up until the text starts actually moving down. You probably don't want to make either value too large (the initial speed nor the gravity), but try out some values and see what you like.
> 1 votes

---
Tags: movement, gui
---


# Question
Title: How can I create the water-like blur effect in Chameleon Run using SpriteKit and Unity?
As the character in Chameleon Run runs, a water-like blur effect is created. I would really appreciate some guidelines on how I could create this effect in SpriteKit and Unity. Please see the image below.

# Answer
> 4 votes
It looks to me like this could be done with a TrailRenderer. This leaves a ribbon of 3D geometry behind a moving object, onto which we can assign a material to control the way it renders.

We can use a custom shader incorporating a GrabPass to take a snapshot of the frame buffer, sampling it with a distortion offset, to get a refractive watery look:

```
Shader "Unlit/DistortionTrail"
{
    Properties
    {
        _Intensity ("Intensity", Range(-1, 1)) = 1
    }
    SubShader
    {
        Tags { "RenderType"="Transparent" "Queue"="Transparent"}
        LOD 100

        GrabPass {"_Refract"}

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag

            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float2 uv : TEXCOORD0;
                float4 projected : TEXCOORD1;
                float4 vertex : SV_POSITION;
            };

            sampler2D _Refract;
            float2 _Refract_TexelSize;

            float _Intensity;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                o.projected = o.vertex;

            // Some video settings flip the captured image - flip it back.
            #if UNITY_UV_STARTS_AT_TOP
                o.projected.y *= sign(_Refract_TexelSize.y);
            #endif

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                // Convert interpolated vertex position in device coordinates
                // into a texture coordinate in the range 0...1
                float2 screenUV = (i.projected.xy / i.projected.w) * 0.5f + 0.5f;

                // Ripple the distortion across the width of the trail.
                // (squaring y makes the ripples look a bit less rigid/uniform)
                float distortion = sin(i.uv.y * i.uv.y * 3.141592653589f * 5.0f);

                // Fade the distortion along the length of the trail.
                distortion *= 1.0f - i.uv.x;

                // Control max distortion using material parameter.
                distortion *= _Intensity;

                // Offset our lookup coordinates using the distortion.
                screenUV += distortion * float2(0.5, 1);

                // Sample the captured snapshot of the frame.
                fixed4 col = tex2D(_Refract, screenUV);

                return col;
            }
            ENDCG
        }
    }
}

```

Here's an example of this in motion:

---
Tags: unity, spritekit, swift, effects, blur
---


title: Slowmotion except main player?

text:
# Question
Title: Slowmotion except main player?
My script works fine except I don't know how to not let the slow-motion affect the main player.

```
public GameObject player;

void  Update () {
    if (Input.GetKeyDown(KeyCode.A)) {
        Time.timeScale = 0.5;
        Time.fixedDeltaTime = 0.02F * Time.timeScale;
    }

    if (Input.GetKeyDown(KeyCode.Z)) {
        Time.timeScale = 1.0f;
    }
}

```

# Answer
Not so experienced with Unity, but i'm pretty sure you can revert that `timeScale` effect by multiplying the `deltaTime` with the `timeScale` whenever you need it. For example:

```
// In a player movement update function
transform.Translate(Vector3.forward * Time.deltaTime / Time.timeScale);

```
> 1 votes

# Answer
You could slow down everything and speed up the player instead. If your game is multiplayer and you need to use this feature there, I suggest that you tie your calculations into `Time.deltaTime` along with a `float scale` variable so that you can "speed up" or "slow down" anything that you need to.

For example (untested code, but the logic should work if you try different stuff):

```
Time.timeScale = 0.5f; //change this to scale your game speed
playerActionScale = 2f; //change this to account for player action speed

if(Input.GetKeyDown(KeyCode.Left))
{
 player.transform.Rotate(angle * Time.deltaTime * playerActionScale);
}

```

If you're planning on using this sort of time scaling too much, I really do recommend designing your game logic around that feature.
> 1 votes

---
Tags: unity
---


# Question
Title: glsl directional light specular seems to be relative to origin not camera
I've been using the LearnOpenGL tutorials to calculate directional light. The diffuse works perfectly fine but the specular seems only work properly when the camera is near the origin and the specular is applied the same to all objects.

When I look at the second to last object i expect the specular to be the same as the object around the origin but instead it seems reacts to the origin and not the camera.

My guess is it's something to do with converting something to model space instead of camera space but as i'm new to glsl i'm lost as to where to look first.

Vertex shader:

```
#version 330 core

layout (location = 0) in vec3 vertexPosition;
layout (location = 1) in vec2 vertexUV;
layout (location = 2) in vec3 vertexNormal;

out vec3 VectorWorldPosition;
out vec2 UV;
out vec3 Normal_cameraspace;

uniform mat4 MVP;
uniform mat4 V;
uniform mat4 M;

void main()
{
    gl_Position = MVP * vec4(vertexPosition, 1.0f);

    VectorWorldPosition = (M * vec4(vertexPosition, 1.0f)).xyz;

    Normal_cameraspace = vertexNormal;//(M*V* vec4(vertexNormal, 1.0f)).xyz;

    UV = vertexUV;
}

```

Fragment Shader:

```
#version 330 core

in vec3 vertexWorldPosition;
in vec2 UV;
in vec3 Normal_cameraspace;

out vec4 color;

struct DirectionalLight{
    vec3 position;
    vec3 ambient;
    vec3 diffuse;
    vec3 specular;
};

struct Material{
    sampler2D diffuse;
    sampler2D specular;
    float shininess;
};

uniform DirectionalLight dirLight;
uniform Material material;

uniform vec3 viewPos;

vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir);

void main()
{
    vec3 output = vec3(0.0f);

    vec3 norm = normalize(Normal_cameraspace);

    vec3 viewDir = normalize(viewPos - vertexWorldPosition);

    output += CalcDirectionalLight(dirLight, norm, viewDir);

    color = vec4(output, 1.0f);
}

vec3 CalcDirectionalLight(DirectionalLight light, vec3 normal, vec3 viewDir)
{
    vec3 lightDirection = normalize(light.position);

    float diff = clamp(dot(normal, lightDirection), 0.0, 1.0);

    vec3 reflectDir = reflect(-lightDirection, normal);

    float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess);

    vec3 ambient = light.ambient * vec3(texture(material.diffuse, UV));
    vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, UV));
    vec3 specular = light.specular * spec * vec3(texture(material.specular, UV));

    return (ambient + diffuse + specular);
}

```

I'm using light position here when the tutorial asks to use direction. My thinking is that relative to the origin, position will be equal to direction. This works fine for diffuse so it should it work for specular.

# Answer
> 2 votes
You need to make sure that all your lighting calculations are done in the same space. Assuming your VertexNormal input is in model space, you can't just output it and call it 'Normal\_CameraSpace'.

Decide where all your maths will be done. If it's in 'World' Space, then you need your normals to be transformed by the Inverse Transpose of the world matrix. Or the IT of the WorldView matrix if in camera space.

Your light vector needs to be transformed to the same space too.

And if you are calculating a vector to the viewer, then you need the world space location of your camera.
If you are in view/camera space, then your camera is always at the origin.

And of course, you need to transform the vertex position to the same space as well. I find it easier to think in 'WorldSpace'. You might want to start there...

```
Vertex Shader:
// World space position
vec4 world_pos = M * vec4(in_position, 1.0);

// perspective transformed position
gl_Position = MVP * vec4(in_position, 1.0);

// Matrix for transforming normals
mat4 invtransmodel =  transpose(inverse(M));

world_normal = normalize((invtransmodel * vec4(in_normal, 0.0)).xyz);

```

---
Tags: opengl, 3d, shaders, glsl, lighting
---


title: Sticking to a moving platform

text:
# Question
Title: Sticking to a moving platform
My character is not sticking on the platform when jumping on it, but I don't know why. I checked, and I have rigidbodys and colliders. The problem appeared when I moved the game to another hard drive.

Here is mycode:

```
void OnCollisionEnter2D(Collision2D other)
{
    if (other.transform.tag == "MovingPlatform")
    {
        transform.parent = other.transform;
    }
}

void OnCollisionExit2D(Collision2D other)
{
    if (other.transform.tag == "MovingPlatform")
    {
        transform.parent = null;
    }
}

```

Why doesn't my character stick to the platform?

# Answer
I'm going to assume that both objects have a ridgidbody attached to them.

```
void OnCollisionStay2D(Collision2D other)
{
    if (other.transform.tag == "MovingPlatform")
    {
        GetComponent<RigidBody>().velocity
                = other.gameObject.GetComponent<RigidBody>().velocity;
    }
}

```

This should make the character stick to the platform. You might want to save each ridgidbody in the `OnCollisionEnter` method and then call them in the `Update` method, to get a bit more efficiency out of it, so that you can also move off the platform by adding velocity along the Y-axis.
> 1 votes

# Answer
> The problem appeared when I moved the game to another hard drive.

Well there is your problem right there. I have noticed that unity tend to loose the custom tag definitions when moving the game. Especially if you use packages for that. Check if your tags are defined.
> 0 votes

# Answer
From the poor information you shared, the only thing that comes up to my mind is that you are using a Rigidbody instead of a Rigidbody2D.
> -2 votes

---
Tags: unity, c#, 2d, moving-platforms
---


title: Unity 5 skybox reflection on terrain

text:
# Question
Title: Unity 5 skybox reflection on terrain
I begin to use Unity 5. I added a terrain and a skybox in my game but there is always reflection of sky on my terrain. As you see in the picture.
I added texture to solve the problem. But the reflection of skybox is always there.
Why terrain is too shiny and like mirror in Unity 5?
Am I missing something?
Thanks in advance...

# Answer
The reason why terrain is too shiny is because of default terrain material.
By default terrain material is `Built in Standart` and this material is too shiny and smooth.When we change this option to other option. It resolve the problem.
In my case i change to `Built in Legacy Diffuse` it solved my problem.
> 0 votes

---
Tags: unity, terrain, terrain-rendering
---


title: Coroutine problem(I think)

text:
# Question
Title: Coroutine problem(I think)
I've developed a loading system that uses coroutines. When I load up the game and hit 'new' or 'continue' game works fine and it loads up the game just as it should. However, when I go back to the menu none of them work. It doesn't seem like the coroutine gets past the yield return new WaitForSeconds(1). I honestly don't understand why this is happening and I can't seem to find any information to help me.

Here's the code I have:

```
    private IEnumerator LoadLevel() {
    yield return new WaitForSeconds(1);//doesn't get past here when i try to reload

    ao = SceneManager.LoadSceneAsync(PlayerPrefs.GetInt("CurrentSceneToLoad"));
    ao.allowSceneActivation = false;

    while (!ao.isDone) {
        RadialLoad.fillAmount = ao.progress;
        if (ao.progress == 0.9f) {
            RadialLoad.fillAmount = 1;

            loadingText.text = "Press any key to continue...";

            if (Input.anyKey) {
                ao.allowSceneActivation = true;
            }
        }
        PlayerPrefs.DeleteKey("CurrentSceneToLoad");
        yield return null;
    }
}

```

That's all of the relevant code basically the sequence of events is:

I start the game and then I load into the first level and everything works as expected. When I go back to the menu. Using the same code as above and then try to load into the first level again it no longer gets past the the first return waitforseconds.

Thanks in advance.

# Answer
> 0 votes
I forgot to set Time.TimeScale back to 1 after I set it to 0 to pause the game whilst in the menu.

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


title: Throw ball - distance and force

text:
# Question
Title: Throw ball - distance and force
I have a question, I need a formula to calculate the distance and a force based on the speed that drags the finger up on the phone. And is there any way I can get a look? And also shows the trajectory of the ball with lines ...

An example is the Pokemon Go, see the image (the user presses the ball and drags the finger upwards).

Are there any examples so that I can study?

# Answer
This can be done by measuring the distance between the touch and release point. Along with measuring the time difference from when the touch started until the release happened.

Then simply take the distance and divide it with the time, and this would give you a relative force.

To give the general idea:

```
clock = new THREE.Clock();

function onTouch(event) {
    startTime = clock.getElapsedTime();
    startPosition = new THREE.Vector3(e.clientX, "y": e.clientY);
}

function onRelease() {
    endTime = clock.getElapsedTime();
    endPosition = new THREE.Vector3(e.clientX, "y": e.clientY);

    diff = startPosition.copy().sub(endPosition.x);
    distance = diff.length();

    // Remember to check if endTime > startTime
    force = distance / (endTime - startTime);

    // Then multiply the force by some factor and apply it
}

```

*`onTouch()` being called when the touch begins and `onRelease()` begin called when it ends.*

Since you already have the touch and release points, you can calculate the angle of the flick. Then project that according to some other vector you have deciding the orientation of the phone in this case.

For getting the trajectory of the path you apply force to an object and simulate it for a n steps tracking the position. After that draw a line between the collected positions.

For an existing project take a look at ezartech/pokemon-go-experiment.
> 1 votes

---
Tags: javascript, html-canvas, node.js, three.js
---


title: OpenGL 3.3 texture rendering all black

text:
# Question
Title: OpenGL 3.3 texture rendering all black
Geometry is rendering fine and works with attribute colors so I've definitely got something wrong with my texture loading / usage code. I've been following along with the tutorials at learnopengl.com as best I can. The code below is in Kotlin, so despite the funky syntax all the objects are standard Java objects. (While it should hopefully be easy enough to follow I've added some additional comments to the less obvious stuff.)

Initialisation:

```
glClearColor(1f, 0f, 0f, 1f)

// these will be overridden further on. (var is mutable, val is not)
var vao = -1
var vbo = -1
var ebo = -1
var texture = -1
var shaderProgram = -1

{ // Set up the geometry. A simple quad.
  val vertexBuffer = BufferUtils.createFloatBuffer(4 * 8) // 4 vertices of 8 floats.
  //                            position            color         uv
  vertexBuffer.put(floatArrayOf(-0.5f, -0.5f, 0f,   1f, 0f, 0f,   0f, 0f))
  vertexBuffer.put(floatArrayOf( 0.5f, -0.5f, 0f,   0f, 1f, 0f,   1f, 0f))
  vertexBuffer.put(floatArrayOf( 0.5f,  0.5f, 0f,   0f, 0f, 1f,   1f, 1f))
  vertexBuffer.put(floatArrayOf(-0.5f,  0.5f, 0f,   1f, 1f, 1f,   0f, 1f))
  vertexBuffer.flip()

  val indexBuffer = BufferUtils.createIntBuffer(3 * 2)
  indexBuffer.put(intArrayOf(0, 1, 2))
  indexBuffer.put(intArrayOf(2, 3, 0))
  indexBuffer.flip()

  vao = glGenVertexArrays()
  vbo = glGenBuffers()
  ebo = glGenBuffers()

  glBindVertexArray(vao)

  glBindBuffer(GL_ARRAY_BUFFER, vbo)
  glBufferData(GL_ARRAY_BUFFER, vertexBuffer, GL_STATIC_DRAW)

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, indexBuffer, GL_STATIC_DRAW)

  glVertexAttribPointer(0, 3, GL_FLOAT, false, 8 * 4, 0)
  glEnableVertexAttribArray(0)

  glVertexAttribPointer(1, 3, GL_FLOAT, false, 8 * 4, 3 * 4)
  glEnableVertexAttribArray(1)

  glVertexAttribPointer(2, 2, GL_FLOAT, false, 8 * 4, 6 * 4)
  glEnableVertexAttribArray(2)

  glBindVertexArray(0)
}

{ // load the texture
  val image = ImageIO.read(File("test_image.png"))
  val pixels = IntArray(image.width * image.height) //image.width corresponds to image.getWidth() in Java, same for height.
  image.getRGB(0, 0, image.width, image.height, pixels, 0, image.width)

  val buffer = BufferUtils.createByteBuffer(image.width * image.height * 4)

  var y = 0
  var x = 0
  while (y < image.height) {
    while (x < image.width) {
      val pixel = pixels[y * image.width + x]
      buffer.put(((pixel shr 16) and 0xFF).toByte()) // "shr" and "and" are the usual ">>" and "&" bitwise operators.
      buffer.put(((pixel shr 8) and 0xFF).toByte())
      buffer.put((pixel and 0xFF).toByte())
      buffer.put(((pixel shr 24) and 0xFF).toByte())
      x++
    }
    x = 0
    y++
  }
  buffer.flip()

  texture = glGenTextures()
  glBindTexture(GL_TEXTURE_2D, texture)
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer)
  glBindTexture(GL_TEXTURE_2D, 0)
}

{ // set up the shader
  val vertexSource = """
  #version 330 core

  layout (location = 0) in vec3 position;
  layout (location = 1) in vec3 color;
  layout (location = 2) in vec2 uv;

  out vec3 vColor;
  out vec2 vUv;

  void main() {
    vColor = color;
    vUv = uv;
    gl_Position = vec4(position, 1.0);
  }
  """
  val vertexShader = glCreateShader(GL_VERTEX_SHADER)
  glShaderSource(vertexShader, vertexSource)
  glCompileShader(vertexShader)

  val fragmentSource = """
  #version 330 core
  precision highp float;

  in vec3 vColor;
  in vec2 vUv;

  out vec4 color;

  uniform sampler2D texSampler;

  void main(){
    color = texture(texSampler, vUv);
    // color = vec4(vColor, 1.0);
  }
  """

  val shader = glCreateShader(GL_FRAGMENT_SHADER)
  glShaderSource(fragmentShader, fragmentSource)
  glCompileShader(fragmentShader)

  shaderProgram = glCreateProgram()
  glAttachShader(shaderProgram, vertexShader)
  glAttachShader(shaderProgram, fragmentShader)
  glLinkProgram(shaderProgram)

  glDeleteShader(vertexShader)
  glDeleteShader(fragmentShader)
}

```

Then when rendering:

```
glClear(GL_COLOR_BUFFER_BIT)

glUseProgram(shader)
glBindTexture(GL_TEXTURE_2D, texture)

glBindVertexArray(vao)
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0)
glBindVertexArray(0)

```

If the commented line in the fragment shader is swapped in it renders the colored quad as expected, but it just renders black when trying to use the texture. Stepping through the code in the debugger shows that the pixel colors being added to the texture buffer are colored as expected.

I've also got additional error checking in the shader loading and in the main loop, but as far as I can see OpenGL isn't showing any errors.

# Answer
> 1 votes
Figured it out. It seems the default min filter is not set to GL\_LINEAR as I had thought. If I do the following everything works as expected.

```
texture = glGenTextures()
glBindTexture(GL_TEXTURE_2D, texture)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer)
glBindTexture(GL_TEXTURE_2D, 0)

```

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


# Question
Title: How do I tell the difference between tapping and holding the touchscreen?
I have a problem with the Unity game engine. I am making an Android game. I want to move an object by a small distance every time the user taps the screen, but not when the user holds the screen.

This is my current code. When the user holds the screen, the object keeps moving. I want to only move the object once the user touches the screen and not move it again until they released it:

```
void Update () {
        if (Input.touchCount > 0) {
            transform.position = new Vector2(transform.position.x, transform.position.y+0.1f);
        }

```

# Answer
Why not use touch phase that is built into unity via the Touch class?

```
void Update () {
    foreach (Touch finger in Input.touches)
    {
        if (finger.phase == TouchPhase.Began)
        {
            transform.position = new Vector2(transform.position.x, transform.position.y+0.1f);
        }
    }
}

```

This will check if the a finger has been detected and will move the object in the same way as the original code did, except the finger must have just been detected on the screen. If it is held the Touch Phase will change from Begin to either `Moved` or `Stationary`.

You might also want to look at tap count if you need to check if the user is repeatedly tapping on screen.

Hope this helps
> 2 votes

---
Tags: unity, android, touch
---


# Question
Title: Is it okay to copy a game's formula? (damage, etc)
Is it okay to copy a game's formula? Formulas like damage formulas, taking the stats STR, DEX, INT, critical rate, etc. into account. Specifically I want to copy Ragnarok Online's damage calculation. But I will probably remove some stuff from the formula to reduce the scope of my game.

---

> Your question has been identified as a possible duplicate of another question.

I think game formulas and the like are different from game mechanics. Game mechanics is how the game is played.

# Answer
Yes, that is legal.

Caveat:

* You may not steal their code, but you are allowed to reproduce what the code does. The code is allowed to end up looking the same, if you can reasonably claim that is wasn't a copy-paste job. See Google vs Oracle.
* Advertising your game as "using Ragnarok Online's damage formula" can be interpreted as an implied endorsement by, or co-development with, Ragnarok's developers. They can sue you to remove this claim.
* If they patented any parts of their application, you're liable for license fees on their terms. Even if their patent is fraudulent and should never have been granted, getting a judge to say so is more expensive than paying the license fees. Their design elements might also be patented by someone else, who can then ask you for license fees.
* They can sue you without having a valid legal case.
> 9 votes

# Answer
Under normal circumstances, so long as you don't steal their actual game code (i.e. reverse engineer stuff or hack the game's files to get the code) you should be fine. Also, seeing as how this is a community-run wiki, it should be fine to use whatever is inside (unless otherwise specified in the wiki), but being careful is never bad.

This is what's written down on the site (including your page):

> Content is available under GNU Free Documentation License 1.3 or later unless otherwise noted.

You can find detailed info about it here and a short explanation here. It basically means you're free to use it however you like.
> 1 votes

---
Tags: rpg, copyright, mathematics
---


# Question
Title: Are these all possible mobile devices resolutions?
In `Unity`, there's a switch where you can set your desired resolution and check if the game looks ok:

If I target the app for portait only - do I have to worry only about these here, marked as 'portrait', or list the possible aspect ratios from somewhere else?

# Answer
Currently there are 5 common aspect ratio types:

* 4:3 (Probably only the IPad)
* 3:2 (Iphone 1-4, it's getting obsolete)
* 5:3 (This is getting obsolete)
* 16:10 (Mostly tablets)
* 16:9 (Iphone 5-7 and newer android phones)

Some of the options in unity are "duplicates", for instance the 320\*480 resolution is just a 2:3 resolution
> 1 votes

---
Tags: unity, mobile, resolution
---


title: JavaScript movement of player

text:
# Question
Title: JavaScript movement of player
Okay so I am quite new, I've got the player to move using up, down, right, and left. But what I am trying to do is make the character move with a left click.

```
var Player = function(id){
    var self = {
        x:250,
        y:250,
        id:id,
        number:"" + Math.floor(10 * Math.random()),
        pressingRight:false,
        pressingLeft:false,
        pressingUp:false,
        pressingDown:false,
        maxSpd:10,
    }
    self.updatePosition = function(){
        if(self.pressingRight)
            self.x += self.maxSpd;
        if(self.pressingLeft)
            self.x -= self.maxSpd;
        if(self.pressingUp)
            self.y -= self.maxSpd;
        if(self.pressingDown)
            self.y += self.maxSpd;
    }
    return self;
}

```

That's what I have for the up, down, left, right movement. I've seen a few documents stating the click but just can't seem to implement it into the file.

# Answer
To do that, you'll have to look into AI pathfinding. "Hold up," you say, "I don't even have any enemies yet! How can I need AI?".

Once you start talking about "go where I click" then you have to deal with a great deal more than is immediately obvious: obstacle avoidance, finding out whether there even is a path (imagine you're between 4 walls), best path etc. for your player to actually be able to get where you click. After all, you're not just moving as the crow flies... are you?

I suggest starting with basic A\* pathfinding (note: there are many, many sources of info on this around the web). You can also try hill-climbing which in some ways is a little simpler to get working - depending on how simple your game is / how many enemies are involved. The good news is you will then have the ability to get your enemies to also go wherever you want them.
> 2 votes

---
Tags: javascript
---