title: Using 3D models in an 2D Game in libGDX

text:
# Question
Title: Using 3D models in an 2D Game in libGDX
In my libGDX 2D RPG-Game (like Zelda or something) I want to display some items as 3D-Objects. Since I'm using an OrthographicCamera like this:

```
this.gameWorldCam = new OrthographicCamera();
this.hudCam = new OrthographicCamera();
gameWorldCameraViewport = new ExtendViewport(FRUSTUM_WIDTH, FRUSTUM_HEIGHT, gameWorldCam);

```

I don't know how to render 3D-Object on it. In my render loop I call this:

```
// 2D
spritebatch.begin();
...
spritebatch.end();

// ----------------------------------------------
// Just some hardcoded model creation for testing
// ----------------------------------------------
Model model;
ModelInstance instance;
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createBox(
  5f,
  5f,
  5f,
  new Material(ColorAttribute.createDiffuse(Color.GREEN)),
  Usage.Position | Usage.Normal
);
instance = new ModelInstance(model);
// ---------------------------------------------

// 3D
modelBatch.begin(gameWorldCam);
modelBatch.render(instance);
modelBatch.end();

// 2D
spritebatch.begin();
...
spritebatch.end();

```

What do I have to do, to get the proper result? Right now, nothing of the green 3D cube is visible.

# Answer
> 1 votes
I don't have the reputation to post a comment, but it looks like it's a problem with the camera as the code looks fine. If the camera is inside the object it will not render properly. if your camera it's on the plane Z on the position 0 and your model it's also on that position your are not going to see it. Lower the z on the object or up the camera. Also the camera should have a far and a near values that will render the object even if you move the camera far away.

It also needs the material ambient set to more than \> 0 to be visible or and environment added to the render that has it's own light.

In this last case you can add environments like this:

```
Environment environment = new Environment();
environment.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.2f, 0.2f, 0.2f, 1f)); //20% of minimum light for all objects on this environment
modelBatch.render(instance, environment);

```

Using environments you can also use an environment with point of ligh to give a dynamic shadow to the object (note, it will not cast a shadow on his own):

```
//cast a light from a point. If the object has this enviroment it will be affected by it.
environmentSun.add(new PointLight().set(1f, 1f, 1f, posX, posY, posZ, 1000));

```

Please note that in this last case the point of light should be outside of the model or it will not work for the model.

---
Tags: 2d, libgdx, 3d, rendering
---


title: Isometric Architecture Map Game Data

text:
# Question
Title: Isometric Architecture Map Game Data
I'm not sure this kind of question has been answered yet, if so i'm sorry to duplicate it.

My question is rather simple :

I'm creating a simple Isometric game with libgdx, i'm using Tiled but only to design the map and render it with OrthographicMapRenderer.

The map is a static map of 6864 * 6880 pixels, one tile is 59\*43 pixels

I wanted to do some pathfinding to my game, so I decided to store my map data into a simple 2D array like this : int cells\[i\]\[j\] which would contains 0 if the tile is walkable or 1 if it's not, it is as simple as that !

Currently I've simply using basic formula to convert world cartesian coordinate to Isometric coord, and formula to get tile pos based on iso pos, (eg : you input a iso coord, the function return a vector like \<2,5\> which is the 2nd x tile and 5th y tile.

It perfecttly work as execepted, I also make it that iso tile coord is always positive ( \<0,0\> is at the top left corner of my world )

**But here is my Question or doubt : How to handle correctly the game data tile ? Does a 2D array is sufficient, if yes, how to, for exemple write a function that get if a tile is walkable or no based on tile coord ? ( example : I click on my map, the coordinate is translated to tile coord ( \< 4,5\> for example,) how to check if this tile is walkable ?**, i dont get on how to do it i'm really lost.

**EDIT : Ive successfully implemented the isometric logic : I can convert world coordinate to tile coorinate ( eg : (5075;4851) -\> (203;28)) and the reverse but i'm confused on how to fill the 2d Array, use it for A\* algorithm and make the bridge between these coordinate and the 2D array**

Thank you for you help, Regard

# Answer
> 1 votes
This answers is valid for any language or framework.

I would wrap the tile info on a class, called for example "MapTile" class. This MapTile will have all the data you need, like if it's walkable the type, the name, an unique Id..

then on the array you will put this MapTile class, and you can access from there to the Tiled info an other any info you want to have there using getters, and change it if you want using setters

To make it easier to manage, I recommend you to create a "TerrainType" class that will have the different terrains that your game will have, so you don't need to repeat that data every time you initialize a tile. Initialize them at the start and save them to an Array so you can reuse this read only data to any tile you add to your main array.

---

TL;DR;

* Create a TerrainType class (or use an enum, whatever you feel like).
* Create a class MapTile that is initialized with the information of this TerrainType and extra info you might add like ids, names, if there is something over the tile (use setters to change this at any time)..
* Add to your Array the MapTile class. Now you can access to all the data in this MapTile, including the TerrainType with all the info you may need.

---
Tags: libgdx, mathematics, isometric
---


# Question
Title: Checking distant 2D objects from the player in pure javascript
I'm checking if the objects are too far from the player to be able to disable some things, I'm doing so:

```
const obj1 = {
     x: 0,
     y: 0
};

const player = {
   x: 0,
   y: 0
};

const sqrMagnitude = (x, y) => {
    return (x * x + y * y);
};

const isAwayFromPlayer = (entity, targetEntity, distanceMax) => {
    if(sqrMagnitude((targetEntity.x - entity.x), (targetEntity.y -
entity.y)) > distanceMax * distanceMax){
        console.log("yes!");
    }else{
        console.log("no!");
    }
};

awayFromPlayer(obj1, player, 250);

```

but when walking with the player, sometimes I approach the objects and I get the `console.log("yes!")`, sometimes I move away and also I get, but it was only to work if I were away from them, I'm forgetting to do some conversion to absolute value with Math.abs for example? I remember that this is how it was when I needed some time ago, but something is not working properly.

# Answer
> 1 votes
I made a playable demo below that does what you want:

```
// Create canvas, set it's dimensions, and get it's rendering context
var canvas = document.createElement('canvas');
var width = 520;
var height = 250;
canvas.width = width;
canvas.height = height;
var cx = canvas.getContext('2d');
cx.imageSmoothingEnabled = false;

// Add to DOM
document.body.appendChild(canvas);

//Get the h1 we'll show when you are near the enemy
var h1 = document.querySelector('h1');

// Player and enemy objects
var player = new GameObject(43, 43);
var enemy = new GameObject(Math.round(width / 2), Math.round(height / 2));
// The enemy's radius, at which point we know that the player is within range
enemy.radius = 43;

// Add on key down event listener for player object.
window.onkeydown = function(event) {
  switch (event.keyCode) {
    // Right
    case 39:
      event.preventDefault();
      player.pos.x += 7;
      break;
      // Up
    case 38:
      event.preventDefault();
      player.pos.y -= 7;
      break;
      // Left
    case 37:
      event.preventDefault();
      player.pos.x -= 7;
      break;
      // Down
    case 40:
      player.pos.y += 7;
      event.preventDefault();
      break;
  }
};

// Game functions

function Vect2(x, y, parent) {
  this.x = x || 0;
  this.y = y || 0;
  this.parent = parent;

  this.getDistance = function(vector) {
    //console.log(Math.round( Math.sqrt( Math.pow(this.x - vector.x, 2) + Math.pow(this.y - vector.y, 2) ) ));
    // Get the distance and round it.
    return Math.round(Math.sqrt(Math.pow(this.x - vector.pos.x, 2) + Math.pow(this.y - vector.pos.y, 2)));
  };
}

function GameObject(x, y) {
  this.pos = new Vect2(x, y, this);
  this.width = 25;
  this.height = 25;
  this.halfWidth = Math.round(this.width / 2);
  this.halfHeight = Math.round(this.height / 2);
  this.render = function() {
    cx.fillRect(this.pos.x - this.halfWidth, this.pos.y - this.halfHeight, this.width, this.height);
  };
  this.update = function() {};
}

// Naive loop
function loop() {
  update();
  render();

  requestAnimationFrame(loop);
}

function update() {
  player.update();
  enemy.update();

  // If the player is within the enemy's range, show message
  if (enemy.pos.getDistance(player) < enemy.radius) {
    h1.style = "visibility: visible;";
  } else {
    h1.style = "visibility: hidden;";
  }
}

function render() {
  cx.clearRect(0, 0, width, height);
  player.render();
  enemy.render();

  // Draw a circle around the enemy
  cx.beginPath();
  cx.arc(enemy.pos.x, enemy.pos.y, enemy.radius, 0, Math.PI * 2);
  cx.stroke();
  cx.closePath();
  // Draw a dot in the middle of player so that you know where on the player the check is ocurring
  cx.beginPath();
  cx.arc(player.pos.x, player.pos.y, 1, 0, Math.PI * 2);
  cx.fillStyle = 'blue';
  cx.fill();
  cx.fillStyle = 'black';
  cx.closePath();
}

loop();
```

```
html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

h1 {
  /*display: none;*/
}

canvas {
  border: 1px solid black;
}
```

```
<h1>Aha! Something's close</h1>
```

So the game checks if the player is within range of the enemy, and if so, it shows a message. I hope this was helpful

---
Tags: 2d, javascript
---


# Question
Title: Can I position a player avatar behind the camera based on rotation?
I'm currently reverse engineering a video game where what's rendered on the screen depends on the proximity of the player avatar to the camera. As such, for my freecam to work properly, I need to bring the player avatar along with the camera.

Since I can't yet find how the player avatar is rendered to the screen, the next best thing I can think to do is to place the player avatar behind the camera at all times (I suppose essentially like making the player avatar orbit the camera, but always be behind it).

I just can't quite pin down how to make this happen.

The values I have are as follows:

**Player Avatar**:

* X
* Y (Up/Down)
* Z

**Camera**:

* X
* Y (Up/Down)
* Z
* Pitch (In degrees natively, but converted to radians for my calculations)
* Yaw (In degrees natively, but converted to radians for my calculations)

**World Orientation**:

To get my camera to move forward in the direction I'm pointing my mouse when pressing the Y key, these are the calculations I'm using (code is in Lua):

```
--//Camera XYZ values
local camCoordX = readFloat("[cameraBase]+990") --Camera X
local camCoordY = readFloat("[cameraBase]+994") --Camera Y
local camCoordZ = readFloat("[cameraBase]+998") --Camera Z

--//Camera pitch and yaw
local pitch = math.rad(readFloat("[cameraBase]+1540")) --Pitch
local yaw = math.rad(readFloat("[cameraBase]+1544")) --Yaw

--//Sine and cosine calculations
local sinOfYaw = math.sin(yaw) --Sine of Yaw
local cosOfYaw = math.cos(yaw) --Cosine of Yaw
local sinOfPitch = math.sin(pitch) --Sine of Pitch
local cosOfPitch = math.cos(pitch) --Cosine of Pitch

--//If Y key is pressed, write new camera XYZ values accordingly
if isKeyPressed(VK_Y) then
    writeFloat("[cameraBase]+990", camCoordX + (sinOfYaw * speed))
    writeFloat("[cameraBase]+994", camCoordY - (sinOfPitch * speed))
    writeFloat("[cameraBase]+998", camCoordZ + (cosOfYaw * speed))
end

```

Based on that information, is it feasible for me to accomplish placing the player avatar behind the camera at all times based on rotation? I'm open to other suggestions or options as well. Thank you for any help you can offer!

# Answer
Here's what I'd do, basically the opposite of what you're already doing to move your camera but instead of adding, subtracting so that you move in the opposite direction of the camera. Gonna use C++ code as that's what I have this code written for already.

```
vec3 Subtract(vec3 src, vec3 dst)
{
    vec3 diff;
    diff.x = src.x - dst.x;
    diff.y = src.y - dst.y;
    diff.z = src.z - dst.z;
    return diff;
}

float DegreeToRadian(float degree)
{
    return degree * (PI / 180);
}

vec3 GetNewAvatarPosition(vec3 currAngle, vec3 cameraPOS, float dist)
{
    vec3 d;

    d.x = cosf(DegreeToRadian(currAngle.x - 90)) * dist;
    d.y = sinf(DegreeToRadian(currAngle.x - 90)) * dist;
    d.z = sinf(DegreeToRadian(currAngle.y)) * dist;

    vec3 newAvatarPOS = Subtract(cameraPOS, d);

    return newAvatarPOS;
}

//Psuedo code:
avatar.pos = GetNewAvatarPosition(camera.angle, camera.pos, 3);
avatar.angle = camera.angle;

```

That would move your avatar 3 units behind the camera

The proper way to do this would be to use matrix multiplication, multiply the 3d coords of the camera (as a vec4) by a translation matrix (vec4x4). Looks like this:

Courtesy of Wikipedia's Euclidean Geometry Translation page. You would just change the first three "1"s to 3 to move a distance of 3
> 1 votes

---
Tags: camera, rotation, transformation, coordinates
---


# Question
Title: "Occlusion culling data is out of date. Please rebake" - No scene specified, Unity 5.6.2
I've inherited a Unity project with hundreds of scenes. When I try to build it for consoles/mobile I get 11 errors saying "Occlusion culling data is out of date. Please rebake" and the build fails. Double clicking on these errors takes me nowhere, and no scenes are specified. It is my understanding that I can only bake occlusion culling by opening the scene manually and hitting the bake button. Due to the size of this project, that would take many hours. The game runs fine from within the editor, but simply won't export to consoles.

How can I do any of the following:

1. Automatically rebuild all occlusion culling information.
2. Find which scenes are out of date.
3. Disable occlusion culling project wide, letting me at least get a build onto dev-kits out for further evaluation.

Thanks for any help at all.

# Answer
I know this is from August 2017, but I just had a similar issue in Unity 2018.2 and this has not been answered. I opened an old project that I had been working on in Unity 5 and one particular scene had the error. To resolve, I did the following:

Click Window \> Rendering \> Occlusion Culling

This brought up the Occlusion Culling settings. There is a button at the bottom that is labelled "BAKE". I clicked on this. I then saved the scene and the project, then Quit and Relaunched Unity and it worked

Here is the link to the Unity article on Occlusion Culling:

https://docs.unity3d.com/Manual/OcclusionCulling.html
> 3 votes

---
Tags: unity
---


title: BUG in sprite GameMaker

text:
# Question
Title: BUG in sprite GameMaker
In the game you have an object called obj\_Corpo, and your image is a 3x3 square. I use it by stretching it horizontally or vertically for 10 or 20 times. Here's an example:

Acontece que no jogo ele não aparece da forma adequada.

It turns out that in the game it does not appear properly.

Note that it only gives horizontal error. This began to happen a few days ago, with no explanation. I've tried other colors and the same thing happens (darkened edges).

# Answer
> 0 votes
After hours of stress I found the solution only by increasing the size of the texture pages from 4096 to 8192.

---
Tags: sprites, game-maker
---


# Question
Title: How can I make my character work in my 2d top down game?
I have two sprite sheets and they have to work together. I don't know how to make frames animation and everything. If you could explain it to me, it would help me so much. I am using unity c++ or c# . I am a total beginner so I don’t know how to cut the sprites because the sprite is a tenplate for players to upload their character . First I need to be able to walk in 4 directions and then to be able to animate my characer so it can hold weapons and the character is supposed to be able to swim and to sit also! I really need help!

Here are the templates:

# Answer
> -1 votes
For Platformers check out https://www.youtube.com/watch?v=dwcT-Dch0bA&t=761s or for top down try https://www.youtube.com/watch?v=Pk3GCgaNVTY&list=PLiyfvmtjWC\_X6e0EYLPczO9tNCkm2dzkm You will need to make your question more specific if you want more than just a pointer to good tutorials :D

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


# Question
Title: Unity: how to implement a sound detection ?
I want to trigger an event if an enemy (or player) can hear a sound generated from other enemy/player.

How to implement a sound detection system ?

Thanks

# Answer
> 3 votes
When it comes to AI actors reacting to noises, then most games do not actually jack into the audio system. The reason is that it is far too unpredictable from a gameplay perspective.

Enemies reacting to noises is something you usually focus on in stealth-based games. And stealth-based games often play more like puzzle games than action games. This also applies to the level design. In order to create a good puzzle, you need to know exactly how your pieces interact. If you use a real audio engine with occultation, dampening, reflections etc. (which Unity won't do out-of-the-box, but there are ways to do these things) and use audio clips as inputs which can change during development, then your AI actors behavior becomes quite unpredictable. This makes it very difficult to design enemy encounters which play out the way you want them to.

It also makes the game very unintuitive to play. In most games, players develop a feeling for the hearing range of the enemies and use that information to plan their strategies. But with a realistic audio engine, hearing ranges can be very dependent on environmental details. It will become very difficult for the player to estimate what the AI opponents will hear and what they won't hear. This can become very frustrating.

For that reason you should create an own audio detection system which is separated from the actual audio system. When the player performs an action which generates a sound the AI actors are supposed to react to, then use `Physics.OverlapSphere` (or `Physics2D.OverlapCircle` if your game uses 2d physics) to find any AI actors in range and inform them of the player's position and the nature of the sound. Your AI should then measure the distance to the player and decide what to do with that information.

If you don't want AI actors to be able to hear the player through walls, you can use a `Physics.Linecast` / `Physics2D.Linecast` to detect obstructions. Increase the distance accordingly when your AI actor decides whether or not it reacts to that input.

# Answer
> 0 votes
From Unity's Audio Listener API it seems like there is no way to check if the camera hears a sound or not.

The only solution I can think, is to control manually the volume of a specific `AudioSource` based on its distance from the camera. So that you can get that `AudioSource`'s volume to see if the sound is actually audible or not.

---
Tags: unity
---


# Question
Title: Player animation mismatches its movement input
I am using the code below to have the character's directional movement match its movement animations but when the player model has a non-zero y-axis rotation, the animations become mismatched.

Code:

```
    moveVector = new Vector3 (movX, 0, movZ).normalized * (movementSpeed * (1 - pInv.totalMass/20)) * (1 + bonusSpeed);

    animBector = pBody.transform.rotation * moveVector;
    moveVector = gameObject.transform.rotation * moveVector;

    pAnim.SetFloat ("moveSpeed", movementSpeed/2);
    pAnim.SetFloat ("Vertical", animBector.normalized.z);
    pAnim.SetFloat ("Horizontal", animBector.normalized.x);

```

Note that pBody is the mesh body of the playerObject and is a child of gameObject. The gameObject does not rotate since this is a top-down project & the `moveVector = gameObject.transform.rotation * moveVector;` part ensures the player moves towards its respective parts of the screen on pressing a directional button.

e.g. forward input while facing North will display a forward animation; forward+right input while facing North East will display a sideways (or strafe) animation, the correct one should be a forward animation.

# Answer
It looks like you want `animBector` to be the movement vector, but local to the apparent direction that the player is facing. This would mean that you need to reverse-apply the rotation of `pBody`.

Please try replacing this line:

```
animBector = pBody.transform.rotation * moveVector;

```

with this one:

```
animBector = pBody.transform.InverseTransformDirection(moveVector);

```

---

If the move vector and the player object might be scaled, but you want `Vertical` and `Horizontal` animation parameters to be unscaled, use `InverseTransformVector` instead.
> 1 votes

---
Tags: unity, animation
---


# Question
Title: Performant Fog-of-War With Sight Blocking in Unity
In games like Command & Conquer or Age of Empires, players can't see all of the map. Terrain and enemies are revealed only when the player has soldiers nearby.

As I understand it, the most performant way of doing this is by representing map visibility as a grid of cells. When a unit moves into a new cell it updates all cells within a circle shape around the unit.

However, I would like to know how to integrate sight blocking. What I mean by this, is that if a cell is occupied by something which a unit can't see past (like a wall) all cells behind the wall are covered by fog-of-war.

Here's a YouTube video of what it should look like. The author doesn't go into how they did it, aside from mentioning "brute force shadow casting".

# Answer
> 1 votes
Basically what I do is, for each pixel in vision range, I go pixel by pixel and check a line to the center (using the Bresenham's line algorithm), if there is no obstacle, then the pixel is visible, otherwise, it is blocked.

It works pretty well, ~100 units at 60fps, check out this tweet to see it working. I plan to write a blog post to explain in detail the implementation.

Don't know if that works for you as an answer.

---
Tags: unity, c#, fog-of-war
---


title: How to raycast in MonoGame 2D?

text:
# Question
Title: How to raycast in MonoGame 2D?
Currently I am using a Ray class that I built myself. The following is for brevity.

```
public class Ray : GameObject
{
    public GameObject Shooter;
    public List<GameObject> Objects;
    public float Speed = 250f;
    public bool Collided = false;

    public void Update(){
        if (Collided) return;
        Position.X += Speed * gameTime;
        Position.Y += Speed * gameTime;

        foreach(var obj in Objects){
            if (this.Intersects(obj) {
                 obj.OnCollide(this);
                 Collided = true;
            }
        }
    }

```

This works, but only if I control the amount of rays, cause if I create too many rays, the game becomes laggy OR the ray/bullet get past through walls (idk why). I am trying to find out which objects that player can see and only draw the visible things, so I need to let out alot of rays. Is there a more efficient way to achieve this objective.

# Answer
> 2 votes
The reason your rays seem to be passing through game objects is that with each iteration for a single ray you're jumping 250 units. Some objects may be smaller than this or have intersecting lines that are smaller than this. An easy solution is to make your ray speed smaller. Unfortunately, this will only make your game lag even more.

Another reason your rays could be passing through objects is that you're not iterating over game objects from nearest to farthest. If a collision is found that's close, then another that's far, your algorithm will end up accidentally preferring the latter. A relatively easy solution to this is to gather your objects in a second container, then sort them from closest to farthest from the start of the ray. Iterate over that and break at the first collision. Again, this will probably increase lag, especially with lots of rays at different positions.

This method is rather slow for large scenes and/or scenes with tons of game objects. A single ray can end up taking more than 1/60th of a second to process, which is when you'll notice lag. Consider your `this.Intersects(obj)` function. By itself, this may be very fast, but if you repeat this call thousands of times per frame, it'll become a problem.

There are many ways to make it faster, though. Here are two:

1) For each ray, don't move in steps. Use math to check if each game object collides with the *whole* ray at once. Eliminates having to iterate over every game object many times. Check out How to find out if a ray intersects a rectangle?.

2) Use spacial partitioning to avoid having to check *every* game object for any given collision detection (not just rays). This could be harder to retrofit into your game engine, but if you intend on having very large levels with many objects and don't want the game run slow, it's definitely worth the investment.

You can combine these two methods to make a much faster raycasting system. However, still be careful casting *tons* of rays.

---
Tags: c#, monogame, raycasting
---


# Question
Title: How to persist Unity camera values changed while running/paused
I have a Unity program where all the GameObjects are created programmatically in C#, so there's nothing to see in the Scene window unless I hit play. I can hit pause and change the settings for a camera, but those changes are all discarded when I exit playmode.

What do I have to do to make the MODIFIED values the new, PERMANENT ones?

# Answer
> 0 votes
> I have a Unity program where all the GameObjects are created programmatically in C#

...

> the camera is the default one that was part of the scene when I created the new project.

...then not "all the GameObjects are created programmatically," if there's at least one (the camera) that's present in the scene before you run. These details matter to the answer, so be sure to always be specific about your situation and what you need.

In this case, once you've modified the camera in the editor's play mode to have the settings you want, you can click on the gear icon at the top-right of the component inspector and choose Copy Component.

After you exit play mode, click on the gear again and select Paste Component Values to overwrite the camera's settings with the ones you copied.

If you need to do this with multiple components, or multiple objects, you can also save the object as a prefab, then apply the changes back to the prefab to save them.

---
Tags: unity, camera
---


# Question
Title: How do I determine how far to move an object in the client when using client-prediction?
I have a game server which, for testing purposes, is updating once per second, or 1hz so I can correctly implement client-side prediction. Everything is running locally at the moment so there is no lag issues to deal with, but this setup replicates potential packet loss, or if the server somehow is behind on processing.

I am using Unity for the client. I have a tunnel where the position is updated on the server and then broadcast to each client each tick (once per second). The client simply then lerps between its current position, and the new position received from the server, and this seems to work nicely.

However, as I have set the tick to 1hz, there are unexpected results where the position seems to pulse, rather than smoothly transition. An example can be seen below.

It can perhaps be seen more clearly without lerping

I have tried constantly increasing the tunnel's position in the client, but if it's moved too far in the client, once the server's position is received, it is snapped back to that position which creates some weird rubber-banding like effects even though there is no lag.

How can I determine how much to move the tunnel in the client to create some *seamless* movement, even when the tick rate is so low? Baring in mind this movement is variable, so it can move faster/slower at times so the movement in the client cannot be a fixed number.

Yes, I can just increase the tick rate which gives smooth movement, however, there is no lag to account for as it's all local so I am just preparing for when I move the server to actual hosting.

---

Instead of lerping between the current position and the received position, should I be trying to lerp between the current position and the *next* received position?

---

Lerp:

```
        Vector3 currentPosition = transform.position;
        Vector3 newPosition = new Vector3(currentPosition.x, currentPosition.y, tunnelPositionZ);

        transform.position = Vector3.Lerp(currentPosition, newPosition, Time.deltaTime);

```

---

DMGregory's solution attempt:

If I decrease the `1.0f` for the `blend` variable, the tunnel will move very slowly and then jolt forward when a snapshot is received. Decreasing the `1.0f` to around `0.1f` seems to align the speeds but there is still a noticeable jolt.

I'm using the same velocity for the `currentPosition` and `newPosition` because the velocity never changes.

```
    float dT = Time.time - latestSnapshot.arrivalTime;
    float blend = Mathf.Clamp01(dT / 1.0f);

    Vector3 currentPosition = transform.position;
    Vector3 currentVelocity = rigidbody.velocity;

    Vector3 newPosition = new Vector3(currentPosition.x, currentPosition.y, latestSnapshot.tunnelPositionZ);
    Vector3 newVelocity = new Vector3(currentVelocity.x, currentVelocity.y, latestSnapshot.tunnelVelocityZ);

    Vector3 velocity = Vector3.Lerp(currentVelocity, newVelocity, blend);

    Vector3 position = Vector3.Lerp(
               currentPosition + velocity * dT,
               newPosition + velocity * dT,
               blend);

    transform.position = position;

```

# Answer
It looks like you're trying to separate the behaviour on the xy vs z axes, but you have not done so correctly.

```
float dT = Time.time - latestSnapshot.arrivalTime;
float blend = Mathf.Clamp01(dT / snapshotPeriod);

float velocity = Mathf.Lerp(
                    latestSnapshot.tunnelVelocityZOnArrival,
                    latestSnapshot.tunnelVelocityZ,
                    blend);

float oldEstimate = latestSnapshot.tunnelPositionZOnArrival +
                    velocity * dT;

float newEstimate = latestSnapshot.tunnelPositionZ +
                    latestSnapshot.tunnelVeloctyZ * dT;

Vector3 position = transform.position;

position.z = Mathf.Lerp(
                    oldEstimate,
                    newEstimate,
                    blend);

transform.position = position;

```

Note that the starting point for our `oldEstimate` is *where we were when the snapshot was received*, NOT where we are now. Using the current position instead of the historical position creates a feedback loop, and over-estimates forward progress when we add `velocity * dT` on top of it, producing the pulsing motion you observed.

When implemented correctly, projective velocity blending is C1 continuous (consistent velocity across snapshot transitions), and transitions naturally to dead reckoning prediction in the event that a snapshot is missed or arrives late.
> 1 votes

---
Tags: networking, client-server, movement-prediction
---


title: How do I fix the YAML error in Unity 5?

text:
# Question
Title: How do I fix the YAML error in Unity 5?
I'm using Unity 5 and I'm getting an error in a YAML file. The error is "Unable to parse YAML file: \[mapping values are not allowed in this context\] at line 1" This comes up every time I open the engine.

I've seen some say to open the YAML file and change some stuff in it. But I can't even find the YAML files. I've also seen that it's caused by meta file issues and version control. The project is local but I don't know if it matters if it's local or cloud based.

Does anyone have a solution for this issue?

# Answer
It seems your scene(s) has/have corrupted, the system can't read some particular scene(s). Try to check every scene to find out which one has corrupted, if you do have a backup then restore the scene files.

Unity Manual: Textual Scene File Format - Format Description
> 1 votes

# Answer
I had the problem of "Broken YAML file" when I tried to open one of my old projects. With the above error, all the game objects in the scene turned to "Missing Prefab".

The project was created using Unity 5.21. I tried to open the project with Unity 5.40 and it worked. Now there were no "Broken YAML file" error nor "Missing Prefab" and it worked fine for me.
> 0 votes

# Answer
Close Unity and open explorer. Now search all the .meta files from your project. Delete them all and open Unity again. It will create new meta files. And issue would be resolved.
> -1 votes

---
Tags: unity
---


# Question
Title: How can I find if a GameObject is not exist in the Hierarchy?
```
var selections = Selection.objects.OfType<GameObject>().ToList();
        if (selections.Count > 0)
        {
            tempSelections = selections;

            for (var i = selections.Count - 1; i >= 0; --i)
            {
                var selected = selections[i];
                transformSelection.Add(selected.transform);
            }

            TransformSaver.SaveTransform(transformSelection.ToArray());
            transformSelection = new List<Transform>();
        }

        for (var i = tempSelections.Count - 1; i >= 0; --i)
        {
            var selected = tempSelections[i];
            if (GameObject.Find(selected.name) == null)
            {
                GUI.enabled = true;
            }
            else
            {
                GUI.enabled = false;
            }
        }
        if (GUILayout.Button("Undo last selection if deleted"))
        {
            transformsCount = TransformSaver.LoadTransform().Length;
            PlayerPrefs.DeleteKey("transform");
        }

```

For testing I'm deleting one of the GameObjects in the tempSelections List

But then I'm getting exception in the editor on the line:

```
if (GameObject.Find(selected.name) == null)

```

Since the GameObject have been deleted it can't access the GameObject.

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

# Answer
The error message is pretty descriptive:

> MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either **check if it is null** or you should not destroy the object.

*(emphasis mine)*
Your `selections` list contains 'zombie' objects that were already destroyed in the C++ engine part and thus it would be semantically incorrect to access them from the C# scripting engine part. Such 'zombie' GameObjects cannot be automatically 'deleted' in the C# part due to technical limitations and its up to you to handle them (drop the reference). Unity for convenience ensures that destroyed objects compare to `null`:

```
var selected = tempSelections[i];
if (selected == null) continue; //skip destroyed objects
//...

```
> 4 votes

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


title: Enemies overlapping

text:
# Question
Title: Enemies overlapping
I have a simple WebGL maze game and has problem with enemies overlapping when they are going to target position. Now i'm detecting there collisions, but dont know what to do with them when they are collide, if i choose to stop enemy when it collide with someone other - then when first enemy will reach target other will just stop one after another, so i cant use this solution. The perfect result will be if enemies will bypass other enemies, and i was trying to repel enemy in opposite direction from enemy with which it collides, but then i cant control it, and it could be repelled into the wall, or stuck between wall and other enemy. Could someone share the right solution? I dont need any code examples, i will be happy to hear your thoughts in theory

# Answer
> 1 votes
This is a very common problem in AI pathfinding, and you generally have three possible solutions:

1. Accept the overlap. But this is far from ideal.
2. Queue your enemies. Detect a collision, and stop the one behind, for up to half a second, then recompute the path and get it moving again. This is a simple, but very naive modification.
3. Make your pathfinding aware of the position of your enemies. At the beginning of each AI "frame" update the map with the positions of each enemy. Treat these "maze cells" as blocked, and compute the path based on these additional blockages. Periodically recompute paths, and update the map as enemies are removed/added. If a valid path can't be found, wait a few frames for a path to open, and try again.

---
Tags: ai, path-finding, collision-resolution, collision-avoidance, npc
---


# Question
Title: How do I use delta time time-stepping in a triple-buffering scenario?
I am creating a graphics application in Metal. One of the things we are suggested to do is to use triple buffers in order to allow for the GPU and CPU to work more in parallel. Essentially instead of writing frequently changing data to the same spot in memory you alternate between three offsets and then pass in a drawing offset for the GPU that way the GPU is not reading something the CPU is currently trying to write.

One problem with this is that it means that what is drawn on screen will be from 2 frames ago.

So my question is what does this mean for time-stepping? Heaven forbid I have an incredibly variable frame-rate how do I make things seem smooth when the dt value I have for the CPU simulation frame is actually two frames behind?

# Answer
> 1 votes
It's worth noting that even without double/triple buffering, if the framerate jumps from 30 to 60, for example, the first 60fps frame would've been calculated with the previous frame's time-step -- 33.333ms instead of 16.667ms. So even if you're not double/triple buffering your dynamic buffers for animation or what not, one still faces the problem of highly variable framerates making the entire simulation more jittery than the actual framerate.

Using a smoothed time-step can help. You just keep a rolling average of several frames' time-step. When the framerate is constant, it makes no difference. When the framerate varies widely and wildly, the average will still mean you're simulating and animating at the correct rate on a macro level, but you'll avoid having your smallest time-steps used in your longest frames (and vice versa).

# Answer
> 0 votes
What technology you are creating your app in is largely irrelevant.

Time stepping only applies to app state updates. Rendering should be performed on the most up to date data available at rendering time:

In a single thread scenario, updates and rendering are sequential, and therefore frame rate is dependent upon how fast you can get through the update phase.

In a two thread scenario, you offload the update work to a second thread, and that is where your app/game state is updated, or *the memory is written to*. In your main thread, you just loop through the renderer, only reading the latest game state updates for rendering. In this way, your rendering is never a frame behind.

Double/triple buffering is a graphics hardware technique to prevent screen tearing, by always ensuring that there is a complete frame to render. It is not necessary to allow the cpu and gpu to work in parallel.

I would advise you to learn the fundamentals and best practices of multithreaded programming, and do some research on multithreaded game engine design.

---
Tags: simulations, timestep, metal
---


# Question
Title: Move car to coordinate with considering z-angle
I have such question:

I have a car, her coordinates (x, y, z) and z-angle (from 0 to 360 degrees).

And i have x, y, z of checkpoint.

how to calculate the angle to which need to turn the car to get to the point, taking into account its direction?

something like that:

Sorry for my English :D

# Answer
If you draw a line between point `b` the target point and the x-axis you can see we always have a Triangle. When you now draw a circle which meets the new 90° corner of the triangle. The idea comes to use tan and arctan.

Is `y (25) = tan(z)` so `z = arcTan(y)`

The last Problem is that we need y when x = 1. We achieve this by dividing y and x: `y / x`;

So when our car is on position x = 15, y = 50 and his target is on x = 60 and y = 75

1. We calculate the different
`route.x = target.x - car.x; (= 45)`
`route.y = target.y - car.x; (= 25)`
2. Get y when x = 1
`Y_When_X_Is_1 = route.y / route.x;`
3. Calculate z
`z = arcTan(Y_When_X_Is_1);(~ 29.055)`

Now you must watch of some special cases:

`if route.y < 0 then z = 360 - z`
`if route.x < 0 then z = 180 - z`
`if route.x < 0 && route.y < 0 then z += 180`

I hope this will help you!
> 0 votes

---
Tags: c#
---


# Question
Title: How do I extract and publish my game made in Code::Blocks?
So I made a 2D adventure game using c++ and SFML with the Code::Blocks IDE and the GNU GCC compiler. I have been working on it for several months and been doing bug fixes and everything. I want to publish my game to steam, or maybe a website for people to download for free and enjoy my game. However I do not know how to take my code on Code::Blocks and put it into a single application that when double-clicked it can be opened and ran as a game. Please help, it would be greatly appreciated.

# Answer
> 2 votes
*Code::Blocks* builds your project before running it, meaning that an actual executable file is created from time to time anytime you run your program.

It is usually located in the "Release" build target folder, inside the current project folder. If your project is named "MyGame", and it is located at "X:{Program Files}\CodeBlocks\Projects\MyGame", then you'll find your executable in the subpath "\bin\Release" (or Debug, if you never ran a Release build).

An alternate way to find such executable is to browse the file browser in the Management section of the IDE. In Windows it looks like this:

Expanding the "bin" folder you'll find the build target subfolders, inside which the executable is located. Right-click on it, and then click "Copy To..." and choose the Desktop or another folder of choice:

This example is about a simple console application, only difference with a full-working application is you must copy other included files as well.

---
Tags: publishing
---


# Question
Title: SFML: How to draw/render from Screen class
Game architecture is as follows:

// main.cpp

```
main() loads data from .csv/.json files.
main() creates an Application class instance as app and passes it data.
main() runs app.genesis();

```

// Application.cpp

```
Application::genesis() creates an sfml window
Application::genesis() creates a Menu class : public Screen as screen

```

// main.cpp

```
main() runs app.loop()

```

// Application.cpp

```
Application::loop() calls screen.step();

```

// Menu.cpp

```
Menu::step() calls draw()/render();

```

How do I either call Application::draw()/render() from Menu::draw()/render() or in which way should I pass screen (Menu) the window to draw to?

# Answer
> 1 votes
> How do I either call Application::draw()/render() from Menu::draw()/render() or in which way should I pass screen (Menu) the window to draw to?

If `Application::draw()` is a member function, you will need to give a pointer or reference to the `Application` to the `Menu` instances. This is typically done in the constructor, especially in the case of a reference:

```
struct Menu {
  Application& m_application; // The reference.

  Menu::Menu(Application& application)
  : m_application(application) { // Store it.
  }

  void Menu::draw() {
     m_application.draw(); // Use it.
  }
};

```

If you don't need the reference stored for the lifetime of `Menu`, you can also pass the reference to `Menu::draw()` instead.

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


# Question
Title: How can I access a method on a child elements script in Unity?
I'm using Unity. I have an empty elements called `GameElements` which I programmatically add child elements to (players can spawn these objects themselves in-game).

Within my script `Play.cs` I have a method to handle the onclick event when someone clicks the Play image/button. I want to run through all of the child elements of my `GameElements` object and run the method on the script `Circle.cs` which is attached to those child elements.

Here is my `Play.cs`:

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

public class Play : MonoBehaviour
{
    public GameObject GameElements;
    public Circle CircleScript;

    public void OnMouseDown()
    {
        Debug.Log("Clicked!", gameObject);

        GameElements = GameObject.Find("GameElements");

        // Loop through game objects and init them
        Transform[] allChildren = GameElements.GetComponentsInChildren<Transform>();
        foreach (Transform child in allChildren) {
            // do whatever you want with child transform object here
            Debug.Log("child...", child);
            CircleScript = (Circle) child.GetComponent(typeof(Circle));
            CircleScript.Init();
        }
    }
}

```

The click events do generate a Debug Log in console for the child objects as expected.

However I get the following:

```
NullReferenceException: Object reference not set to an instance of an object
Play.OnMouseDown () (at Assets/Game/Scripts/Play.cs:22)
UnityEngine.SendMouseEvents:DoSendMouseEvents(Int32)

```

Any help appreciated.

# Answer
`child.GetComponent(typeof(Circle))` is not finding a `Circle` component, and thus returning null. You don't check for null, you just assume success and call `Init` on the resulting reference.

This is probably *happening* because, as you note in your own answer, `GetComponentsInChildren` returns components of the given type in the invoking game object *and* its children.

Regardless, you may want write the loop in a way that you protect against a failure to find the `Circle`:

```
foreach (Transform child in allChildren) {
  CircleScript = child.GetComponent<Circle>();
  if (CircleScript != null) {
    CircleScript.Init();
  }
}

```

You can alternatively check if the `child`'s game object is the `GameElements` object simply using `==`. Both options are somewhat more robust than checking the *name*, since you may change the name elsewhere some day and forget to update this code.
> 1 votes

# Answer
It seems that `foreach (Transform child in allChildren) {` iterates the children and the original object itself. So, if I have 2 children, I get 3 iterations, the first being the parent.

I simply need to check the name isn't of the parent:

```
foreach (Transform child in allChildren) {
    // do whatever you want with child transform object here
    Debug.Log(child.name);
    if(child.name != "GameElements") {
        CircleScript = (Circle) child.GetComponent(typeof(Circle));
        CircleScript.Init();
    }
}

```
> 0 votes

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


title: Bullet Spray RNG

text:
# Question
Title: Bullet Spray RNG
So I have a Nuclear-Throne like weapon system in my game, and I'm working on bullet spray. Originally, there was equal odds that the bullet sprayed at any angle within the spray range.

That felt weird and very inconsistent, so I used a power function to randomize the vector. Power functions are locally crushing at zero, so the vector was more likely to hit exactly where the player was aiming and less likely to spray at the extremes, although it was still possible.

However, this just feels unnatural as well. For most of the hits, the bullets go exactly where you want, and then suddenly a single bullet shoots far off to the right or something. Are there better ways of randomly spraying weapons? I've heard of normal distributions and am considering that, but I'm wondering if there are any industry standard methods of doing this.

# Answer
This is a question of game balance and feel, so existence of an 'industry standard' is unlikely.

If you're trying to somewhat approximate real-world projectile spray patterns, a normal distribution will work well. You can tweak the variance to control how accurate the weapon/player are. *(If there is an industry standard, this is it.)*

If you aren't concerned with matching real-world feel and instead want your projectiles/weapons to seem a bit artificial/alien, you could combine your prior approaches (or something new) probabilistically.

I.e., write something simple like

```
if(Random.value < randomThreshold){
  directionVector = getRandomizedVector(sprayRange);
} else {
  directionVector = getPowerVector(sprayRange);
}

```

Then you can tweak randomThreshold until it feels right.
> 3 votes

---
Tags: mathematics, random, bullet-physics
---


# Question
Title: What are these yellow lines between toggles, and how do I turn them off in Unity?
I don't understand what these faint yellow lines are and how to turn them off (see screen shot). I have created toggles from a prefab and to save time have been duplicating them and moving them. Unity chugs everytime I move a group of them, and I imagine it is because it is recalculating how to draw these lines. All of the toggles have lines between them. Send help!

# Answer
These yellow arrows visualize the navigation graph for keyboard / DPad selection focus on UI elements.

eg. If the player currently has UI widget A in focus, and presses the right arrow key, which UI widget gets input focus next?

You can click the "Visualize" toggle button in the "Navigation" section of the UI component to turn these arrows on or off.

You can also disable automatically computing navigation links entirely by setting the navigation mode to None (for no directional button navigation) or Explicit (to specify the next UI element in each direction yourself, in the Inspector). Note that directional navigation is important for accessibility (eg. for players with lower visual acuity or motor precision), so I'd recommend ensuring your UI is still navigable in this way.
> 1 votes

---
Tags: unity
---


# Question
Title: How can I implement revolute (hinge) joints in a 2d physics system?
Further to my previous question on fixed joints, I am now going toe-to-toe with hinge joints in 2D physics. Though the answer to the previous question was excellent, I have come across a few problems in extending it to hinge joints.

My approach was to extend that given here by implementing the following algorithm:

1. Find the 'target' point for both hinge points by taking the midpoint between them (I actually use mass to give a ratio here but assume the bodies are of equal mass -- in my simulation they all are). The target point is labelled **T** in the diagram below.
2. For body **a**, find the angle between the hinge point **A** and the target point **T**. This is done by transforming **T** from global space to local space, then taking the difference of `Atan2(y, x)` for each point - this should return the angle between them.
3. The body **a** is then rotated by a matrix created from this angle, so that **A** and **T** now lie along the same vector. **a** is then translated by `T-A`; now **A** should be at **T**.
4. Repeat steps 2 and 3 for body **b**.

The algorithm seems logical to me, but I have found that there is some kind of stability issue whereby the bodies will stay constrained for a short time, then as the angle between the two bodies becomes slightly more acute (in either direction), they will both shoot off at high velocity. The number of constraint iterations is not the issue as far as I can tell - the same problems occur at 1 iteration as at 10.

Pseudocode to my algorithm given below:

```
// EntityA and EntityB are the two objects
// HingeA and HingeB are represented as vectors relative to their local transforms
Transform tA = EntityA.Transform;
Transform tB = EntityB.Transform;

Vector2 delta = tA.LocalToGlobal(HingeA) - tB.LocalToGlobal(HingeB);

// Locate the target in global space by finding the midpoint of the delta vector A-B
// then translating it by B
Vector2 Target = (delta * 0.5) + tB.LocalToGlobal(HingeB);

// Locate target in Entity A's local space
Vector2 TargetA = tA.GlobalToLocal(Target);

// Avoid undefined behaviour for Atan2
if (TargetA != Vector2.Zero && HingeA != Vector2.Zero)
{
   // Get the angular difference between A and T
   float angleA = Math.Atan2(TargetA.Y, TargetA.X) - Math.Atan2(HingeA.Y, HingeA.X);
   tA.Angle += angleA;
}

// Re-convert the target to local co-ordinates and translate EntityA towards it
tA.Pos += tA.GlobalToLocal(Target) - HingeA;

// Repeat for entity B...

```

Am I on the right track with this algorithm? Is there some minor detail I have missed that is aggravating the simulation?

# Answer
This is an interesting question

Just thinking out load ( well writing it down)

you know the position of A, Vector2 you know the position of B, also Vector2

you can calculate the distance between A and B =\> C = SQRT( (Bx - Ax)² + (By - Ay)²)

the equal distance between the 2 points is C/2.

mmm. I'v been drawing up to 10 different triangles and I think I come to the same conclusion, that T's position is always ( in 2D)

in pseudo code :

Tx = ABS(Bx-Ax) /2;

Ty = ABS(By-Ay) /2;

TA\_Angle = tan( Tx /Ty);

TB\_Angle = 90 - TA\_Angle;

Maybe this could help ?

Or maybe it is too early and I completely missed the ball :/

T.
> 1 votes

# Answer
As is the way with most things, I had my Eureka moment at 5:30am after roughly 10 hours of debugging, head-scratching, beer-drinking etc.

My error was in the line

```
// Re-convert the target to local co-ordinates and translate EntityA towards it
tA.Pos += tA.GlobalToLocal(Target) - HingeA;

```

This translates the object along the **local** vector towards the target, but is translated in **global** space. For some bizarre mathematical reasons that I don't even want to begin to think about, this was fine up to +/- 45 degrees - at which point the sim blew up.

By replacing the line with

```
tA.Pos += Target - tA.LocalToGlobal(HingeA);

```

We have our hinge joint :)
> 1 votes

# Answer
I think you can’t solve this equation of motion using only kinematic method, Because joint can transfer linear force between each body.
> 0 votes

---
Tags: physics, rigid-body-dynamics
---


# Question
Title: C++ exensible resource manager class with dynamic registration of factories
I've done some some research on my own, so I hope someone can help me finish it. I'm trying to replicate the design of an extensible asset manager featured in this answer.

At the moment I have created this and have no clue on how to proceed.

```
class ResourceManager {
    public:
        template<typename T>
        bool addFactory( std::unique_ptr<ResourceFactory<T>> factory ) {
            std::type_index ti = std::type_index(typeid(T));

            auto searchResult = factories.find(ti);
            if(searchResult != factories.end()) {
                return false;
            } else {
                factories[ti] = std::move(factory);
                return true;
            }
        }

        template <typename T>
        ResourceHandle<T> load(const std::string &path) {
            std::type_index ti = std::type_index(typeid(T));
            auto searchResult = factories.find(ti);

            if(searchResult == factories.end()) {
                throw NoValidFactory(std::string("No registered factory of type ") +
                                     ti.name());
            }

            // TODO SOMEHOW DO LOADING
            //return searchResult->second->load(path);
        }
    private:
        std::unordered_map<std::type_index,
                           std::unique_ptr<ResourceFactoryI>> factories;
 };

```

I assume that `TextureHandle` featured in the answer is probably a `typedef` for something like a custom reference counted smart pointer (e.g. `ResouceHandle<Texture>`, like in my engine) but how do I return something like that? I'm not (YET) good with templates but I know that it's impossible to have a virtual specifier with a template method, so I CAN'T do something like this:

```
class ResourceFactoryInterface {
    public:
        template <typename T>
        virtual ResourceHandle<T> load(const std::string &path) = 0;
};

template <typename T>
class ResourceFactory : public ResourceFactoryInterface {
    public:
    ResourceHandle<T> load(const std::string &path) {
        // loading
    }
};

// TODO Template specializations for object types? Inherit from ResourceFactory?

```

**What should I do? Am I even close or am I doing a complete nonsense? How should I proceed?**

If someone wants to know why I need something like that: *at the moment I have one huge, difficult to maintain and extend `ResourceManager` class with a different method (loadTexture, loadMesh, loadSound, etc.) for each resource type. Having something that can be extended dynamically would make my hobby engine's resource management system more reusable. Moreover, I have a few places where I'd benefit from instantiating separate resource managers with only several registered (level specific) resource types.*

# Answer
> 5 votes
Back in the days of C and no templates... we had void pointers. Good thing they weren't made obsolete, because you have just seen that templates aren't omnipotent gods. This situation is perfect for some void pointer hacks.

Here, I tried to make an example that was as simple as possible:

Edit: The example below makes a dangerous use of `shared_ptr`, please see the edit at the bottom.

```
    struct ResourceManager {

        typedef std::function<void* ()> TFactoryFunctor;

        std::map<std::string, TFactoryFunctor> m_factories;

        void subscribe (std::string key, TFactoryFunctor factory) {
            m_factories[key] = factory;
        }

        template <class T>
        std::shared_ptr<T> load (std::string key) {
            auto& factoryFunctor = m_factories.at(key);
            void* ptr = factoryFunctor();

            return std::shared_ptr<T>(static_cast<T*>(ptr));
        }

    };

    struct ResourceFactory {

        std::string m_path;

        void setFilePath (std::string path) {
            m_path = path;
        }

        std::string getFilePath() const {
            return m_path;
        }

        virtual void* load() =0;

        void* operator() () {
            return this->load();
        }

    };

    struct TextureFactory : ResourceFactory {

        std::shared_ptr<Texture> m_texPtr;
        Texture* m_tex;

        TextureFactory (std::string fileName) {
            setFilePath(TEXTURES_FOLDER + fileName);
        }

        void* load() override {
            if (!m_texPtr) {
                m_tex = new Texture();
                m_tex->loadFromFile(getFilePath());

                m_texPtr = std::shared_ptr<Texture>(m_tex);
            }

            return m_tex;
        }

    };

    // ---

    ResourceManager daMan;

    void subscribeTextures() {
        daMan.subscribe("hero", TextureFactory("hero.png"));
        daMan.subscribe("foe", TextureFactory("foe.png"));
        daMan.subscribe("tileset", TextureFactory("tileset.png"));
    }

    void loadHeroTexture (Hero& hero) {
        auto texPtr = daMan.load<Texture>("hero");

        hero.claimOwnership(texPtr); // Maybe you want to keep track of who's using the resource?
        hero.sprite.setTexture(*texPtr);
    }

```

I didn't test this code to make sure that it's functional and I'm not sure whether it's a good idea to manipulate a raw pointer that's stored in a `shared_ptr` in the way within `TextureFactory::load`, but I hope you get the idea.

In a different, more object-oriented language you would probably use `object` (or some other more specialized base class) and downcasts instead of `void*`, but C++ doesn't have such luxuries. Maybe you can make your own `ResourceBase` base class? You'd have to make *some* wrappings, do so at your own expenses.

Edit: I have found that it is dangerous to transfer a raw pointer that's already owned by a `shared_ptr` to another `shared_ptr`. The second `shared_ptr` will have a different reference counting from the first and it is 100% certain that the object will be destroyed at least twice.

Instead of returning `void*` or `BaseClass*`, prefer to return `shared_ptr<void>` or `shared_ptr<BaseClass>` and *remember to use the aliasing constructor of `shared_ptr`* before returning `shared_ptr<T>` in your equivalent of the `ResourceManager::load<T>` method from the example.

Something like:

```
    struct TextureFactory {

        std::shared_ptr<Texture> texturePtr;

        /* ... */

        std::shared_ptr<ResourceBase> load() {
            if (!texturePtr) {
                texturePtr = std::make_shared<Texture>();
                texturePtr->loadFromFile(/* ... */);
            }

            return texturePtr;
        }

    };

    /* ... */

    struct ResourceManager {

        template <class T>
        std::shared_ptr<T> load(std::string key) {
            auto& factoryFunctor = m_factories.at(key);
            std::shared_ptr<ResourceBase> ptr = factoryFunctor();

            auto castRawPtr = dynamic_cast<T*>(ptr.get());
            assert(castRawPtr);

            return std::shared_ptr<T>(ptr, castRawPtr);
        }

    };

```

# Answer
> 2 votes
Some better idea based on your approach:

You have `template<typename T> bool addFactory( std::unique_ptr<ResourceFactory<T>> factory )` so every factory added is a `std::unique_ptr<ResourceFactory<T>>`.

So your loading code should be:

```
template <typename T>
ResourceHandle<T> load(const std::string &path) {
  std::type_index ti = std::type_index(typeid(T));
  auto searchResult = factories.find(ti);

  if(searchResult == factories.end()) {
     throw NoValidFactory(std::string("No registered factory of type ") +
                                     ti.name());
  }

  auto loader = *static_cast<ResourceFactory<T>*>(searchResult.get());
  return loader.load(path);
}

```

The cast is guaranteed to work due to how the ptrs are inserted.

On how to implement the loader: Either do specialize `ResourceFactory` for every T or redirect it:

```
template <typename T>
class ResourceFactory {
    ResourceHandle<T> load(const std::string &path) {
        T* res = static_cast<T*>(doLoad(path)); // May return fancy unique_ptr
        if(!res) throw... // If required
        return {res}; // Convert to handle
    }
    protected:
    void* doLoad(const std::string &path) virtual = 0;
};

```

Now you can subclass `ResourceFactory<T>` and implement the `doLoad` method.

Or you can have a look at ENTT: https://github.com/skypjack/entt/tree/master/src/entt/resource There you pass the loader type into the load function.

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


# Question
Title: i want to upload to 2gb model animation to vram with VBO technic but i am getting this error with nvidia (with amd no error)
when i try to work with amd its working with amd hd6870 and ati x1550 but when i try to work with gtx 950 its giving this error. if i upload less than 2gb example 300mb then its working but i want to upload 2gb. what can i do ? sorry for bad english.

# Answer
> 1 votes
It seems the GTX 950 has only 2GB of RAM.

The Nvidia driver/architecture may not allow active datasets to be partially contained in system RAM.

You're also trying to allocate over 2GB of virtual memory total in a 32bits program on a 64bits windows system that is limited to 2GB per 32bits process.

32bits windows can accommodate 3GB per 32bits process, 64bits windows is limited to 2GB per 32bits process.

Rebuild your project as a 64bits application and try again.

---
Tags: opengl
---


# Question
Title: How can I convert a List<GameObject> to Transform[] array?
```
var selection = Selection.objects.OfType<GameObject>().ToList();
tempTransforms = selection;

```

selection is List and tempTransform is Transform\[\] And I want to assign the selection to the tempTransform.

# Answer
For simple C# syntax questions that don't require game development expertise, don't forget to search our general programming sister site StackOverflow first \- they'll often have more coverage of topics like these.

```
// Store intermediate selection as an array so we can use the ConvertAll method.
var selection = Selection.objects.OfType<GameObject>().ToArray();

// Provide a lambda to look up the corresponding Transform, given a GameObject.
tempTransform = Array.ConvertAll(selection, item => item.transform);

```
> 2 votes

# Answer
The simplest way to get an array of `Transform`s from the selection is

```
tempTransform = Selection.transforms;

```
> 4 votes

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


# Question
Title: How do I calculate a new position from current and target position for intuitive non-instant dragging?
I have a simple 2D game where I can move an object using the mouse. I've been improving on the 'feel' of the movement gradually, however it still doesn't behave as you'd expect if the object were to be moved by human hands in a real-world scenario. My improvements were as follows:

**New position = mouse position** Sharp unrealistic movement. No max speed.

**Cap the maximum speed** Nicer. Still stops abruptly. Doesn't accelerate smoothly

**Add 'inertia', recording last change in position and applying it to subsequent moves**

Vastly improved, however...

* Object is dragged as if on elastic, slow to accelerate, very slow to stop.
* Once moving, object oscillates or orbits around a stationary mouse position.

---

I'm looking for suggestions on how to make the movement more **intuitive**:

* Moving an object from A to B a human would rarely overshoot
    + A user shouldn't need to correct *against* inertia to stop an object
* I'd like to be able to adjust the weight of the object so that heavier things are harder to get moving

My current code is as follows:

```
float maxInertiaChange = 0.1;
Vector2 lastPosition = Vector2.negativeInfinity;
Vector2 inertia = Vector2.zero;

private Vector2 InterpretPosition(Vector2 mousePosition) {
    Vector2 newPosition;
    if (lastPosition.x != float.NegativeInfinity) {
        newPosition = lastPosition + (inertia * Time.deltaTime);
        newPosition = GetPointTowardsTargetWithMaxDistance(newPosition, mousePosition, maxInertiaChange);
        inertia = (newPosition - lastPosition) / Time.deltaTime;
    } else {
        newPosition = mousePosition;
    }
    lastPosition = newPosition;
    return newPosition;
}

private static Vector2 GetPointTowardsTargetWithMaxDistance(Vector2 startVector, Vector2 targetVector, float maxDistance) {
    float lerpScale = maxDistance / Vector2.Distance(startVector, targetVector);
    return Vector2.Lerp(startVector, targetVector, lerpScale);
}

```

Thanks in advance!

# Answer
> 0 votes
Something I've used before is to plan the movement as a Bézier curve.

The first control point on the curve is the current position of the object. The first tangent is proportionate to the current velocity of the object. (This gives you first-derivative continuity so the motion is smooth) The final control point is the position of the mouse, and the final tangent is zero (the object should slow to a rest as it arrives).

The advantage of planning the trajectory as a spline this way is it lets you explicitly control the total duration the motion should take (eg. if you want the object to always catch up and stop within half a second of the mouse stopping/releasing).

When the mouse moves, you plan a new Bézier curve, choosing a duration (eg. proportionate to the distance of the object from the mouse, up to some max), and then setting:

```
P_0 = draggedObject.position;
P_1 = P_0 + dreaggedObject.velocity * duration / 3f;
P_2 = P_3 = mousePosition;

```

Then at each timestep after this, you can get the object's position & velocity by evaluating the cubic Bézier's parametric equation at `t = Clamp01(timeSinceMouseMove/duration);`

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


# Question
Title: How can I make the loop only once when it's inside OnGUI?
The script is EditorWindow type.

```
private void OnGUI()
{
var selections = Selection.objects.OfType<GameObject>().ToList();
        if (selections.Count > 0)
        {
            for (var i = selections.Count - 1; i >= 0; --i)
            {
                var selected = selections[i];
                transformSelection.Add(selected.transform);
            }

            TransformSaver.SaveTransform(transformSelection.ToArray());

            tempTransformSelection = transformSelection;
            transformSelection = new List<Transform>();
        }
}

```

When I select with the mouse a object in the Editor Hierarchy it will keep making the loop nonstop since selections.Count is large then 0.

I tried to add after the loop:

```
selections = new List<GameObject>();

```

But it didn't help.

I want that it will make the loop and the whole code inside the if (selections.Count \> 0) only once each time when selecting one or more objects in the editor.

If I select one object make the whole code once if I then selected another more object make the whole code over again for the two selected objects and so on but make it once. Now it will keep making the loop over and over again even if I didn't select more other objects.

Since in the editor the first object is still selected it will keep making the code the loop over and over again.

This is what I tried:

```
var selections = Selection.objects.OfType<GameObject>().ToList();
        if (selections.Count > 0 && isSelected == false)
        {
            for (var i = selections.Count - 1; i >= 0; --i)
            {
                var selected = selections[i];
                transformSelection.Add(selected.transform);
            }

            TransformSaver.SaveTransform(transformSelection.ToArray());

            tempTransformSelection = transformSelection;
            transformSelection = new List<Transform>();

            isSelected = true;
        }

```

The flag boolean isSelected is global variable and set to false as init.

UPDATE what I tried:

```
var selections = Selection.objects.OfType<GameObject>().ToList();
        int currentSelectionCount = selections.Count;
        if (currentSelectionCount != lastSelectionCount)
        {
            lastSelectionCount = currentSelectionCount;
            for (var i = 0; i < currentSelectionCount; ++i)
            {
                var selected = selections[i];
                transformSelection.Add(selected.transform);
            }

            TransformSaver.SaveTransform(transformSelection.ToArray());

            tempTransformSelection = transformSelection;
            transformSelection = new List<Transform>();

            Selection.objects = new UnityEngine.Object[0];
        }

```

But when I select object in the editor in hierarchy it's immediately unselecting the object since the line:

```
Selection.objects = new UnityEngine.Object[0];

```

# Answer
> 1 votes
I don\`t know what are you really trying to archive in OnGUI method logic but you problem can be solved easily by saving previous OnGUI call selection object count.

The main idea is to process same selection only once, to solve this we just need to compare previous and current selection size so we will need extra int variable:

```
public class FooBar : EditorWindow {

    [MenuItem("Window/Foobar")]
    public static void ShowWindow() {
        GetWindow<FooBar>("Foobar");
    }

    int lastSelectionCount = 0;

    private void OnGUI() {
        var selections = Selection.objects.OfType<GameObject>().ToList();
        int currentSelectionCount = selections.Count;
        if (currentSelectionCount != lastSelectionCount) {
            lastSelectionCount = currentSelectionCount;

            // your logic with loop and other stuff goes here
            for (var i = 0; i < currentSelectionCount; ++i) {
                Debug.Log(selections[i]);
            }
        }
    }
}

```

I just log selected objects here - you obviously can change everything to what you need.

---

But there's one major problem here - when you select 1 object and processed it, you'll have `lastSelectionCount` equal to 1 and when you select **another** object, `selections.Count` would be equal to 1, so it wouldn't be processed in OnGUI callback. In general, that won't work for any same number of selected objects.

The most trivial solution is to cancel current selection simply by clicking anywhere on the scene view but sometimes there's no place in your scene without objects so you can cancel selection after processing in OnGUI callback:

```
private void OnGUI() {
    var selections = Selection.objects.OfType<GameObject>().ToList();
    // your logic here, loops, file ops, anything
    for (var i = 0; i < selections.Count; ++i) {
        Debug.Log(selections[i]);
    }

    // after selected objects processing you can cancel selection with this
    Selection.objects = new Object[0];
}

```

As you can see, you don't need any checks at all. When selected objects are processed, selection is canceled and `selections.Count` would be equal to 0 on the next OnGUI call, so for-loop won\`t be executed.

---

You also can cancel selection by button via first variant with saving selection count:

```
private void OnGUI() {
    var selections = Selection.objects.OfType<GameObject>().ToList();
    int currentSelectionCount = selections.Count;
    if (currentSelectionCount != lastSelectionCount) {
        lastSelectionCount = currentSelectionCount;

        // your logic with loop and other stuff goes here
        for (var i = 0; i < currentSelectionCount; ++i) {
            Debug.Log(selections[i]);
        }
    }

    if (GUILayout.Button("Cancel selection")) {
        Selection.objects = new Object[0];
    }
}

```

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


title: Unity game resolution lowered

text:
# Question
Title: Unity game resolution lowered
I recently upgraded unity from 2018.1 to 2018.2 and also upgraded my nvidia geforce.

I have seen that the letters resolution of the program itself are better now but my game tab is going lower res then before.

In the image I attached you can see the difference between the game emulation on game tab (windows) and the scene tab

The girl on the scene tab looks much smoother and better then how it appears on the game tab , before updating these were the same look and resolution.

Is there some options that control resolution of game tab in unity? (resolution as in dpi not in width and height)

Thanks

# Answer
Thanks to some friends, I have found the answer and thought I'd post it for others. Unity 2018.2 seems like it has a new option called : "Low Aspect Resolution Aspect" that can be found in the game tab under Free Aspect (or something else if you have set it) which is next to Display.
> 1 votes

---
Tags: unity, resolution
---


# Question
Title: Why does Unity heavily blur edges of a single cube despite 8x antialisaing
I was messing around a random project and everything was working perfectly, when all of a sudden jagged edges appeared on all objects. I've been trying to resolve this issue for the past two dails, only to no avail. I have tried changing various settings, when at last I've uninstalled unity and removed all projects. After re-installing it, however, the problem still persists:

**What I've tried:**

* changing settings in Nvidia Control Panel (for example, settingantialisaing mode to application-controlled)
* changing the Quality settings inside Unity
* removing any normal/texture maps
* changing metallic and smooothness of the material and removing specular highlights
* reinstalling Unity

**These pictures depict current settings/object properties:**

Properties of material added to the cube

Camera properties:

Quality settings:

Graphics settings:

# Answer
The jagged edges were present due to the fact that the game view (first image in my post, the panel in the right part of the image) has been scaled to 3.47, instead to 1. **Scaling the game view to 1 resolved the issue**.

Thank you for the answer @Hellium and for the suggestion to answer @John Hamilton
> 1 votes

---
Tags: unity, shaders, antialiasing, multisampling
---


title: AI world exploration?

text:
# Question
Title: AI world exploration?
For one of my exams, we have to make an AI for some sandbox survival game.

Well to be exact, we have been given a framework, and need to make a plugin that contains the AI logic.

So far, I already have the movement down, items, enemies, ... (movement uses a navmesh)

This is an image that show how the "world" could look like. (The AI has no way to get the exact layout of the map.)

The AI does have a navmesh, but can only ask for the closest node to a certain vector (so that it can use that node to move to). It starts with nothing, and the world doesn't change once the program starts. However, the pickups respawn (only inside houses) and thus I want to map all the houses. The agent has an FOV (I can't really see how big it is) and items, enemies and houses inside that FOV suddenly reveal all their data (position, size, ...)

However, following the checkpoints is not the most optimal way of exploring the world... The teachers want us to have "smart world exploration logic". This is the part I am struggling with. Is there some kind of algorithm or logics to exploring this world?

I guess the question I'm asking is "How do I determine the goal to move to, if there's nothing in FOV?"

Maybe there's some "smart" wandering I could do? However, all I know for wandering is ones where it constantly changes its direction withing a certain limit.

# Answer
> 4 votes
There's a couple of different ways to approach the problem of searching a space for something of interest.

First, you need to separate the related ideas of *searching* versus *patrolling*:

* Searching just examines a space. Once you've checked it, you don't need or want to recheck it.
* Patrolling involves repeatedly checking a space (or if you want to get technical, you're searching not just in space, but also over the dimension of time).

Many ideas on how to search are connected to patrolling, but the time aspect can have a significant impact & often needs to be considered up front. If your target of interest is dynamic, you have a patrolling problem as a regular search can fail if the object 'doubles back' & moves into a region that has already been searched. With that out of the way, here's an overview of techniques:

One approach seeks to eventually net as much information as possible. As such, the ultimate objective is an exhaustive search of the space. The key idea here is to minimize overall wasted effort (that is, revisiting the same location more than once). Here are some of the relevant search patterns used when looking for missing persons, lost objects, etc:

Computationally, these are basically what are called space filling curves.

Another approach is to find as much information as possible, as soon as possible. As opposed to the previous approach, the key idea here is to trade potential wasted effort in the interest of getting information sooner. This only works if you have some reason to favor certain areas over others. Essentially, these amount to conducting search in one area until some threshold is met & then moving into a new area. Here's an example where the search starts spiralling in one area (black), then moves to another (green), transitions back to expand the search around the first area (blue) and then moves on to a third region (gray):

In your situation, the transition threshold might be based on previous buildings you've seen, last known heading of an enemy, or maybe picking up supplies that you didn't need/have room for when first discovered, but need now.

Last, there's a connection between this problem & the travelling saleman problem (TSP) and its related problems. The TSP is well studied, challenging problem. In generally, the main thing to keep in mind is that you often don't need an ideal solution - you just need one that's good enough & can be computed quickly enough with the resources (memory & processor) available to you. So if you approach your problem through this lens, I would start with the various well know heuristic & approximation algorithms.

One final point - any search or patrol that's observed by someone with more information than the searchers will eventually look dumb. At some point, you'll say to yourself "Over there! Just turn! It's so close!". This isn't unique to AI. To some extent, meeting your teacher's expectation of a "smart world exploration logic" will depend on your ability to explain what decisions it makes & why, not just implementing the logic.

# Answer
> 1 votes
First of all, your AI agent needs to remember which parts of the map it has and has not explored yet.

When the AI agent decides where to move next, it should look for some point where the explored territory transitions into unexplored territory and then just go there.

Now the question is how you prioritize different unexplored areas. The most simple one is distance. Simply keep moving towards the closest unexplored area until the whole map is explored. A more advanced heuristic could also prioritize areas by the likeliness of finding something interesting. For example, when the AI finds a wall, it might prioritize that area over empty spaces so it prioritizes exploring buildings over exploring empty fields.

---
Tags: ai
---


# Question
Title: Unity: Loading screen without a coroutine (is it possible?)
I need to accomplish something specific but I'm not sure how to do it exactly:

My game has 2 scenes:

* The main menu that has a couple of buttons...
* ... and the game scene that displays a different mesh (which is imported from a folder on the HDD at runtime) depending on which button you pressed and that also lets you walk around.

My approach for this: Clicking on a button makes a script A call a static class B (used for sharing data between scripts), which then in turn creates an instance of another class C, which inherits from ScriptableObject and takes care of the whole "import and display the mesh" part.

Importing a mesh takes a while, so I'd like to display some kind of loading screen (a panel that overlays everything else in the 2nd scene) and this is where I'm stuck.

Importing a mesh accesses the Unity API, so I can't do it in an extra thread (or Task, which would be perfect) but I also can't use a coroutine because class C derives from ScriptableObject, not MonoBehaviour (which I can't use because I can't create a new instance then).

Another problem is that the game is stuck on the main scene with the button pressed and doesn't display the second scene until the mesh is loaded, so even if I set the loading panel active (`loadingPanel.setActive(true)`) before I start importing the mesh, it doesn't display it until after the model's already imported.

What can I do here? There's no need to display a loading screen while switching scenes, so I'm guessing that there's no point to load the second scene asynchronously, is there?

# Answer
The reason why the button gets stuck until the scene loads is, you are not loading the mesh in a parallel thread or a coroutine that allows the game loop to keep ticking, hence, you are loading it in a concurrent environment, which means that the next frame will tick once that mesh (and whatever more resources) finish loading.

What you can do is having an IEnumerator (what is used for coroutine'a pattern in C#) on your ScriptableObject, but call it on whatever MonoBehaviour Instance you have. Since you didn't provide example code, I'll just leave the kinda IEnumerator's template:

```
public class DataContainer : ScriptableObject
{
    private IEnumerator AsynchronousStuff()
    {
        while(condition)
        {
            //...
            yield return null;
        }
    }
}

```

So you could do something like that, which is perfectly valid, since StartCoroutine takes an IEnumerator, it does not matter where it comes from, the MonoBehaviour is needed to make the call, since it runs while that instance is active:

```
public class SceneController : MonoBehaviour
{
    public DataContainer data;
    private Coroutine loadingOperation;

    public void LoadResources()
    {
        /// By storing a reference in a coroutine, you could check if there is an operation running, so you don't execute it by accident again
        loadingOperation = StartCoroutine(data.AsynchronousStuff());
    }
}

```

You could do it on threading, just take values that are allowed, in the case of UnityEngine's namespace, structs (Vectors, Quaternions, Colors, Bounds, Rect, Rays, etc.) are allowed for multithreading, so you could also modify structs, and once the thread is done, interpret that data to create meshes / resources with the given data.

Hope it helps.
> 2 votes

---
Tags: unity, multithreading, coroutines
---


# Question
Title: Opengl texture rendered as solid color,why?
her is my vertex array and texture coordinate..

```
float POS[]=
{
    -0.5,-0.5,-1.0,
    0.5,-0.5,-1.0,
    0.5,0.5,-1.0,
    -0.5,0.5,-1.0
};

float texCoords[] = {
0.0,0.0,
1.0,0.0,
1.0,1.0,
0.0,1.0
};

```

here is my texture creation

```
stbi_set_flip_vertically_on_load(1);
    openglTexBuff=stbi_load("lena.jpg",&w,&h,&c,0);

    glGenTextures(1,&TexID);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D,TexID);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB,w,h,GL_FALSE,GL_RGB,GL_UNSIGNED_BYTE,openglTexBuff);
    glGenerateMipmap(GL_TEXTURE_2D);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);

    glBindTexture(GL_TEXTURE_2D,0);
    stbi_image_free(openglTexBuff);'

```

and these are my shaders

```
#shader vertex
#version 330 core

layout(location = 0) in vec4 positions;
layout(location = 1) in vec2 texCoords;
uniform mat4 translation_matrix; //inactive shader variables..
uniform mat4 rotation_matrix;

mat4 model_matrix; //
mat4 projection_matrix;
out vec4 pos;
out vec2 frag_TexCoord;

void main()
{

rotation_matrix;

gl_Position=rotation_matrix*translation_matrix*positions; //translation matrix operated with POS vector..
pos=positions;
frag_TexCoord=texCoords;
translation_matrix;

}

#shader fragment
#version 330 core

layout(location=0) out vec4 color;
in vec4 pos;
in vec2 frag_TexCoord;rag_TexCoord;
uniform float col;
uniform sampler2D  a_texture;
void main()
{
col;
a_texture;

color=texture(a_texture,frag_TexCoord);

}

```

when i use (solid)color instead of texture in shader..everything works fine but when i use shader it gives solid color instead of texture..It seems like my whole tex is super-zoomed to output single color

here is draw call

```
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    box.shader.setUniformat4x4("translation_matrix",translation);
    //box.shader.setUniformat4x4("rotation_matrix",rotation_arr);
    box.shader.setUniform1f("col",1.0);
    glBindTexture(GL_TEXTURE_2D,TexID);
    box.shader.setUniform1i("a_texture",0);
    box.render();

```

box.render

```
void render()
    {
        vertices.bind();
        indices.bind();
        shader.bind();
        glDrawElements(render_As,vertices.getSize(),GL_UNSIGNED_INT,NULL);
        vertices.unbind();
        indices.unbind();

    }

```

# Answer
> 1 votes
```
layout(location = 1) in vec2 texCoords;

```

**This is happening because your texture coordinate attribute is not at index 1 in your C/C++ code**.

Typically one of three things will cause this.

1. You're using the legacy glTexCoordPointer to set it up, which does not alias to index 1.
2. You're using a glVertexAttribPointer call with an index other than 1.
3. You're not actually setting a pointer for texture coordinates at all.

The default value for an unspecified attribute is {0, 0, 0, 1}, which - when that attribute is used as a texture coordinate - will sample from the bottom-left of the texture every time.

---
Tags: opengl, textures
---


title: Execute function every X points

text:
# Question
Title: Execute function every X points
In my game, the score can go up quite rapidly and by varying amounts, depending on the action taken.

For instance, at the start of the game, one could climb from 1 - 50 one by one, or they could rocket past 50 by getting a score of 10, 25, and 40.

My question is: How do I call a function every time they pass a factor of 50 (50, 100, 150, 200, etc.)?

# Answer
Here is code that works by polling the current score. This allows you to separate score-keeping code from the code meant to react to score. You can have multiple score-reactors.

You don't actually need polling. You could make it an event-based system. Add objects with a `CheckScore` function to a list in your score-keeping class. Then treat that list as a list of callbacks. Or just do it every `FixedUpdate`.

```
private long step = 50;
private long nextReward = CurrentScore() + step;

public void CheckScore()
{
    while (CurrentScore() >= nextReward)
    {
        nextReward += step;
        // Give reward here
    }
}

```

---

It's also easy replace the `while` loop with an `if` then implement a kind of cooldown effect so you don't spawn every reward during the same frame.

```
private long step = 50;
private long nextReward = CurrentScore() + step;
private int countDown = 0;
private int coolDownFrames = ...;

public void FixedUpdate()
{
    if (CurrentScore() >= nextReward)
    {
        if (countDown == 0)
        {
            countDown = coolDownFrames;
            nextReward += step;
            // Give reward here
        }
        else
        {
            countDown -= 1;
        }
    }
}

```
> 0 votes

# Answer
I would use a property, so that you can modify the score and compute when a step has been passed;

```
[SerializeField]
private int step = 50;

private int score ;

public int Score
{
    get { return score ; }
    set
    {
        int delta = value - score ;
        if( value > score && value % step < score % step ) // Handle cases such as score = 45 and newScore = 55
        {
            OnStepPassed() ;
        }
        score = value < 0 ? 0 : value ; // Make sure the score is positive
        while( delta >= step )
        {
            delta -= step ;
            OnStepPassed() ;
        }
    }
}

```
> 0 votes

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


# Question
Title: Game Maker Studio 2 problems with too many instances
So I am trying to make a management game, a space station simulator if you will, with potentially hundreds and thousands of customers entering and leaving the station every game day. So my plan of handling this is to first create a persistent object called oManager. Over the course of the game, oManager will continuously spawn instances of this object called oPerson.

The part of oManager that spawns person:

```
global.dailyflow = 100;
show_debug_overlay(true);
var number_a_day = irandom_range(ceil(global.dailyflow*0.6),global.dailyflow);
trader_base = floor(number_a_day*0.02);
trader_extra = floor(trader_base*(1+global.trader_modifier/100));
tourist_base = ceil(number_a_day*0.1);
tourist_extra = ceil(tourist_base*(1+global.tourist_modifier/100));
passerby_base = ceil(number_a_day*0.53);
passerby_extra = ceil(passerby_base*(1+global.passerby_modifier/100));
shopper_base = ceil(number_a_day*0.25);
shopper_extra = ceil(shopper_base*(1+global.shopper_modifier/100));
mercenary_base = floor(number_a_day*0.1);
mercenary_extra = floor(mercenary_base*(1+global.mercenary_modifier/100));

repeat(trader_base+trader_extra){
    with instance_create_layer(0,0,"instances",oPerson){
        guy_type = 0;
        event_user(0);
    }
}

repeat(tourist_base+tourist_extra){
    with instance_create_layer(0,0,"instances",oPerson){
        guy_type = 1;
        event_user(0);
    }
}

repeat(passerby_base+passerby_extra){
    with instance_create_layer(0,0,"instances",oPerson){
        guy_type = 2;
        event_user(0);
    }
}

repeat(shopper_base+shopper_extra){
    with instance_create_layer(0,0,"instances",oPerson){
        guy_type = 3;
        event_user(0);
    }
}

repeat(mercenary_base+mercenary_extra){
    with instance_create_layer(0,0,"instances",oPerson){
        guy_type = 4;
        event_user(0);
    }
}

```

Each oPerson instance decides on how many days he stays, where he would go to and how much money he spends each day, with much more to come in the future. However, the problem I am currently facing is that the game would just crash after about one game day. I think the problem is there are just too many instances and the game just cannot handle it. I tried to create only one oPerson of each type per day and it worked fine. I consider it essential to make each person an instance itself, considering they have to make pretty complex decisions, but I don't know how to make it work.

The game crashes specifically when I click on a button to change room. All of the objects are persistent.

# Answer
> 2 votes
*GM:S* is generally able to deal with as many instances as your machine is capable of handling, both in memory and CPU usage; every engine limitation is bonded to the machine the program is running on most of the times. Nowadays many games need to spawn a lot of instances simultaneously, and you can hear of projects displaying thousands of instances at once such as this one talked about on Reddit. In my experience, *GM* games usually crash because of code errors/exceptions, or memory/stack overflows, rarely because of instances number.

If your game crashes when you move to another room, you must be sure the transition doesn't trigger instance spawning over and over: you would be creating hundreds of instances without noticing, and that would cause memory to grow up until the application crashes; even worse, if object spawning happens inside a bad-formatted loop statement it may be mistakenly spawning objects without stopping, thus causing an infinite loop in your code leading the application to crashing.

Solutions to such problems include reviewing your code about checking the number of maximum instances you want to be in the game at once: you may think your code is bulletproof and not more than `number_a_day` *oPerson* objects will be spawned in your room; but if the spawning script is called more often that planned, it will result in uncontrolled growth of instance number in your game.

You could implement a slot system for the *oManager* object, which is given a maximum size and spawns a *oPerson* only if there's enough room in this variable (an array, a *ds\_map*, or whatever you like to use). No objects are allowed to be spawned if it's full, and its size can be computed knowing the value of `number_a_day` or a larger value if you want to have room for extra instances. Recommendation is having an upper bound value to limit how many instances are moving around in your room.

**EDIT**
Persistent objects in GM may cause troubles as well. If you need to move to another room but getting back to the previous one having objects in the same state they were before leaving, you want to use persistent rooms.

This way objects aren't persistent anymore (and they will not be carried along when changing room), but anytime you get back to such persistent room everything will be in the same position and doing the same things they were doing before leaving.

Also there's no trouble for resetting a persistent room. User *arirish* shows a simple snippet in this *GM:S* forum discussion that allows a persistent room to return to its original state (thus, as it was when the game started).

This solution shall work for you, as persistent instances could cause the game to crash when moved to a different room (due to persistence) than the one they were supposed to move around.

# Answer
> 1 votes
Is this code in a step event? And what do you mean by "crash", you get any error or the game just freezes?

Instance numbers in GM:S don't matter as much as the code that your instances have. Having a huge number of instances that have complex codes each can cause major slowdown (and you can follow that with show\_debug\_overlay(), as you did) but since you said the game instantly crashes, I'm guessing you are spawning too many instances at once, and GM:S thinks you are on an infinite loop and the game freezes (that, or you are actually spawning hundreds in a single step which is not good).

You didn't show what global.trader\_modifier and global.tourist\_modifier, etc are, so I'm not exactly sure how many of these instances you are spawning, but either way if this code is in a step event this code is just not viable, since you are at the very least spawning 31 passerby's per step which in a 30 room\_speed game is 930 instances per second, and if this is in a create event, again, GM:S might consider this an infinite loop or its just too much.

I'm not too sure how you want your game to work, but either way spawning instances more smoothly throughout your game day would probably fix the issue, and in regards to how many of these instances you can spawn, that comes down to how complex their code is. You can check how many microseconds its taking to complete the code in your instances using get\_timer() at the beginning of the code and storing it in a variable (like var t = get\_timer()), and at the end of the code do show\_debug\_message("Code timer: " + string(get\_timer()-t)).

---
Tags: game-maker
---