# Question
Title: Is this a suitable "pathfinding" algorithm for a tower defense game?
Note: I put "pathfinding" in quotes because I'm not sure if it's the proper term for this.

My goal is to create a 2D tower defense game with HTML5/JavaScript. It's mostly for learning purposes, so I'm trying to come up with solutions myself before looking how others did it.

One of my first questions was: How do I get enemies to follow a path? After thinking about it for a while, I came up with an idea which I think might be a bit counter-intuitive. It appears to work perfectly in testing, but I'm not sure if I should do it this way because I couldn't find any similar examples. Although that may just be because I'm not sure how to search for it.

The general idea works like this:

* The map has a path, which the enemies follow. The path is an array of waypoints (each with X and Y coordinates) which are implicitly connected in sequence by straight lines. So the length of the path can be measured by adding the distances between consecutive waypoints.
* Each enemy's position is represented by a single number, which refers to how far they are on the path (i.e. their progress). There's also a field for their two-dimensional position on the map (needed for rendering), which is initially empty.
* Every frame, the algorithm recalculates and updates each enemy's 2D-position. This is done by taking its 1D-position, checking which waypoint was the last one the enemy passed, and then calculatig the correct position between that waypoint and the next (even if they're at an angle).

The reason I like this idea is that each number between 0 and the length of the path corresponds exactly to one single point on the path. That way it should be impossible for objects to glitch out of bounds or be rendered at the wrong place. It also makes finding the first or last enemy in a given range a trivial task.

My main concern so far is performance. Running this calculation for each enemy on every frame seems rather time-consuming, especially if the map gets filled with enemies, towers and projectiles later on. **Are there any other problems with this approach?**

In case my description doesn't tell you enough, here's what my code looks like:

```
posOnMap(pos) {
    if (typeof pos !== 'number') throw TypeError('pos is NaN');
    if (pos < 0) return new V2(map.path[0].x, map.path[0].y);
    if (pos >= map.pathLength) return new V2(map.path[map.path.length - 1].x, map.path[map.path.length - 1].y);

    var last, next, offset, len = 0;
    for (var i = 0; i < map.path.length - 1; i++) {
        offset = len;
        len += V2.distance(map.path[i], map.path[i + 1]);
        if (len > pos) {
            last = map.path[i];
            next = map.path[i + 1];
            break;
        }
    }
    var posRel = pos - offset;
    var dist = V2.distance(last, next);
    var fraction = posRel / dist;
    return new V2(last.x + (next.x - last.x) * fraction, last.y + (next.y - last.y) * fraction);
}

```

`map.path` is the path array, as described above. So `map.path.length` is the total number of waypoints, while `map.pathLength` is the length of the path in in-game units.

# Answer
> 2 votes
Like some have said, you should test it.

Realize that you'll likely be looping over all your enemies and doing multiple more complicated calculations for other aspects of the game, and until this starts causing you trouble, don't prematurely optimize it.

That being said, if you find that you have so many enemies that making this seemingly similar calculation takes too long, you can think about precomputing all of the positions along your paths ahead of time and then map each enemy to the precomputed locations each frame instead (assuming all your paths stay the same for the duration of a level). The trade off here is space vs speed. If you do the calculation for all paths earlier in the game, you can then use a simpler function that only does a lookup based on some key. Your mapping function would do some kind of array or map lookup.

---
Tags: 2d, javascript, algorithm, path-finding, tower-defense
---


# Question
Title: Not allowing me to show ads because of errors in the console
A few days ago my ads in my game were working perfectly then suddenly out of nowhere they stopped working. I think it has something to do with unity not importing the ads extension into my game. I tried turning off the built in extension and getting the sdk from the asset store manually the errors went away but the ads would not show up. I don't know whats wrong I have everything set up my build settings is set to android and my ads are turned on I don't know why it's behaving like this

Here is my code:

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

public class Ads : Money {

  void Update()
    {
        Advertisement.Initialize("1424659");
    }

    public void ShowRewardedAd()
    {
        if (Advertisement.IsReady("rewardedVideo"))
        {
            var options = new ShowOptions { resultCallback = HandleShowResult };
            Advertisement.Show("rewardedVideo", options);
        }
    }

    private void HandleShowResult(ShowResult result)
    {
        switch (result)
        {
            case ShowResult.Finished:
                money = money + 90;
                PlayerPrefs.GetInt("money", money);
                PlayerPrefs.SetInt("money", money);
                Debug.Log("The ad was successfully shown.");
                break;
            case ShowResult.Skipped:
                Debug.Log("The ad was skipped before reaching the end.");
                break;
            case ShowResult.Failed:
                Debug.LogError("The ad failed to be shown.");
                break;
        }
    }
}

```

As you can see I basically copied this from the unity code samples section and modified it a little to fit my needs.

Here are the errors:

> Assets/Ads.cs(4,19): error CS0234: The type or namespace name Advertisements' does not exist in the namespaceUnityEngine'. Are you missing an assembly reference?
>
> Assets/Ads.cs(24,35): error CS0246: The type or namespace name \`ShowResult' could not be found. Are you missing an assembly reference?

# Answer
> 1 votes
Let's take a look at the first error message:

> Assets/Ads.cs(4,19): error CS0234: The type or namespace name Advertisements' does not exist in the namespace UnityEngine'. Are you missing an assembly reference?

The compiler is saying that it can't find UnityEngine.Advertisements. This means you don't have ads enabled. To enable ads, as of Unity 5.2, you should use the Unity Service Window and **not** the Asset Store package. Before you can use Unity Services, you need to get a Unity Services Project ID.

From the Unity documentation for Unity Services:

> To get started with Unity’s family of services, you must first link your project to a Unity Services Project ID.
>
> \[...\]
>
> Go to Window \> Unity Services, or click the cloud button in the toolbar.
>
> \[...\]
>
> Select your organization and click Create.

Your project now has a special ID it can use to talk to Unity servers and ask for advertisements. Now you can enable Unity Ads. From the documentation for Unity Ads:

> 1. Open the Ads configuration window from Window \> Services \> Ads.
> 2. Click the switch on the right-hand side to turn Ads on, then answer a few questions about the game you are making.

At this point, the compiler should stop showing errors, and your code should run just fine.

---
Tags: unity, unity-ads
---


# Question
Title: Does cube map texturing works only for objects which vertices are is in [-1,1] range?
Im attempting to texture an .obj file that is not a skybox. So the question is, every tutorial about cubemap creates their hardcoded cubes with vertices ranging from \[-1, 1\]. Probably not, but is it necessary to scale my .obj model to be in that range?

Also, to map my fragments with the right texel - I saw people online telling that I should take a point `p` then subtract it with the model center `c` in the shader. Some said that I should normalize them? `normalize(p - c)` I hope you can help me deliver a brief explanation.

# Answer
> 1 votes
# Do the vertices need to be in the \[-1,1\] range?

No. This is only done to improve readability of the code. As long as the model you're using is a cube, and the vertices are all outside the near clip plane of the projection, everything will be fine.\*

# Do I need to use `p-c`?

No. The **direction** of the vertex, which is what you use to do the texture lookup, is just the position of the vertex relative to the origin of the model, which is the model space position of the vertex. So to do the texture lookup you can just pass the model space position straight through the vertex shader without any changes directly into the fragment shader, and use the code `texture(MY_TEXTURE,MODELSPACE_VERTEX_POSITION);`

## What about `normalize()`?

From the OpenGL wiki (emphasis mine):

> The texture coordinates for cubemaps are 3D vector directions. These are conceptually directions from the center of the cube to the texel you want to appear. **The vectors do not have to be normalized**.

So you don't need to use `normalize()` either, as OpenGL will automatically use a normalized version of the lookup vector when you use `texture()`

# TL;DR

The vertices of the model don't need to be in the \[-1,1\] range, `p-c` is equal to the model space vertex position, and you don't need to `normalize()`.

---
Tags: opengl, c++, cubemap, vertex-shader
---


title: Understanding pixel art in Unity 2d

text:
# Question
Title: Understanding pixel art in Unity 2d
I am struggling to understand the basics behind pixel art in Unity.

I understand what a unit is, and that if I draw my sprite with 16x16 pixels, I should set PPU to 16.

Take stardew valley for example, in the image below you can clearly see that the player is not square. The creator of the game said he made everything in 16x16, but then how is there so much detail in the characters? Surely you do not patch several 16x16 squares together to make a character (as you would with a tilemap)?

What is the "common" way of dealing with things that are not square, like the characters in the image. Do you just make 16x32 sprite and set PPU to 16? Wont that make it look a bit weird next to 16x16 sprites? Do you generally pick one size (i.e 16, 32, 64) And then stick to that for everything in the game?

The visual Issue I've seen is this, where a 32x32 sprite looks very out of place (too sharp) next to a 16x16 sprite.

So I am wondering, how do you mix sizes wihout getting this effect where one image looks much sharper than the other. If I for example wanted a character to be 16x32, or any non-square value, when my tiles are 16x16

# Answer
Summarizing the points above, what matters for two pieces of pixel art to match is that their pixel density (texels per screen area / world unit) is the same.

Using some sprites from Stardew Valley as an example, we can see that even though the sprites have different texture dimensions, they match up on a consistent grid because each pixel is drawn the same size.

If we think of the size of the plant as one tile / one unit of world space, we can see this unit spans 16 pixels horizontally and vertically. The character, having twice the height of the plant, also covers twice the number of tiles / world units, so the density of pixels stays the same at 16 pixels per world unit.

For Unity specifically, it exposes this for you as a **Pixels Per Unit** setting in the Sprite import settings inspector. As long as you use one consistent number here for all of your sprites, Unity will automatically handle drawing them at the right size in your world to keep this pixel density — even if they're odd sizes and not power-of-two or exact multiples of your tile size. So in this example, both the shrub and the character, and everything else in the game would use a PPU OF 16.

The exact number you choose isn't a big deal, it's consistency that matters most. If we wanted each tile to span 2 world units, so that when level editing we can easily snap to tile corners (odd numbers) and tile centers (even numbers), then we'd use a PPU of 8 instead for all our sprites.

Just don't turn it down *too* low. You'll see some articles out there recommending a PPU setting of 1, meaning a 256-pixel sprite will span 256 world units. While this might not sound alarming, systems like physics are tuned assuming most of your gameplay will be happening on scales of tenths to tens of units, and making your scale too large can cause them to behave poorly. Try to choose a number of pixels that's meaningful in your gameplay, like the width of your character or your tile. This will also make your math easier for programming & level design (eg. "I want this character to dash 3 tiles right, so that's `x + 3.0f`")

Note that scaling a sprite, UI image, or its parents using transform properties will distort them away from this consistent pixel density, so be very careful with scale properties, and keep most or all of your scene at a scale of 1.0 for simplicity.

One last caution is that none of this determines how big your sprites actually end up on your screen - that's determined by the size of your game window / screen, and the size/FoV/angle of your camera. For pixel perfect 2D, you'll also need to ensure that the height of your window is a whole-number multiple of the number of sprite pixels your camera sees (orthographic height of camera x 2 x PPU)
> 20 votes

---
Tags: unity, 2d, resolution, pixel-art
---


# Question
Title: How to smooth viewport panning when using minimap (in typical RTS)?
Let's take typical modern RTS game which features a large map (say 256x256 tiles). There's also a minimap in the GUI, typically up to 256x256 pixels in size. *(Let's take these numbers for upcoming example)*

We can move viewport with very high accuracy and precision using scrolling (WASD or by screen edges) or dragging (e.g. with middle mouse button), e.g. as precise as 0.001 tile (when zoomed in). However, when viewport is being moved using minimap, this means that for each 1px move of our cursor in GUI we need to move the viewport by exactly 1 tile. The problem is that this feels quite jittery. There's no room for interpolation, since GUI can not go past 1px accuracy.

Which leads to the question: How to smooth viewport movement when using minimap?

# Answer
> 3 votes
I think you should avoid setting your viewport position to the value selected in GUI in one, single frame.

Instead, I'd add a `target position` and `current speed` to your camera. Then, clicking and dragging your minimap would just set a `target position` of your camera to a new value, but the Camera would use it's speed and target to follow the target pos. during few frames. This way the precision of your clicking on minimap would be still 1 tile but the camera positions can be interpolated between tiles, so you have smooth movement with varying speed.

---
Tags: interpolation, rts, viewport, minimap
---


# Question
Title: How can I stop showing camera image in my Scene? Unity
How can I stop showing camera image in my Scene in Unity? As you can see on the screenshot there is an image of a camera inside a player in the Scene view. How can I disable the image?

# Answer
> 3 votes
Found on Unity forums

> Disable the gizmos. There should be a drop down bar for the scene view called Gizmos. Click on it and then uncheck the camera icon.

http://answers.unity3d.com/questions/790305/make-camera-invisible.html

---
Tags: unity, ide
---


# Question
Title: Make standard Unity 3D objects non transparent
I have a problem. When I add a cube or sphere to the scene they are transparent. How can I disable it? I tried adding materials, but it didn\`t help and even if it would have helped it still a very dumb way of making standard objects non transparent.

# Answer
> 2 votes
I don't think they are transparent, they just don't have any light on them. Try adding a directional light to the scene.

## Explanation

The reason they look transparent is because they look like the skybox. They look like the skybox because there isn't a light in the scene, meaning the colour of the objects will be equal to the ambient light, which by default in Unity is tied to the skybox.

---
Tags: unity, ide
---


title: HTML5 Multiplayer movement

text:
# Question
Title: HTML5 Multiplayer movement
I'm making a 2d multiplayer html5 game that needs client-side movement, collision etc.

Client sends active cursors to the server (w,a,s,d), server updates cursors on all clients and clients handles movement for each other. Every client sends server it's x,y every 100ms and server updates sender's x,y on all clients.

It works perfectly if player's latency is \<1ms but even if player has 40ms latency everything seems like teleporting.

How can i make everything smooth without handling movement on the server? (like transformice.com do)

Sorry for my grammar.

# Answer
> 0 votes
The general answer is to do movement on the client but correct it when you get server updates. So like move the player to where the server says he is (probably interpolate rather than jump to that position.)

---
Tags: 2d, movement, multiplayer, html5
---


# Question
Title: Entity Component System - Physics Animation Matrix Calculation?
The problem is how many times the matrices representing the bones (for animation and rendering) of an entity get calculated.

If i have these components:

* Position
* Skeleton (holds matrices for bones)
* Physics
* Animation

When the physics get's updated, the position is changed to move the entity. This sends a message, that position has changed. The skeleton takes note and updates the matrices for the changed position (and potentially rotation). The animations are then updated in a separate system, the skeleton then gets updated and changed again. So essentially the matrices are being updated twice (unnecessarily) instead of just once.

Am i going about this the wrong way? Is this just the price of having everything disjoint?

# Answer
> 1 votes
The question really revolves around whether to process events right away or delay them until it is a system's turn. This is a case where you would use the latter.

Instead of updating the animation's matrix right after an event, instead mark in your animation system that a change has occurred and needs to be processed for that node. Then only during the Animation system's turn, run a computation update across those nodes which were marked dirty earlier. This allows for the skeleton to be modified multiple times in multiple places ahead of the animation system update, and the animation system to only update its relevant data once, for example, right before rendering happens.

---
Tags: entity-system
---


# Question
Title: Gradually rotate vector towards another vector
For a game I'm making there is an AI bot in it. I want it to rotate so that it is facing it's opponent. The direction it is facing is determined by a vector (it will face the direction that the vector represents.) I can rotate it to face it's opponent like so:

```
 glm::vec3 opponentRefPos = opponentPos - position;      //for comparing AI's opponent's position to AI's position

glm::vec3 directionTarget = glm::normalize(opponentRefPos);
direction = directionTarget;

```

Where direction is the direction that the AI bot is facing (and it is a vec3) I want to gradually rotate it to face directionTarget. So let's say that I have a constant variable called SPEED (and deltaTime, which is the time between frames that SPEED will be multiplied by to keep the speed that it rotates at constant), which is the speed that I want the AI bot to rotate at. How can I rotate it towards this vector at that speed?

# Answer
Here it is how I did it. I store the angle of my enemy in a variable m\_Angle. Then you update every tick (elapsedTime) the target angle towards your opponent. Please keep in mind that you need to switch direction at +/- 180, so turn right or left (I assume your opponent moves as well). The general approach is to turn the angle of the sprite only partly based on your m\_Turnspeed instead of directly letting your sprite facing your opponent. As long as the target angle is not the actual angle you add a fraction to the angle towards your opponent.

Start with initializing m\_Angle, e.g.45.0f. And here is the update function for every tick:

```
// Buffer the direct angle from your bot to the opponent
float targetAngle = ((std::atan2(opponentLocation->y - m_Position.y, opponentLocation->x - m_Position.x) * 180) / 3.141);

// Calculate the difference
float diff = targetAngle - m_Angle;

// Make sure you turn less than 180 degree
while (diff < -180){
    diff += 360;
}
while (diff > 180){
    diff -= 360;
}

// Based on the difference, turn left or right.
// Wrote it without trying, probably need to switch statements
if (diff > 0){
    m_Angle += m_Turnspeed * elapsedTime;
} else if (diff < 0) {
    m_Angle -= m_Turnspeed * elapsedTime;
}

```

My enemies are tanks. So I consider their speed in the calcualtion. I do not know if this is helpful to you as well, but take this is a hint. The faster the enemy moves the slower it turns.

```
m_Angle += m_Turnspeed * (1 - 0.5f * (m_Speed/m_Maxspeed)) * elapsedTime;

```
> 1 votes

# Answer
Seems you have the current direction and the desired direction figured out. The difference between these vectors is the *steering vector*.

After normalizing the steering vector you can multiply it by your desired speed. Add this result to the current direction... and you're done. Make sure the result has the same length as your initial vector and you're set.
> 0 votes

---
Tags: glm
---


# Question
Title: Unity3d Resources.LoadAll<Sprite> empty array
In my resources folder structure I have myself a file, now in the unity editor this file is a `Texture Type Sprite (2D and UI)`, now when I attempt to run this code in one of my scripts

`var icons = Resources.LoadAll<Sprite>("Images/BuffIcons");`

My icons variable is empty, now if I change the line above to

`var icons = Resources.LoadAll("Images/BuffIcons");`

It comes back with an array which has a `Texture2D` and then multiple `Sprite` objects. Now why can't I cast the objects to a `Sprite`?

Also just for your information the `Sprite (2D and UI)` is a `Multiple` sprite so this sprite in total has like 42 different sprites. It seems to me the sprite which holds all the other sprites is classed as a `Texture2D` and then all the sprites inside of the `Texture2D` are Sprites. How can I just tell the Resources.LoadAll to load the sprites?

Basically the same problem as this user http://answers.unity3d.com/questions/900990/assetdatabaseloadallassetsatpath-not-loading-asset.html however the answers provided don't work for me either :(

# Answer
> 3 votes
So this is a really silly answer however I'm not going to delete this question because around the web I have seen this question in a view places and all the answer's didn't work for me so. Here is my fix :D

Basically I have a `Sprite (2D and UI)` file in Assets/Resources/Images/BuffIcons, in my code I have this line

```
BuffIconSprites = Resources.LoadAll<Sprite>("Images/BuffIcons");

```

Basically all I had to do was simply close Unity and re-open it, it seems if you create the sprite asset which contains multiple sprites you need to close and reopen Unity, I think this is something to do with the solution file which is constantly updated when stuff changing in your Unity file.

P.S. as you can see the line of code I provided hasn't changed. So I'm 100% sure this problem is something to do with the Unity solution

# Answer
> 1 votes
Going to Unity's menu system, selecting `Assets` and then `Reimport All` will do the trick.

This better than re-opening unity, since that does not always reimport your assets fully when the project is in a funny state. This will ensure all such issues are corrected. (Just had this issue, and opening / closing did not help - `Resources.LoadAll()` failed to load *anything* until `Reimport All` was used. Checked textures after first close/reopen and they were in an unreadable state in `Project` tab).

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


# Question
Title: Jitter Physics not working correctly. Going through objects and getting pushed back when touching walls
I am trying to use the Jitter physics engine, however, I can't get it to work correctly. For example, when I touch the side of a cube, it pushes me far back in the opposite direction. While I am flying back, if I hold the opposite directional key, I keep getting slower until I come to full stop.

Other times, I go right through the floor. I followed this tutorial.

I gave my floors `BoxShapes` and a `RigidBody`. I set them to `static` so the rigidbodies won't move. I did the same in my `Player` class but didn't set it to static.

How do I make it work correctly? If someone knows a better tutorial or physics engine I can use in C# with MonoGame/XNA, please let me know.

# Answer
> 1 votes
It's been a while since I used Jitter, but here's my two cents:

* The push-back happens because a force is applied to your character in order to avoid penetration with the wall. Setting `World.ContactSettings.BiasFactor` to a lower value should reduce the force used, but may also cause slight penetration or other issues.
* I had a similar problem with errant collision, which was caused by a Jitter bug. If you are using the 0.1.7.0 version (the last download, from Oct 2011), you are affected by it. The first line in `JVector.TransposedTransform` should be

`float num0 = ((position.X * matrix.M11) + (position.Y * matrix.M12)) + (position.Z * matrix.M13);`

The incorrect version has `M31` instead of `M13`.
* I don't know about current .Net physics engines, but Jitter certainly seems long since abandoned and somewhat incomplete.

# Answer
> 0 votes
Make sure your faces are oriented the right way; use IDebugDrawer to verify this.

---
Tags: c#, xna, physics, monogame
---


title: Change texture settings for each object

text:
# Question
Title: Change texture settings for each object
So I'm kinda new to Unity, but I've used it a couple of times before. Here's my issue:

I have two cubes with a random texture applied to them (drag'n'dropped something from the Asset Store). These cubes have different sizes, where one is a square and one is a rectangle. I want to set the tiling size to be different on them (because they are obviously stretched on the rectangle), but when I click on one and change it, the settings changes for both of them.

This is how it looks right now: https://i.stack.imgur.com/0UuOk.png

Is it possible to make these settings unique for each object somehow?

# Answer
> 1 votes
The **Tiling Size** property belongs to the **Material** that you apply onto the cubes. So if you change the material on one cube, naturally it will affect the other which is not the action you wanted. You should create different materials with same texture (**Albedo** property of the material) and set the tiling settings seperately. Hope this helps

---
Tags: unity
---


# Question
Title: Which better? Write all scripts on timeline or write it partially on `.as` file?
I'm going to create a flash game. But I don't know which way for me to write my scripts.

Is it better if I write script part by part and by object so every object has they own script .. or write all of those object's script on single timeline?

# Answer
I'd personally go with individual AS files. Timeline coding is very AS2 and is more for animators as someone else stated.

If your game gets complicated, breaking classes out into AS files will definitely help with organization as well. I recommend an editor like flashdevelop over doing it in the Flash/Animate IDE
> 1 votes

# Answer
.as files and use more powerful libraries, such as starling and citrus and don't use vector graphics, it's taxing on the CPU.
> -1 votes

---
Tags: flash, actionscript-3
---


# Question
Title: Clearing just the object, not the whole canvas, leaving an uwanted trail
I'm working on a platform game via poo.

I heard is more efficient to **clear just the object** you're drawing instead of clearing the whole canvas. So I'm working on this, and all goes well when the player's velocity `player.Xvel` has an integer value.

But when I use a floating point value for the velocity, then my object leaves a banded trail behind it, like a barcode of stripes and gaps.

Can you help me identify what's causing this artifact?

```
var canvas = {};
canvas.obj = document.getElementById('canvas');
canvas.ctx = canvas.obj.getContext('2d');
canvas.width = canvas.obj.width;
canvas.height = canvas.obj.height;

var Object = function() {
  this.draw = function() {
    switch (this.fill) {
      case true:
        canvas.ctx.fillStyle = this.color;
        canvas.ctx.fillRect(this.x, this.y, this.width, this.height);
        break;
      case false:
        canvas.ctx.strokeStyle = this.color;
        canvas.ctx.strokeRect(this.x, this.y, this.width, this.height);
        break;
      default:
        console.log('draw err');
    }
  };
  this.clear = function() {

    var prevCoords = {};
    prevCoords.x = this.x - this.xVel;
    prevCoords.y = this.y - this.yVel;
    // lineWidth:fix
    canvas.ctx.clearRect(prevCoords.x, prevCoords.y, this.width, this.height);
  };
};

var player = new Object();
var game = {};

player.width = 10;
player.height = 50;
player.x = 200;
player.y = 150;
player.xVel = 0.9; // try to change this to integer/float value then run
player.yVel = 0;
player.color = 'white';
player.fill = true;
player.movement = function() {
  this.x += this.xVel;
  this.y += this.yVel;
};

game.key = [];
game.fps = 15;
game.obj = setInterval(function() {
  player.clear();
  player.draw();
  player.movement();

}, 1000 / game.fps);
```

```
body {
  background: rgb(110, 110, 110);
  color: rgb(230, 230, 230);
}

canvas {
  background: rgb(60, 60, 60);
}
```

```
<canvas id="canvas" width="460" height="360"></canvas>
<form action="">
  <label>Game:</label>
  <input type="button" value="run" onclick="" />
  <input type="button" value="stop" onclick="clearInterval(game.obj);console.log('end');" />
</form>
```

# Answer
> 1 votes
In your clear() function, the first time it clears a rectangle with the x coordinate at x + xVel, which is 200.9. Clearing just draws a rectangle the same color as the background, and when you draw in the middle of a pixel not at an integer value, it will anti-alias that pixel, and it will not be fully cleared. what you need to do is clear the full pixel, so you can floor the value and it will be an integer. Also, because, you are making the x value a little bit less, you need to add one to the dimensions

```
    this.clear = function() {

    var prevCoords = {};
    prevCoords.x = Math.floor(this.x - this.xVel);
    prevCoords.y = Math.floor(this.y - this.yVel);
    // lineWidth:fix
    canvas.ctx.clearRect(prevCoords.x, prevCoords.y, this.width+1, this.height+1);
    };

```

jsfiddle

sorry if this makes no sense. this is my first answer.

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


title: How does D* pathfinding work?

text:
# Question
Title: How does D* pathfinding work?
I would like to understand on a fundamental level the way in which D\* pathfinding works. Any code or psuedo-code implementations as well as visualizations would be helpful.

# Answer
D\* isn't used anymore. Its replacement, called D\*-lite, does the same thing as D\*, but is faster and easier to implement.

D\*-lite is based on an algorithm called LPA\* (aka. Incremental A\*). D\*-lite is trivial to understand once you understand LPA\*, but unfortunately LPA\* is less trivial to understand.

Unfortunately I'm not aware of any good "layman" explanation online. Your best bet is to just read the paper introducing LPA\*. After that the paper on D\*-lite should be an easy read. Good luck!

---

Also, since this is a Game Dev site: it's unlikely you truly need to implement D\*-lite to get acceptable performance for a game. D\*-lite is mostly for traversing a single unit through a very large, complicated, changing graph, whereas most games require navigating many units through 2D/3D grids that are fairly open and usually static.

If you explain your actual problem better *(in another question)* we can help you determine a better solution.
> 2 votes

---
Tags: algorithm, path-finding
---


# Question
Title: WebGL .NETCoreApp 1.1 - UnityLoader.js - SyntaxError: expected expression, got end of script
After creating a release build of my game using Unity 5.6, I could navigate to the created folder and open the 'index.html' file and my game would load and play normally. However, when trying to integrate it into my WebApp (.NETCore 1.1), I would continually get this error in Chrome, Firefox, IE, etc..:

UnityLoader.js - SyntaxError: expected expression, got end of script

Invoking error handler due to TypeError: UnityLoader\[r\] is not a function

# Answer
> 1 votes
I thought I would share my resolution with you here.

I tried a variety of things, including lengthy web.config changes per recommendations on Unity's site, and others found in other forums, but the only thing I ended up needing to add was the following code to my Startup.cs file in the Configure() method:

```
StaticFileOptions option = new StaticFileOptions();
FileExtensionContentTypeProvider contentTypeProvider = (FileExtensionContentTypeProvider)option.ContentTypeProvider ??
new FileExtensionContentTypeProvider();
contentTypeProvider.Mappings.Add(".unityweb", "application/octet-stream");
option.ContentTypeProvider = contentTypeProvider;
app.UseStaticFiles(option);

```

The main point being that files with the extension ".unityweb" were located in my \Build folder and were the ones being used, despite the option being selected to use Gzip compression. Once built I never ended up with any \*.unity3dgz file extensions. However, if your release does contain files with those extensions, you might want to try adding another Mapping for that, for example:

```
contentTypeProvider.Mappings.Add(".unity3dgz", "application/octet-stream");

```

---
Tags: unity, webgl, mvc
---


# Question
Title: Play animation with the help of the animator once, wait until it ends playing and continue script code
How can I play animation with the help of the animator once, wait until it ends playing and continue script code?

I am playing an animation with the help of the animator this way:

```
animator.SetBool(what, toAnimate);

```
1. I am starting my animation in that way:

rabit.animate("die", true);
2. I am making a transition to another animation this way:

rabit.animate("die", false);

I need to wait after step 1. before making step 2. so that animation plays. How can I do that?

# Answer
You can use AnimationEvent. It will besically give you an opportunity to call a function in the end of your animation. More on that here here.
> 0 votes

# Answer
You can call a coroutine:

In C#:

```
IEnumerator PlayWaitPlay(){
      rabit.animate("die", true);
      yield return new WaitForSeconds(3); // your animation time
      rabit.animate("die", false);
}

```

To call it use

```
StartCoroutine(PlayWaitPlay());

```

Hope it helps :)
> 2 votes

---
Tags: unity, animation
---


# Question
Title: Don't message systems slow down game engines?
I am wondering, aren´t messaging systems slowing the speed of engines down? I mean, lets say that I want to zoom in my camera, without messaging I would do something like:

```
_camera->zoomIn(0.005f);

```

But with messaging, I have to broadcast the message (to the bus for example)

```
Data data;
data.float = 0.005f;
MessageBus::sendMessage(CAMERA_ZOOM_IN,&data);

```

Then iterate through all systems (all systems that can possibly handle the message) and at the end, when it arrives to my camera system, I have a handling function that calls proper method based on the message type.

```
eventFunctions[CAMERA_ZOOM_IN](data);

```

That means it needs some additional time to "do stuff" and also harder implementation. (imagine for different data types I also need some static casts etc.)

So, will it affect the actual speed of my engine?

# Answer
> 4 votes
This is the line that's the crux of your question "Then iterate through all systems (all systems that can possibly handle the message)".

In reality, it depends how you register your listeners.

If you have *few*, or worse, only have *one* event type, then yes, you would be looping through most all systems. But that's the point; you *don't want* your systems to register to the `EventSystem` for *any* event; this would force each system to decide for themselves if they'll handle it.

*All* events a system registers for are ideally events that they *have to* handle. If that's the case, you're iterating over exactly those systems which need to be notified anyway- event system or not. If you find that that's not the case, your events may not be **granular** enough (see below).

---

So how does having multiple event types help?

Say you allow for `CameraEvent`s in your `EventSystem`.

If you have a system that wants to subscribe to `CameraEvent`s, it would do so by registering with your `EventSystem` and saying that it's subscribing to `CameraEvents`; your `EventSystem` would store the system (or more likely just it's update call) in a list of listeners for specifically `CameraEvent`s.

`camEventListeners:List<IListener<CameraEvent>>`

When an object broadcasts a `CameraEvent`, the `EventSystem` would only loop through all the `camEventListener`s, *not* all listeners of all types. Essentially, only those listeners who would need to handle a `CameraEvent` would be notified.

---

**If** you find that you have a **lot** of systems that are registering for events and then checking certain event parameters to decide whether they handle or ignore those events, your events may not be **granular** enough.

Imagine you have systems that only care about when a camera zooms but not when a camera pans. Clearly listening for a `CameraEvent` would make for a bunch of useless calls **if** you have a lot of these systems that *only* care about zooming. In this case you may decide to break up your `CameraEvent` into a `CameraZoomEvent` and `CameraPanEvent` and reorganize your systems to broadcast and/or listen to these more specific events.

In this scenario, your `EventSystem` would then have multiple lists of listeners: one for `CameraZoomEvent` listeners and one for `CameraPanEvent` listeners. This can be implemented as a map in your `EventSystem`.

`listenerMap:Map<EventType, List<IListener<EventType>>>`

When a new listener is registered, the `EventMap` adds it to the correct list:

```
function registerListener(eventType, listener){
    listenerMap.get(eventType).push(listener);
}

```

When a new event comes in, the `EventMap` grabs the list for that `EventType` and updates all the elements in that list.

```
function broadcastEvent(event){
    // You could either use your programming language's built in type
    // checker or pass in the eventType as a parameter into the broadcast event function.
    for( listener in listenerMap.get(Type.typeof(event))){
        listener.update(event);
    }
}

```

# Answer
> 2 votes
It depends on what you use it for, and you're right, you'd have to iterate all systems that could possibly make use of the message.

The overhead is: **messages\_sent * possible\_receivers * handling\_overhead**

A system like this will slow to a crawl if you distribute, for example, low level AI messages from AI agent to AI agent because the above equation will grow exponentially with the amount of agents. For talking to the camera or triggering an story event it's ok though since the amount of messages and receivers is very limited and controlled by the developer.

Message systems have their place, you don't always want to make variables/objects global or overload constructors beyond good and evil etc.

it can be very tidy and light, if used where there is an actual use case for it.

---
Tags: architecture, optimization
---


# Question
Title: Unity Rigidbody2d jittering movement in the y-axis
As said, rigidbody moves fine, even smoothly in the x axis.

Problem comes in on the y axis. Whenever the character goes up or down, it noticeably shakes.

Additional Info:

* Unity 5.6
* Using linear interpolation
* Mass is 5
* Linear Drag is 20
* Gravity is 0
* Angular Drag is 0
* Locked rotation on the z-axis
* Dynamic Rigidbody
* No parent Object, not even a child

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

public class PlayerMovement : MonoBehaviour {

Rigidbody2D rbody;
//Animator anim;
public float speed = 0;
/*SpriteRenderer sr;
Vector2 movementVector;
void Start () {
    rbody = GetComponent<Rigidbody2D> ();
    anim = GetComponent<Animator> ();
    sr = GetComponent<SpriteRenderer>();
}*/

void Update(){
    //sr.sortingOrder = ((int)Camera.main.WorldToScreenPoint (sr.bounds.min).y) * -1;
    movementVector = new Vector2 ((Input.GetAxisRaw("Horizontal"))*3, Input.GetAxisRaw("Vertical"));
    /*if (movementVector != Vector2.zero) {
        anim.SetBool ("isWalking", true);
        anim.SetFloat ("inputX", movementVector.x);
        anim.SetFloat ("inputY", movementVector.y);
    } else
        anim.SetBool ("isWalking", false);
}*/

void FixedUpdate(){
    rbody.AddForce (movementVector * speed);
}

```

}

I also noticed that changing the mass and linear drag affected the movement speed on the y axis but not on the x axis, and movement on the y axis is noticeably faster than on the x axis, which is why I multiplied the horizontal input by 3.

# Answer
Fixed it!

For the varying speed at the axes:

1. Head over to Project Settings -\> Input
2. Make sure gravity is 0 for both axes

For the camera, I tried to lock it and watch my character move around, and it moved without a jitter, my solution was:

1. Make sure that Camera's movement is under the same type of execution function as the target's movement is. So if target's at Update() then so should the camera.

Originally, my camera was at late update which must be why it jittered, because they were not moving at the same time.
> -1 votes

# Answer
Check to see if the rigidbody on your character has a gravity scale being applied to it;

That's my own guess for what's wrong. It's a common enough pitfall that I fall into every now and then myself, but it's a bit hard to tell without knowing what it looks like or what type of game you're doing.

On the code itself, I wouldn't recommend directly manipulating the Input, rather adjusting the input after getting it provides better insight as to whether the input itself is working.

```
...
// Let's divvy up the x and y speeds
public float xSpeed = 5;
public float ySpeed = 5;
Vector2 movementVector;

void Update(){
    ...
    movementVector = new Vector2 ((Input.GetAxisRaw("Horizontal")), Input.GetAxisRaw("Vertical"));
    ...
}

void FixedUpdate(){
    // Now we have more control for the x and y speeds, neato
    movementVector = new Vector2(movementVector.x * xSpeed, movementVector.y * ySpeed);
    rbody.AddForce (movementVector);
}

```
> 0 votes

---
Tags: unity, 2d, movement, unityscript, rigidbody
---


# Question
Title: SDL2.0.5 - SDL_KEYDOWN shows two identicle presses when only one key is pressed
SDL2.0.4 using this code:

```
SDL_Keycode key = 0;

while(SDL_PollEvent(&(Global->event)) != 0)
{
    if(Global->event.type == SDL_QUIT)
    {
        /* Allow users to exit the game */
        break;
    }
    else if(Global->event.type == SDL_KEYDOWN)
    {
        /* Actual Keypresses */
        key = Global->event.key.keysym.sym;

        if(key == getSDLKValue("p-key"))
        {
            /* ... p key is pressed */
        }
        else if(key == getSDLKValue("q-key"))
        {
            /* ... q key is pressed*/
        }
    }
}

```

Works fine to get a single `p` key press when the key is pressed down. However, when manually compiling, and using 2.0.5 logging shows that a single key press has:

```
Key pressed: 112
Key pressed: 112

```

It gets pressed twice in the window, when only once in reality.

Is this a bug with SDL2.0.5? Running on Ubuntu 16.04, manually compiled SDL2.0.5.

# Answer
> 1 votes
`event.key.repeat` is `0` for actual key presses, and `1` for fake presses (which are generated if you hold a button long enough).

To fix this issue, this question suggests to just check if `event.key.repeat == 0`.

It's possible that 2.0.5 behaves in the way described to make it easier to separately handle text and non-text input.

---
Tags: sdl2, keyboard
---


# Question
Title: how to convert FoV into zoom 2x, 3x, 4x...?
so I have the value of the FoV in degrees,
now I need to convert it to a zoom value of 2x, or 3x, for scopes and binoculars.

I placed some objects equally distanced between each other,
but when I zoom in from FoV 100 to FoV 90, (and I am calling that a 2x zoom), the visible objects in the edges of the reticle are not the ones I expected.
Yes, I am using this big FoV of 100 to 10 just to try to calculate the 2x, 3x value properly.

**So I need the ending/maximum FoV to be at 10 degrees.**

what happens in the highest zoom levels, from FoV 30 to 10, is that the zooming becomes too high and hard to control, so I wonder if I am calculating it wrong?

I mean, should the FoV steps, to let results of zoom 2x, zoom 3x, be not a fixed value like:
FoV 100 = zoom 1x
FoV 90 = zoom 2x
FoV 80 = zoom 3x
I should instead use some calculation to give me a result something like (or not like):
FoV 100 = zoom 1x
FoV 85 = zoom 2x
FoV 73 = zoom 3x
and what could be such calculation?

or should I use some other rule, like impose some FoV limits and fixed fov values instead of making any calculation?

# Answer
Technically changing the FOV isn't zooming, but it does the same thing, so let's not take that into account.

You can calculate the size of the view plane where the object lies using trigonometric functions:

```
width = tan(FOVX) * dist
height = tan(FOVY) * dist

```

(Make sure the angles are in radians, and FOVX is the horizontal FOV, which is equal to FOVY * aspect ratio)

Here is where you'll have to decide what you mean by zoom 2x. You can think in separate axes, and halve the width and height of the view plane at the object's position. This makes the object feel like it's doubled, but because it's in 2d, it will actually have an area 4 times larger than on the default value. If you want to make the area twice as big, then you'll have to multiply the width and height of the object by the square root of 2. For simplicity I'm going to refer to this value (either x or sqrt(x) for a zoom of x) as `ZOOM_FACTOR`.

Now we can reverse the algorithm I used above to find the width and height of the view plane. Because the sizes of this plane are linear (aka. a view plane at distance d is half as big as a plane at distance 2d), we can simplify it. The algorithm becomes

```
newFOVY = atan(tan(FOVY) / ZOOM_FACTOR)

```

This first calculates the size of the plane at distance of 1 with `tan(FOVY)`, then calculates the new plane's size, then runs uses the result to calculate the new fov. As always, the input and output angles are in radians.

You can achieve the same thing by making the left, right, top and bottom parts of the projection matrix smaller or bigger depending on what you need.
> 4 votes

---
Tags: mathematics, first-person-shooter
---


# Question
Title: Physical attributes as a function of age
My `worker`class has physical attributes such as `physical_fitness` and `sexual_fitness` which are intended to be functions of their age (the attribute is, unsurprisingly, called `age`). When the class is initialized, the initial values of `XYZ_fitness` are computed by a randomized normal distribution.

In each game tick, `worker`'s grow a year older. I want to appreciate/depreciate the values of their physical attributes such that, for example, they increase until they are at their maximum value around age 35, and decline with age after that. What is an efficient way of defining this function?

Would this involve something like running their age through a quadratic function with its maxima at the age value 35? I'm sure there's some elegant math/statistics here that's escaping me.

# Answer
I would suggest that you do NOT try to create a mathematical formula for this, since you will sooner or later find that the curve needs special shapes - it will be very tricky to achieve these with an f(age).

Instead write the value pairs in a table and linearly interpolate between two age values and grab the corresponding other value. If you have for example only 10 rows, for ages 0...90 years, with 10 year intervals (ie. age in column 1 and for example strength in column 2), the curve will have a bit of sharpness, but otoh it is easy to insert more points AND you can use for example Newton interpolation (C code sample) to smooth between the points; this will create the nice roundness you'd get when drawing between the points with a pen, by hand.

It is easy to create and adhoc-view a suitable table in Excel or OpenOffice, then copy/paste it. Or simply write it into a .txt file.

Above all, you'll open for further development and maintenance this way. Doing it with some polynomial formulas seems to me like *harakiri*.
> 1 votes

---
Tags: mathematics
---


# Question
Title: Unity 5 - Input Field - How to confirm password entry with ENTER only and not a click/loss of focus
I have an input field password box, currently the password is 'submitted' either by clicking Enter or by clicking elsewhere on the screen. This seems to be the designed way, as it states this in the documentation (https://docs.unity3d.com/Manual/script-InputField.html) -

*"A UnityEvent that is invoked when the user finishes editing the text content either by submitting or by clicking somewhere that removes the focus from the Input Field."*

As I have other buttons on the same screen that users can click on, I would like it so mouse clicks are not counted as an invoke.

Is this possible?

Many thanks in advance

# Answer
> 1 votes
You could use this method to check if the password is correct every time a new character is entered into the text field

https://docs.unity3d.com/ScriptReference/UI.InputField-onValueChange.html

You may want to add some checks before seeing if it is correct, like only checking once password is over minimum length so that you don't send unnecessary requests to the login server.

# Answer
> 0 votes
Simple solution:

```
using UnityEngine;
using UnityEngine.UI;

public class CustomSubmit : MonoBehaviour
{
    public Button SomeButton;
    public InputField Field;
    private bool wasFocused;

    private void Awake()
    {
        SomeButton.onClick.AddListener(() => {
            Submit(Field.text);
        });
    }

    private void Update()
    {
        if (wasFocused && Input.GetKeyDown(KeyCode.Return)) {
            Submit(Field.text);
        }

        wasFocused = Field.isFocused;
    }

    private void Submit(string text)
    {
        Debug.Log("Submit=" + text);
    }
}

```

---
Tags: unity, input
---


# Question
Title: I added a terrain in Unity, but can't see it
In Unity I added a terrain through **Create → 3D Object → Terrain.** It didn't show up and I can't see it. I tried to press `F` to focus on it, but I still don't see it. What am I doing wrong?

Here is a screenshot:

# Answer
I found an answer. I should just have turned the coordinate system the way it is on the screenshot below:

So my terrain was just hiding in the z-plane.
> 3 votes

---
Tags: unity, terrain
---


# Question
Title: Why am I unable to edit the Input Field object's script?
When attempting to edit an Input Field object's script like so

I get the following error:

> Unable to open C:/Program Files/Unity/Editor/Data/UnityExtensions/Unity/GUISystem/UnityEngine.UI.dll: Check external application preferences.

Why is Unity attempting to open a \*.dll, here?

# Answer
> 2 votes
The component script you are trying to open is built into that DLL file (i.e. part of that dll). To open the dll file you can use .net decompiler like ILSpy or dotPeek.

Alternatively, you can find the component code at InputField.cs, as part of the Unity-Technologies repo, available under the MIT license.

# Answer
> 2 votes
Input Field is a class that belongs to the `UnityEngine.UI` namespace. Unity is attempting to open a \*.dll because you are telling it that you would like to edit a class that belongs to that \*.dll file. We can see this from the documentation; `InputField` is listed under `UnityEngine.UI.InputField`.

You generally wouldn't actually edit the base code for this component, any more than you would edit the base code for a Transform or a Rigidbody. The ability to do so has *possibly* just been left in due to the way they implemented the component class, though that is just speculation. Ultimately, you wouldn't touch it, directly.

---
Tags: unity
---


# Question
Title: Moving several rectangles by dragging a single one in Monogame
I am trying to make a simple card game in which the hand of cards is displayed on a row to the player on screen, and by dragging a single card, all others should move accordingly, with the same speed as the mouse on the X axis only. This is my current code:

```
public void HandleInput(GameTime gameTime)
{
    _previousMouseState = _currentMouseState;
    _currentMouseState = Mouse.GetState();

    if (_currentMouseState.LeftButton == ButtonState.Released)
    {
        _dragged = false;
    }

    _mouseDown = _currentMouseState.LeftButton == ButtonState.Pressed
        && _previousMouseState.LeftButton == ButtonState.Released;
}

public void Update(GameTime gameTime)
{
    foreach (Card card in _players[0].Cards)
    {
        if (_mouseDown)
        {
            if (card.Area.Contains(_currentMouseState.Position))
            {
                _dragged = true;
            }

            if (_dragged)
            {
                int movementDelta = _previousMouseState.X - _currentMouseState.X;
                Debug.WriteLine("previousX: " + _previousMouseState.X
                    + " currentX: " + _currentMouseState.X);

                _players[0].Cards.Select(c =>
                {
                    Rectangle area = c.Area;
                    area.Offset(movementDelta, 0);
                    c.Area = area;
                    return c;
                }).ToList();
            }
        }
        card.Update(gameTime);
    }
}

```

`HandleInput` runs before `Update` on the game loop. I have implemented a screen manager, but I don't think that is the issue, here. The thing with this code is that the mouse previous X, most of the time, is exactly equal to the current X, and movement is erratic at best (meaning that 90% of the time nothing happens, and the other 10% all cards move on a huge, uncontrollable leap). I have also tried using `gameTime` in the calculations for the movement delta, but that doesn't work, either. I'm not sure in what other way could I could tackle this (dabbled a bit on using `Vector2`, but unsuccessfully). I'm kind of noobish to Monogame, but I understand that polling is preferred to event handling here.

# Answer
Actually... The reason was that the event was triggering once per frame.

```
public void HandleInput(GameTime gameTime)
    {
        _previousMouseState = _currentMouseState;
        _currentMouseState = Mouse.GetState();

        if (_currentMouseState.LeftButton == ButtonState.Released)
        {
            _dragged = false;
        }

        _mouseDown = _currentMouseState.LeftButton == ButtonState.Pressed
            && _previousMouseState.LeftButton == ButtonState.Pressed;
    }

 public void Update(GameTime gameTime)
    {
        foreach (Card card in _players[0].Cards)
        {
            if (_mouseDown)
            {
                Point clickPoint = _currentMouseState.Position;
                if (card.Area.Contains(clickPoint))
                {
                    _dragged = true;
                }

                if (_dragged)
                {
                    _speed = new Vector2((float) ((clickPoint.X - _previousMouseState.Position.X) * gameTime.ElapsedGameTime.TotalMilliseconds), 0);
                    _players[0].Cards.Select(c =>
                    {
                        Rectangle area = c.Area;
                        area.Offset(_speed.X * 0.01f, 0);
                        c.Area = area;
                        return c;
                    }).ToList();
                }
                else
                {
                    //bleed out speed
                }
            }
            card.Update(gameTime, new Point(card.Area.X, card.Area.Y));
        }
    }

```

This way it works. However I would like to bleed out the speed over time, but that's another matter for another question.
> 0 votes

# Answer
Your methods probably run at a frequency that's quite high so the differences between mouse positions are going to be small (or even zero since the position is an int). Instead of moving the cards for the delta distance between frames a better approach would probably be saving the cards' initial positions when the mouse button gets pressed and then every frame check the current position to find the delta distance from the initial distance.
> 0 votes

---
Tags: movement, monogame
---


# Question
Title: Unity 2D: Why does my character stutter if I add deltaTime to moveSpeed?
So I'm following a tutorial on youtube, first time Unity user, but been making games in other frameweorks before. In the tutorial he does not use deltaTime for movement, which has always been the standard for me, so I added it my self, but it makes my character "stutter/lag" really weirdly (does not stutter without deltaTime). Surely I must use deltaTime for movement in the `Update()`method?

Script for Player movement:

```
void Update () {

     playerMoving = false;

     if (!playerAttacking) {
         Vector2 direction = new Vector2();

         if (Mathf.Abs (Input.GetAxisRaw ("Horizontal")) > 0.5f) {
             Debug.Log ("Moving on X");
             playerMoving = true;
             direction.x = Input.GetAxisRaw ("Horizontal");
             lastMove.x = direction.x;
             lastMove.y = 0;
         }

         if (Mathf.Abs (Input.GetAxisRaw ("Vertical")) > 0.5f) {
             Debug.Log ("Moving on Y");
             playerMoving = true;
             direction.y = Input.GetAxisRaw ("Vertical");
             lastMove.y = direction.y;
             lastMove.x = 0;
         }

             if (playerMoving) {
                 myRigidBody.velocity = direction.normalized * moveSpeed * Time.deltaTime;
             } else {
                 myRigidBody.velocity = Vector2.zero;
             }
     }

```

My Camera (Stutters unless I use fixedUpdate):

```
void FixedUpdate () {
    targetPos = new Vector3 (followTarget.transform.position.x, followTarget.transform.position.y, transform.position.z);
    transform.position = Vector3.Lerp (transform.position, targetPos, moveSpeed);
}

```

# Answer
The problem is that you're setting velocity. Since it goes without saying that `distance = time x velocity`, what you're doing now is `distance = time x (velocity x time)`. If you were setting the position of your object, then multiplying by delta time would have made sense.

In short, you shouldn't be multiplying velocity by time. Again, if it was something like acceleration that you were using, since `velocity = time x acceleration`, the formula would've changed as follows:

```
myRigidBody.velocity = myRigidBody.velocity + (direction.normalized * acceleration * Time.deltaTime);

```
> 5 votes

---
Tags: unity, 2d, movement
---


# Question
Title: Creating a UI health bar image for each enemy object
I would like to create a small health bar on top of each enemy in my game. I know how to do this for one enemy, but I'm not completely sure how best to expand it to work for each enemy in the game. I'm guessing I should instantiate the UI health bar prefab somewhere, each time an enemy is spawned maybe? Currently, I don't even have an enemy spawner, I'm just testing by dragging enemy prefabs into the scene. I'll post the relevant scripts.

```
public class EnemyHealthBarController : MonoBehaviour
{
    private Image remainingHealthImage;

    private EnemyHealth enemyHealth;

    void Start()
    {
        remainingHealthImage = transform.Find("Remaining Health Image").gameObject.GetComponent<Image>();

        enemyHealth = GameObject.FindGameObjectWithTag("Enemy").GetComponent<EnemyHealth>();
    }

    void Update()
    {
        remainingHealthImage.fillAmount = enemyHealth.currentHealth / enemyHealth.maxHealth;

        if (enemyHealth.isDead)
        {
            gameObject.SetActive(false);
        }
    }
}

```

and

```
public class ClampEnemyHealthBar : MonoBehaviour
{
    private GameObject enemyHealthBar;

    private Vector3 offset;

    void Start()
    {
        enemyHealthBar = GameObject.Find("Enemy Health Bar");

        offset = new Vector3(0f, 30f, 0f);
    }

    void LateUpdate()
    {
        Vector3 desiredPosition = Camera.main.WorldToScreenPoint(transform.position) + offset;
        enemyHealthBar.transform.position = desiredPosition;
    }
}

```

Right now, I'm using GameObject.Find to set a reference to the preexisting enemy health bar in the scene. Also, I'm only finding the EnemyHealth component of one of the enemies. How might I better structure this in order to do the kind of thing I'm trying to do?

# Answer
Make your health bar a child object of your enemy object. Then either just use `transform.parent.gameObject` to get to the parent object, or just reference your game object in the health bar's script by using `public GameObject parentObject;` and then dragging the parent object in there.

This way, you won't have to think about setting each and every health bar to the correct object, because the objects will already have health bars.

At least this is how I would do it. There are tutorials on how to use World Space UI objects and how to do parent-child relationships and prefabs online, check those out if you want to learn more.
> 2 votes

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


# Question
Title: How would one program potions that can change virtually every aspect of the character?
In Witcher 3, there are various potions that the character can consume. There seems to be potions that have various effects during their effect time:

* Restores a certain number of health points per time
* Instantly restores a certain number of health points
* Increases the defense points
* If one delivers a critical blow, the damage will be amplified
* If one is attached by a vampire and it draws blood, the vampire will become poisoned
* Increases the maximum weight capacity by 20 pounds.
* Lets you see at night
* Improves sight under water and extends the time that the character can hold his breath

Then there are various properties of the equipment that also have various effects (extra 5% experience points, extra attack points, ...) and runes one can put into the equipment.

I can imagine how one could program each of them separately, I do not see how one could program this in a non-intrusive and extensible fashion. It seems the potions must have access to virtually every aspect of the game.

Or is it the other way around? In the attack code, there are hooks for certain potions. In the diving code, there is hook for the one relevant potion.

How does one implement this kind of thing?

# Answer
> 4 votes
When you have more than just potions which causes effects like that, it can be useful to put another layer of abstraction between the potions and the game mechanics in form of a *temporary status modifier* system.

This system keeps track of what status modifiers are currently active, how long they are still active, and what aspect of the character they affect. Other game systems should be able to query this system as a black box to get its current sum for any character stat. For example, when the character has drunk a +10 attack potion, has a -20 attack curse and a +15 attack weapon equipped, `getTemporaryStatusModifier(ATTACK)` returns `5`.

You would have to call that function in any code which operates on data which can be subject to temporary status effects. Yes, that means you might have to add not just obvious keys like `ATTACK`, `HEALTH_REGENERATION` or `CRIT_DAMAGE` but also obscure stuff like `VAMPIRE_POISON_FEEDBACK` or `NIGHT_POSTPROCESSING_GAMMA_ENHANCEMENT`.

Instant effects, like the `Instantly restores a certain number of health points` potion, can be implemented as status effects with a duration of a single game-tick.

---

A different approach is to implement status effects with functions. This system makes new status-effect creating game mechanics more complicated, but leads to cleaner code at those places which use this system.

Temporary status effects don't have a simply numerical effect. They are instead objects with one or more callback-functions which get called at specific places in the code. This is again abstracted behind a `TemporaryStatusModifier` system.

For example, when you recalculate the stats of the player-character, your core game-mechanics call the `TemporaryStatusModifier` system to run the PlayerStats-object through the `calculateStats` callback-functions of all currently active temporary status effects which have such a function. For a simple +attack effect, this function would look like that:

```
void calculateStats(PlayerStat& stats) {
    stats.attack += 10;
}

```

These functions can be as complex as you want. So you can hide the code for status effects with complex and situational mechanics away at where they are defined and keep your core game-mechanics code relatively clean. For example, your "poison vampires" effect could implement the callback function which calculates damage on the player-character like this:

```
void calculateDamageOnPlayer(Player& player, Enemy& enemy, Attack& attack, int& damage) {
    if (enemy.monsterType == VAMPIRE && attack.hasTag(DRAW_BLOOD)) {
         StatusModifier poison;
         // ...build the status effect object...
         enemy.addStatusModifier(poison);
    }
}

```

All the effects mentioned in the question could be implemented by having just four places in the core-code which make a call to the status modifier system:

* At the beginning of each tick when recalculating all player stats
* When the player receives damage
* When the player does damage
* Before rendering when the engine determines the current parameters for the post-processing stack.

---
Tags: design-patterns, effect-modifier
---


title: (Abstract) Game engine design

text:
# Question
Title: (Abstract) Game engine design
I am writing a simple 2D game (for mobile platforms) for the first time. From an abstract point of view, i have the main player controlled by the human, the enemies, elments that will interact with the main player, other living elements that will be controlled by a simple AI (both enemies and non-enemies). The human player will be totally controlled by the player, the other actors will be controlled by AI. So i have a class CActor and a class CActorLogic to start with.

I would define a CActor subclass CHero (the main player controlled with some input device). This class will probably implement some type of listener, in order to capture input events. The other players controlled by the AI will be probably a specific subclass of CActor (a subclass per-type, obviously). This seems to be reasonable. The CActor class should have a reference to a method of CActorLogic, that we will call something like CActorLogic::Advance() or similar.

Actors should have a visual representation. I would introduce a CActorRepresentation class, with a method like Render() that will draw the actor (that is, the right frame of the right animation). Where to change the animation? Well, the actor logic method Advance() should take care of checking collisions and other things.

I would like to discuss the design of a game engine (actors, entities, objects, messages, input handling, visualization of object states (that is, rendering, sound output and so on)) but not from a low level point of view, but from an high level point of view, like i have described above.

**My question is: is there any book/on line resource that will help me organize things (using an object oriented approach)?**

Thanks

# Answer
"Organizing things using an object oriented approach" is a subset of Computer Science. It has nothing to do with "games," it is simply how programs are put together.

Since you're talking about an "abstract point of view" search online for references to OOAD (object oriented analysis & design), or if you like books the Head First series is really really good. This will give you mental tools to break down problems into object oriented designs.

Those designs you can then implement in your OOP language of choice, for mobile phones that's probably Java or Objective C.

Now that I've completely divorced the "game" thing from your question, the programmer's stack might be a better place to get OOP design answers. Then back to here at gamedev stack for specific questions on efficient rendering, GUI options, game state handling, audio and things like that.

After that go take a look at the mobile platform SDK that you're writing for. Even odds bet that they have sample code for a simple, 2D graphics display and probably a scrolling map with sprites and a main loop.

Another resource will be to check out commercial mobile game engines, they typically have design overviews showing how their systems fit together and they will have forums that you can use to get an idea of how people are using their system design and the problems they have.
> 3 votes

# Answer
So the simplest approach to OOD Game engine would be what you sketched out in your question.

* you got actors, derive human actors from that and npc actors and other objects
* each object has either 'draw()' or informations to draw it and used in an graphics engine
* same goes for sounds, inputs/controls and so on
* the main work happens in the game loop, which calls 'draw()','processinput()' etc. for every object or a system to do that forine of those functions

All of this has nothing to do with an engine in particular, but just for simple games in general, and has many flaws.

What you should do is look on this site for general pattern used for games. It's a really good site for people coming with your approach of design, what the problems are and the alternatives. It doesn't provide a tutorial of that sort, but rather examples and pitfalls.

In the comments someone said that component based design would be to difficult to do, but learning why it's a thing can't do harm either.
> 0 votes

# Answer
It's not a solved problem because designs optimize for various things, optimization being one. But other designs optimize for coupling, reuse, fast to implement, easy to extend, statically typed, dynamically typed, etc. There's no common approach. Heck, you can't even find a definitive answer of what OOP is with regards to general programming. You'll only ever find patterns and ideas that have come and gone. One general source of that would be gameprogrammingpatterns.com
> -1 votes

---
Tags: architecture
---


# Question
Title: dependency between engine and 3d model software. Resolution - what is it really
I have a few questions about gamedev as a beginner.

1) Why someone tells that Unreal Engine has better graphic then for example Unity? I can create any quality model in 3ds max, for example, and import to Engine. Will this model look different in UE4 Editor and Unity Editor ?

And pls tell me do I understand it correct - each graphical engine (UE4, Unity and 3ds max) has own algorithm for drawing. And some one can render 10k poly for 1 second and another for 5 sec and that's why people say that one engine looks better then another, just because the same object render faster without lags. Is it true?

2) About game resolution - as I understand, model doesn't have resolution. Raster graphics has resolution, texture has resolution, but not model.

Again pls tell me, am I right or not - when I'm selecting in game resolution, I'm changing texture\material resolution ? If it's true, so how can we say that this game has Full HD or 4k resolution when each model can have many different textures with different resolution? For example, Call of Duty had good characters resolution, very clear, but at the same moment, walls or boxes looked worse then Minecraft. So resolution option just something virtual, because each object has own resolution?

# Answer
**1** \- It will look different depending on a number of factors, such as:

* Lighting (A horrifically underrated aspect of game development)
* Shaders

**2** \- Correct, models don't have a resolution. The level of model detail is measured in vertices, polygons and edges. Whilst raster graphics and textures do, models are very different. The way that a game is *4K* or *HD* is because of the display size it supports. It has nothing to do with models or textures, only window/screen size.

If this answer was no help, please tell me!

(btw good question)
> 0 votes

---
Tags: unity, unreal-4
---


title: Smooth shading in Unity

text:
# Question
Title: Smooth shading in Unity
I would like to have more higher poly sphere than in Unity standard sphere.

I have made sphere in Blender, set smooth and imported in Unity as fbx.

Now, I have problem that for every face there is a black border showed. It doesn't look very nice. How to fix that ?

# Answer
> 1 votes
Read the error message at the bottom. You forgot to add Albedo UVs.

---
Tags: unity, lighting, fbx
---


# Question
Title: Best way to let the player know there are multiple solutions to a problem?(and force them to play again)
I am going to work on a map for my game that is in first person mode. This is the story(planned).

He is on a sinking ship and he wants to escape before the ship sinks. He has a few ways of doing so, either with the on board seaplane or an emergency raft. Both methods will lead the player to different maps in the game. So here is the question:

How can I notify the player that there is another way of "winning" the map if he chooses one. I do not want to just pop out and say "hey you could have used the boat" or even include a progress map of some sorts, but I still want the player to visit the map again in the future to figure out the paths. Any suggestions would be awesome.

The lighting would be dimmer as the scene is set at night. There will be blood, grease and other dirty stuff on the player's screen. The ship itself is most probably going to wobble around.

**edit** Sorry that I didn't clarify, but I want to know methods to lure players to play the map again. Methods of letting the player know that there are different methods works, but I think that should not be the only method. I'll change the title.

# Answer
There are probably an infinite number of ways of doing this. And any of these ways will be *the best* for its specific situation.
In spite of that I am going to address a few rather broad concepts based on different mechanisms and indicators:

## A) Give them an overview of their situation

Depending on how open your level/world is, you have different ways to do this.

An obvious and easy way would be to provide a room they have to pass through on their journey which gives them an overview of the area.

This could be e.g.:

* The Bridge of your ship; A room that is central to the vessel, situated on top of it and offering a panoramic view of the upper decks. Add visual indicators like *runway lights* for the seaplane catapult (or whatever you use to launch it) or e.g. lights recessed into the floors, leading to the emergency rafts. Or even go plain aggressive and light these things up with floodlights.
* The Security Room; A room in the bowels of the vessel, full of TV screens that are displaying the views from different cameras all over the ship. You can make some of these screens stand out by making them brighter, turn other screens off, show people running along hallways towards something, etc.
* Maps & Escape Route Signaling; Add maps and signs to thoroughfares and cross-ways that indicate important areas you want the player to be aware of. E.g. add signs pointing towards *The Seaplane Hangar* or *Starboard/Port Lifeboats*.

## B) Force them to make a decision

If you're willing to restrict the player in their movements to some extent you can present them with a situation where they have to make a decision: Go either *left or right*, *up or down*, etc.

You can make them aware that they've made a decision by adding different less and more obvious cues to the mix. E.g. remove the signs pointing towards the other option, add a radio transmission or a scene of someone using the other option to escape themselves, etc.

## C) Show them possible alternatives

In the spirit of forcing them to make a decision you can also show them that there's other ways to achieve the same goal.

* For example, you could design your level that by choosing one path, you will eventually move along a path that leads you past the other option, showing it maybe behind a chain-linked-fence or a window - unattainable but still there. Maybe adding some animations, again of the other solution being used by an NPC.
* While eventually escaping you could show someone using the other option, e.g. the seaplane flying over the character sitting in the life-raft.
* You could add cues to the next map, e.g. a radio-log of someone asking if anyone made it off the ship using the plane/boat/etc.

---

Now, all of these have obvious advantages and flaws. It is up to you to find out which works best for your map/scene. You will also see that your planned audience will influence your decisions in a major way.
While some people are of the curious kind, wanting to find out if there's other ways. Others will already be satisfied by having made it off the ship, and will never even spend a thought on there having been possible other ways.

An example of this is the *opening sequence* of Skyrim. There's a very first decision in the game right after the dragon's attack, but I doubt that most people have ever become aware of it, even now.
The decision is to either go with the stormcloaks or the empire. And while it ultimately doesn't really matter, it still changes the early game by some extent - shoving you off onto different factions and slightly different initial questlines.
> 2 votes

---
Tags: maps, level-design, levels
---


# Question
Title: Can I change the tile size of a 2D isometric game in the middle of development?
First things first:

* This is just a side project.
* It's going to be my first "real" game.
* In real life I'm a full time web developer (ASP.Net) with several years of experience.
* I also have some basic knowledge of working in Unity 3D from several courses and small demos I've built.
* My pixel art skills still suck, but I'm working on it.

So, I'm working on a game design for quite some time now (years) and just completed the latest draft of the design document. It's going to be a 2D isometric tile-based game. I adore the pixel art of Undungeon in terms of character proportions, and want to aim for a similar style.

Here's my problem: I'd love to just get started with implementing my game, but I have no assets yet.

* Is it a reasonable approach to just start coding using placeholder assets, even if the whole grid size / character proportions are uncertain and probably going to change at some point? (Let's say my main characters sprite is 16x16 but I change it to 32x16 later on.)
* Should I just abstract everything away that deals with pixel sizes?
* Or bite the bullet and settle with a grid size from the very beginning?

I hope this isn't too broad of a question. Thanks for your help!

# Answer
1. Very early in your project, define two constants `TILE_WIDTH` and `TILE_HEIGHT`.
2. Use these constants whenever you refer to the measurements of your tile. This also includes indirect values which are derived from them. If you ever need, for example, half the width of a tile, write `TILE_WIDTH / 2`. By the way, most compilers will notice that you are dividing a constant by a literal and calculate it at compile-time, so that's unlikely to affect performance.
3. Whenever you handle coordinates, distances, velocities etc. in your game, handle them as floating point values where 1 unit is one tile, not one pixel. That way you make sure that your game mechanics are decoupled from your pixels-per-tile resolution.

That way you should be able to keep all of your code completely resolution-agnostic.

You will have to throw away most of your assets if you decide to change the resolution later (rescaling pixel art automatically usually doesn't turn out well). A possible way around that is using sprites and tiles derived from pre-rendered vector-art or 3d models. You just need to pre-render them again in a different resolution. But that will lead to different aesthetics than pixel-art (not necessarily *worse* aesthetics, though).
> 2 votes

# Answer
> * Should I just abstract everything away that deals with pixel sizes?

Yes, definitely. A basis of one unit per tile is probably the most intuitive one.
Once your whole game uses tile-related units, changing the pixel (or vector!) size of your assets won't bother you at all.
> 1 votes

---
Tags: unity, sprites, grid, pixel-art
---


# Question
Title: What is the most efficient method to write a multiple choices story?
I’d like to tell a story through a video game, and I’m starting to write it. But I got like 8 characters, some of them dies, some don’t, player has important choices changing the way characters talk to him or interact to eachother and I’m looking for an efficient way to get the story on paper before starting to code.

Do you guys know a clever way to write this ? I tried to make a file for each path, but its a bit messy

# Answer
When you have a very branching story, it can be helpful to keep track of the main story outline in form of a flowchart. Here is one for the visual novel Katawa Shoujo (posting it inline would be quite pointless due to the huge size of the image). This image was created by fans after the game was published. It is not the one they used during development. But it still gives a good impression how such a flowchart could look.

There are lots of programs to create charts like that. I would use Microsoft Visio, but there are lots of alternatives available which don't cost nearly as much.

Behind each of these boxes is a dialog scene which you would have to write down separately. When you have an author-friendly toolchain, it might make sense to write them directly in the format in which your game engine can read it. That way you can test them immediately. A short test-cycle is just as important for the story as it is for the gameplay. Dialog lines often read differently in the context of your game than when you read them in a text editor. If you don't have an author-friendly toolchain, invest the time into building one. That investment will amortize itself quickly.

The nice thing about such a chart is that you can use it as a kind of todo-list which you can print out and put checkmarks on after you wrote, proofread and testplayed a scene.
> 15 votes

# Answer
I haven't worked with it myself, but I've been pointed to Twine for something like that. It is an editor and a story player, but there should be plenty of export function to get it in the game editor of your choice when you are done.
> 1 votes

# Answer
There is mathematical formalism to make sure you get branching story where events can happen in various orders. It is called Petri Nets. There is nice write-up. You can either use Petri Net editor or MUSE storytelling engine.

This should greatly simplify your task!

Why? Because it is rather time consuming to get all possible playthrough through exhaustive testing. It is preferred to find a way to automatically map and test your story.

One way to quickly playtest a story, is to just write it as interactive fiction in InkleStudios Ink, and then improve.

However automatic testing will decrease the time that humans need to spend on the task.
> -1 votes

---
Tags: storyboard
---


# Question
Title: Collision not working in phaser node multiplayer
I'm writing a tank trouble clone just for fun using phaser and node, so this is my tank instantiation

```
tank = game.add.sprite(Math.random() * 800, Math.random() * 640, 'tank');
tank.anchor.setTo(0.5, 0.5);
tank.scale.setTo(0.5, 0.5);
game.physics.arcade.enable(tank);
tank.body.immovable = true;
tank.body.collideWorldBounds = true;

```

This is how an enemy tank is defined at the client

```
var Enemy = function (game, id, x, y, angle) {
    this.id = id;
    this.x = x;
    this.y = y;
    this.angle = angle;
    // set the tank properties
    this.tankEnemy = game.add.sprite(this.x, this.y, 'enemy');
    this.tankEnemy.anchor.setTo(0.5, 0.5);
    this.tankEnemy.scale.setTo(0.5, 0.5);
    // game.physics.arcade.enable(this.tankEnemy)
    // this.tankEnemy.body.immovable = true;
    // this.tankEnemy.body.collideWorldBounds = true;
}

```

**The problem is** in the above case I have enemy tank at the client as a non body (which means I'm checking the collision between a "body" and a "non body") and when I try to check collision

```
game.physics.arcade.collide(tank, enemies[i].tankEnemy);

```

It doesn't work.

So I tried making it a body by un-commenting the code, now the enemy tank behaves more weirdly than before. Whenever a client moves, it gains velocity for other clients, making it go beyond the map and becoming invisible. Whereas I'm just changing the coordinates for other clients -

```
function tankUpdate (data) {
    // when the update event is fired
    var moveTank = findTank(data.id);
    if (!moveTank) {
        console.log('tank not found');
        return;
    }
    // update the tank location
    moveTank.tankEnemy.x = data.x;
    moveTank.tankEnemy.y = data.y;
    moveTank.tankEnemy.angle = data.angle;
}

```

This is how a client emits update event -

```
socket.emit('update location', {x: tank.x, y: tank.y, angle: tank.angle});

```

The server in turn broadcasts this update, which leads to the calling of `tankUpdate`.

What is the right way to implement this? I just want to prevent the collision between tanks.

**EDIT**

After a long discussion with @Hexus on slack we concluded with these points which solved the issue -

1. I was not sending the velocity to the server. (@Hexus mentioned it in his answer).
2. I was setting the `sprite.x` property which was conflicting with the position of `body`. `sprite.body.x` is the right property to set.
3. I was updating the position and velocity as soon as I received from the server which leads to a shaky and not-so-smooth movement. The idea is to create a buffer and then update.
4. **Lastly but the most important**, if you are testing the game without two instances running on the same machine/browser make sure you set `game.stage.disableVisibilityChange = true;` in your `create` method.

Again thanks a lot to @Hexus for helping!

# Answer
> 1 votes
Make sure you're sending the **velocity** of your physics bodies from the server too. Position alone won't cut it, because it's not the only thing that impacts how the game objects move.

The most secure way to do this, to help prevent cheating, is to only send *input* from the client to the server. You can then simulate physics server side for an authoritative game state.

You can of course still simulate physics on the client, but do so while updating the state as sent from the server.

Ultimately, make sure your server sends across **any state that affects the movement** of your physics bodies. If you interpolate all of these properties over time, you should hopefully achieve some smooth results.

I know that running Arcade Physics with Node.js is pretty difficult because it's so tightly coupled to the rest of the framework, so in your case it will probably be easiest to trust the client's state, at least to see it working.

**Edit:**

For physics-enabled Phaser sprites, make sure you're setting `sprite.body.position.x` and `y`, not the sprite position, because the body will always override this.

**Edit 2:**

Having looked over your code, I noticed you're updating physics bodies **as soon as you receive the data**. This doesn't play well with Phaser, as it expects certain changes to happen at certain times.

If you buffer your updates in an array, then loop through and apply them in your **update()** method, you should be good to go.

---
Tags: collision-detection, javascript, phaser, node.js
---


# Question
Title: What record stores the inventory in a Skyrim savegame file?
For The Elder Scrolls V: Skyrim, I'm looking for a way to read the player's inventory without having to go into the game to do it.

I've scoured the pages from the UESP wiki on save file format but I couldn't find where *the player's inventory* is, even after writing a crude REFR change form reader. The wiki has a lot of information on many structures, but none are clearly identified as the player's inventory.

So, does anyone know where the inventory (RefID and count) is in the savegame file?

# Answer
Late to the party, but it is in the change forms. More specifically, it's an ACHR record (type = 1) in the change forms. Unfortunately, the change forms for ACHR records aren't documented at all on UESP.

Back when Skyrim was released, I released an alchemy tool like what you're wanting to do. I wanted to do what you're doing, but I ran into the same brick wall that you are - information about the inventory wasn't available. Now I'm working with FO4 doing something that similarly needs to read the inventory. What I've decided to do is place a stipulation that the items I'm looking for can NOT be in an actor's inventory (player or NPC) -- they can be in any other kind of inventory. With that stipulation, you can read the change records and figure out what the player has moved (thus assuming ownership) by reading the REFR records like you've already done. It's hackish, but it should work for your purposes, I believe.

Better for *your purposes* might be adding a special type of container via a mod, and have the player put their ingredients in it. Then you can search for your container's RefID (or BaseID), and read the REFR for it.
> 1 votes

---
Tags: file-format, savegame, skyrim-modding
---


title: Use tilesets or a complete image?

text:
# Question
Title: Use tilesets or a complete image?
Whats the advantage of using tilesets instead of importing the entire image itself ? Is it giving us some sort of advantage (in terms of memory maybe) ? Also, how much of a disadvantage would it be to use whole image instead of tilesets ?

# Answer
> 1 votes
It's simply more convenient. If you store the tiles with ids, then you can easily convert those to coordinates on the texture, so you don't need to store the textures in an array or use switches. You also don't need to rebind the textures if you use an API like OpenGL or DirectX, and you only need a single reference for the textures instead of multiple ones.

It doesn't save too much memory, a couple of bytes at most.

# Answer
> 1 votes
Your question is a bit unclear, but I assume you are asking:

> Why render the world of a 2D game using a single texture holding an indexable tileset instead of having the world pre-rendered from said tiles? What is the advantage to building the image of the world at runtime?

There are many advantages to this.

---

Firstly you are right that less memory is used.

Let's say you're using tiles of 32x32 pixels, you have 100 different types of tiles, your map is 128x64 tiles and 1 pixel is 3 bytes large.

If you were storing the image, that would be 4096x2048 pixels, which is 8388608 pixels, which is 25165824 bytes (~24 MB).

Now imagine you're using the alternative approach of indexing tiles. Having only 100 tile types means you can use a single byte for indexing the tiles, so your map takes 128x64 bytes, or 8192 bytes (8KB). The texture for your tiles is 3200x32 pixels, which is 102400 pixels, which uses 307200 bytes (~300KB). So that's 315392 bytes (~308 MB), which is 79.79 times smaller than storing the whole image. By using the tile method, you use roughly 1/80th of the memory for the exact same map.

This is precisely why older games consoles had special tile-base graphics processors. They'd have a fixed amount of tile data and they'd build the screen buffer using tile indexes. It was incredibly effective.

---

Secondly, by using the tileset method you can animate your tiles. The other method would require a different full sized image of your map for every frame (even ones that don't change), and if you had individual tiles with different numbers of frames you'd have to account for the fact their animations would be out of sync (a 3 frame tile would loop back to frame 1 whilst a 5 frame tile was on its 4th frame, so you'd need 15 full images to account for that discrepency).

If you use tiles, every tile can be animated individually with minimal detriment. You need only store the number of frames each tile has and you can always find the correct frame by using the modulo operator.

---

Lastly, (I'm not sure whether this counts as an optimisation or something better, but it's an important fact nonetheless) with the tileset method you only need to draw what's on screen at the time, so you'll only ever need to draw a few tiles per frame. Say your monitor has a resolution of 1920x1080, you'd only need to draw 60x34 tiles per frame (61x35 worst case if transitioning diagonally).

# Answer
> 0 votes
Tilesets (a single texture subdivided into parts each containing other textures) have the advantage that you could render all geometry that used the tiles from a set in one go instead of having to rebind the texture for every tile.

However with bindless textures and texture arrays this is less of an issue.

---
Tags: tiles, tilemap, assets, asset-management, tilesets
---