# Question
Title: How do I make the camera aware of the position of the object it is tracking?
I'm making a 2D game with a `Camera` that tracks `GameObject`s (usually the player). At the moment, a `GameObject` holds a `RenderingComponent`.

```
struct GameObject {
  std::shared_ptr<RenderingComponent> renderingComp;
};

```

The `RenderingComponent` holds a `CameraMotionTarget`. The `CameraMotionTarget` is a rectangle represented by a center and half size.

```
using CameraMotionTarget = Math::RectCS<float, Math::Dir::RIGHT, Math::Dir::UP>;

struct RenderingComponent {
  virtual void update() = 0;
  virtual const CameraMotionTarget *getMotionTarget() const = 0;
};

struct RenderingComponentImpl final : RenderingComponent {
  void update() override {
    //modify target and do other stuff
  }

  const CameraMotionTarget *getMotionTarget() const override {
    return ⌖
  }

  CameraMotionTarget target;
};

```

The `CameraMotionTracker` stores a `const CameraMotionTarget *` to the object in the `RenderingComponent` and moves the `Camera` according to the `CameraMotionTarget`.

```
struct CameraMotionTracker {
  glm::vec2 getMotionTargetPos(CameraProps) {
    //calculate the target position of the camera to keep the target
    //well within the window
  }

  const CameraMotionTarget *target;
};

struct Camera {
  void update() {
    const glm::vec2 targetPos = motionTracker.getMotionTargetPos(properties);
    const glm::vec2 newPos = mover.getPos(properties, targetPos);
    properties.pos = newPos;
  }

  CameraProps properties;
  CameraMotionTracker motionTracker;
  CameraMover mover;
};

```

This gets the job done. When the player moves, the camera moves smoothly to keep the player on the screen. If I wanted this to be safer, I could use an `std::shared_ptr` and an `std::weak_ptr` but that's not why I'm here. The reads and writes to the `CameraMotionTarget` need to be synchronized. This is easy in my single threaded game but what if I wanted more threads? I'd like the `RenderingComponent` to somehow call a function on the `CameraMotionTracker` but I don't know how.

Ideally, the `CameraMotionTracker` should only be aware of a rectangle and the `RenderingComponent` should only need to know that it **can be tracked** and unaware that it **is being tracked**. My current design is decoupled but unsafe. So my question is:

**How do I architect a safe, decoupled, system where a camera tracks a rectangle?**

# Answer
> 0 votes
In a multithreaded environment, you'll likely have a single physics thread that updates the positions of objects and the player(s). You'll also likely have a rendering thread where the camera exists. The physics thread need not run in lockstep with the rendering thread. (You might want the physics thread to update more frequently to improve collision accuracy, for example.) But if the `CameraMotionTracker` has a pointer to the player, it can directly query it to get the current or last-known position of the player (or whatever the target is).

If that's still too coupled for you, another option is to have some sort of messaging or notification system where the target object sends a message saying it has updated its position and includes the new position (and possibly the old to aid in calculations). Then the `CameraMotionTracker` could listen for notifications from whichever object is the current target. This can still work in a multithreaded environment. This completely decouples the `Camera` from the `CameraMotionTarget`. It also allows there to be multiple listeners if you need that as well. They can all just sign up to receive notifications of changes from the target.

---
Tags: c++, 2d, architecture, camera
---


title: Creating a Robust Item System

text:
# Question
Title: Creating a Robust Item System
My aim is to create a modular / as generic as possible item system which could handle things like:

* **Upgradeable Items (+6 Katana)**
* **Stat Modifiers(+15 dexterity)**
* Item Modifiers(%X chance to do Y damage, chance to freeze)
* Rechargeable Items(Magic staff with 30 usages)
* Set Items(Equip 4 piece of X set to activate Y feature)
* Rarity(common, unique, legendary)
* Disenchantable(breaks into some crafting materials)
* Craftable(can be crafted with certain materials)
* **Consumable(5min %X attack power, heal +15 hp)**

\*I was able to solve features that are bold in following setup.

Now I tried to add many options us to reflect what I have in mind. I don't plan to add all of these features necessary, but I would like to be able to implement them as I see fit. These are also should be compatible with inventory system and serialization of data.

I am planning to **not use inheritance** at all but rather an entity-component / data driven approach. Initially I thought of a system that has:

* BaseStat: a generic class that holds stats on-the-go(can be used for items and character stats too)
* Item: a class that holds data such as list of, name, itemtype and things that are related to ui, actionName, description etc.
* IWeapon: interface for weapon. Every weapon will have its own class with IWeapon implemented in. This will have Attack and a reference to character stats. When weapon is equipped, it's data(Item class' stat) will be injected into character stat(whatever BaseStat it has, it will be added to character class as a Stat bonus) So for example, we want to produce a sword(thinking to produce item classes with json) so sword will add **5 attack** to character stats. So we have a **BaseStat** as ("Attack", 5)(we can use enum too). This stat will be added to character's "Attack" stat as a **BonusStat**(which would be a different class) upon equipping it. So a class named **Sword** implements **IWeapon** will be created when it's **Item Class** is created. So we can inject **character stats** into this sword and when attacking, it can retrieve total **Attack** stat from **character stat** and inflict damage in Attack method.
* BonusStat: is a way of adding stats as bonuses without touching the BaseStat.
* IConsumable: Same logic as with IWeapon. Adding direct stat is fairly easy(+15 hp) but I'm not sure about adding temporary weapons with this setup(%x to attack for 5 min).
* IUpgradeable: This can be implemented with this setup. I am thinking **UpgradeLevel** as a base stat, which is increased upon upgrading weapon. When upgraded, we can re-calculate weapon's **BaseStat** to match its Upgrade level.

Until this point, I can see that system is fairly good. But for other features, I think we need something else, because for example I can't implement Craftable feature into this as my **BaseStat** would not be able to handle this feature and this is where I got stuck. I can add all ingredients as a Stat but that would not make sense.

To make it easy for you to contribute this, here are some questions that you may help with:

* Should I continue with this setup to implement other features? Would it be possible without inheritance?
* Are there any way that you can think of, to implement all of these features without inheritance?
* About Item Modifiers, how could one achieve that? Because it is very generic in it's nature.
* What can be done to ease the process of building this kind of architecture, any recommendations ?
* Are there any sources that I can dig that is related to this problem?
* I really try to avoid inheritance, but do you think these would be solved / achieved with inheritance with ease while keeping it fairly maintainable?

Feel free to answer just a single question as I kept questions very wide so I can get knowledge from different aspects/people.

---

# EDIT

---

Following @jjimenezg93's answer, I created a very basic system in C# for testing, it works! See if you can add anything to it:

```
public interface IItem
{
    List<IAttribute> Components { get; set; }

    void ReceiveMessage<T>(T message);
}

```

---

```
public interface IAttribute
{
    IItem source { get; set; }
    void ReceiveMessage<T>(T message);
}

```

---

So far, IItem and IAttribute are base interfaces. There were no need(that I can think of) to have a base interface/attribute for message, so we will directly create a test message class. Now for test classes:

---

```
public class TestItem : IItem
{
    private List<IAttribute> _components = new List<IAttribute>();
    public List<IAttribute> Components
    {
        get
        {
            return _components;
        }

        set
        {
            _components = value;
        }
    }

    public void ReceiveMessage<T>(T message)
    {
        foreach (IAttribute attribute in Components)
        {
            attribute.ReceiveMessage(message);
        }
    }
}

```

---

```
public class TestAttribute : IAttribute
{
    string _infoRequiredFromMessage;

    public TestAttribute(IItem source)
    {
        _source = source;
    }

    private IItem _source;
    public IItem source
    {
        get
        {
            return _source;
        }

        set
        {
            _source = value;
        }
    }

    public void ReceiveMessage<T>(T message)
    {
        TestMessage convertedMessage = message as TestMessage;
        if (convertedMessage != null)
        {
            convertedMessage.Execute();
            _infoRequiredFromMessage = convertedMessage._particularInformationThatNeedsToBePassed;
            Debug.Log("Message passed : " + _infoRequiredFromMessage);

        }
    }
}

```

---

```
public class TestMessage
{
    private string _messageString;
    private int _messageInt;
    public string _particularInformationThatNeedsToBePassed;
    public TestMessage(string messageString, int messageInt, string particularInformationThatNeedsToBePassed)
    {
        _messageString = messageString;
        _messageInt = messageInt;
        _particularInformationThatNeedsToBePassed = particularInformationThatNeedsToBePassed;
    }
    //messages should not have methods, so this is here for fun and testing.
    public void Execute()
    {
        Debug.Log("Desired Execution Method: \nThis is test message : " + _messageString + "\nThis is test int : " + _messageInt);
    }
}

```

These are the setup needed. Now we can use the system(Following is for Unity).

```
public class TestManager : MonoBehaviour
{

    // Use this for initialization
    void Start()
    {
        TestItem testItem = new TestItem();
        TestAttribute testAttribute = new TestAttribute(testItem);
        testItem.Components.Add(testAttribute);
        TestMessage testMessage = new TestMessage("my test message", 1, "VERYIMPORTANTINFO");
        testItem.ReceiveMessage(testMessage);
    }

}

```

Attach this TestManager script to a component in scene and you can see in debug that message is successfully passed.

---

In order to explain things: Every item in the game will implement IItem interface and every Attribute(name should not confuse you, it means item feature/system. Like Upgradeable, or disenchantable) will implement IAttribute. Then we have a method to process the message(why we need message will be explained in further example). So in context, you can attach attributes to an item and let the rest do for you. Which is very flexible, because you can add/remove attributes at ease. So a pseudo-example would be Disenchantable. We will have a class called Disenchantable(IAttribute) and it in Disenchant method, it will ask for:

* List ingredients(when item is disenchanted, what item should be given to player) note: IItem should be extended to have ItemType, ItemID etc.
* int resultModifier(if you implement a kind of boost the disenchant feature, you can pass an int here to increase the ingredients received when disenchanted)
* int failureChance(if disenchant process has a failure chance)

etc.

These information will be provided by a class called DisenchantManager, it will receive the item and form this message according to item(ingredients of the item when disenchanted) and player progression(resultModifier and failureChance). In order to pass this message, we will create a DisenchantMessage class, which will act as a body for this message. So DisenchantManager will populate a DisenchantMessage and send it to the item. Item will receive the message and pass it to all of it's attached Attributes. Since Disenchantable class's ReceiveMessage method will look for a DisenchantMessage, only Disenchantable attribute will receive this message and act on it. Hope this clears things as much as it did for me :).

# Answer
I think you can achieve what you want in terms of scalability and maintainability by using an Entity-Component System with basic inheritance and a messaging system. Of course, have in mind that this system is the most modular/customizable/scalable I can think of, but it will probably perform worse than your current solution.

I'll explain further:

First of all, you create an interface **`IItem`** and an interface **`IComponent`**. Any item you want to store must inherit from `IItem`, and any component you want to affect your items must inherit from `IComponent`.

`IItem` will have an array of components and a method for handling **`IMessage`** . This handling method simply sends any received message to all stored components. Then, the components which are interested in that given message will act accordingly, and the others will ignore it.

One message, for example, is of type damage, and it informs both the attacker and attacked, so you know how much you hit and maybe charge your fury bar based on that damage. Or the enemy's AI can decide to run if it hits you and makes less than 2HP damage. These are dumb examples but using a system similar to this I'm mentioning, you won't need to do anything more than creating a message and the appropiate handlings to add most of this kind of mechanics.

I have an implementation for an ECS with messaging here, but this is used for entities instead of items and it uses C++. Anyway, I think it can help if you take a look at `component.h`, `entity.h` and `messages.h`. There are a lot of things to be improved but it worked for me in that simple university work.

Hope it helps.
> 8 votes

---
Tags: unity, c#, architecture, design-patterns, effect-modifier
---


# Question
Title: How to align text dynamically inside a rectangle with Phaser JS
I am just starting to learn the Phaser JS framework with my first game. I did not managed to find a way how i can align text inside a rectangle element dynamically without specific coordinates. Here is what i have

```
pointH11L1 = game.add.text(0, 0, '20');
pointH11L1.stroke = "#000";
pointH11L1.strokeThickness = 4;
pointH11L1.font = 'oswaldbold';
pointH11L1.fontSize = 22;
pointH11L1.fill = '#999999';
//pointH11L1.alignIn(graphicsRectH12L2, Phaser.CENTER);
graphicsRectH12L2.addChild(pointH11L1);
pointH11L1.x = pointH11L1.width / 2 - 6;
pointH11L1.y = -2.5;

```

//graphicsRectH12L2 is the rectangle inside which i need to align.

```
var graphicsRectH12L2 = this.game.add.graphics(950, 405);
    graphicsRectH12L2.beginFill(0xffcd00, 1);
    graphicsRectH12L2.drawRect(0, 0, 44, 29);
    graphicsRectH12L2.endFill(0xffcd00, 1);
    group.add(graphicsRectH12L2);

```

# Answer
I extended the Phaser.Graphics and added a Phaser.Text inside it, and center the text inside the graphics, like so:

```
var textStyle = {
    font: "normal 24px Arial",
    fill: '#ffffff',
    align: 'center',
    boundsAlignH: "center", // bounds center align horizontally
    boundsAlignV: "middle" // bounds center align vertically
};
var textElement = new Phaser.Text(game, 0, 0, "Hello World", textStyle);
var graphics = new Phaser.Graphics(game, 0, 0);

// graphics and textElement bounds/sizes must be the same
// so your text area covers the whole rectangle
graphics.drawRect(0, 0, 400, 100);
textElement.setTextBounds(0, 0, 400, 100);

graphics.addChild(textElement);
game.world.addChild(graphics);

// That's it! Now the text should be centered horizontally and vertically
// in the graphics element

```
> 0 votes

---
Tags: text, phaser
---


# Question
Title: Unity using different NaveMesh for the same position
I have differents environments (they are on the same position, and they are prefab) , each environment have differents obstacles.

The problem comes with the navMesh.

What I want is to have one navMesh for each environment and switch them at runtime

Example:

User choose Environment 1 ----\> I switch to NavMesh 1 User choose Environment 2 ----\> I switch to NavMesh 2

but every time I bake the navmesh it override the last one, also, How I can switch between navmesh?

Thanks in advance

# Answer
> 2 votes
I'd try to work around this using additive scene loading.

Create three different copies of your scene file. In each one, bake a navmesh for one corresponding version of your environment. Then delete the unneeded visual assets from these helper scenes, and remove navmesh from your main scene.

Now, at runtime, you can additively load or unload one of these helper scenes at a time to pull in just the navmesh variant you want.

If you have any common bits of navmesh in your main scene that need to connect to the others, you'll need to join them dynamically with off-mesh links as described here.

---
Tags: unity, navmesh
---


# Question
Title: Component based architecture in TypeScript
I'm doing a game using Phaser with TypeScript. I want to implement a component based architecture for Actors. **What I'm trying to achieve** is this:

```
var component:AwesomeComponent = actor.getComponent<AwesomeComponent>();

```

I know there's a workaround by constructing objects of type T. But I don't like it because I'd probably need to define tons of different constructors to represent all differents kinds of components.

**What I'm doing so far** is passing a string with the type (of course a number would be better, but I'm still prototyping):

```
getComponent<T>(componentType:string): T
{
    for (let i = 0; i < this.components.length; i++)
    {
        if (componentType == this.components[i].componentType)
        {
            return <T><any>this.components[i];
        }
    }
    return undefined;
}

```

It works, but the result is not good, you have to type the class name twice:

```
var animComp = actor.getComponent<AnimationComponent>("AnimationComponent");

```

Any suggestions on how to solve it?

Thank you for your time!

# Answer
I've got some good suggestions on Phaser forum, the solution shown by user @flyovergames was what I was looking for:

```
<script src="https://raw.githubusercontent.com/photonstorm/phaser/master/v2/src/Phaser.js"></script>
class Component {
    public actor: Actor;
}

interface ComponentType<T extends Component> { new(...args: any[]): T }

class Actor {
    public components: Component[] = [];

    private getComponentIndex<T extends Component>(type: ComponentType<T>): number {
        for (let i = 0; i < this.components.length; ++i) {
            const component: Component = this.components[i];
            if (component instanceof type) {
                return i;
            }
        }
        return -1;
    }

    public hasComponent<T extends Component>(type: ComponentType<T>): boolean {
        return this.getComponentIndex(type) !== -1;
    }

    public getComponent<T extends Component>(type: ComponentType<T>, ...args: any[]): T {
        const index: number = this.getComponentIndex(type);
        if (index !== -1) {
            return this.components[index] as T;
        }
        return this.addComponent(type, ...args);
    }

    public addComponent<T extends Component>(type: ComponentType<T>, ...args: any[]): T {
        if (this.hasComponent(type)) { return this.getComponent(type); }
        const component: T = new type(...args); // this needs ES5
        component.actor = this;
        this.components.push(component);
        return component;
    }

    public delComponent<T extends Component>(type: ComponentType<T>): T {
        const component: Component = this.getComponent(type);
        this.components.splice(this.components.indexOf(component), 1);
        component.actor = undefined;
        return component as T;
    }
}

class AwesomeComponent extends Component {
    public message: string;
    constructor(message: string) {
        super();
        this.message = message;
    }
    public alert(): void {
        console.log(this.message);
    }
}

function test(): void {
    const actor: Actor = new Actor();
    if (actor.hasComponent(AwesomeComponent)) { throw new Error(); }
    actor.addComponent(AwesomeComponent, "awesome!");
    const awesome: AwesomeComponent = actor.getComponent(AwesomeComponent); // automatic cast!
    awesome.alert();
    actor.delComponent(AwesomeComponent);
    if (actor.hasComponent(AwesomeComponent)) { throw new Error(); }
}

test();
```

Link to full thread: Solution
> 2 votes

---
Tags: javascript, entity-system, component-based, phaser, entity-component
---


# Question
Title: directx render order / alpha blend rendering
I have a question about how to proper render 3d objects in a good order. I use blend states to render some 3d models with a transparent texture. This works but if there are multiple alpha objects in the scene it gets messed up because of the seemingly random render order.

Now I ask myself how should I do it?

The first theory I have in mind would be: When I render something I actually don't render it, I just save it in some sort of queue and sort it later at the final end call (expensive because I have to allocate / deallocate memory a lot and sort).

But even with this theory I still dont know how I should sort them. I cant just look how they are positioned because at some times they are kind of in each other so looking for these values would produce in wrong results.

I already guessed that i have to order in the way the camera is positioned or some way.

Hope you can help me

# Answer
Rendering transparency is a tricky subject and hard to completely overcome. Many rendering engines are just using hacks to overcome complexity, achieve good performance for the price of reduced visual quality.

The easiest way is just to sort your objects from back to front and render with alpha blending. Obviously, this approach is very limited and can easily produce incorrect results. with overlapping objects and even just overlapping geometry within a single object.

You could use a blend state which doesn't require correct ordering, like additive blending. This is probably not what you want, but maybe you can get away with it for some objects and art which takes it into account. I've seen a game for example with transparent umbrella being rendered this way. Users probably won't notice if you don't overuse it.

Then there are the advanced ways of order independent transparency (OIT). For example depth peeling renders the geometry several times in multiple layers from back to front to overcome the sorting issues with overlapping geometry. This is probably very costly. The more recent graphics APIs and hardware lets you use advanced data structures in your rendering, like you could create per pixel linked lists and sort per pixel. Some games are already utilizing techniques like this.

As you can see it is an advanced topic, but you have some options already and probably plenty opportunity for research as well, good luck!
> 2 votes

---
Tags: c++, rendering, directx11
---


# Question
Title: Unity Profiling - Mesh.Bake PhysX CollisionData Doubling CPU cycles
I have a mob that, when it dies, spawns smaller versions of itself. When this happens there's a huge resource spike. The profiler narrowed it down to baking the meshes of the new objects. I have a couple of smaller questions related to this, but the crux of the issue is that it looks like the baking is occurring twice (doubling CPU usage) as shown below in both Instantiate and Transform.SetParent. I'd normally say it's redundant, but in every way it looks like it's happening twice and take over one full second total. Why would this happen twice on the same set of object (there are a variable number of spawned mobs, so the actual numbers can vary)?

As an aside, can this be backed in the prefab somehow to avoid this?

# Answer
Possible solution:

Currently, I've set the `isConvex` bool to `false`, which has resolved the immediate situation. I'm not sure if this will impact anything else - with `RigidBody` attached to each mob, it doesn't appear to cause issues with collision, and so far it doesn't seem to cause any major issues with the mesh during animations, but this will need to be evaluated further.
> 1 votes

---
Tags: unity, performance, profiling, physx
---


# Question
Title: Looking for collision detection algorithms for broad and narrow phases between non-convex polyhedrons
I have some experiences on particle system simulation (namely DEM - Discrete element method), in which an individual particle with realistic shape (convex and non-convex) is approximated by gluing 3D spheres together (non-overlapping or overlapping), and act like rigid body. The collision detection is performed by the simplest sphere-sphere contact.

Nevertheless, for particle shape representing by polyhedrons, almost all the collision detection algorithms for broad and narrow phases are based on **convex** polyhedron (e.g. GJK). For **non-convex/concave** shapes, convex decomposition is required to divide the concave object into many convex components (e.g. V-HACD).

At this point, I really want to know the details on:

> 1) how to store the concave objects via many convex components into memory (like BSP tree?);
>
> 2) collision detection and contact forces calculation between convex-concave, concave-concave objects.

I have searched quite a few relevant books like "Real-time collision detection" and "3D game engine design", etc, unfortunately I haven't find any details on this topic yet. Could some veteran game developers give some advice or insight on how to implement collision between concave objects?

Cheers,

David

---

**Update 1:**

Seems the physics engines likes **Bullet3** and **reactPhysics3D** are able to simulate collision of non-convex objects. Can someone give some rough idea on how to do this? before I dig into the source codes, since i have only some academic experiences on molecular dynamics / DEM simulations mainly based on 3D spheres.

# Answer
There are almost no algorithms to detect collision with a concave object, because there's no reason to have one. Every concave object can be approximated with convex object. See the following image for an example:

There are algorithms to convert a set of points defining a concave polygon to multiply convex ones. A very easy, but inefficient one would be to simply triangulate the object. You could improve the triangulation version by merging the triangles if the produced polygon stays convex, but this is a hill-climbing-esque algorithm, so it won't always produce the best possible combination.
> 3 votes

---
Tags: collision-detection, game-mechanics, physics-engine, convex-hull
---


# Question
Title: Is there an HLSL equivalent to GLSL's "map" function?
Google has not helped me in this area.

Here is the GLSL shader:

```
vec3 globalIllumination(vec3 p, vec3 n) {
vec3 g = vec3(0.0);
float dist;
for (float i = 1.0; i <= samples; i++) {
    dist = stepDistance * i;
float d =  vec3(dist - map(p + n * dist, returnColor));
    g += returnColor*d/ i;
}
return g;
}

```

I know how to convert this to HLSL, except for that map function. I could use some help.

# Answer
> 5 votes
### Answer with best guess of what map could be

Based on the link you posted, `map` should be provided by you and it should return the distance of the provided 3d position (first argument) and set the second argument to the color of the nearest object. If you don't know how to write such a function, I advise you to read this article.

### Answer with the traditional meaning of map

`map` doesn't exist in neither glsl nor hlsl, but it's very easy to implement it.

The five arguments to a usual map function are

```
float map(float value, float min1, float max1, float min2, float max2)

```

it takes the value and converts it from the range defined by `min1` and `max1` to the equivalent in the range defined by `min2` and `max2`. The implementation would look like this:

```
// Convert the current value to a percentage
// 0% - min1, 100% - max1
float perc = (value - min1) / (max1 - min1);

// Do the same operation backwards with min2 and max2
float value = perc * (max2 - min2) + min2;

```

---
Tags: shaders, glsl, hlsl
---


# Question
Title: How can I reference the frontmost part of a mesh in my Unity code?
I have started making a PC game using Unity. It's just a test project, where I'm making as basic as possible FPS shooter.

I'm using the FPS Controller prefab, and I have also a rifle model attached to it. The result is pretty much what I wanted.

Now I'm considering how I want to create projectiles for the gunfire. I think it will be best for me to create each bullet as just being a ray from the gun barrel heading forwards, OR I might create rigidbodies from the gun barrel I'm not sure yet.

**My question is**: What is the proper way to reference the point in space in which the gun barrel current ends? At the moment, I am thinking just attach ANOTHER gameObject to the gun model, and just manually position it where the barrel finishes. But this seems 'cheaty' and I think perhaps there is a better way (something like mesh.position.z + mesh.length, but I can't seem to find anything like mesh.length).

I haven't posted code at all, because I haven't really written any on this project yet.

# Answer
Your proposed method of creating an empty game object to "mark" the muzzle of the weapon is generally considered a good approach.

This gives your model artists direct visual control over where they want the projectile / muzzle effects to spawn, without dealing with the complexities of some kind of automated mesh analysis. They can even set up this marker object in their 3D tools so it's imported as part of the same asset file.

This also gives you flexibility to go wild with the weapon shapes without breaking the spawn position. You can have weapons with lights, bayonettes, or launchers that protrude past the barrel, or with multiple muzzles in exotic arrangements, just by positioning (optionally several) marker objects.

The overhead of one extra transform is generally negligible, and well worth it for the simplicity and flexibility it offers.
> 2 votes

---
Tags: unity, c#, first-person-shooter
---


# Question
Title: Rifle bullets/projectiles in Unity, raycasting or rigidbody?
Hello again gamedevers :) I'm trying to create a fairly simple FPS shooter game. Im using a `Rigidbody` FPS Controller prefab from `Unity`. I have a rifle model attached to that, with a further gameobject for the bullet spawn location on the rifle.

I can see in the `Editor`, that the `bulletSpawn` object already knows which way it's supposed to be facing (ie. `Z axis` is pointing correct direction). I've never really used `Raycasts` before except mobile games to select an object on screen, but my head is telling me that this might be the best way to make realistic bullets.

I've been reading about, particularly this: http://answers.unity3d.com/questions/22800/raycast-shooting.html

It suggests to use `Raycasts` and I understand how to call a ray from the `bulletSpawn` and set it's direction, and to see what it hits. But what I don't understand is how fast the ray will travel, and how to limit the speed of said ray.

I'm not sure if this is a good way to acheive the gunfire or whether it might be better to create `Rigidbodies` and `addforce()` to them.

You guys are always so helpful and often make things MUCH easier to understand that travelling through dozens of old posts and the docs which I cant always follow along with.

How to achieve this effect?

# Answer
> 2 votes
A simple raycasting would be instantaneous. This is usually referred to as Hitscan. A simple example would be in Doom, some weapons and enemies hit immediately while others can be dodged after they are shot.

However, using physics objects moving at the speed of bullets, you're likely to have trouble when for example a bullet moves so far in a single fixedUpdate frame that it goes from being in front of an object to behind it. There's sometimes no collision event that occurs, or requires a lot more work out of the physics engine.

Also, if you have a lot of bullets flying at once, large numbers of physics objects might put a strain on the game.

If you're looking for more realistic ballistic simulation, like that in Battlefield, you could produce a formula based on weapon type. Essentially you're just creating a line in 3d space with a way to pick a point at a given time. This makes each bullet a simpler set of data, a reference to the formula, a starting time, and starting position.

**Edit**
Adding a nice tutorial suggested by Nick in the comments.

---
Tags: unity, c#, raycasting, bullet-physics, projectile-physics
---


# Question
Title: OpenGL - must I always preserve data that is uploaded to a VBO?
If I load my vertex data from a file into a buffer in RAM, and then upload this to the GPU (say, to a static VBO so no need to modify the data), do I need to keep that buffer around? If not, how do I know that the upload is complete?

# Answer
> 1 votes
All OpenGL functions, with the exception noted below, will be finished with any pointer you give it upon that function's return. So `glBufferData` and `glBufferSubData` will have finished all reads from their pointers by the time they have returned.

This does *not* necessarily mean that they have read into those buffers. The implementation may have allocated a piece of storage and copied your data into it, after which it will schedule the upload of the data asynchronously.

The only exception to this rule is every function that ends in the word "Pointer". Things like `glVertexAttribPointer`, `glTexCoordPointer`, and the like. When you use client-side memory with these functions (no longer legal in core profile OpenGL 3.2+), these functions store a pointer to that memory. Therefore, you must ensure that this pointer is valid for as long as you intend to render with those vertex attributes.

After each rendering call using client-memory, OpenGL requires that the implementation have finished reading from client memory by the time the rendering function returns. So you can call `glDrawArrays`, then delete the pointers in question. And as long as you don't make another draw call until you've changed those pointers, you're fine. This means OpenGL has to have copied out all relevant vertex data by the time the rendering call returns (one of the reasons why using buffer objects is faster).

# Answer
> 1 votes
glBufferData will block until all data is copied over somewhere safe.

You can instead map the buffer into RAM and populate that. Then when you unmap the data transfer will be complete.

# Answer
> 0 votes
No, you don't need to preserve the data in RAM.

The function calls for uploading data stall your application until the uploading is complete.

---
Tags: opengl
---


# Question
Title: Setting collider in 3D map (blender file)
New to gamedev and I also have no idea about 3D files but, I'll try to explain the best I can. We are using our own custom engine built in C++ with OpenGL (glm, gl3w, glfw, entityx)

We have a 3D map in a Blender file (.dae), We want to set the colliders for the hitboxes so the player can't step outside. My colleagues started doing it by hand, but it would take a tremendous amount of work none of us want to spend doing a trivial task.

We worked with the same map in 2D (doing the same game in 2D and 3D), and my colleagues used a program to do it visually and then importing a .tmx file (I don't really know how or what program). The question is, is there a way to do the same in 3D? They say Blender (used to create the map) does not provide the tools necessary, or they probably don't know how.

Thanks in advance and sorry if I explained something wrong, I'll gladly answer any questions.

# Answer
The program they used was probably tiled. It's a 2d tilemap editor and it supports 2d shapes.

If you don't want to create the colliders by hand, then create your own tool for it. It shouldn't be hard, it's literally just throwing together a renderer, a flying camera and a way to create colliders, then make the program save these into a file with a custom file format and process it in your game. Just make sure you don't start focusing more on the program than on your game.
> 1 votes

---
Tags: c++, collision-detection, 3d, maps, blender
---


# Question
Title: Unity 2d_ Constant Player movement along the x axis
The movement of my player depends on swipes,

swipe left-\> character moves to the left

swipe right-\> character moves to the right

right now i am only getting a small movement, meaning that the player moves along the X axis but it stops inmediatelly. This is the code i have to check the swipes direction:

PLayer.cs:

```
public Vector2 desiredPosition;

void Update()
{
    if (MobileInput.Instance.SwipeIzquierda)
    {
        desiredPosition += Vector2.left;
    }
    if (MobileInput.Instance.SwipeDerecha)
    {
        desiredPosition += Vector2.right;
    }

    transform.position. = Vector2.MoveTowards(transform.position, desiredPosition, moveSpeed * Time.deltaTime);

```

In the MobileInput script i control the swipes:

```
private const float DEADZONE = 100.0f;
public static MobileInput Instance { set; get; }
private bool swipeIzquierda, swipeDerecha, swipeAbajo, swipeArriba;
private Vector2 swipePuntoAhora, touchComienzo;

public bool SwipeIzquierda { get { return swipeIzquierda; } }
public bool SwipeDerecha { get { return swipeDerecha; } }
public bool SwipeArriba { get { return swipeArriba; } }
public bool SwipeAbajo { get { return swipeAbajo; } }

private void Awake()
{
    Instance = this;
}

// Use this for initialization
void Start () {

}

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

    Debug.Log(SwipeIzquierda);

    swipeDerecha = swipeIzquierda = false;

    #region Input Pc
    if (Input.GetMouseButtonDown(0))
    {
        touchComienzo = Input.mousePosition;
    }
    else if(Input.GetMouseButtonDown(0))
    {
        touchComienzo = swipePuntoAhora = Vector2.zero;
    }
    #endregion

    #region Mobile Input
    if (Input.touches.Length != 0)
    {
        Debug.Log("hola");
        if (Input.touches[0].phase == TouchPhase.Began)
        {
            touchComienzo = Input.mousePosition;
        }

        else if (Input.touches[0].phase == TouchPhase.Ended || Input.touches[0].phase == TouchPhase.Canceled)
        {
            touchComienzo = swipePuntoAhora = Vector2.zero;
        }
    }
    #endregion

    #region Calcular distancia

    swipePuntoAhora = Vector2.zero;
    if (touchComienzo != Vector2.zero)
    {
        //Mobile
        if (Input.touches.Length != 0)
        {
            swipePuntoAhora = Input.touches[0].position - touchComienzo;
        }
        //PC
        else if (Input.GetMouseButton(0))
        {
            swipePuntoAhora = (Vector2)Input.mousePosition - touchComienzo;
        }
    }

    #endregion

    #region Calcular DEadzone del swipe

    if (swipePuntoAhora.magnitude > DEADZONE)
    {
        float x = swipePuntoAhora.x;
        float y = swipePuntoAhora.y;

        if (Mathf.Abs(x) > Mathf.Abs(y))
        {
            //Izquierda o Derecha
            if (x < 0)
            {
                swipeIzquierda = true;
            }
            else
            {
                swipeDerecha = true;
            }
        }
        else
        {
            //Arriba o Abajo
            if (y < 0)
            {
                swipeAbajo = true;
            }
            else
            {
                swipeArriba = true;
            }

        }

        touchComienzo = swipePuntoAhora = Vector2.zero;
    }

    #endregion
}

```

The goal of all of this is to:

If i swipe to te right, the player starts to walk to the right AND continues doing so unless i swipe to the left, only then the player starts to move to the left. I want the movement to be constant in one direction until the other swipe changes it

Any help with this will be really appreciated

# Answer
> 0 votes
Try

```
public Vector2 desiredPosition;

void Update()
{
    string dir;
    if (MobileInput.Instance.SwipeIzquierda)
    {
        dir = "left";
    }
    if (MobileInput.Instance.SwipeDerecha)
    {
        dir = "right";
    }
    if (dir == "left")
    {
        desiredPosition += Vector2.left;
    }
    if (dir == "right")
    {
        desiredPosition += Vector2.right;
    }

    transform.position. = Vector2.MoveTowards(transform.position, desiredPosition, moveSpeed * Time.deltaTime);
}

```

This will change `dir` to either left or right, and then later in the update it will move either left or right. This means that you first check to see if the direction has changed (or set it for the first time), and then you move along that direction. I wouldn't personally use Vector2.MoveTowards for the movement along an axis, but this will solve your problem.

---
Tags: unity, movement
---


# Question
Title: Unpacking Sprite Sheet Into 2D Texture Array
**I am using WebGL 2. A tag for it does not exist but it should.**

I have a 10x10 sprite sheet of squares that are 16x16 pixels in size (all in one PNG image).

I'd like to create a 2D texture array out of them, where each 16x16 square gets its own, unique Z/depth value.

```
let texture = gl.createTexture();
let image = new Image();

image.onload = function() {
    gl.bindTexture(gl.TEXTURE_2D_ARRAY, texture);
    gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);

    gl.texStorage3D(gl.TEXTURE_2D_ARRAY, 5, gl.RGBA, 16, 16, NUM_IMAGES);

    // Now what?
    // gl.texSubImage3D doesn't let me copy in a section of the src image
}

image.src = "https://source_url.fake/image.png";

```

I know that `gl.texSubImage3D` exists but it only accepts an entire image as a source?

glTexSubImage3D: https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glTexSubImage3D.xml

# Answer
IIRC you can select a portion of the image using the various settings to `gl.pixelStorei`

Here's some code that makes a 128x128x8 2D Array texture from a 512x256 2D image

```
  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex);
  const levels = 7;
  const width = 128;
  const height = 128;
  const depth = 8;
  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, levels, gl.RGBA8, width, height, depth);
  // Tell WebGL the size of one row
  gl.pixelStorei(gl.UNPACK_ROW_LENGTH, img.width);
  for (let d = 0; d < depth; ++d) {
    const xoff = d % 4 * width;
    const yoff = (d / 4 | 0) * height;
    // Tell WebGL where to start copying from
    gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, xoff);
    gl.pixelStorei(gl.UNPACK_SKIP_ROWS, yoff);
    const level = 0;
    gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, level, 0, 0, d, width, height, 1, gl.RGBA, gl.UNSIGNED_BYTE, img);
  }
  gl.generateMipmap(gl.TEXTURE_2D_ARRAY);

```

Here's the image

And here's a working sample

```
"use strict";

const img = new Image();
img.onload = main;
img.crossOrigin = "";
img.src = "https://webglfundamentals.org/webgl/resources/noodles.jpg";

const vs = `#version 300 es
uniform mat4 u_worldViewProjection;

in vec4 a_position;
in vec2 a_texcoord;
in uint a_faceId;

out vec4 v_position;
out vec2 v_texCoord;
flat out uint v_faceId;

void main() {
  v_faceId = a_faceId;
  v_texCoord = a_texcoord;
  gl_Position = u_worldViewProjection * a_position;
}
`;
const fs = `#version 300 es
precision mediump float;

in vec4 v_position;
in vec2 v_texCoord;
flat in uint v_faceId;

uniform mediump sampler2DArray u_diffuse;
uniform uint u_faceIndex[6];

out vec4 outColor;

void main() {
  outColor = texture(u_diffuse, vec3(v_texCoord, u_faceIndex[v_faceId]));
}
`;

function main() {
  twgl.setDefaults({attribPrefix: "a_"});
  var m4 = twgl.m4;
  var gl = document.querySelector("canvas").getContext("webgl2");
  if (!gl) {
    alert("Sorry, this example requires WebGL 2.0");  // eslint-disable-line
    return;
  }
  var programInfo = twgl.createProgramInfo(gl, [vs, fs]);

  var arrays = {
    position: [1, 1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1, -1, 1, -1, 1, 1, 1, 1, 1, 1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, -1],
    normal:   [1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1],
    texcoord: [1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1],
    faceId:   { numComponents: 1, data: new Uint8Array([0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6]), },
    indices:  [0, 1, 2, 0, 2, 3, 4, 5, 6, 4, 6, 7, 8, 9, 10, 8, 10, 11, 12, 13, 14, 12, 14, 15, 16, 17, 18, 16, 18, 19, 20, 21, 22, 20, 22, 23],
  };
  var bufferInfo = twgl.createBufferInfoFromArrays(gl, arrays);

  const tex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D_ARRAY, tex);
  const levels = 7;
  const width = 128;
  const height = 128;
  const depth = 8;
  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, levels, gl.RGBA8, width, height, depth);
  // Tell WebGL the size of one row
  gl.pixelStorei(gl.UNPACK_ROW_LENGTH, img.width);
  for (let d = 0; d < depth; ++d) {
    const xoff = d % 4 * width;
    const yoff = (d / 4 | 0) * height;
    // Tell WebGL where to start copying from
    gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, xoff);
    gl.pixelStorei(gl.UNPACK_SKIP_ROWS, yoff);
    const level = 0;
    gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, level, 0, 0, d, width, height, 1, gl.RGBA, gl.UNSIGNED_BYTE, img);
  }
  gl.generateMipmap(gl.TEXTURE_2D_ARRAY);

  var uniforms = {
    u_diffuse: tex,
    u_faceIndex: [0, 1, 2, 3, 4, 5],
  };

  var oldTime = 0;
  function render(time) {
    time *= 0.001;
    twgl.resizeCanvasToDisplaySize(gl.canvas);
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

    oldTime = time;

    gl.enable(gl.DEPTH_TEST);
    gl.enable(gl.CULL_FACE);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    var projection = m4.perspective(30 * Math.PI / 180, gl.canvas.clientWidth / gl.canvas.clientHeight, 0.5, 10);
    var eye = [1, 4, -6];
    var target = [0, 0, 0];
    var up = [0, 1, 0];

    var camera = m4.lookAt(eye, target, up);
    var view = m4.inverse(camera);
    var viewProjection = m4.multiply(projection, view);
    var world = m4.rotationY(time);

    uniforms.u_worldViewProjection = m4.multiply(viewProjection, world);

    gl.useProgram(programInfo.program);
    twgl.setBuffersAndAttributes(gl, programInfo, bufferInfo);
    twgl.setUniforms(programInfo, uniforms);
    twgl.drawBufferInfo(gl, bufferInfo);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
}
```

```
body {
    margin: 0;
}
canvas {
    display: block;
    width: 100vw;
    height: 100vh;
}
```

```
<canvas></canvas>
<script src="https://twgljs.org/dist/3.x/twgl-full.min.js"></script>
```

Note you might want to set all those settings back to 0 after you're done as they'll affect all other calls to `gl.texImageXXX` and `gl.texSubImageXXX`

You could even just turn it into a function

```
function texImageBySlice(gl, target, level,
                         sliceWidth, sliceHeight,
                         format, type, image) {
  const slicesAcross = image.width / sliceWidth;
  const slicesDown = image.height / sliceHeight;

  // Tell WebGL the size of one row
  gl.pixelStorei(gl.UNPACK_ROW_LENGTH, img.width);

  for (let y = 0; y < slicesDown; ++y) {
    for (let x = 0; x < slicesAcross; ++x) {
      const xoff = x * sliceWidth;
      const yoff = y * sliceHeight;
      const depth = y * slicesAcross + x;

      // Tell WebGL where to start copying from
      gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, xoff);
      gl.pixelStorei(gl.UNPACK_SKIP_ROWS, yoff);

      gl.texSubImage3D(target, level, 0, 0, depth,
                       sliceWidth, sliceHeight, 1,
                       format, type, img);
    }
  }

  gl.pixelStorei(gl.UNPACK_ROW_LENGTH, 0);
  gl.pixelStorei(gl.UNPACK_SKIP_PIXELS, 0);
  gl.pixelStorei(gl.UNPACK_SKIP_ROWS, 0);
}

```
> 2 votes

---
Tags: opengl, javascript, opengl-es2, webgl
---


# Question
Title: Why is the character not walking right when creating new animator controller for the character?
I created a new controller called it SoldierController and dragged it to the character Controller under Animator component in the Inspector.

Also unchecked Apply Root Motion

Then attached a new script to the third person character called the script Soldier.

Then I set the Animator controller and I added two new States to it:
Walk and Idle. HumanoidIdle and HumanoidWalk.

Then I did that the default start state will be Idle. Set StateMachine Default State.

Then I did a Transition from Walk to Idle. This way when I press on "W" it starts walking a bit. Then it keep moving the character but without the walking animation.

If I delete this transition and make transition from the Idle to Walk then when I press on "W" it will walk but then if I leave "W" key it's idling.

Then after 2-3 seconds the character will walk on place I mean it will animate walking without moving and I'm not pressing anything it's starting automatic when idling.

The character had another animator controller but I created a new one and using only the new one.

The script:

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

public class Soldier : MonoBehaviour
{
    private bool _isWalking = false;
    private Animator anim;

    // Use this for initialization
    void Start ()
    {
        anim = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update ()
    {
        var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;

        transform.Rotate(0, x, 0);

        if (Input.GetKey("w"))
        {
            if (!_isWalking)
            {
                _isWalking = true;
                anim.Play("Walk");
            }
            var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
            transform.Translate(0, 0, z); // Only move when "w" is pressed.
        }
        else
        {
            if (_isWalking)
            {
                anim.Play("Idle");
            }
            _isWalking = false;
        }
    }
}

```

# Answer
remove the `time.DeltaTime` from where you want to pick up the horizontal input. In the animator create a horizontal movespeed parameter and set idle as the default anim. then when you transition set the param float 'horizontalspeed' to if greater than .1 it will transition to walk. then in your playerscript you can have the horizontal input update the parameter `anim.SetFloat("HorizontalSpeed", Mathf.Abs(x));`
> 1 votes

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


# Question
Title: What does NavMesh.AllAreas specify in Unity?
I'm trying to calculate the path to a point in my game using NavMesh.CalculatePath, it takes an argument NavMesh.AllAreas. I read the Unity Manual and couldn't clearly understand what it meant.

# Answer
# TL;DR

`NavMesh.AllAreas` let you compute a path considering all the NavMesh Areas are walkable for your agent.

---

# Long answer

### Areas and costs

When you build a NavMesh in Unity, you have the possibility to divide it into multiple parts (called areas)

Each of these areas can have a different "cost" (for example, walking on the sand costs more efforts than walking on the grass).

### Preventing agents to walk on certain areas

An other possibility is to prevent agents from walking on certain areas by specifying the 2nd argument when calling `NavMesh.CalculatePath` (if you have an enemy able to walk on the water but not another one for example). When specifying `NavMesh.AllAreas`, you allow your agent to find a path on *every* part of your NavMesh. In the `Agent` component, you can tell which areas he can walk on, using the `AreaMask` member.

### What is `areaMask` and how do you compute it?

The value of `areaMask` when calling `NavMesh.CalculatePath` is a binary number. If you take a look at the first image, we have an array of areas. To indicate whether the character can walk on those areas, you have to specify 1 (walkable) or 0 (not walkable).

Supposing you agent can walk on every areas except "Non Walkable" and "Water"

* Layer 0 : "Walkable" =\> 1
* Layer 1 : "Not walkable" =\> 0
* Layer 2 : "Jump" =\> 1
* Layer 3 : "Water" =\> 0
* Layer 4 : "Door" =\> 1

Result (from right to left) : 10101

```
  (1 << 0) + (0 << 1) + (1 << 2) + (0 << 3) + (1 << 4)
= 1 + 0 + 4 + 0 + 16
= 21 // Value to specify when calling NavMesh.CalculatePath

```

Now, supposing you agent can walk on every areas except "Non Walkable"

* Layer 0 : "Walkable" =\> 1
* Layer 1 : "Not walkable" =\> 0
* Layer 2 : "Jump" =\> 1
* Layer 3 : "Water" =\> 1
* Layer 4 : "Door" =\> 1

Result (from right to left) : 11101

```
  (1 << 0) + (0 << 1) + (1 << 2) + (1 << 3) + (1 << 4)
= 1 + 0 + 4 + 8 + 16
= 29 // Value to specify when calling NavMesh.CalculatePath

```

The `NavMesh` class provides the `GetAreaFromName` function to help you computing the values above :

```
int mask = 0 ;
mask += 1 << NavMesh.GetAreaFromName("Walkable");
mask += 0 << NavMesh.GetAreaFromName("Not walkable");
mask += 1 << NavMesh.GetAreaFromName("Jump");
mask += 1 << NavMesh.GetAreaFromName("Water");
mask += 1 << NavMesh.GetAreaFromName("Door");

// Make sure you don't call multiple times the `GetAreaFromName` with the same area name.

```

### And what about `NavMesh.AllAreas`?

The value of `NavMesh.AllAreas` is `-1`. Converted into the binary format, it is `11111111111111111111111111111111` (32 x `1` because an integer is written on 32 bits). So, if you specify `1` for every areas, you indicate all of them are walkable for your agent.

Source : https://docs.unity3d.com/Manual/nav-AreasAndCosts.html
> 5 votes

---
Tags: unity, navmesh
---


# Question
Title: MonoGame Cross-Platform Conditional Compilation Symbols
**What are the possible compiler directives for MonoGame?**

For example, XNA contained directives for `WINDOWS`, `XBOX`/`XBOX360`, and `WINDOWS_PHONE`.

I've also seen `DIRECTX` and `OPENGL`, but **when would you need to leverage those?**

---

Supported Platforms:

* PC
* Windows 8 Store App
* Linux
* Android
* OUYA
* Mac
* iOS
* Playstation Mobile

# Answer
> 5 votes
If you look inside each project file on github you can see the constants defined for each platform. I've extracted them here:

* Android - TRACE;ANDROID;GLES;OPENGL
* Linux - LINUX;OPENGL
* MacOS - MONOMAC;OPENGL
* Ouya - TRACE;ANDROID;GLES;OPENGL;OUYA
* PSMobile - DEBUG;PSM
* Windows - DEBUG;TRACE;WINDOWS;DIRECTX;WINDOWS\_MEDIA\_SESSION
* Windows8 - TRACE;NETFX\_CORE;WINRT;WINDOWS\_STOREAPP;DIRECTX;DIRECTX11\_1;WINDOWS\_MEDIA\_ENGINE
* WindowsGL - TRACE;WINDOWS;OPENGL
* WindowsPhone - TRACE;DEBUG;SILVERLIGHT;WINDOWS\_PHONE;WINRT;DIRECTX
* iOS - IOS;GLES;OPENGL

# Answer
> 1 votes
in addition to the other answer for windows UWP apps you can use:

```
#if WINDOWS_UAP
    // windows UWP specific code
#endif

```

---
Tags: c#, cross-platform, monogame, mono
---


# Question
Title: What would be theoretical the perfect texture size?
I am more a newbie considering game development but I am dealing very often with optimization of games for work and because I am interested in it.

So as far as I know higher texture size need less draw calls if you make serveral objects share the same texture but it takes up more VRAM. Also you have to consider how acuit you want to have your textures.

But the more I thought about the topic I thought there would be a theoretical perfect texture size, correct me if I am wrong.

Thought experimet: Considering you always want the same acuity of your game and you have 4 objects that take the exact same amount of UV space but have different textures.

Then there would be a perfect spot between texture size and number of objects that share the same texture considering your goal is best performance. In this case there would be 4 possibilities:

* 1 texture where all objects share the same one
* 2 texture for two of the objects
* 3 texures where it would be a mix of those above
* or 4 textures where every object have their own

If performance is your main goal then there would be only one variable to change depending on how acuit you want your game, the acuity, wouldnt it?

Hope you understood my thoughts^^

# Answer
> 5 votes
It's very rare in gamedev to have a single optimum / perfect answer to anything - there are so many interacting concerns that we're constantly forced to make judgement calls between.

For instance, to a first approximation, combining textures so we can render more objects in a single pass is preferred, because it saves us draw calls which are often a limiting factor on our game's performace. But if you're not draw call bound (say you're using only a dozen different passes) then you might not see any benefit from this at all. And it's not without downsides:

* Content rendered in a single pass usually needs to share one set of transform data. (Ignoring instancing for the moment) This is easiest to accomplish with static scene geometry, or small batches of simple dynamic objects that you bake into a shared buffer CPU-side, so it might not even apply to everything you want to render in your scene.
* Setting up your textures and object UVs to use the atlas rather than their own texture space is an extra step in your asset creation workflow (and possible blocking point if two artists need to work on objects in the same atlas), or an extra process you need to build into your importer pipeline if it doesn't do it out of the box.
* If your typical game scenes use only a few objects but in random combinations, pulling in a giant pre-baked atlas that covers every combination might make your loading times longer than you'd need if you just loaded each texture individually.
* You could instead generate the atlas dynamically, hosting only the textures you need for the present scene, but that management layer adds a lot of complexity to your code, which might not be worth the development effort it will cost you if you're not seeing big wins from saving draw calls.

We're also limited by the maximum texture size that a given platform will support (particularly on older platforms that don't let us combine textures in arrays), which can put an upper bound on how many objects we can combine onto a single texture.

Finally, increasing texture size isn't the only way to improve detail. You're unlikely to want to paint every square meter of the game world in 4096 resolution, just in case a player with a 4K monitor decides to ram their camera straight into every wall & prop to see it as magnified as possible. You might instead layer repeating detail & grime textures at high magnification to break up interpolation artifacts. (Those textures might be in their own separate array, since you need a second sample anyway)

This is just a rough sampling of some of the different concerns a game development team would need to weigh when deciding on a batching / atlassing strategy, and it doesn't have a single common answer or formula that will be right for every game.

# Answer
> 2 votes
A 1024x1024 texture would take up as much space as four 512x512 textures in VRAM and the number of draw calls will be equivalent.

The win with using 1 larger texture instead of 2 smaller is that you load it and bind it into memory once and which might give some performance gain since you are not changing the state of the GPU (depending on the API you're using).

A downside is reduced flexibility. Imagine having 1 texture that (including mesh and other data) fills up 1GB of VRAM, and that this texture contains all texture data for all objects that are drawn in a specific scene. Running this scene on a GPU with 1GB of VRAM will theoretically be possible.

If we later want to draw another scene that adds a mesh to the memory, we have suddenly exceeded our memory limit. To solve this problem we can remove stuff from memory that isn't being used. Unfortunately we wont be able to remove the giant texture from memory since it is used by all objects that are drawn.

Loading and removing from memory and changing the state of the GPU (binding and unbinding textures) has an overhead cost which is why you want to combine textures **as much as possible**.

To calculate the optimal size of your textures is highly dependent on your game and the system it is running on.

---
Tags: textures, performance
---


# Question
Title: Using an interpolated game loop (such as Gaffer's final game loop), will the frame be rendered out of sync?
A highly recommended game loop is one from an article called Fix Your Timestep. It presents a method to update using a semi-fixed time step with interpolated rendering.

The problem with this is that, by interpolating the rendering, you are effectively averaging two states in the game - the current and the previous. If the previous frame is averaged with the current frame, the player will be shown the game slightly delayed.

If the player is stationary in one update, then teleports in the next, the interpolation will show a state where the player is mid-way between a teleport very briefly.

For time-critical games, is my thinking correct that the player may see a different/slightly lagged state on screen (the interpolated state) than what is actually stored in memory?

The only fix I can think of is to interpolate the current state + the next, not yet calculated, state. This gives the correct image on screen instead of a slightly delayed previous image... but then we are stuck in a paradox of calculating the next future update.

Or perhaps the time difference is so minimal that it doesn't matter?

I am referring to the following line, the current state is where we are at this moment in time and not fully displayed:

```
State state = currentState * alpha + previousState * ( 1.0 - alpha );

```

# Answer
> 5 votes
Firstly, on the subject of teleportation: most interpolation systems will simply disable interpolation for an object on a frame where it's teleported.

You can see this for example in Unity, when using the interpolation options on the `Rigidbody` and `Rigidbody2D` components. If you move them solely with physics - forces, velocities, torques, `MovePosition()` etc. - then their display position and orientation is interpolated between the two most recent physics steps.

But if you set their position or rotation via the `Transform` component, the engine disables the interpolation for the object on this frame. Under the hood this could be done by setting a flag, or by overwriting both the current and previous physics step outputs with the teleported position/orientation. The position and orientation you see on the next display frame will be the fresh values from the `Transform`, and rigid body simulation and interpolation will resume next frame.

So, in a well-designed system, you don't need to worry about teleporting objects showing momentary "ghosts" between their previous and new positions due to physics interpolation. You can simply turn it off when it's not valid.

---

I think the thornier concern here though is this: "If I interpolate with a previous simulation state, isn't my displayed state 'old' or 'lagged' behind the true game state?" - ie. are we introducing unwanted *latency* into our game by this method?

Let's start by bounding the maximum latency we can introduce this way.

The worst case is when our rendered frame falls *just* after the "previousState" timestamp, and alpha is very close to zero. At this point we're one full frame in the past, 20ms if we're stepping our game simulation 50 times per second. That's already at the low end compared to typical latencies in realtime online games, where similar techniques are used to transition smoothly between discrete updates from the server/host/peers. Response times of 80-100ms can still be perceived as instantaneous, so we're already in fairly safe territory.

But we can do better. :) When the current frame falls just before the "currentState" timestamp, alpha is very close to one and our latency is practically nothing! (If we're only counting latency due to the fixed timestep - input processing and display latencies still add on top of this)

In practice we'll vary between these extremes with no particular bias. So overall, at 50 ticks per second, we're displaying a state that's an average of 10 ms old. For most purposes, this is below the threshold for visual perception of synchronicity, and closing in on the threshold for synchronous audio perception too.

And we can still do better! Because not all game feedback is tied to the fixed timestep. When the player presses a button to fire their weapon, we can spawn the muzzle flash and play the shooting sound immediately in the same frame. Depending on when we are in our interpolated time span, the projectile (assuming it's a literal projectile and not a hitscan raycast) might be rendered closer or further from the barrel, but either way the player gets immediate feedback at the very earliest opportunity we could offer - even if our updates were in lockstep. Similarly, if the player presses jump, we can immediately start blending the character into their jump animation, even if it will take another physics step or two before the upward motion becomes apparent in their physics. UI changes too, like hit markers on a reticle, can react instantly according to the rendered frame time, keeping perceived latency as low as it can be at our rendering framerate.

This helps highlight an important distinction here: how does a player know when data is "old"? Yes, technically that box moving at 1 m/s is now at (0.01, 0, 0), since its most recent calculated state is 10 ms ahead of the frame we rendered with it at (0, 0, 0). But from the player's point of view, it's moved exactly 0.0166 m since the last rendered frame 16.66 ms ago, so it's exactly where they expect to see it. The only yardstick the player can use to judge what's "now" is how the game reacts to their own input, and as we've seen above a well-designed feedback system can begin to react immediately, without adding frames of latency. Beyond that it's second-order consequences of game systems reacting to the effects of player actions, or the consequences of players' reactions in turn, all of which gets swamped by the round trip time of perception to action, which is typically a factor of 10 slower than the latencies we're considering. So while the current state might be old in terms of the pure math of the underlying system, from a player experience standpoint it's often not appreciably different from realtime.

So, tl;dr: At a decent framerate & fixed timestep, the latency introduced by decoupling your game updates is minor and very manageable for most game types.

---

The idea of blending with "the next, not yet calculated, state" is a related technique called extrapolation. This has somewhat the opposite trade-offs: simple, linear motion is represented precisely, but things like collision reactions appear a full frame late (so you might observe two objects touch or even interpenetrate before any corresponding collision effects or sounds trigger). Complex motion can also appear jagged, as the naive prediction keeps overshooting & correcting next frame. Generally these artifacts are easier to perceive than the slight latency of a single frame of interpolation, so the main reason to go this route is for simplicity (since you can skip storing two steps' worth of transform data)

# Answer
> 2 votes
A small clarification, in addition to DMGregorys excellent considerations:

The article Fix Your Timestep by Gaffer on Games discusses **physics updates** only.

The article proposes to use multiple physics steps vithin a single visual step. This could be an API call like:

```
SimulateFixedStep(VerySmallButFixedStepTime, FlexibleFrameTime)
 // Eg. SimulateFixedStep(0.005, 0.01666666667) <- we seem to be at 60 fps atm
 // NB. 0.005 fits 3.333333334 times in 0.01666666667

```

When executing the call above, the physics calculator (may it be built-in 3rd party, or own code) would execute 3 iterations, "consuming" 0.015 seconds in total. It would then store (accumulate) the remaining 0.00166666667 seconds for the next frame (note that this number has a zero more!).

This might produce visual stutter, as the remainder changes. Big sometimes, small sometimes.

As an alternative, the article proposes to consume the entire frame time, by **running a last calculation with the remaining (very very small) time**:

```
0.005 secs
0.005 secs
0.005 secs
0.00166666667 secs <- could be anything between 0 and 0.005 s
------------------
0.01666666667 secs consumed, ie. the entire time of measured previous cycle (up to measure point in the code)

```

The article dismisses this way to do it, by claiming that the physics calculation may become unstable if the remainder is very small, like 0.00001 s. May be so - depends on the internals. Hard to say.

As the eventual, best solution, the article proposes to **pre-calculate** one additional physics result, ahead of time, by maintaining the `VerySmallButFixedStepTime` of 0.005 seconds. Then it proposes to **linearly interpolate** between the two last results:

```
0.005 secs
0.005 secs
0.005 secs <- 2nd last result (or "state)
lerp here, that's what the next visual frame uses
0.005 secs <- last result (and this is already ahead of time)

```

Ie. the final result (your "state") is lerp'ed from between 2nd last and last. This is by all means a good way to do it, but modern physics engines should have features like this built-in. Interpolatng between two states is a job too - takes time as well! :-) Id really propose to see what the built-in physics engine can do! If this is NOT about physics, then different rules apply.

But this is not a matter of showing out-of-sync, rather one of showing as-sync-as-ever-possible. To then sneakily/quickly perform tasks that aren't hard-bound to core physics calculation may be a good idea, as proposed by DMGregory.

---
Tags: architecture, game-loop
---


# Question
Title: OpenGL Is High Efficiency For Large Number of Vertices Necessarily Highly Efficient For Low Numbers of Vertices
To test my program, I rendered hundreds of times more vertices than the program will ever actually have (about 5000 vertices total for the exaggerated version). The exaggerated program lagged when using GL\_FLOAT and did not when using GL\_SHORT. What I'm wondering is if this optimization (and other optimizations) actually uses less energy than using GL\_FLOAT for low numbers of vertices (since I read that some GPUs need to emulate integer functionality and I'm not sure if the increased speed is just because the float version passed some kind of memory limit (which it seems like it did, because lag immediately ended upon removing an exact number of vertices in the float version))). I'm using OpenGL es 1.1 right now, but advice for any version would be greatly appreciated.

# Answer
Floating point math is generally slower due to their nature than fixed point math.

Mobile GPUs may be able to process many more fixed point operations at a time than floating points and there is added pipelined latency for floating points so the effective GFLOPs are much lower than peak figures. But publicly-available GPU details from manufacturers are scarce.

The biggest performance difference however is most likely because your vertices take twice as much memory and bandwidth when stored as GL\_FLOAT compared to GL\_SHORT.
> 1 votes

---
Tags: opengl-es
---


# Question
Title: How to loop through functions dependent on previous function?
In Unity, I need to generate a series of platforms in a specific order for a sidescroller I am working on. The issue is that the generation of the next platform is dependent of the previous platform meaning I can not generate the next platform before the previous platform is made. In this case I cannot predict where the next platform will be at since its length is based off randomized parameters. Also I the generation function is based off of multiple scripts so it has to go through multiple scripts before the generation is complete.

I am currently using a Bool function to wait for the completion of the generation but I do not think this is the appropriate way to go about this. What would be an appropriator structure for calling multiple functions dependent on the previous call?

**This function is used to call the functions to generate the platform**

```
    public void GeneratePlatformSequence ()
{
//For loop to
    for (int i = 0; i < TerrainSequence.Count; i++) {
        bool isComplete = TerrainSequence [i].Transition (TerrainSequence [i+1], new Vector3(50*1,0,0));
    }
}

```

**Abstract class for Platform Generation**

```
public abstract class TerrainMesh : MonoBehaviour {

    public abstract bool Transition(TerrainMesh CurrPlatform, Vector3 LastPosition);

}

```

**One of the mesh generation classes I use to create the platform**

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

public class GroundTerrain : TerrainMesh {

    public override bool Transition(TerrainMesh CurrPlatform, Vector3 LastPosition) {
        bool isStepComplete =   GroundTransition(CurrPlatform, LastPosition);
        return isStepComplete;
    }

    public bool GroundTransition (TerrainMesh CurrPlatform, Vector3 LastPosition){
        if (CurrPlatform is WaterTerrain) {
            print ("Generating WaterTerrain");
//Here is where I generate the Actual mesh for the platform.
            bool GeneratedMesh = MeshGenerate ();
            return GeneratedMesh ;
        }

        return false;
    }

}

```

# Answer
> 1 votes
If your mesh generation is done on a single thread (no coroutines), then there is no need to wait for completion using a boolean variable.

`GeneratePlatformSequence()` will not return until all the function calls within `GeneratePlatformSequence` have finished. In other words, `GeneratePlatformSequence()` will wait for `Transition()` to finish, and `Transition()` will wait for `GroudTransition()` to finish, and so forth.

That means you don't need the bool returns. C# will wait for function calls to finish.

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


title: Battle of the Vectors

text:
# Question
Title: Battle of the Vectors
When building a Unity2d game, is it better to use Vector3's for waypoints, etc... or to use Vector2's ?

The advantage I can see of using a Vector2 is that it is smaller (2 floats vs. 3) and therefore more space efficient, However Unity is not really designed with 2d in mindd, therefore all object positions are stored as Vector3s.

Is the memory saved from usinng Vector2s instead of vector3s worth the amount of time the computer spendds converting Vector2s to vector3s and the reverse?

# Answer
So, let's say a Vector2 occupies 8 bytes and a Vector3 occupies 12 (they don't, but this should make our lives easier). A typical "minimum requirement" computer has 4GB of RAM. Since mos of this place is occupied by textures, gameobjects and such, let's say you only use 0.5 GBs (this is still a very big chunk of memory relatively) to store your vectors. In this case you could theoretically store up to 67,108,864 Vector2s and 44,739,242. It's safe to say that you ran out of possibilities and time before running out of space (you'll still need to shovel all these information to the GPU to do anything useful with it).

When you look for ways to optimize your code before you encounter a performance bottleneck, then we call the premature optimization. It's usually a waste of time. Use a profiler when you need to optimize.
> 0 votes

---
Tags: unity, efficiency
---


title: Radial/circle placement of meshes

text:
# Question
Title: Radial/circle placement of meshes
How to place 10 static meshes in circular pattern so they are equaly aligned from the center ?

# Answer
> 4 votes
In code, this is really simple to do. The following pseudo-code assumes that the objects' origins are in the center, but if they are not, then all you have to do is to translate the final positions to account for the objects' actual origins.

```
float offset = 0.0f;  // Allows you to offset the initial object.

const float step = 360.0f / objectCount;
for (float angle = offset; angle < 360.0f + offset; angle += step)
{
    const float radians = angle * PI / 180.0f;
    const float x = circleCenter.X + cos(radians) * circleRadius;
    const float y = circleCenter.Y + sin(radians) * circleRadius;

    object->SetPosition(Vector2(x, y))
}

```

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


# Question
Title: Unity Rotate Object Around Local X Axis , then Local Y Axis, then Local Z Axis (like a turtle)
I am having trouble getting my unity gameobject to rotate in the manner I would like.

I would like my gameobject to act kind of like a turtle from a drawing program, where I could input a Vector3 like (10, 25, -5) and then it would rotate around its x axis by 10 degrees. Then rotate around it's Y axis by 25 degrees, and then rotate around it's z axis by -5 degrees.

Here's a picture example: (rotations not exact)

The problem is that the axes (the green, blue, and red gizmos you see when you have an object selected) change direction as the "turtle" goes through the Vector3.

It seems like transform.Rotate(new Vector3(10,25,-5), Space.Self) should be what I'm looking for. But it doesn't give me the result I would like! It still seems to rotate around it's start up, right, and forward vectors.

```
public Vector3 rotation;

Quaternion zero = new Quaternion(0,0,0,1)

void Update()
{
    transform.rotation = zero;
    transform.Rotate(rotation, Space.Self);
}

```

I have also tried doing some things with Quaternions to get the desired result, but I can't figure out exactly what is need. If anyone has any advise it would be greatly appreciated!

# Answer
By nature, rotating an object will change its local axes. If you want a persistent set of "local axes", you can parent the gameobject to another gameobject, which holds the "local axes".

You can rotate around these axes in a custom order using Transform.RotateAround:

```
void Update()
{
   Transform par = transform.parent.transform;
   transform.rotation = Quaternion.Identity;
   transform.RotateAround(transform.position, par.right, rotation.x);
   transform.RotateAround(transform.position, par.up, rotation.y);
   transform.RotateAround(transform.position, par.forward, rotation.z);
}

```
> 1 votes

# Answer
Unity's default rotation order when specified in local Euler angles is:

1. Rotate `angles.z` degrees around parent's Z+ axis
2. Rotate `angles.x` degrees around parent X+
3. Rotate `angles.y` degrees around parent Y+

Or, equivalently (if we start from the identity rotation):

1. Rotate `angles.y` degrees around local Y+ axis
2. Rotate `angles.x` degrees around *the resulting* local X+ axis
3. Rotate `angles.z` degrees around *the resulting* local Z+ axis

Which differs from your desired order by exchanging x & y. To change this, we can define our own version of the Rotate method:

```
public static class RotationExtensions {

    static void RotateCustom(this Transform t, Vector3 angles) {
        // Do the x rotation first.
        t.Rotate(angles.x, 0, 0);
        // Then do the y & z rotations.
        angles.x = 0;
        t.Rotate(angles);
    }
    static void RotateCustom(this Transform t, float x, float y, float z) {
        t.RotateCustom(new Vector3(x, y, z));
    }
}

```

Now you can call `transform.RotateCustom(angles)` the way you would with regular `Transform.Rotate` to get your custom rotation order.
> 0 votes

---
Tags: unity, c#, rotation, quaternion
---


# Question
Title: Why game roms are lighter than their original version?
I would like to know if you could help me with this question , I was wondering

Why the rom made of a videogame is ligther than the game itself or an indie game of today? I mean a rom can be 20mb while an indie game can be 200mb! An Snes rom, GBA or even a ds file is lighter than an actual game of today... why is this? why old videogames roms were so ligth but yet finished?

How can I make a game like that: complete but light? Thank you!

# Answer
It's mostly because of the assets. Audio was only a couple of kilobytes at most, because there was no space for it. Old games didn't have enough memory to store the screen completely, thus they had to make a compromise. The screen was divided into 8x8 blocks, each of them could have 2 or 4 colors depending on the system (the original NES used 4 for example). The color of sprites where separate from this.

You can notice this very easily, if you look at Super Mario Bros 3 for the NES you'll never see more than 4 colors in a tile and this is the same reason the right edge had a strange color.

Because of this, a single sprite could be represented in 17 bytes (16 for the image, 1 for the color palette). If you take a modern format and make an image with a similar size, you'll get a lot bigger size (120bytes with a PNG for instance). This overhead is present in almost every format.

We also started using a lot bigger images, the sprite sheet of Super Mario could probably fit in a 512 x 512 image, while a single modern texture is bigger than that.

Also, old games weren't 3 dimensional. Storing a model takes up a huge space. Same with game engines. Old games simply couldn't use one, because the code had to fit on the cartridge, and they also introduce a huge overhead in file size.
> 2 votes

---
Tags: roms
---


# Question
Title: Simulating long distance migrating monsters in a large minecraft-like world
I want to create an effectively infinite world, like Minecraft, where chunks are generated as users come close to the edge of their current chunk.

As I understand it, monsters in Minecraft are put to sleep when the chunk they are currently in is unloaded (as far as I understand, if a player moves away from a chunk and that chunk is not close to any player, it is unloaded). That is, they don't move or do anything, and are just stored statically on disk.

This means that all the monsters are effectively territorial and have the behavior of being awake only if a player is nearby - otherwise they sleep forever.

EDIT: Actually in Minecraft mobs despawn when a certain distance away from the player, resulting in a more random experience.

What if I want to simulate the behavior of large scale migrating herds? In an infinitely large world, there should be infinitely many monsters randomly wandering around. There might be herds of monsters wandering around. Obviously they cannot be all loaded in memory at once.

Now, if a player discovers such a herd, he might want to walk away some distance, and then come back later to follow the herd's tracks, which might be quite some distance, but he will eventually catch up to it. This seems impossible with Minecraft's way of dealing with loading/unloading chunks.

Is there some way of simulating long distance monster migrations whilst maintaining Minecraft's advantage of having memory usage be linear with respect to the number of players (rather than the size of the world)?

# Answer
> 2 votes
To have consistent mob migration without storing & ticking them all, the mob behaviour has to be something you can query as a function of time & space.

ie. Given a point in spacetime, your system needs to be able to answer "what mobs are nearby?"

Probably the easiest way to do this is to make mobs migrate on periodic paths — loops or lines across your world, where a mob crosses a given point on the path at regular intervals (either the same mob looping around, or a new mob following the same trail).

There are ways to make these behaviours aperiodic & more organic too, but that can be added as an extra layer of complexity later, if you find you need it, so I'll focus on the simplest case for now, assuming roughly circular periodic migrations.

1. Generate a psuedorandom seed based on the location of your chunk, using something like a spatial hash function.
2. Use this seed to pseudorandomly choose parameters:

* mob composition
    * center of migration route (within this chunk)
    * radius of migration route (potentially outside this chunk)
    * frequency & phase offset of migration

Because these are chosen from a seed that depends only on the chunk's location, whenever you arrive at this chunk you'll generate the same mob parameters, so they remain consistent even if you walk away.
3. Based on these parameters, we know where the mob will appear at any point in time:

`phase = 2π * frequency * time + phaseOffset
 mob.x = center.x + cos(phase) * radius
 mob.y = center.y + sin(phase) * radius`

You can displace this curve to be more organic, or to conform to walkable portions of the chunk(s) it crosses (since by the time you're close enough to realize the mob, you should have the terrain it crosses loaded), as long as this displacement is deterministic.
4. Now, when we enter a new chunk, we can query the location of this chunk's mob(s), as well as the mobs of any chunks within the maximum migration radius, to see if any are close enough to realize.

This approach isn't without its problems. If you kill one or more members of a mob, then walk away and come back so it's re-realized from the math formulas above, poof, those dead members will have resurrected.

To prevent this, you'll want to store the states of any mob the player interacted with (or observed them interact with each other, if you have predators who chase prey, for example). You don't need to store this data forever, thankfully. The data can "decay" over time and ultimately be discarded once it's old enough that the mob could plausibly have returned to its natural state (or that the player is likely to have forgotten them) When you want to query a mob, first check if it has one of these "exceptions to the rule" stored, and modify the result accordingly.

This strategy can also cause issues if the player can lure or herd a mob off its prescribed course. Once again you can store this detour and offset the mob's migration until sufficient time has passed for them to get back on-track.

This should give at least a basic recipe for implementing this kind of feature, with room for elaboration.

---
Tags: game-design
---


# Question
Title: Image added to Canvas via script is not rendering
So I have a pointer script I attach to a Canvas, which is used to create a simple sprite cursor for selecting menu items (similar to old RPGs). It works great in my Main Menu, but it's invisible in all the other menus it's attached to.

The pointer object exists for the other Canvases it's attached to - I can see it in the hierarchy - and it's responding to controller input and moving around according to its rect transform, but I can't see it in the Game view.

I've also found that if I create a new GameObject, give it an Image component, give the Image component a sprite, and add it to a Canvas, it also won't display. And yet that's exactly what I do for the pointer, and it works at least once - on my main menu. When I select an option on the main menu, it hides the current canvas and enables another canvas, which is appearing and functioning, but with the pointer not rendering.

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

// This component is added to a Canvas to provide it with a pointer
public class Pointer : MonoBehaviour
{
// Public variables
public bool pointerEnabled;
public bool isometric;
public Sprite pointerSprite;
public int columns;
public int columnDistance;
public int rows;
public int rowDistance;
public Vector2 canvasStartingPosition;
public Vector2 currentIndexPosition;
public bool horizontalWrap;
public bool verticalWrap;

// Private variables
private GameObject pointerObject;
private Image pointerImage;
private RectTransform pointerTransform;

private float previousInputTime = 0f;       // Time that the last executed input happened
private float inputDelay = 0.5f;            // Delay between inputs if stick or D-pad is held down
private bool pointerDelay;                  // Pointer is currently delayed

private string eventAButton;
private string eventBButton;

private bool pointerAButton;
private bool pointerBButton;

private UnityAction listenerPointerEnable;
private UnityAction listenerPointerDisable;

// Use this for initialization
void Awake()
{
    pointerObject = new GameObject();
    pointerImage = pointerObject.AddComponent<Image>();
    pointerTransform = pointerObject.GetComponent<RectTransform>();
    pointerObject.GetComponent<Transform>().SetParent(gameObject.transform);
    pointerImage.sprite = pointerSprite;

    pointerTransform.sizeDelta = new Vector2(pointerSprite.bounds.size.x * pointerSprite.pixelsPerUnit, pointerSprite.bounds.size.y * pointerSprite.pixelsPerUnit);

    if (isometric)
    {
        pointerTransform.anchoredPosition = new Vector2(canvasStartingPosition.x + ((currentIndexPosition.x - currentIndexPosition.y) * rowDistance), canvasStartingPosition.y + ((currentIndexPosition.x + currentIndexPosition.y) * -columnDistance));
    }
    else
    {
        pointerTransform.anchoredPosition = new Vector2(canvasStartingPosition.x + (currentIndexPosition.x * columnDistance), canvasStartingPosition.y + (-currentIndexPosition.y * rowDistance));
    }

    pointerDelay = false;

    EventManager.StartListening("PointerEnable", enablePointer);
    EventManager.StartListening("PointerDisable", disablePointer);

    if (pointerEnabled)
    {
        enablePointer();
    }
}

public void enablePointer()
{
    pointerEnabled = true;
    pointerImage.enabled = true;
}

public void disablePointer()
{
    pointerEnabled = false;
    pointerImage.enabled = false;
}

public void setEventAButton (string eventName)
{
    eventAButton = eventName;
}

public void setEventBButton(string eventName)
{
    eventBButton = eventName;
}

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

    //Is the pointer enabled?
    if (pointerEnabled)
    {
        // Handle the delay mechanics of the pointer
        if (pointerDelay)
        {
            // User let go of controller? We can take an input again
            if (Mathf.Abs(Input.GetAxis("Horizontal")) < 0.1f && Mathf.Abs(Input.GetAxis("Vertical")) < 0.1f)
            {
                pointerDelay = false;
            }

            // Check if the input delay has passed, and we can register an input
            if (Time.realtimeSinceStartup - previousInputTime > inputDelay)
            {
                pointerDelay = false;
            }
        }

        // Pointer is not delayed? Check for input
        if (pointerDelay == false)
        {

            if ((int)Input.GetAxis("Horizontal") != 0 || (int)Input.GetAxis("Vertical") != 0)
            {

                    int pointerXInput = (int)Input.GetAxis("Horizontal");
                    int pointerYInput = (int)Input.GetAxis("Vertical");

                    currentIndexPosition.x += pointerXInput;
                    currentIndexPosition.y -= pointerYInput;

                if (currentIndexPosition.x < 0 && horizontalWrap) currentIndexPosition.x = columns - 1;
                if (currentIndexPosition.x < 0 && horizontalWrap == false) currentIndexPosition.x = 0;

                if (currentIndexPosition.x >= columns && horizontalWrap) currentIndexPosition.x = 0;
                if (currentIndexPosition.x >= columns && horizontalWrap == false) currentIndexPosition.x = columns - 1;

                if (currentIndexPosition.y < 0 && verticalWrap) currentIndexPosition.y = rows - 1;
                if (currentIndexPosition.y < 0 && verticalWrap == false) currentIndexPosition.y = 0;

                if (currentIndexPosition.y >= rows && verticalWrap) currentIndexPosition.y = 0;
                if (currentIndexPosition.y >= rows && verticalWrap == false) currentIndexPosition.y = rows - 1;

                if (isometric)
                {
                    pointerTransform.anchoredPosition = new Vector2(canvasStartingPosition.x + ((currentIndexPosition.x - currentIndexPosition.y) * columnDistance), canvasStartingPosition.y + ((currentIndexPosition.x + currentIndexPosition.y) * -rowDistance));
                }
                else
                {
                    pointerTransform.anchoredPosition = new Vector2(canvasStartingPosition.x + (currentIndexPosition.x * columnDistance), canvasStartingPosition.y + (-currentIndexPosition.y * rowDistance));
                }

                pointerDelay = true;
                previousInputTime = Time.realtimeSinceStartup;
            }
        }

        pointerAButton = Input.GetKeyDown("joystick 1 button 0");
        pointerBButton = Input.GetKeyDown("joystick 1 button 1");

        if (pointerAButton)
        {
            EventManager.TriggerEvent(eventAButton);
        }
        else if (pointerBButton)
        {
            EventManager.TriggerEvent(eventBButton);
        }

    }
}

```

}

# Answer
> 1 votes
So I found the problem, and it had nothing to do with the pointer itself.

Since I use multiple Canvases - one per menu screen - I was enabled and disabling them, but this was messing up the pointer script. I'm now instead setting the sorting order of the Canvases to -1 when I'm not needing them.

---
Tags: unity
---