# Question
Title: How can I maneuver an AI pirate ship for a sea battle?
I'm trying to picture in my head what would be required to make an AI controlled enemy do the following in a top down pirate sailing game:

1. Approach the player ship
2. Bring player in line with port / starboard guns
3. Keep guns trained on player
4. Be able to manoeuvre around obstacles
5. Not cheat acceleration to achieve the above

When I first started thinking about the idea it was quite simple, but the more I think about it, the more complex the requirements become; with the major problem being the AI calculating perfectly the curve required to come up along side the player, or to better yet, make a pass along their bow / stern before coming along side without needing to let them quickly speed up / slow down to achieve this.

# Answer
I think we can actually plan a complete curve that meets your needs, using some techniques similar to my earlier answer about spaceship waypoints.

I'm going to assume that we can model your ships' movements using Newtonian physics (ie. masses moving inertially and accelerating quadratically under constant force). Depending on how much simulation of real wind/waves/water resistance/buoyancy you're doing, this might not be fully accurate, but it should be close enough to capture the broad-scale behaviour we need to plan, with error terms that will diminish as we close in on our target.

First we need a time horizon over which to plan: "how long will it take us to reach our desired passing / parallel position?" We can estimate this iteratively, starting with a naive guess (like the total distance to the target divided by our current speed) and improving it based on the results of our last planning attempt.

As we get closer to our target position, this time horizon gets smaller and smaller, helping to diminish errors we get from using a simplified model.

Next, we need to predict where the target ship will be at that time. For instance, we could track its current velocity and acceleration and assume it will continue that behaviour. Then we can use \\$\vec p(T) = \vec p\_0 + \vec v\_0 T + \frac 1 2 \vec a\_0 T^2\\$ and \\$\vec v(T) = \vec v\_0 + \vec a\_0 T\\$ to plot its expected position & velocity at the end of that time interval. You can also use more sophisticated predictors if you like.

Now we can construct our own desired position & velocity relative to this predicted target ship. Like choosing a spot nearby along our approach line so our forward guns can stay trained on it as we close. Or planning to cross a set distance ahead / behind along its velocity vector for a bow or stern pass. Or choosing a spot parallel at a given distance left or right, with matching velocity for a broadside or boarding attempt.

Now we have a target endpoint with a given velocity, and of course our ship's own starting point with a given velocity. We can join these with a cubic Bezier curve like so:

(Disclaimer: it's first thing in the morning and I won't have time to thoroughly check the math here until after work. I *think* that square on the T in acceleration is right, but not certain)

Our current position \\$p\_0\\$ and target position \\$p\_T\\$ form the anchor points of the curve.

We get our first control point \\$p\_A\\$ by advancing from our current position by our current velocity times one third of our time horizon.

We get our second control point \\$p\_B\\$ by backtracking from our target position by our target velocity times one third of our time horizon.

The acceleration needed to follow this curve is greatest at the very beginning \\$a\_0\\$ and the very end \\$a\_T\\$.

You can offset these two vectors by a constant representing how much wind/current your ship is fighting against to get the input acceleration it would need to provide to overcome the resistance and achieve this net accelerated path.

If that acceleration value is outside your ship's limits (here's where we enforce no cheats), then the time horizon we chose is too short. We're trying to close too quickly or turn too sharply. So, we increase our time horizon for the next attempt. You can do multiple attempts in a loop, or refine it iteratively frame by frame, falling back on the last good/naive approach path for one frame when planning fails.

If the needed acceleration has less magnitude than our ship's limits, then we can tighten our time horizon to approach more aggressively in our next planning update.

Bouncing between too-tight and too-loose time bounds, we can iteratively zero-in close to the edge of feasible trajectories.

Next, for collision checking, once you have a path with permissible acceleration: the entire path is contained in the convex hull of the anchor & control points, so we can use those bounds to do a crude check for any obstacles. You can then iteratively subdivide the Bezier curve into rectangular segments (similar to how we draw might Bezier curves with straight lines) to check it more precisely when that broad check hits something.

To plan around an obstacle, we use an offset from the obstacle's position (or the narrow gap between two obstacles) as our target, and repeat the same planning procedure to that intermediate point.

I haven't explicitly covered top speeds above, so the planned path might at times predict your ship moving faster than it's allowed to go in your game's actual physics simulation. As long as you still move your ship with permitted accelerations, any speed deficit should just feed back as input into the next planning iteration ("oh, we're not as far along as I thought we'd be. Oh well, I'll just plan from here instead"). Assuming you're fast enough to overtake the player ship, this should mainly happen in reasonably straight-line chase segments of the path, rather than introducing errors into the fine maneuvering once you've matched speed with it.
> 5 votes

# Answer
> Approach the player ship
>
> With the major problem being for the AI to calculate perfectly the curve required to come up along side the player, or to better yet, make a pass along their bow / stern before coming along side without needing to let them quickly speed up / slow down to achieve this.

You'll need to solve these problems iteratively, as there's no "perfect curve" because ships are in constant motion, with their motion affected by player twitches, sea and wind conditions. So the best your AI can do is to try to approach, updating the course every few frames (10x a second, for instance). Also, it doesn't need a full battle plan at each moment, it just needs to worry about what it needs to do to get to the next stage of the plan - *"let's cross that bridge when we get to it."*

I would suggest approaching on a line that is tangent to a circle of some radius representing the distance we want to be from the enemy ship. So say your maximum firing range is 500 yards, but you want to be quite accurate, so you decide on getting quite close, 250 yards. Then you aim for the nearest edge of a circle of 250 yards radius, that surrounds the target ship. Or maybe not the nearest, but rather the one that will bring you parallel to their current heading.

> Keep guns trained on player

This will come second to just getting close to (or getting away from) the target. Once that has been achieved, you can begin to think about gradually changing the tactic to "line up a broadside".

Remember also that historically, the guns didn't move a whole lot inside their gunports, so you should expect maybe 10 degrees of movement to be a lot, and that's you taking artistic license! If I remember my naval history correctly, carronades were something of an exception and could be wheeled around freely above decks, but had a shorter range than main cannon.

> Bring player in line

There is some variability on defining this. If you want to deliver a full broadside, you need to check that your current motion vector matches the enemy ship's, and that the centres of each ship line up on a perpendicular between those two parallel motion vectors. Otherwise you can be as parallel as you like, but you'll still miss!

Also, *how* parallel the two facing vectors are, is up to your own code; use the dot product here to check similarity, and some epsilon value to check equality *within some margin of error*. In history, there were times where they took shots even when *not* parallel, for example targeting the quarterdeck from astern. May even be that it depends on how desperate the AI is feeling, or how much it thinks it can gain by firing at the stern or bow of an enemy. P.S. I would imagine there is a much higher chance of deflection when firing directly at the bow, due to its shape.

> Be able to manoeuvre around obstacles

This is the least of your worries, and in any case, as in many historical naval battles, collisions *will* happen and ships will sink if only because of the fickle nature of the ocean and winds, in spite of the crew's best efforts. Of course, any time you get too close to another ship, especially when facing vectors are different (i.e. one is going to plunge right into another), emergency manouevres will need to engage. Same applies for land or rocks.

Get the rest right first - movement, alignment, firing - then worry about this at the end.

**Considering all the above...**

You need to order your implementation according to importance, *start simple* and see what evolves:

* Proximity to enemy (approach or escape)
* Alignment (once fairly close in, but not too close, as we need space/time to do get aligned)
* Side-to-side (matching position / speed once aligned)
* Firing or boarding (once close up)
* Obstacle avoidance

In terms of the first two points, I would set up debug circles and projected curves and watch them change size / shape as AI thinking adapts to the current situation. This should really help you to visualise the situation and work with it more easily than trying to sum everything up in your head.

About realistic winds... I would not worry about that early on, if at all. For now just assume that ships are under their own power. Then if you want to, you can gradually introduce the effects of (and indeed, need for) wind-powered sailing, later.

To sum up, AI will constantly change tack (arr! maritime jokes!), and the rest relies on vector maths.
> 2 votes

---
Tags: ai, path-finding, movement-prediction
---


title: How can I destroy the trigger forever?

text:
# Question
Title: How can I destroy the trigger forever?
I have a trigger that plays an animation but when i switch scene and i come back to the original scene, the animation plays again. I want to remember actioned triggers in order to play triggers once per scene. How can I do that?

**The GlobalScript**

```
public class GlobalScript : MonoBehaviour
{
    public static GlobalScript Instance;
    public Animator ani;
    void Awake ()
       {
        if (Instance == null)
        {
            DontDestroyOnLoad(gameObject);
            Instance = this;
        }
        else if (Instance != this)
        {
            Destroy (gameObject);
        }
      }
}

```

**The current script (Running every time i load the scene)**

```
    public Animator ani;
    public AudioClip sound;
    public GameObject text;
    private int seconds = 2;
    //var delay = 2.0; //This implies a delay of 2 seconds.

//  public void SavePlayer(){
//      GlobalScript.Instance.ani= ani;
//  }

    // Use this for initialization
    void Start () {
        ani= GlobalScript.Instance.ani;
        ani.enabled = false;
        text.SetActive (false);
    }

    void OnTriggerEnter(Collider other){
        AudioSource.PlayClipAtPoint (sound, transform.position);
        ani.enabled = true;
        text.SetActive (true);
        Destroy (gameObject);
        Destroy (text,3);
        //text.SetActive (true);
        //StartCoroutine(Die());
    }

    //And function itself
    IEnumerator Die(){
        //play your sound
        text.SetActive(true);
        yield return new WaitForSeconds(2); //waits 3 seconds
        Destroy(gameObject); //this will work after 3 seconds.
    }
}

```

# Answer
> 0 votes
What I would suggest is this. The idea is that you have all your game logic in normal classes that could run on a web site or console app be unit tested etc.

You then have a static instance of it in your unity app which all the Behaviours can reference to get the state of the game.

You can fill up your Game class with all the data and logic you need and not worry about persisting data in your Behaviours (which may be destroyed)

```
//this is your game logic which should not reference any unit objects
//its just the core logic
public class Game
{
    public List<Area> Areas {get;set;}
    public Game()
    {
        this.Areas = new List<Area>();
    }
}

public class Area
{
    public string Id {get;set;}
    public bool HasBeenVisited {get;set;}
}

///Add to DoNotDestroy object
public class GlobalScript : MonoBehaviour
{
    public static Game CurrentGame;

    public void Start()
    {
        this.CurrentGame = new Game();
        this.CurrentGame.Areas.Add(new Area() {Id="area1"});
        //setup the game as required...
    }
}

public class ColliderBehaviour :MonoBehaviour
{
    //bind this in the editor to the name of the area its in
    public string AreaName;
    public void OnTriggerEnter(Collider other)
    {
        var area = GlobalScript.CurrentGame.Areas.First(i=>i.Id == this.AreaName);
        if(!area.HasBeenVisited)
        {
             //do the thing
             area.HasBeenVisited = true;
        }
    }
}

```

# Answer
> 0 votes
Another option is to use DontDestroyOnLoad. I created this script for that purpose called Persistence.cs:

```
public class Persistence : MonoBehavior
{
    void Awake ()
    {
        DontDestroyOnLoad (gameObject);
    }
}

```

Just put it on any GameObject and all of its sub-GameObjects will receive that too. What it does is to prevent the GameObjects to be deleted when switching scenes - or rather unloading the scene they are in (and therefore not trigger their OnDestroy, and not trigger Start and Awake *again*). Alternatively just add the line of code `DontDestroyOnLoad (gameObject);` into the Start or Awake of your global script.

So if you store data viewable in the inspector of such a GameObject, it will persist. Static values are the other option, but that has already been mentioned. They can't expose values to the inspector (custom editor scripts may change or circumvent that), can't have multiple instances, but appear to be more persistent (for whatever it's worth).

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


# Question
Title: How to make the background tilemap in Unity3D have a "far away fog effect" filter in a sidescroller game?
I would like my background made of the same tiles as my foreground but with a filter which makes it appear further away from the camera.

Making the objects smaller is easy, I just have to decrease the scale of the tilemap.

But I also want it to have a "fog effect". So for example if the sky is blue then the tiles will be as blueish as far they are from the camera.

How could I implement this?

Example for fog effect:

# Answer
> 3 votes
If you are only interested in 2D fog, you can simply change the color of the background sprites so it looks like it is behind a fog. In Unity, you can simply change the color of the `Image` component, or the color of the material (depending how you are drawing them).

For example, try adding a dark grey color to it.

This has the disadvantage that you can't apply light-colors, as white means use the Texture's original color. Instead, you can make a trick shader-wise, if you feel comfortable with that, simply making pixels of an object whiter than they should, the further away they are from the camera.

---
Tags: unity, tilemap, graphic-effects
---


title: make the ball stick to the path

text:
# Question
Title: make the ball stick to the path
Hi guys , I want the ball to stick to the path and whenever it find a corner like in the image it continue normally without flying away .

# Answer
Did you try using a path? I mean using a line renderer to create a visual path and later on you take the positions of this path and simply let you ball follow it.

```
LineRenderer line = Get...;
ball.LookAt(line.GetPosition(currentIndex));//just an example

```

You also could try to give the ball a huge mass and no drag and move the ball with rigid.velocity = x; This way it should fall down quicker but I´m not sure if it works and i would not recommend doing it because it´s less accurate
> 1 votes

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


# Question
Title: how can i make an object in a canvas always look at the mouse cursor
this is my code

```
var myGamePiece;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas");
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
         window.addEventListener('keydown', function (e) {
            myGameArea.keys = (myGameArea.keys || []);
            myGameArea.keys[e.keyCode] = (e.type == "keydown");
        })
        window.addEventListener('keyup', function (e) {
            myGameArea.keys[e.keyCode] = (e.type == "keydown");
        })
    },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    }
    }

function component(width, height, color, x, y) {
    this.gamearea = myGameArea;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.update = function(){
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
    }
    this.newPos = function() {
        this.x += this.speedX;
        this.y += this.speedY;
    }
}

function updateGameArea() {
    myGameArea.clear();
    myGamePiece.speedX = 0;
    myGamePiece.speedY = 0;
    if (myGameArea.keys && myGameArea.keys[37]) {myGamePiece.speedX = -5; }
    if (myGameArea.keys && myGameArea.keys[39]) {myGamePiece.speedX = 5; }
    if (myGameArea.keys && myGameArea.keys[38]) {myGamePiece.speedY = -5; }
    if (myGameArea.keys && myGameArea.keys[40]) {myGamePiece.speedY = 5; }
    if (myGamePiece < 299) {myGamePiece.speedX = -5}
    myGamePiece.newPos();
    myGamePiece.update();
}

```

I want myGamePiece to look exactly were the mouse cursor is looking. How can I do this?

# Answer
Ahhh, this took me awhile to figure out for my project, and I ended up stitching together about 5 different SO&SE GameDev posts and then modified it myself to end up with this code:

```
this.update = function(){
  ctx = myGameArea.context;
  ctx.fillStyle = color;
  //center object
  this.center.x = this.x + this.w / 2;
  this.center.y = this.y + this.h / 2;

  // Find angle from the X axis that the mouse is
  // from center of myGamePiece. Add 90deg so it is from the Y axis
  this.angle = Math.atan2(mouse.y - this.center.y, mouse.x - this.center.x) + (Math.PI/2);

  // set rotation center to player center
  ctx.translate(this.center.x, this.center.y);
  ctx.rotate(this.angle);
  // set rotation center back
  ctx.translate(-this.center.x, -this.center.y);
  ctx.fillRect(this.x, this.y, this.width, this.height); //render
  ctx.setTransform(1, 0, 0, 1, 0, 0);   // reset canvas transforms
}

```

You also need to add an `EventListener` to track where the mouse is. This will work with the code above.

```
document.body.addEventListener("mousemove", function (e) {
  mouse.x = e.pageX;
  mouse.y = e.pageY;
}, false);

```

Since many people have already explained each of these concepts probably better than I can, I'll just post them below.
> 1 votes

---
Tags: javascript
---


# Question
Title: What happens to OpenGL buffer data that isn't used?
I have a vertex struct that has 5 glm::vec3 but some of my objects only use 2 or 3 of those members. So I have two questions :

1.) What happens to the large buffer I create, even though I don't use all the data.

```
Struct Vertex {
          glm::vec3 pos, color, UV, normal, tangent
              };
std::vector<Vertex> vertices; // will store the vertex data
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW);

```

That creates a buffer that is larger than needs to be. Is the additional buffer data not send?

2.) If I send empty data to the buffers, is it causing any performance issues?

```
glVertexPointer(2, 3 , GL_FLOAT, GL_FALSE, size of(Vertex), reinterpret_cast<GLvoid*>(Offsetof(Vertex, unusedData));

```

Thanks for the information!

# Answer
> 1 votes
> That creates a buffer that is larger than needs to be. Is the additional buffer data not send?

`glBufferData` creates a buffer of the specified size, no matter what. If you want a smaller buffer, specify a smaller size.

It doesn't copy any data unless you pass a non-null value to the `data` parameter, in which case it will copy all of it (where "all" is "the size of the buffer") internally to use for initialization.

It is too early at this point for OpenGL to perform the kind of "optimization" you are wondering about, even if it were possible (in your case it would be impractical since you have intermixed your "used" and "unused" vertex fields into the same buffer anyway). And as a sort of general rule, that kind of higher-level management decision is something OpenGL leaves to you.

> If I send empty data to the buffers, is it causing any performance issues?

If you routinely find yourself with a buffer where you are only using a subset of the vertex data, it's probably worth investigating whether or you not you can

* create a new buffer with a new vertex format containing only the data you need or
* spread the vertex data across multiple buffers instead of interleaving it in one

There is likely, technically, to be a small performance hit in terms of how efficiently the GPU can cache vertex data, as you'd be wasting a lot of its cache on data not actually used by the shaders. The bigger issue is simply the fact that you're routinely ignoring the data you've put into the GPU's memory, so you're just kind of wasting the memory.

If you can compact your vertex format or otherwise spread it across multiple buffers you don't always need mapped, that may be a net win. But it's difficult to say for sure, as those changes have their own performance wins and loses as well, depending on the context of your use of the features and the way your application processes data, et cetera.

---
Tags: opengl
---


# Question
Title: How can I measure ms between frame to reproduce it
Hello I'm coding a extension to an existing game - not really an extension since a re-code all so the it looks like another adventure for player - and to achieve it I use existing tilesets and so, but my main problem is for animated tilesets, I can't find anywhere the frame rate, sometimes I assumed it was simply 60fps (16.67ms between frame) because I figured out testing that it should be somewhere between 15ms and 20ms, but I have to good way to figure it out, I wanted to use something like OBS in 1000 fps but it doesn't seem available, in any other recording app neither. How would/did you guys do what I need to? Thanks in advance and gl in your own projects!

EDIT1: I'm trying to find the *intended* frame rate of the animation (that is, how long the author of the animation expected each frame to stay on screen?) ; Because sometimes it's really really short like around 15ms how can I do that? My question is not about global fps but some animated tile fps

# Answer
> 1 votes
If you don't know where the data that specifies the animation's rate is stored in the game (which would be the best place to extract it from), you'll be forced to use empirical observation to derive the framerate.

You can do this with OBS or other screen recording software, as you posited, and you don't need the game to run at 1000 FPS to do so. Faster would be better, but if you're suspecting that the animation frames have a delay of about 15-20ms, 1000 FPS is overkill. 60 is perfectly fine.

Just record a video of the animations in question and play it back frame by frame, counting how many video frames a given animation frame is active before changing. Multiply that by the frame time of the recording to get the frame time of that animation frame. If your recording is high-fidelity enough and matching the actual game render rate enough, this will give you a reasonable approximation of the animation rate, which you can fine-tune by hand if needed.

Note that if the game alters the framerate for its animations under any circumstances, such as for dramatic effect or simply such that each frame of an animation may stay on screen for its own period of time, your observations will be impacted by that.

---
Tags: frame-rate
---


# Question
Title: How can I detect "rooms" in a 2D side scrolling game?
I'm looking to create a system that recognizes certain types of buildings and rooms you can create in game, like how Terraria detects "residences." In that game, a house can be constructed in a tile-based world by constructing a zone of blocks satisfying a set of conditions:

1. The zone is completely insulated from the "outside" by player-placed blocks.
2. The zone can fit a 5x7 rectangle.
3. there is at least one table, one light source, and chair in the enclosed area.
4. There is a door leading out from the zone.
5. Terraria has both a foreground and background tile layer. The entire background of the zone must be filled with player-placed blocks.

How can I efficiently detect when a player has constructed a suitably-sized area, and how can I efficiently check that the area contains all the required furnitture/components?

Example of an interior zone that satisfies all the housing requirements:

# Answer
I'm not familiar with Terraria, but that can be easily done using a flood-fill algorithm.

Instead of pixel, you check the tiles, and for each tile checked, you evaluate if the algorithm can proceed checking other tiles, while storing in an array or list which objects are found during the process.

The algorithm starts at the tile where the character is at. You can start each 1 second, 2... it's a matter of tweaking to find the best interval.

It's also a good idea to prevent the algorithm to run for too long, which can be accomplished by limiting the number of tiles that the algorithm can run per run, otherwise your algorithm will cause long lags when the character is in an open area.

**Edit**

As stated in the comments, you can use other approaches on when to start the algorithm, such as when the player change a tile, or the tiles having an `am I modified?` variable that, if `true`, start the algorithm. However, you must be careful with this approach:

* What if a tile that is part of the room, but not a tile that your character is at, is modified? Maybe the tile was changed by other player, or an environment event, or the life-time of the tile ended. Your character will be unaware of the modification and won't execute the algorithm to detect the updated room, an error-prone situation.

You could implement some sort of approach to detect these modifications on tiles that your character is not at, but executing the algorithm on intervals is the simplest approach, and less error-prone. Just make sure to not execute flood-fill on every frame.

**End of edit**
> 36 votes

# Answer
Like @Ferreira da Selva said, try the flood fill algorithm. Though, you can use a few different criteria when running the algorithm to determine whether it is enclosed.

For example, for each tile you check if there is a background tile, and if there isn't, then you know that it isn't enclosed. Or you could have it perform a deferred execution by separating it over a number of frames, thus lightening the load on the processor and reducing lag. Or you could create a room size limit that the player would have to adhere to.

Using a combination of these would allow you to do it more efficiently and for effectively.
> 3 votes

# Answer
There are 2 hard problems in computer science. Naming things, cache invalidation and off-by-one errors.

This is a cache invalidation problem.

If you have a record of "is this inside", whenever a block is placed or removed it is pretty easy to update it and its region via a flood fill.

To optimize this you may want to have a set of tiers of "insideness".

A "cell" is a region surrounded by player-placed blocks (up to a certain size).

A "room" is a cell with background tiles.

"Inside" is a room with a door, a light and a chair.

When you place a player-placed foreground block, do a clockwise/counterclockwise walk to see if a new cell is formed. When you remove a player-placed foreground block, examine if it breaks any cells -- if so, see if a new cell is formed by merging the two.

When a new cell is formed or unformed, check for it being a room or an inside.

Cells can keep track of how many background tiles they need to be a room. Then a simple count when a cell is formed, a background tile is added or removed from the cell, can determine if it is a room.

Similarly, Cells can keep track of how many chairs and light sources (and in fact objects of all kinds) are within them. Then the inside check is trivial.

A count of entrances can also be done.

---

So we augment the map with "cells". When tiles are added or removed we check the cell of the location, and increment/decrement the count in the cell.

Use clockwise/counterclockwise walking to define the interior and exterior of a cell when a foreground block is added or removed. As the size of cells is limited, this walk will take a bounded number of steps.

As a bonus, you now have a cheap way to talk about "opulant" rooms, or "room is blessed by a holy fountain", or anything else about a room, as rooms have a count of each object type within them. (Or, as rooms are bounded in size, just do an iteration; this removes a cache).

Each location is in at most one cell, so you can store the cell-id of each location on the main map.
> 3 votes

# Answer
When using the flood fill algorithm, make also a variable, that will increment with each tile checked, so if it is higher than 35 (7\*5, the max size of the room) it just stops checking!
> 0 votes

---
Tags: spatial-partitioning
---


# Question
Title: How can i reproduce the bird to catapult animation in angry birds?
I've seen tutorials on producing an angry birds like game but non of them explain how to get the next bird on the catapult after the current bird is shot. Also how would i go about doing this if the catapult could change position and i want to get the next bird on the catapult taking into account that the birds are not all in the same position.

# Answer
1)make an empty object and place it where you want to shot your bird of 2)make a reference in your script to this object use its position... 3)use code like this:

```
void ShootBird()
{
   //start position is the position of your object
   GameObject newBird = Instanciate(birdPrefab, startPosition, startRotation);
   //do stuff with your newBird object e.g apply forces etc.
}

```

Also if you wanna move the next bird into the catapult simply get a reference to it and let it move towards your start position. There are already asked questions which should answer how to move objects to a point.

if you have a specific question go ahead and ask... next time describe your question more precisely. You´ll get better answers
> 1 votes

---
Tags: unity, c#, animation, game-mechanics
---


title: Strange realtime shadows in Unity3D

text:
# Question
Title: Strange realtime shadows in Unity3D
I'm trying to do realtime lighting, and my shadows are acting very strange. When I project a spotlight out from the camera (like a flashlight in a first person game) my shadows show up as 3D skews of the objects, and I can actually clip through them if I move the camera in the right way... if I detach lights from the camera and just have them sit in one position, I don't seem to have this issue (cylinder to the right is just the model Im using for the flashlight... its attached to the camera):

* All objects have Cast Shadows set to "On"
* All objects have Receive Shadows checked
* All objects have Light Probes and Reflection Probes set to "Blend Probes"
* All objects have Motion Vectors set to "Per Object Motion"
* All objects have Lightmap Static unchecked
* All objects have Dynamic Occluded checked
* All lights have Mode set to "Realtime"
* All lights have Shadow Type set to "Soft Shadows"
* All lights have Realtime Shadow Strength set to 1
* All lights have Realtime Shadow Resolution set to "Very High Resolution"
* All lights have Realtime Shadow Bias set to 0 (changing this doesn't seem to effect the issue)
* All lights have Realtime Shadow Normal Bias set to 0 (changing this doesn't seem to effect the issue)
* All lights have Realtime Shadow Near Plane set to 0.1 (changing this doesn't seem to effect the issue)
* All lights have Draw Halo unchecked
* All lights have Render Mode set to "Auto"
* All lights have Culling Mask set to "Everything"
* Camera has Clear Flags set to "Solid Color"
* Camera has Background set to #000000
* Camera has Culling Mask set to "Everything"
* Camera has Projection set to "Perspective"
* Camera has Field of View set to 60
* Camera has Near Clipping Plane set to 0.3
* Camera has Far Clipping Plane set to 1000
* Camera has Viewport Rect set to 0, 0, 1, 1
* Camera has Depth set to 0
* Camera has Rendering Path set to Use Graphics Settings
* Camera has Occlusion Culling checked
* Camera has Allow HDR checked
* Camera has Allow MSAA checked
* Camera has Allow Dynamic Resolution unchecked
* Camera has Target Display set to "Display 1"
* In Player, Rendering Color Space set to "Linear"
* In Player, all Rendering Auto Graphics APIs checked (win, mac, lin)
* In Player, Rendering Static Batching checked
* In Player, Rendering Dynamic Batching checked
* In Player, Rendering GPU Skinning unchecked
* In Player, Rendering Graphics Job (Experimental)\* unchecked
* In Player, Rendering Lightmap Encoding set to "High Quality"
* In Graphics, all Built-in Shader Settings are set to "Built-in shader"
* In Graphics, Shader Stripping Lightmap Modes is set to "Automatic"
* In Graphics, Shader Stripping Fog Mode is set to "Automatic"
* In Graphics, Shader Stripping Instancing Variants is set to "Strip Unused"
* In Graphics, Preloaded Shaders Size is set to 0
* In Lighting, Skybox Material is set to "Default-Skybox"
* In Lighting, Sun Source is set to "None (Light)"
* In Lighting, Environment Lighting Source is set to "Color"
* In Lighting, Environment Lighting Ambient Color is set to #000000
* In Lighting, Environment Lighting Ambient Mode is set to "Realtime" (and the dropdown box is greyed out, so I can't change it)
* In Lighting, Environment Reflections Source is set to "Custom"
* In Lighting, Environment Reflections Cubemap is set to "None (Cubemap)"
* In Lighting, Environment Reflections Compression is set to "Auto"
* In Lighting, Environment Reflections Intensity Multiplier is set to 0
* In Lighting, Environment Reflections Bounces is set to 1
* In Lighting, Realtime Global Illumination is checked
* In Lighting, Baked Global Illumination is unchecked
* In Lighting, Fog is unchecked

# Answer
Just like your main rendering camera, your shadowcasting lights have a near plane. They can only see geometry that's out past the near plane - anything closer along the light's axis gets clipped out.

As described in the Unity manual on shadowing:

> A low **Shadow near plane offset** value create the appearance of holes in shadows

When you let a shadowcasting light get arbitrarily close to an object, eventually the object will clip that near plane. The clipped region will no longer be visible in the light's shadow map, and so it won't block light from reaching content further away.

As you've found, just reducing the light's shadow near plane parameter alone won't fix this issue - we can't reduce the near plane below about 1/100th of the light's range for a spot light, or 0.1, whichever is smaller. (This constraint helps keep the shadow map's depth precision well-distributed over the light's range, to minimize shadow acne and leaking). If our light can get closer to the object than that, we're basically\* out of luck.

So, we need to keep the light from pushing that close to an object. One way you can do this for a moving light is to check it against the object colliders, using eg. SphereCasts or ComputePenetration to find a safe place to stop the light before it clips in.

Whatever collision shape you use should encompass the whole tip of the light cone closer than the near plane, so don't forget to account for the width of the light disc at near plane distance. ie...

```
float halfAngle = 0.5f * light.spotAngle * Mathf.Deg2Rad;
nearConeRadius = light.shadowNearPlane * Mathf.Tan(halfAngle);
nearConeSideLength = light.shadowNearPlane/Mathf.Cos(halfAngle);

```

To help match the collision volume you need for good shadow rendering against the rendered geometry of the flashlight, you can situate the point of the light itself deeper inside the housing of the light source, and use the front lens/reflector section to fill out the no-go zone for collisions.

> * I say "basically" because there are *potential* workarounds, but they're not pretty. For most cases, you're better off keeping the light slightly away from potential occluders.
>
> If you really need close shadows though, you can set up a kind of cascaded setup, stacking:
>
> * A second light at the same position of the first, with its far plane at the original light's near plane, and its near plane correspondingly closer.
> * A camera at the same position as this "near light" that renders the same depth range into a masking RenderTexture
> * Use this RenderTexture mask as a light cookie or shadowcaster seen by your far light, to pass shadow information from the near light down to the more distant end of the light cone.
> * If needed, you could in principle stack this multiple layers deep.
> 3 votes

---
Tags: unity, graphics, lighting, graphics-programming, shadows
---


# Question
Title: Detect if a sprite has left the camera in libgdx?
Is there a method to know if a sprite has left the camera of the stage? or I have to do my operations? :P

# Answer
The Camera class contains a Frustum object with the public method pointInFrustum (Vector3 point) which returns true if your sprite is within the frustum of the camera . You can also have a look at the user wiki for other culling techniques. http://code.google.com/p/libgdx-users/wiki/Culling
> 5 votes

# Answer
If you are creating a 2D game with tiles you can easily implement your own culling which is a lot cheaper since you only itterate over exactly what you need within your tile array.

Things you should know:

* Camera location
* Viewport width/height
* Tile width/height

Now we can calculate how many tiles should be drawn.

* Total horizontal tiles on screen = `viewport.width / tileWidth`
* Total vertical tiles on screen = `viewport.height / tileHeight`

The math depends on how everything is set up but is very simple. For example it makes a difference if the center of the screen is the camera location, the top left or bottom left.

You should end up with something like this:

```
int startX = cameraWorldPosX / tileWidth;
int startY = cameraWorldPosY / tileHeight;

//When you have the position of the camera in the center of the screen you do something like this:

int startX = (cameraWorldPosX - viewport.width / 2) / tileWidth;
int startY = (cameraWorldPosY - viewport.height / 2) / tileHeight;

for (int y = startY; y < startY + viewportWidth / tileWidth; y++)
{
    for (int x = startX; x < startX + viewportHeight / tileHeight; x++)
    {
        //Draw logic
    }
}

```

The benefit of this over checking if a point is within your frustum is that with the latter you need to iterate over each point instead of using some simple array where you always itterate over a set amount of tiles that is equal to the amount of horizontal tiles * vertical tiles that actually need to draw. This way you can have huge maps and still have a good frame rate. Unfortunately this gets harder and trickier when using 3D but gets exponentially harder with the freedom the user gets with the camera. You can imagine a fixed perspective camera that moves with the character just needs a couple of hardcoded variables to do the same tricks on an array of meshes that represent your map.
> 3 votes

# Answer
Just use bounding sphere check.(you can calculate radius using pythagoras ) It fast as hell and also work with rotation. It's not perfect but never cause false culling.

For ad hoc optimized version Intersector have some rectangle contain rectanle methods these can work too. But you need to calculate rectangle for camera frustum your self.
> 0 votes

# Answer
This function checks if an actor is visible (works only for 2D). Works in all situations, for example when the actor is inside a group.

```
    /**
     * Returns if the actor is visible or not. Useful to implement 2D culling.
     **/
    public static boolean actorIsVisible(Actor actor) {
        Vector2 actorStagePos = actor.localToStageCoordinates(new Vector2(0,0));
        Vector2 actorStagePosTl = actor.localToStageCoordinates(new Vector2(
            actor.getWidth(),
            actor.getHeight()));

        Vector3 actorPixelPos = new Vector3(actorStagePos.x, actorStagePos.y, 0);
        Vector3 actorPixelPosTl = new Vector3(actorStagePosTl.x, actorStagePosTl.y, 0);

        actorPixelPos = actor.getStage().getCamera().project(actorPixelPos);
        actorPixelPosTl = actor.getStage().getCamera().project(actorPixelPosTl);

        return !(actorPixelPosTl.x < 0 ||
                 actorPixelPos.x > Gdx.graphics.getWidth() ||
                 actorPixelPosTl.y < 0 ||
                 actorPixelPos.y > Gdx.graphics.getHeight()
                );
    }

```
> 0 votes

---
Tags: android, camera, libgdx
---


# Question
Title: How to find the degree of interpolation?
I have two quaternions: `A` and `B`. I want to lerp between them.

Given another quaternion `C`, I want to find the variable `unknown`, as seen in the equation below:

```
Quaternion.Lerp(A, B, unknown) == C

```

(Unfortunately, the equation above is misleading. In the scenario that `C` is "out of range" -- i.e. not along the shortest path to get from `A` to `B` -- `unknown` should simply be `0` or `1`.)

How can I do so?

# Answer
This is trickier than it looks on the surface for a couple of reasons:

1. Lerping Quaternions isn't the same as Lerping scalars, Euclidean vectors, or Colours.

You can think of an orientation Quaternion as a point on the surface of a 4-dimensional sphere with radius 1.

To perform a Lerp between two Quaternions, we draw a straight line between their respective points on the sphere (so this chord cuts inside the sphere, rather than wrapping around its surface). Then we Lerp along this straight line, as though we were working with Euclidean 4-vectors.

Since the result will generally not sit on the surface of the sphere, we finish up by normalizing it, to snap it back to unit length. This is effectively a Gnomonic projection, so it distorts our nice uniform Lerp along the straight line chord into a non-uniform blend along the geodesic arc on the surface of the sphere. Changes in the parameter `t` make smaller changes in the output Quaternion when t is close to zero or close to 1 (where the chord is closest to the sphere surface), and larger changes when t is close to 0.5 (where the chord is furthest from the sphere's surface, and the gnomonic projection magnifies it out)

For this reason, when we want a perfectly uniform rate of rotation between two orientations, we'll prefer the more expensive `Quaternion.Slerp`, which uses more sophisticated math to blend along the arc directly. Ratchet Freak's answer is a correct formula to use if you want to work with Slerp instead.
2. Quaternions have identical twins.

For any given orientation, there are two quaternions that describe it: one with a rotation angle less than or equal to 180 degrees (w \>= 0), and one with a rotation angle greater than or equal to 180 degrees in the opposite direction (w \<= 0).

To get the closest intermediate between two given orientations, we'll sometimes need to exchange one of the inputs for its twin, which we can form by negating all four components x, y, z, and w.

With all that out of the way, here's a method to extract the Lerp parameter t from an initial orientation `a`, a final orientation `b`, and an intermediate between them `c`:

```
float EstimateLerpFactor(Quaternion a, Quaternion b, Quaternion c) {

    float aa = Quaternion.Dot(a, a);
    float ab = Quaternion.Dot(a, b);
    float ac = Quaternion.Dot(a, c);

    // If the two rotations on opposite sides of the hypersphere,
    // replace b with -b. This is an equivalent orientation:
    // if b = (angle, axis) then -b = (360 - angle, -axis).
    if(ab < 0f) {
        ab *= -1f;
        b = new Quaternion(-b.x, -b.y, -b.z, -b.w);
    }

    float bb = Quaternion.Dot(b,b);
    float bc = Quaternion.Dot(b,c);

    float cc = Quaternion.Dot(c,c);

    float denom = (bb - 2 * ab + aa) * cc - (bc - ac) * (bc - ac);

    if (Mathf.Approximately(denom, 0f))
        return 0f;

    float t = (ac * (bc - ac) - cc * (ab - aa)) / denom;

    return Mathf.Clamp01(t);
}

```
> 1 votes

# Answer
Assuming all quaternions are unit length, you can get the angle between 2 quaternions by taking the acos of the dot product between them. Then the result is

```
acos(dot(A, C)) / acos(dot(A, B))

```

But this is only valid when C is an actual interpolation between them. To verify this you can add one more test:

```
if(abs(acos(dot(A, C)) + acos(dot(B, C)) - acos(dot(A, B))) > epsilon) return 0;

return acos(dot(A, C)) / acos(dot(A, B));

```

Basically the sum of the angle between A and C and the angle between B and C must be the angle between A and B (within error margin).
> 0 votes

# Answer
This is based on a theory, since I don't really know how the subtracion of Quaternions work. But, I will base it on the basic interpolation formula, and the method I'll provide has worked for me on Vectors, since subtraction is a matter of a difference between each component.

The first is the linear interpolation formula, the second a way to get the time t, which is in your case, the unknown value.

You just need the output, which is C and the initial and final values (A and B respectively). Since the interpolation is linear, it does not matter which components you pass, as long as they are the same axes (in this case I pass all the X's, but you could pass all the Y's, Z's or W's).

Again, this has been proved to work for me with Vectors and numbers, but I don't really know how Quaternion subtraction works, I may investigate it and update the answer. In the meantime, I hope it helps.

**Edit:**

After some corrections from @DMGregory, I realized I haven't fully tested the function, so I solved for t and found the correct formula:

It is the same formula I found in a book used for getting the Membership Degree on a Fuzzy Logic's System given an input (in your case Quaternion C).

Code corrected:

```
float GetInterpolationTime(float output, float initialValue, float finalValue)
{
    return ((output - initialValue) / (initialValue - finalValue));
}

void Update()
{
    float t = GetInterpolationTime(C.x, A.x, B.x);
    // Here I use LerpUnclamped in case t is out of range [0, 1]
    if(Quaternion.LerpUnclamped(A, B, t) == C) /// Good to go...
}

```

Sorry for the misinformation, and hope it helps.
> -1 votes

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


# Question
Title: Mitigating the noticability of a frame drop in XNA
I have been having some minor frame drop issues in a 2D XNA game.

To start with, I am a vsync'ed, mixed timestep. That is:

```
IsFixedTimestep = false;
graphicsDeviceManager.SynchronizeWithVerticalRetrace = true;

```

This is combined with a fixed physics timestep of 120hz, implemented with the pattern used in Fix Your Timestep! to avoid jittery physics movement. So, Update runs with a variable timestep, and another Tick runs with a fixed timestep (the idea is from Unity's Update/FixedUpdate).

When a sprite moves across the screen at a steady pace, every couple of seconds a jitter/hiccup is noticable. Some googling around led me to this forum post several years ago talking about the same issue.

To test this, I added this code to an Update method:

```
if(gameTime.ElapsedGameTime.TotalMilliseconds > 22)
{
    Logger.Log(gameTime.ElapsedGameTime.TotalMilliseconds.ToString());
}

```

Sure enough, every couple of seconds the log showed a time above 30 milliseconds, usually around 32. Seeing as one frame at 60 fps is 16.6 milliseconds, it seems that a frame is simply being lost. I added some additional code to flash the screen red whenever this happens. Again, sure enough, I notice the bullet hiccuping when the screen flashes red. If it is simply dropping a frame, that means that the bullet will hold still, then when the frame finally runs, the physics will run 4 times (since it runs twice as fast as the monitor, over two frames) and move the bullet a lot.

Now, I'm not sure if I can fix this. If this is indeed a quirk of XNA (and gamedev in general?) the frame drop may be unavoidable. So, I would either know how to either get rid of the frame drop, or mitigate how visible it is. A few more points:

**1. It's probably not the GC.**

In that forum post, they seemed to hone the problem down to a point where the GC would never/hardly run, and still saw the problem. To check myself, I added some code that checked `GC.GetTotalMemory(false)` every frame, and if it dropped from the last frame, log "GC". I *think* a drop in that would show a GC collect, but I could be wrong. "GC" was logged *independent* of the other log when a frame was dropped.

**2. I can't use a variable timestep**

I need the physics to be reproducible across a network. This means I need it to be as deterministic as possible (it actually doesn't matter 100%, but it will cause noticable artifacts the less deterministic it is). So, I can't just multiple the velocity of objects by `gameTime.ElapsedGameTime`.

**3. I don't want to use IsFixedTimeStep**

I like to keep the framerate under my control a bit. It gives more control over drawing, and allows several somewhat independent framerates. The forum post also stated that setting IsFixedTimeStep to *false* helped the problem. Granted though, I basically reimplented IsFixedTimeStep myself!

Additionally, setting `IsFixedTimeStep = true;` doesn't help the stuttering.

**4. Some ideas?**

So if I can't fix the problem, perhaps I can mitigate it somehow. Some ideas I've had are:

* Motion blurring
* Give trails to bullets
* Increase the amount of "noise" on the screen so that a frame drop is a small issue
* Separate update and draw in to separate threads?
* Deal with tearing and unsync from the vertical retrace? This almost completely solves the problem, but GPU usage goes to **100%** as it's updating and drawing as fast as it can.

Maybe something has also happened with XNA since the forum post in 2008, that I can use. Otherwise, I'm not sure what to do about the issue. Is it a really small issue? Yeah! I'd love to have a silky-smooth game, though. I'd love any ideas!

# Answer
> 1 votes
To start, there's a good post by Shawn Hargreaves on GameTime (more specifically, Fixed and Unfixed timestep) over here. Perhaps it will give you an idea or some things to try.

However, I'm not entirely sure that you can rule out the garbage collector.

**For Garbage:**

Run your game through CLR Profiler and see what it tells you. If you have access to an Xbox 360, you can use the XNA Remote Performance Monitor to tell you more quickly if there's an issue (although, unlike CLR Profiler, it won't tell you *where* the issue is). There's a series of blog posts by Shawn about using XNA RPM located here, and here.

Also, your method of checking garbage *should* work. However, my personal favorite way is something like this:

```
 WeakReference GarbageTracker = new WeakReference(new object());
 int GarbageCollections = 0;

```

Then, in your update:

```
if(!GarbageTracker.IsAlive)// if it's not alive.  If it's been collected, it will be set to false
{
      GarbageTracker = new WeakReference(new object());
      GarbageCollections++;
}

```

This will tell you when a collection happens, as that WeakReference will be collected with every collection that's run. Then, if it's been collected, we increment our counter and set it reset it.

**Generally:**

Some frame skips are unavoidable. Sometimes an update or (less often) a draw takes longer than it should, and there's no great way to adapt for that (well, more accurately, no great *easy* way to adapt for that). Off the top of my head, you might want to check gameTime.IsRunningSlowly for any lag. If XNA doesn't think it's running slowly, it's more than likely a refresh-rate problem.

Hopefully this helps!

# Answer
> 0 votes
On the subject of using DirectX/DXGI/XNA and .NET languages -- if your application adheres to DirectX/.NET patterns and practices, garbage collection will not hurt your frame. Unless your application is doing something silly on another thread or you're creating a large amount of objects in a tight loop without proper disposal, 9/10 times it's an issue with main loop logic (rounding errors is a common one) or with rendering code.

---
Tags: xna, fixed-timestep, lag
---


# Question
Title: Why is there a white border around my app icon?
EDIT: This is because Unity did not support Android's adaptive icons. As of Unity 2018, it is supported natively.

---

I am developing an Android app in Unity. I have two versions of the app on my phone, both with identical icons. The white border is only on the newer version of the app. I am using a Google Pixel.

Why is this there, and how do I get rid of it?

Is this tied to my phone or my app? If it is tied to my phone, why is it on one icon, but not the other (they are same icon)? I don't want other users to have this pointless border around the app, as my icon already has a border.

# Answer
> 4 votes
Reading about the issue at https://forum.unity.com/threads/android-oreo-icon-is-incorrect-on-unity-5-5-0p4.492300/:

* The issue seems to be due to the Adaptive Icons feature in Oreo.
* Unity will be working on a fix in an upcoming major release.
* In the meantime, you can either export to Android Studio and specify an adaptive -icon in your manifest: https://developer.android.com/guide/practices/ui\_guidelines/icon\_design\_adaptive.html
* or in Unity you can change your target SDK version API level 25 since the features were added in API level 26.

# Answer
> 0 votes
White border are there because of new icon system(Adaptive icons) in android oreo+. If your targetSDK is greater than 25 you have to integrate adaptive icons to avoid white borders. Adaptive icons

For integrating adaptive icons in Unity17 I have created small plugin. Unity Plugin

# Answer
> -1 votes
Because there is a white background in your new icon. If you have selected default icon in your player setting then all icon will be saved as it is. See the image below for reference:

You have to select override icons for every dimensions. See image below:

I hope it helps you. Good luck.

---
Tags: unity, android, launcher
---


# Question
Title: Object movement in Unreal using BPs and input touch and ARCore
So I am trying to move an object in Unreal through input touch using ARCore. The problem is that I can't use the simple Screen to world position because it just returns a world position wherever the camera is at the time that you touch. I'm trying to convert the X and Y positions to actual space but, I am having a difficult time with it. Here's what I have so far:

This works okay, but the movement isn't equal if that makes sense. Obviously it's because I am just pulling the raw coordinates but, I honestly have no idea what I need to do to them in order to get it to move smoothly.

If you're still not following, basically, the closer I get to the left, top edge the slower the object moves and the closer I get to the right bottom edge the faster the movement. This happens because the X and Y coordinates get smaller/larger

What can I do to compensate for this disparity between coordinates?

Is there a way to get like a percentage from the edge of the screen?

# Answer
Try supplying GetActorRelativeLocation to your "+" Node instead of GetActorLocation.
> -2 votes

---
Tags: mobile, unreal
---


# Question
Title: Loading texture from Resources folder not working C#
So I want to load different textures for my game object when different conditions are met. There are no errors when I compile this code. The colours change according to the condition, that part does work. The textures do not load though. The textures are stores in a Resources folder in Unity. The first code works but the second does not. Why is this the case? Below is my code:

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

public class Level4 : MonoBehaviour
{

    Material _mat;
    GameObject Sphere;

    // Use this for initialization
    void Start()
    {
        Sphere = GameObject.FindWithTag("Player");
        //Material _mat = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;

    }

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

            if (Input.GetKeyDown(KeyCode.UpArrow))
            {
                Renderer _rend = GetComponent<Renderer>();
                Material _mat = _rend.material;
                _rend.material.mainTexture = Resources.Load("face1") as Texture;
                _mat.color = Color.red;
            }
        }
        catch (System.Exception)
        {
        }
    }
}

```

this is the second code that does not work:

```
    using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class arduino : MonoBehaviour
{

    SerialPort sp = new SerialPort("//.////COM6", 9600);// Com port and the baud rate of the arduino
    Material m_Material;
    GameObject Sphere;

    void Awake()
    {
        Sphere = GameObject.FindWithTag("Player");
        m_Material = GameObject.FindWithTag("Player").GetComponent<Renderer>().material;
    }
    void Start()
    {
        if (!sp.IsOpen)
        { // If the erial port is not open
            sp.Open(); // Open
        }
        sp.ReadTimeout = 250; // Timeout for reading
    }

    // Update is called once per frame
    void Update()
    {
        if (sp.IsOpen)
        { // Check to see if the serial port is open
            try
            {

                string portreading = sp.ReadLine(); // get the string output of the serial port
                float amount = int.Parse(portreading);

               if ((amount > 251f))
                {

                    Renderer _rend = GetComponent<Renderer>();
                    m_Material = _rend.material;
                    _rend.material.mainTexture = Resources.Load("face1") as Texture;
                    m_Material.color = Color.red;

                }
            }
            catch (System.Exception)
            {

            }

        }

    }
}

```

# Answer
Take a look at the documentation for examples. Renderer.material

also make sure you have placed the texture in a folder named Resources.

you can reference the Renderer then get a reference to the material and then load it and change the color.

```
if ((amount > 151f) && (amount < 200f))
{
    Renderer _rend = GetComponent<Renderer>();
    Material _mat = _rend.material;

    //make sure face2 is in Assets/Resources
    _rend.material.mainTexture = Resources.Load("face2") as Texture;
    _mat.color = Color.blue;
}

```
> 1 votes

---
Tags: unity, assets
---


# Question
Title: Implementing reference counting from scratch or using shared_ptr for resource?
In an OpenGL application that I am writing, I want to have a simple shader class to wrap the OpenGL shader handle. Ultimately, I want this shader class to behave very similarly to a shared\_ptr in c++ (that is, keep a reference count and free the resource when no references are left). While it is relatively trivial to implement this reference counting from scratch, I was wondering if it is considered a better design choice to instead use `std::shared_ptr` with a custom deleter to free up the resource.

The main source of my doubt is the fact that it might be considered unconventional due to the fact that (as far as I know), creating an OpenGL shader program handle does not actually involve heap memory (which is what shared\_ptr takes care of) but I still feel that it could apply here because I want this resource to be handled very similarly to how heap memory would be handled. The purpose of this question is basically to seek the opinion of others as to whether this actually is unconventional, because I do not know.

Also, although I used shaders as an example, the same question also applies to textures and buffers in OpenGL as they also must be allocated and freed.

# Answer
There is *generally* nothing wrong with using `shared_ptr` for that purpose. You would RAII the OpenGL handle (to the shader/buffer/texture) in a typical way, and let `shared_ptr` manage the object's lifetime. Everything works, forget how it works.

Of course, `shared_ptr` does things that you do not necessarily need or want, and those are not free. Notably, the reference count is maintained atomically. Which is effectively zero overhead and totally unimportant if you create half a dozen references per frame. Who cares!

On the other hand, if you create some ten thousand references per frame, the atomic increments/decrements may very well become a dominating factor by saturating memory bandwidth, and there's very little you can do about it.

Also, one has to consider whether automatic management is really what's needed. `shared_ptr` is not really just "reference count and too lazy to check". It is intended to *share* ownership (as the name implies!). If that's what you do, it's the right tool. If it's not what you actually do, then you may use it anyway but there may be better designs. It is tempting since you can create weak references, and stuff "just works" even if you don't know when something is needed, but in a scenario where you know *exactly* whether or not something will be needed for the next frame, it is possibly sub-optimal.

You might find that using a `unique_ptr` or even raw pointers may mean maybe some extra management work, but not really all that much, and is zero overhead in total. Note that from a logic point of view, a function that e.g. draws from a buffer *does not own it*. The resource management system does. If a function *does not* own something, then passing a (const) raw pointer is just fine. It's actually "more correct" than passing a shared one since you do not communicate something that isn't true.

Will `shared_ptr` work? By all means. If that's all that counts, please use it, do not reimplement it yourself.
> 2 votes

# Answer
`shared_ptr` will work fine holding your buffers/texture/shader resources if you really need shared ownership of those resources. I'd like to argue the case (or underscore it, I guess, since others have touched on it) that shared ownership is *not* what you want for these resources. It just doesn't make sense for them.

Somewhere in your code is a class or other module of code, usually called a `GraphicsDevice` or similar, that is responsible for actually creating these resources and handing out the `shared_ptr`s to them. By using `shared_ptr`, you are declaring that the ownership for those resources is now shared between `GraphicsDevice` and whoever gets a `shared_ptr` to a reference.

That's an abstraction that you cannot make true, in reality. Once the `GraphicsDevice` goes away (once you shut down OpenGL), any outstanding `shared_ptr`s to those resources are still "alive." From the perspective of the client code, that's fine, because you said the client code can share ownership of that resource. But in practice the resource is now a zombie, and it cannot even be *deleted* safely, since you've shut down the graphics API.

This is illogical. It leads to a general inability to destroy resources (since no one place can do so with authority), and to crashes on shutdown as things release zombie references to graphics resources after the graphics system is gone.

Consider instead an approach where you hand out *non-owning* references to the resources. A bare pointer makes more logical sense (although doesn't prevent dangling reference crashes). An index/version handle like the kind used in slot map implementations can be even better, since any such references left dangling cannot cause a crash since you they can no longer be used to resolve to the actual resource at all.
> 1 votes

# Answer
`std::shared_ptr`, although named this way, it not intended only for dynamic memory mangement. As per the cppreference, it

> retains shared ownership of an object through a pointer

Note the usage of the word *object* rather than *memory block*. This means that a `std::shared_ptr` is a tool for general resource management, with a very common application being memory management.

Support for the management of other resource types of offered by having constructors that take a different deleter, to substitute the standard `delete` call, for example.
> 0 votes

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


# Question
Title: How do I use Android's adaptive icons in Unity?
As of API 26, Android uses something called adaptive icons.

When targeting API 25 and lower, my app's icon looks fine:

But when targeting API 26+, it shows up in a white circle like so:

* How can I target API 26+ while utilizing Android's adaptive icons?
* What if I want to target API 26+, but not use Android's adaptive icons?

# Answer
> 40 votes
## How can I target API 26+ while utilizing Android's adaptive icons?

In your Player Settings under Android on Unity 2018 or higher, there is a spot in the Icon's section to set your icons. You can set Legacy, Round, and Adaptive icons. The Legacy and Round icons are for API 25 and lower. Just add the icon you want, alpha and all, and you're done. The adaptive icons, for API 26+, are a bit more complicated.

Adaptive icons consist of two parts. The **background** and the **foreground**.

**Background**

The Background is where you put the background for your icon. This image must not have any alpha. It should be continuous, as you do not have control over which parts of the background are shown.

Android determines the cropping and translation of the background image. In the example below, the background is a blue image with a white grid on it. *Notice how the background looks fine despite the square being cropped into a circle, and the background being moved around.*

**Foreground**

The foreground will be your actual icon. Alpha is required for this image. The outter 1/6 of your image may be hidden behind the cropping. That means the image must be scaled down to 66.67% or the original size, while the canvas remains the full size. In the example below, the image is 432x432 pixels; however, the left, right, top, and bottom of the image are each 72 pixels of transparency.

The end result of 66.67% scaling of the image will fill the sprite perfectly within the circle, while the background shows up behind transparent pixels.

On various devices, the icon could be shifted outside of the cropped area given that there was no buffer. For example, in the blue icon above, the foreground is approximately 35% of the original size. If it were 66.67% of the original size, then the Android face would slide out of view.

**Example**

So if this was our background and foreground, such that the contents of our foreground is 2/3 the size of our background:

Then this is the uncropped version of our icon:

But what we could actually see on device (assuming Android is not doing anything "adaptive" at the moment) is this:

---

## What if I want to target API 26+, but not use Android's adaptive icons?

You cannot.

---

## I still don't understand.

Perhaps Android or Unity can explain it better.

---
Tags: unity, android
---


title: Why integrate over accumulation?

text:
# Question
Title: Why integrate over accumulation?
I'm starting to learn how to DIY physics, and I have a question about implementing integration at the most basic level (i.e. this is *not* a Euler vs. RK4 question).

Nearly every example I come across has some `integrate()` function which gets the timestep since the last update, and updates the acceleration (and/or velocity and/or position) since the last update.

In the simplest form: `position += velocity * deltaTime`

However, I don't understand why it's accumulated like this when it could just as easily be gotten by changing a *function*. For example: `getPosition = makeNewFunction()` which could return something that has the signature of `Time -> Position`, and the inner workings of that function are generated via the appropriate mathematical formula.

That way, there is no accumulation... whenever the position needs to be gotten, it calls that function with the current time.

My newbie understanding is that this would also avoid the errors that come from accumulation... so why does this not work, what am I missing?

(fwiw I *did* put together a basic proof of concept of this idea- though it's also testing a few other things at the same time so it's not the cleanest example: https://github.com/dakom/ball-bounce-frp)

**EDIT 1:** as mentioned in the comments, it's probably important to point out that I have *not* learned about changing acceleration yet, or dealing with jerk and other things that require higher-order integration than constant acceleration.

**EDIT 2:** here is some basic sample code of the idea, and pseudo javascript syntax - note that `getKinematicPosition` is *partially applied* so it is returning a new function of just Time -\> Position:

I'm sticking to position here but it could be something else, like `getVelocity`, I guess...

```
getKinematicPosition = initialVelocity => acceleration => time =>
  ((.5 *acceleration) * (time * time)) + (initialVelocity * time);

getPosition = getKinematicPosition ([0,0,0]) (GRAVITY);

onTick = totalTime => {
   position = getPosition (totalTime);
   onCollision = () => {
     getPosition = changeTheFunction(totalTime);
     //changeTheFunction uses totalTime to base updates from 0
     //it could use getKinematicPosition or something else entirely
   }
}

```

# Answer
> 34 votes
> ...the inner workings of that function are generated via the appropriate mathematical formula...

This will work for certain classes of problems, and the key phrase to search for is a **closed-form** solution. For example, in Kerbal Space Program, the motion of a spacecraft in orbit is calculated this way. Unfortunately, most non-trivial problems (e.g. atmospheric reentry of said spacecraft) have no known closed-form solution. Thus the need for mathematically simpler numerical approximations (i.e. `integrate()` over time).

# Answer
> 9 votes
The problem with your approach is, that you don't have a *history* of your object. You can calculate the position if you move in a direction, but what happens if you hit something and bounce back?
If you accumulate from your last known position, you can handle the impact and go on from there. If you try to calculate it from the start, you have to recalculate the impact every time, or set it as new start position.

Your example reminded me of a racing game. (I don't know if the position would be controlled by the physics engine, but i think it works great to explain)
If you drive with your car you can accelerate and slow down. You can't calculate your position without knowing how the speed profile of your car looked like from start to now. Accumulation the distance is way easier than storing the speed you had in every frame from start to now.

Disclaimer: I haven't written game physics by now, that's just how i see the problem.

**Edit:**
In this diagram you can see how the values change over time.
red = acceleration (from start accelerating to sloving down)
green = speed (from starting to stopping)
blue = the way you went.

The total speed is the integral of the acceleration from your start point to your actual logation. (The area between line and axis)
The way is the integral of your speed.
If you know the values for your acceleration, you can calculate the other values. But if i'm not mistaken are integrals also calculated by accumulation on PCs. And it's way more overhead to have all acceleration values stored.
Plus it's probably too much to be calculated every frame.

I know, my paint skills are great. ;)

**Edit 2:**
This example is for linear movement. Canging direction makes this even more difficult.

# Answer
> 8 votes
> However, I don't understand why it's accumulated like this when it could just as easily be gotten by changing a function. For example: getPosition = makeNewFunction() which could return something that has the signature of Time -\> Position, and the inner workings of that function are generated via the appropriate mathematical formula.

**You can!**

It is called using an *analytical* or *closed form* solution. It has the benefit that it is more accurate, since rounding errors that accumulate over time are non-existent.

However, this works *if and only if* you know such a closed form beforehand. For games, this is quite often simply not the case.

Player movement is erratic and simply can not be put into some pre-computed function. The player can and will change their velocity and orientation quite often.

NPCs could potentially utilize closed form solutions, and in fact they sometimes do. This has some other drawbacks, however. Think about a simple racing game. Every time your vehicle collides with another vehicle, you have to change your function. Maybe the car moves faster depending on the underground. Then finding such a closed-form solution will be quite difficult. In fact, there are likely more cases where finding such a closed form is either impossible or so complicated that it is simply not feasible.

A great example of using a closed-form solution is Kerbal Space Program. As soon as your rocket is in orbit and not under thrust, KSP may put it "on rails". Orbits are pre-determined in the two-body system, and are periodic. As long as the rocket doesn't apply any more thrust, you already know where the rocket will be, and you can simply call `getPositionAtTime(t)` (its not named exactly that, but you get the idea).

In practice, however, just using step-by-step integration is often much more practical. But when you see a situation where a closed-form solution exists and is easy to calculate, go for it! There is no reason *not* to use it.

For example, if your character is aiming a cannon, you could easily show the predicted impact point of the cannon ball using a closed-form solution. And, if your game does not allow for the course of the cannon ball to be altered (no wind for example), you can even use it to move the cannon ball. Note that you need to take special care of obstacles moving into the path of your cannon ball, then.

There are lots of similar situations. If you are building a round-based game, then there are likely to be far more closed-form solutions available than when building an RTS game, since you know all parameters beforehand and can say with certainty that they do not change (nothing moves suddenly into that path, for example).

Note that there are techniques to combat then numerical inaccuracies of stepped integration. For example, you can keep track of the accumulated error and apply a corrective term to keep the error in check, e.g. Kahan Summation

# Answer
> 8 votes
In the case of just a simple bouncing ball, coming up with closed form solutions is easy. However, the more complex systems tend to require solving an Ordinary Differential Equation (ODE). Numerical solvers are required to handle all but the simplest cases.

There are indeed two classes of numeric ODE solvers: explicit and implicit. Explicit solvers provide a closed form approximation for your next state, while implicit solvers require solving an equation to do so. **What you describe for your bouncing ball is actually an implicit ODE solver, whether you knew it or not!**

Implicit solvers have the advantage of being able to use much larger time steps. For your bouncing ball algorithm, your timestep can be at least as large as the duration until the next collision (which would change your function). This can make your program run much faster. However, in general, we can't always find good implicit solutions to the ODEs we are interested in. When we can't, we fall back on explicit integration.

The big advantage I see with explicit integration is that the gotchas are well known. You can open up any textbook from the '60s and read all you need to know about the little quirks that arise with particular integration techniques. Thus, a developer learns these skills once, and they never have to learn them again. If you're doing implicit integration, each use case is slightly different, with slightly different gotchas. It's a bit harder to apply what you learned from one task to the next one.

# Answer
> 1 votes
pos(t) = v(t) * t

only works if pos(0) = 0 and v(t) = k

you can't relate position to time without knowledge of the initial condition and the entire velocity function, so the equation is as an approximation of the integral

pos(t) = integral of v(t)dt from 0 to t

EDIT \_________

Heres a little proof per the comments (assuming pos(0)=0)

let v(t) = 4

eqn 1: pos(t) = 4 * t (correct)

eqn 2: pos(t) = c + 4 * t from 0 to t = 4 * t (correct)

let v(t) = 2 * t

eqn 1: pos(t) = 2 * t^2 (wrong)

eqn 2: pos(t) = c + t^2 from 0 to t = t^2 (correct)

I should add that your equation already factors in constant acceleration (i.e. your equation is eqn 2 where v(t) = v0 + a * t and the limits of integration are t0 and t), so your equation should work as long as you update the initial position, initial velocity, and the acceleration remains constant.

EDIT2 \________

I should also add that you could also calculate position with initial pos, initial velocity, initial acceleration, and constant jerk. In other words, you can create a function based off of eqn 2 that represents position vs time by separating it into it's derivatives i.e. velocity, jerk, whatever comes next, etc, etc, etc, but you will only be accurate in your equation if v(t) can be modeled that way. If v(t) can't be modeled with just velocity, acceleration, constant jerk, etc, then you need to go back to an approxomation of eqn 2, which tends to happen when you have things bouncing, air resistance, wind, etc.

---
Tags: physics, physics-engine
---


# Question
Title: First "If" Enemy Selection Function being recognized as a syntax error in Python
I have an issue with trying to under the syntax error with the line `if enemy_select = 1:` in this type of code:

```
enemy_select = random.randit(1, 11)

for enemy_select in range(1):
    if enemy_select = 1:
        enemy_type = character 1

    elif enemy_select = 2:
        enemy_type = character 2

    elif enemy_select = 3:
        enemy_type = character 3

    elif enemy_select = 4:
        enemy_type = character 4

    elif enemy_select = 5:
        enemy_type = character 5

    elif enemy_select = 6:
        enemy_type = character 6

    elif enemy_select = 7:
        enemy_type = character 7

    elif enemy_select = 8:
        enemy_type = character 8

    elif enemy_select = 10:
        enemy_type = character 9

    elif enemy_select = 10:
        enemy_type = character 10

    elif enemy_select = 11:
        enemy_type = character 11

```

# Answer
> 1 votes
It seems you lack the correct indentation for all your lines after `for...`.

Add few spaces or tab at the beginning of every line, starting from first `if`.

**EDIT:**

I was wrong, the problem is that you're using `=` instead of `==` in `if` lines.

BTW: I've tried it in CMD window and it has shown me a `^` sign at the exact character that caused an error. May be helpful in the future.

---
Tags: python
---


# Question
Title: Button stays highlighted after being clicked - Unity3D 4.6 GUI
Sometimes, after clicking a button created by unity's new UI Button, the button stays in its highlight state. Note that Button script has `Color Tint` set as it's `Transition` property and the `Interactable` checkbox is checked.

How can I solve this?

# Answer
> 17 votes
The `Navigation` property of buttons is set to `Automatic` by default, allowing you to navigate through buttons using arrow keys.

If you disable this by changing the `Navigation` property to `None`, buttons will not stay highlighted.

# Answer
> 1 votes
*(In addition to the accepted answer, this is another answer if you are not able to set the `Navigation` property of buttons to `None` in your context.)*

You can also use `UnityEngine.EventSystem.SetSelectedGameObject` to manually deselect the button. For example:

```
private void DeselectClickedButton(GameObject button)
{
    if (EventSystem.current.currentSelectedGameObject == button)
    {
        EventSystem.current.SetSelectedGameObject(null);
    }
}

```

---
Tags: unity, gui
---


# Question
Title: Unity Build not working because resources.assets is over 10GB in size.
I made a application where a bunch of images are loaded and placed in 3d. The total amount of images in the asset folder are about 10.000 images. Only 1100 random of these images get actually used in the application. This is different eachtime on startup. The total size of the Assets folder is 3.2GB.

See the Image below for confirmation:

Now when i build the application the application wont display any of the images in 3D space... :( So i went to investigate, and i found out that my `resources.assets` file is over 10GB in SIZE!! And i found out that unity cant really handle a `resources.assets` file more then 4GB. See the proof below:

So i have no idea what happens here or what to do about it.. All suggestions are welcome!
If more explaination or details are needed let me know.

**Edit:**
Maybe the image import settings are useful to know.. I just used the default settings.. See image below:

# Answer
Check your Build Report: When you have finished your build in Unity go to **Console \> Open Editor Log.** Search the document on **Build Report** You'll see a nice overview (in percentage) of data usage divided in categories. Most of the time the textures are the biggest load!

Reducing the 'image' size scales down your Texture dimensions as well. Down your 'max size' to 1048 or 512 could help. I'm also used to using the best quality images but it's most of the time just an overkill.

Also the 'Crunch Compressing' works pretty good. (in my short experience with Unity) I see it's not ticked.

The Unity Docs explain Crunch compression very well: Crunch is a lossy compression format on top of DXT or ETC Texture compression. Textures are decompressed to DXT or ETC on the CPU and then uploaded on the GPU at runtime. Crunch compression helps the Texture use the lowest possible amount of space on disk and for downloads. Crunch Textures can take a long time to compress, but decompression at runtime is very fast.

If you haven't check your build report please do so, it's very helpful to see where it could be going wrong :)
> 3 votes

# Answer
When you put an image in your project, regardless of the import settings, the full image is saved in the `Assets` folder. So if you take an image that has a size of 100MB, and import it to be small and low quality, this will only appear in your final app and **not** in your `Assets` folder.

Also regardless of how many images you use in your app, **all** images exist in the `Assets` folder. What Unity Cloud does, is take everything that is part of the project, and *then* it decided if it should include an image to the final build, or to scale down an image.

So if you have a 1GB project but you use half of the assets there, and they all are imported as low quality, the final build could be even less than 100MB.

How to solve this? Either build the project yourself, or remove assets that you are absolutely sure you are not gonna include them in your project. 10.000 images are **a lot** for most project, so there is a chance you are doing something wrong. If I'm mistaken, and you need them all, then you simply cannot use Unity Cloud for this project.

You can also resize the images to more manageable sizes, but I suspect that's going to be too cumbersome.
> 1 votes

---
Tags: unity, assets, image, build-process
---


title: 3D Character Animation Effects

text:
# Question
Title: 3D Character Animation Effects
I'm using blender for the 3d stuff and am trying to make game effects for the character I made, I am using unity. I am not really familiar with creating game visual effects but I do know how to make sprite sheets. How do I create a 3d effect in unity? like a shock wave or an explosion, because I cant do it using a sprite sheet.

# Answer
> 0 votes
Sprite Sheets are only the 'visual' part of an particle. You need to use unitys particle system in order to make such effects. As a programmer, you would normally buy assets or let someone else do the job (especially if the particle system is much more complex). It's seems that you are coming more from the artistic direction, which is pretty good because it takes a little bit of practice to get good results.

Check out Unitys official tutorial on this specific topic:

Click Here

---
Tags: unity, blender, character, special-effects
---


# Question
Title: How to identify individual keyboard keys across devices from different locales
I'm trying to make a UI system that adapts images for key binding depending on the keyboard type (azerty/qwerty/etc).

For the moment I've done the binding with DirectInput Key Codes so it does not depend on the type of keyboard, so that part is OK.

But for the choice of UI image to display I face an issue.

The nearest solution I have is to translate the tszName of DIDEVICEOBJECTINSTANCE to ASCII or Virtual-Key Codes and use this code to find the appropriate image for my UI. But tszName is localized depending on the device (eg. the tszName of a french keyboard will return "ESPACE" instead of "SPACE")

So I haven't found a way to bypass this localization in tszName to get an unique code that's consistent across devices with similar keys. Have you some idea?

# Answer
> 2 votes
I finally found two answers : First one, I didn't get that DirectInput Key Codes are called ScanCode. So with that in mind there is this answer wich is linked . So the use of MapVirtualKeyEx translate my Scan Code into VirtualCode and I choose the my UI asset with that code.

The other mean will be to create juste the background of UI asset without any string in it and use the DIDEVICEOBJECTINSTANCE.tszName to fill it.

---
Tags: directx, input, keyboard, localization, directinput
---


# Question
Title: Normal doesn't appeared on shadow/dark area in Mobile Shader
Let's look at this picture:

You can see the red rectangles, those are shaded by normalmap.

Here, is the same model with different light angle, there's no normal shading in dark area.

It only happens in Mobile Shader(simplified blinnphong actually). I'm targeting on Android devices, and using Mobile Shader with Normalmap. How do I fix this?

# Answer
> 1 votes
Since normals encode the facing direction of your surface, they only produce a change in lighting for directional lighting terms:

* Direct illumination from a directional, point, spot, or area light
* Indirect illumination or reflection from a light/reflection probe, directional lightmap, or skybox sample
* Fresnel edge reflection when the view direction just glances along the surface

In shadow, you're not getting any direct lighting so that's out. The standard shader includes a directional ambient term but the mobile shader appears to use a constant ambient light instead, and does not include Fresnel effects.

So, your options are:

* Use (or make) a shader that uses a directional ambient/global illumination term for some directional variation, or
* Add a secondary directional light to your scene, pointing at a different angle, to model the directional component of the ambient sky / bounce lighting. This light can be faint so it doesn't overly bias the appearance in lit areas, and non-shadow-casting so it's cheaper and reaches into every enclosed space.

---
Tags: unity, android, shaders, lighting, normal-mapping
---


# Question
Title: Logic for npc/customer for cafe simulator game
I need help for logic or pseudo code on how to implement a rules/formula for customer in how they choose drinks(& the toppings). I have more than 10 types of customer and I want to set preferences for everyone of them. E.g : a boy prefer juice (60%), soda(30%) and tea (10%), while an adult in suit prefer coffee(80%), juice (20%). The boy would decide to add topping (70%), and would prefer chocolate(50%), jelly(30%),bubble(20%) as the topping.

What is the best way to implement that? And one thing that concern me that some of the toppings or even drinks are actually might be unavailable because its not ready or need to be unlocked first by leveling up or another reason.

Additional info: i am using unity, and have game manager, customer and player/shop scripts.

# Answer
To deal with items changing in availability over time, I'd store your characters' preferences for each drink/topping as a relative weight:

```
// Data structure that can be shared between
// characters with the same tastes.
[CreateAssetMenu( filename = "NewPreferences.asset", menuName = "Characters/Preferences")]
public class Preferences : ScriptableObject {
     public struct Preference {
          public readonly DrinkItem item;
          public readonly float weight;

          public Preference(DrinkItem item, float weight) {
               this.item = item;
               this.weight = weight;
          }
     }

     // Expose in Inspector, but keep private.
     [System.Serializable]
     Preference[] preferences;

     // You can also digest this to a dictionary
     // if your lists get huge.
     public Preference GetPreference(DrinkItem item) {
          return System.Array.Find(preferences, p => p.item == item);
     }
}

```

So if the boy archetype has a relative preference weight of 3 for orange juice and 6 for apple juice, then he's twice as likely to choose apple juice as he is to choose orange juice, whenever both are available. Your numbers don't need to hit any specific total, they just have to be non-negative. A weight of zero (or absence from the list) means they will never order the item.

Next, your ordering system can have something like this:

```
 // Keep this around so it doesn't need to be re-allocated.
 List<Preferences.Preference> weightedOptions = new List<Preferences.Preference>();

 public DrinkItem Choose(Preferences preferences) {
      // Build a shortlist of options the customer likes.
      float totalWeight = 0f;
      weightedOptions.Clear();

      foreach(var item in CurrentDrinkMenu) {
           var pref = preferences.GetPreference(item);
            if(pref.weight == 0f)
                 continue;
            totalWeight += pref.weight;
            weightedOptions.Add(pref);
      }

      // Pick a point in this range.
      float choice = Random.value * totalWeight;
      totalWeight = 0f;

      // Find which item corresponds to this pick.
      foreach(var option in weightedOptions) {
            totalWeight += option.weight;
            if(totalWeight >= choice)
                 return option.item;
      }
      // Should hit only in exceptional scenarios
      // (Customer likes nothing on the menu,
      // or data was ill-formatted with negatives/NaNs)
      return DefaultOrder;
 }

```

If you need, you could also return a very tiny weight for items the customer doesn't like, so they'll fall back on those options if there's nothing else in the menu they like.
> 4 votes

---
Tags: unity, game-mechanics, random
---


# Question
Title: Unreal Engine: Access Violation on FObjectFinder
I got a problem with my project in unreal. I wrote some code about a month ago and it worked fine until yesterday when the editor started crashin on launch. I get this error message in the log:

```
[2018.06.25-20.39.29:731][  0]LogWindows: Error: === Critical error: ===
 [2018.06.25-20.39.29:731][  0]LogWindows: Error:
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: Fatal error!
 [2018.06.25-20.39.29:731][  0]LogWindows: Error:
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: Unhandled Exception: EXCEPTION_ACCESS_VIOLATION reading address 0x000008d0
 [2018.06.25-20.39.29:731][  0]LogWindows: Error:
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x000000002548206A UE4Editor-Landscape.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x000000000B927D45 UE4Editor-Engine.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x000000000B95BF0E UE4Editor-Engine.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x00000000145DE8FD UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x000000001469DABC UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x00000000146B5259 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x00000000146B4774 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:731][  0]LogWindows: Error: [Callstack] 0x00000000146CB0C3 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000146D5A3A UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000146D51B2 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000F7A72E21 UE4Editor-Lyfe_Game.dll!ConstructorHelpersInternal::FindOrLoadObject<UParticleSystem>() [c:\program files\epic games\ue_4.18\engine\source\runtime\coreuobject\public\uobject\constructorhelpers.h:35]
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000F7A7314F UE4Editor-Lyfe_Game.dll!UCompound_ParticleComponent_Cell::UCompound_ParticleComponent_Cell() [c:\users\megapoort\desktop\lyfe\lyfe_game\source\lyfe_game\private\compound_particlecomponent_cell.cpp:30]
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000144605CD UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x0000000014698696 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000145E3EC4 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000F7A6B41D UE4Editor-Lyfe_Game.dll!ACompoundCloud_Cell::ACompoundCloud_Cell() [c:\users\megapoort\desktop\lyfe\lyfe_game\source\lyfe_game\private\compoundcloud_cell.cpp:64]
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000144605CD UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000146D91B0 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000146BB41F UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x0000000014462547 UE4Editor-CoreUObject.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000149CE6C0 UE4Editor-Core.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x0000000014C22282 UE4Editor-Core.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x000000004489F60D UE4Editor-Projects.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x000000004489F91E UE4Editor-Projects.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B66F7F71 UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B66FC4EC UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B66F525A UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B66F54AA UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B6702379 UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x00000000B6703D57 UE4Editor.exe!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x000000005ED03034 KERNEL32.DLL!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x000000005F271431 ntdll.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error: [Callstack] 0x000000005F271431 ntdll.dll!UnknownFunction []
 [2018.06.25-20.39.29:732][  0]LogWindows: Error:
 [2018.06.25-20.39.29:750][  0]LogExit: Executing StaticShutdownAfterError
 [2018.06.25-20.39.29:751][  0]LogWindows: FPlatformMisc::RequestExit(1)
 [2018.06.25-20.39.29:751][  0]Log file closed, 06/25/18 22:39:29

```

`compoundcloud_cell.cpp:64` is where I create a default subobject for the actor. In its constructor (`compound_particlecomponent_cell.cpp:30`) The code that crashes the editor is located. The line that is logged here is:

```
auto psAsset = ConstructorHelpers::FObjectFinder<UParticleSystem>(TEXT("ParticleSystem'/Game/ParticleSystems/PS_CompoundCloud_SingleCelled.PS_CompoundCloud_SingleCelled'"));

```

The code snippet where I create the component looks like this:

```
std::string center = "CenterSystem";
    UCompound_ParticleComponent_Cell* temp = CreateDefaultSubobject<UCompound_ParticleComponent_Cell>(center.c_str());
    particles.Add(temp);
    RootComponent = temp;

```

By now I tried loading different particle systems and in differen classes and I always get access violations. I'm not entirely sure anymore it's my mistake. Could this be a bug within the engine?

It would be fantastic if someone could help me with this. Thanks in advance.

Edit: Still no answer to this problem. Still no solution. If anyone wants to have a look: https://github.com/GameAboutThings/Lyfe

# Answer
Okay, so it was nothing to do with the FObject finder or the particle system itself. There were some unconnected nodes in the material used in the particle system. Check your materials!
> 0 votes

---
Tags: c++, unreal-4, particles
---