# Question
Title: How to find grid cells not seen by an object
I am writing a VB.NET program.

I have a grid view which is made of multiple small cells called grid cell.

On the grid view, I have placed an obstacle (red box) and an observer (blue box).

My task is to find how to find grid cells which are not seen by the blue box. You may refer to the screenshot below.

Take note that the yellow box shape is not necessary a rectangle.

1) I have considered to loop through all grid cells in the grid view and check each of them if it is seen by the blue box.

However, there could be millions of grid cells in the grid view and looping through each of them will consume a lot of time and is not efficient.

Is there any better way to locate grid cells not seen by the blue box other than looping through all the grid cells in the view?

Thank you.

# Answer
> 1 votes
You haven't specified what sort of output you're looking for. If there really could be millions of grid cells unseen, finding them all will necessarily require processing millions of grid cells. So you'll need to limit your algorithm to finding a subset of those, for example:

1. Finding whether a single cell is unseen, on demand
2. Finding all unseen cells within a certain distance from your observer
3. Finding the nearest unseen cell

The first one is easy: perform a single line-of-sight test between the cell and the observer.

The second is also easy, just perform a line-of-sight test over a subset of the entire grid. Eric Lippert's Shadowcasting algorithm is a nice one that minimises revisiting cells, but I've found a really simple one that performs line-of-sight tests to the boundary cells can also suffice.

For the third one, you can repeatedly perform line-of-sight tests starting from cells nearest to the observer and gradually search outwards, for example in a spiral pattern. Depending on your algorithm, you can avoid unnecessary duplication of cell tests - for example, if a cell that's in the same direction and closer to the observer is seen, we can assume that the current cell is also seen by the observer, and avoid performing the full test all the way to the observer. You probably still want to limit this search somehow, since if the observer is in the middle of an empty field, then the nearest unseen cell could be very far away and you'll have to search many cells. If your grid is especially sparse, you can try a ray-based approach searching for obstacles instead of cells.

# Answer
> 0 votes
For grid problems, I usually use clustering instead of operating on a single cell I take for example group 5x5 cells and loop through such clusters. So instead of looping through every cell, you could loop through clusters of cells that are made of many cells and loop through cells in the cluster only if it meets some cluster visible condition. And going further you can make a cluster of clusters and repeat this operation recursively.

You can search more about quadtrees: https://en.wikipedia.org/wiki/Quadtree

# Answer
> 0 votes
There is probably a way for you to divide up your grid into larger pieces, and determine visibility of the pieces as a short cut. For example, if a bigger chunk (say, like an 8x8 group of cells) isn't visible (checking the 4 corners), then you can mark the entire set of cells as not visible.

I haven't tried this, but I think something like this would work...

Take your entire grid, and dividing it into quarters. Determine visibility on each quarter by checking if you can see any of the corners of that quarter. If you can't see any of the corners, then mark the entire quarter's cells as not visible. If any **one** corner of a quarter is visible, then at least part of it is visible. In that case, recursively divide that quarter up into sub-quarters and repeat the process for them.

---
Tags: algorithm, grid, line-of-sight, vb.net
---


# Question
Title: How can I make it not possible to type after reaching a max number of lines in my textarea?
I have a EditorGUI.TextArea that is 300x100 in size. How can I make it impossible to type after reaching a max number of lines in my textarea (no wrapping)?

# Answer
> 1 votes
I am not sure if you can do this in Unity, but you need some way to monitor the text as the user types it in. If you can do that, then you can calculate the render size of what is typed in using the Font.GetCharacterInfo method, and with that calculate and count how many line breaks occur due to word wrap. Given you know how many line breaks occur, you can know how many lines have been entered.

What you have to do is start calculating the render width of the string character by character, starting at the beginning of the string. As soon as you reach your width of 300 pixels, you know that a word wrap needs to occur.

At that point, if it happens when you are looking at a space or the first character of a word, the word wrap will occur then. If it happens in the middle of a word, you are going to have to back up character by character until you find a space where you can do a word wrap.

After each word wrap, increment your count of how many lines occur in the text, and start your measurement up to the 300 pixels again for the next word wrap.

Once your count of lines reaches some maximum you've got in mind, you could do something like disable the submit button (if there is one), and display an error message to the user that there are too many lines.

---
Tags: unity, gui
---


# Question
Title: How do I import multiple animations into the same file in Unity?
I have hit a major stump in my development: applying transitioning animations to the same model. I have learned how to do a single animation with keyframes, but have no clue on what to do with more than one. I tried importing different animations seperately and applying them to the same model, but it didn't work. How can I get past this stumbling block?

# Answer
> 1 votes
If you are referring two or more animation on one object, I assume that you want to transition one animation to other. You would create states in Animator and transition states based of the parameter.

**I would recommend this tutorial:**

http://www.theappguruz.com/blog/creating-2d-animated-sprites-using-unity2d

**Note:**

This blog is for Unity2D games, but It is possible to use in Unity3D

# Answer
> 0 votes
I'm not sure if you are referring to playing two animations at the same time on a single object or simply transitioning from one animation to another, I will assume you mean transitioning from one animation to another.

The way I handle multiple animations is I get a separate file(commonly fbx) for each animation. Then, you would create states in your animator component and transition to those states based off parameters.

I would suggest reading up on animators if you have not already and follow a tutorial. There are a few good tutorials that cover animators and transitions.

Here is a Unity tutorial on the Animator controller: https://unity3d.com/learn/tutorials/topics/animation/animator-controller

---
Tags: unity, maya
---


# Question
Title: Unity: Moving player using Rigidbody with UI Buttons?
i have been using `transform.position`since the start but now i want to switch to rigidbody instead since i am facing some collision problems. i can use the keyboard to move the player using this code:

```
input = new Vector3 (Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));

        if (GetComponent<Rigidbody> ().velocity.magnitude < maxmovespeed) {
            GetComponent<Rigidbody> ().AddForce (input * movespeed);
        }

```

but since i am building for mobile and have added UI buttons for right/left on screen, i wish to use those for moving my player. how can i use those buttons to move in that specific direction like left for left only and right for right?

# Answer
If you only need to move left and right, you could try something like this:

```
if (GetComponent<Rigidbody> ().velocity.magnitude < maxmovespeed) {
    if (leftButton.IsPressed()) {
        GetComponent<Rigidbody> ().AddForce (-Vector3.right * movespeed);
    } else if (rightButton.IsPressed()) {
        GetComponent<Rigidbody> ().AddForce (Vector3.right * movespeed);
    }
}

```

Just assign leftButton and rightButton as public variables in the editor.
> 1 votes

# Answer
We use two Event triggers and Delegate for one is Left side button and second is Right side button.

```
public class EventManager : MonoBehaviour
{
    public delegate void OnMoveLeft ();
    public static event OnMoveLeft onMoveLeft;
    public static void RaiseOnMoveLeft ()
    {
        if (onMoveLeft != null)
            onMoveLeft ();
    }

    public delegate void OnMoveRight ();
    public static event OnMoveRight onMoveRight;
    public static void RaiseOnMoveRight ()
    {
        if (onMoveRight != null)
            onMoveRight ();
    }
}

```

When UI button clicked, same time event must raise either Left Side or Right Side.

```
public class GamePlayView : MonoBehaviour
{
    public void OnLeft(){
        EventManager.RaiseOnMoveLeft();
    }

    public void OnRight(){
        EventManager.RaiseOnMoveRight();
    }
}

```

Player Script We have to use Event Register and Deregister for Both Event triggers. When Button click that time according to that Event handlers method are called. And player performed.

```
public class Player : MonoBehaviour
{
    public float forwardSpeed;
    private Rigidbody rigidbody;

    void Awake(){
        rigidbody = GetComponent<Rigidbody>();
    }

    void OnEnable(){
        EventManager.onMoveLeft += EventManager_onMoveLeft;
        EventManager.onMoveRight += EventManager_onMoveRight;
    }

    void OnDisable(){
        EventManager.onMoveLeft -= EventManager_onMoveLeft;
        EventManager.onMoveRight -= EventManager_onMoveRight;
    }

    void EventManager_onMoveLeft ()
    {
        rigidbody.AddForce(-Vector3.right * forwardSpeed);
    }

    void EventManager_onMoveRight ()
    {
        rigidbody.AddForce(Vector3.right * forwardSpeed);
    }
}

```
> 0 votes

---
Tags: unity, rigidbody
---


# Question
Title: Unity2D: Using UI buttons to move Player
I've created a script that allows my player to move using UI button, however my player's movement isn't very smooth or flowing, instead it's very clunky and somewhat looks like my player is teleporting. I tried following tutorials on YouTube, however I was having problem with accessing the 'Unity Standard Assets' as for some reason it wasn't there. I read up for information about people re-importing it into their projects only to have it mess up parts of their games. Overall I was wondering if there any one can help me fix my problem! Thank you :)

My script:

```
public float moveSpeed;

void Update () {
    if (moveRight == true) { // Here I have tried methods like Addforce and velocity, but for some reason it wasn't working!!
        GetComponent<Rigidbody2D>().AddForce (transform.right * maxSpeed);
    } else if (moveRight == false) {
        GetComponent<Rigidbody2D>().AddForce (transform.right * maxSpeed);
    }
}

public void MoveLeft() {
   transform.position -= transform.forward * Time.deltaTime * moveSpeed;

  // moveRight = false;
}

public void MoveRight() {
   transform.position += transform.forward * Time.deltaTime * moveSpeed;

 // moveRight = true;

}

```

# Answer
> 1 votes
Here's my version:

These values decide how fast the increase or decrease will happen and what the base values are (so that I don't lose track of them or have to change them one by one)

```
public float angle = .1f; //public so that I can modify it from the Unity UI
float angleStart = .05f;
float timerStart = 0f;
float timer = 0;
float timerIncrease = 0.001f;

```

This is the partial update function, the rest is the button functions.

```
Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        TurnLeft();
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        TurnRight();
    }
    if (Input.GetKeyUp(KeyCode.UpArrow) || Input.GetKeyUp(KeyCode.DownArrow)
        || Input.GetKeyUp(KeyCode.LeftArrow) || Input.GetKeyUp(KeyCode.RightArrow))
    {
        angle = angleStart; //reset values so that the next time buttons are
        timer = timerStart; //pressed, they won't be at their max increase values
    }
}

```

These are the functions that are actually doing all the calculations, of course function names will differ and what they do will also differ in your version.

```
public void TurnRight()
{
    if (timer < 0.1)
        timer = timer + timerIncrease;
    transform.Rotate(0, 0, -angle); //only this part is different between right and left
    if (angle < 5)
        angle = angle + timer;
}

public void TurnLeft()
{
    if (timer < 0.1) //guarantees that timer won't go too high and make janky movement
        timer = timer + timerIncrease;
    transform.Rotate(0, 0, angle);
    if (angle < 5) //guarantees that the angle increase won't go overboard and make stupid turns
        angle = angle + timer;
}

```

Changing `transform.Rotate()` to something else that uses the `angle` variable will give you smooth movement. Of course, my suggestion would be to just re-write these and use as necessary.

One example would be to change `TurnLeft()` to `MoveLeft()` (I'm assuming go left means go towards minus on the X axis for this example):

```
public void MoveLeft()
{
    if (timer < 0.1)
        timer = timer + timerIncrease;
    if (speed < 5)
        speed = speed + timer;
    transform.position = new Vector3(transform.position.x - speed, transform.position.y, transform.position.z);
}

```

Of course, if you want to use `AddForce()` you can figure that out pretty easily from these examples. I'm not going to give an example of that as I don't really have means to test that code.

# Answer
> 1 votes
This post is extremely relevant. Basiclly, you need to add event triggers to the buttons, then add the following script to the buttons:

```
using UnityEngine.UI;   // add to
//the top

private bool moveLeft;
private bool moveRight;

void Update()
{
    if(moveLeft && !moveRight)
     rigidbody2D.AddForce
(Vector3.left * forwardSpeed);

 if(moveRight && !moveLeft)
     rigidbody2D.AddForce (Vector2.right * forwardSpeed);
}

public void MoveMeLeft()
{
    moveLeft = true;
}

public void StopMeLeft()
{
    moveLeft = false;
}

// do the same for right

```

Fair warning: I didn't write this code, so I am not sure if it works properly, though it looks like it will work.

# Answer
> 1 votes
We use two Event triggers and Delegate for one is Left side button and second is Right side button.

```
public class EventManager : MonoBehaviour
{
    public delegate void OnMoveLeft ();
    public static event OnMoveLeft onMoveLeft;
    public static void RaiseOnMoveLeft ()
    {
        if (onMoveLeft != null)
            onMoveLeft ();
    }

    public delegate void OnMoveRight ();
    public static event OnMoveRight onMoveRight;
    public static void RaiseOnMoveRight ()
    {
        if (onMoveRight != null)
            onMoveRight ();
    }
}

```

When UI button clicked, same time event must raise either Left Side or Right Side.

```
public class GamePlayView : MonoBehaviour
{
    public void OnLeft(){
        EventManager.RaiseOnMoveLeft();
    }

    public void OnRight(){
        EventManager.RaiseOnMoveRight();
    }
}

```

Player Script We have to use Event Register and Deregister for Both Event triggers. When Button click that time according to that Event handlers method are called. And player performed.

```
public class Player : MonoBehaviour
{
    public float forwardSpeed;
    private Rigidbody2D rigidbody;

    void Awake(){
        rigidbody = GetComponent<Rigidbody>();
    }

    void OnEnable(){
        EventManager.onMoveLeft += EventManager_onMoveLeft;
        EventManager.onMoveRight += EventManager_onMoveRight;
    }

    void OnDisable(){
        EventManager.onMoveLeft -= EventManager_onMoveLeft;
        EventManager.onMoveRight -= EventManager_onMoveRight;
    }

    void EventManager_onMoveLeft ()
    {
        rigidbody.AddForce(-Vector3.right * forwardSpeed);
    }

    void EventManager_onMoveRight ()
    {
        rigidbody.AddForce(Vector3.right * forwardSpeed);
    }
}

```

---
Tags: unity, movement
---


# Question
Title: How do we coordinate which order the systems get processed within an ECS?
If I knew all of the systems at compile time, I could order them myself. However, I intend on having user-defined mods. This adds a level of complexity, in that I (as the framework developer) don't know which mods will be developed, or installed on a particular user's machine.

I've thought about adding some sort of execution ordering

```
// within core code
systemRegistrar.register(PhysicsSystem.class).before(RenderingSystem.class);

// within third-party mod
systemRegistrar.register(ModSystem.class).before(PhysicsSystem.class);

```

I've thought about an *incidental ordering* using some sort of message or event bus

```
// within core code
// - PhysicsSystem
public void update() {
    // do physics-y stuff
    eventBus.send(new PhysicsSystemUpdatedEvent());
}

// - RenderingSystem
public void handle(PhysicsSystemUpdatedEvent event) {
    // do rendering stuff
    eventBus.send(new RenderingSystemUpdatedEvent());
}

```

But this blurs the line between what *will* happen, and what *could* happen.

Another thought that came into my mind is that we can be a little bit *dirty* and not care too terribly much about what order the systems get executed in, because even if we render before the physics are applied, the next frame will then render the physics update that was made in the previous frame. It's consistent, but it blurs the line between what happens within a frame.

# Answer
In general, I find that it's better to be explicit. If possible, I would advocate for simply fixing the ordering at compile time, as you noted.

But if the nature of your planning modding system is such that you want to introduce the ability for a mod to inject an *entirely new class of functionality* into the core update ordering, then the next level down I'd suggest would be akin to your first example: explicit ordering of the new system relative to an existing old system. I find it better to keep that ordering in a single place so it's clear and obvious, so I'd expect to see a mod bunch all it's `register()` (in your case) methods with their associated `before()` calls at a single point during initialization, rather than implicitly spreading that ordering information around via the more-distributed second example you've provided. This makes it much easier to reason about and to discover when you've accidentally got two things ticking in the wrong order.
> 3 votes

# Answer
in my ECS solution it would be a mistake to rely on the order of the engines. Instead I use the concept of a "Sequencer" that allows systems to communicate with each other in a given order. Sequencer actually are more complex, allowing conditional branching and loops.

A sequencer is an external dependency that knows the instance of the systems involved. The sequencer is then injected in to the involved systems by constructor.

Inside the System you can then do `sequencer.Next(condition);` to step to the next system method (the method is defined through an IStep interface that the involved system must implement). The System itself doesn't know about the other systems involved in the sequence, it just triggers the next step. The sequence of steps is actually defined in the sequencer.

I understand this explanation is not enough to give a clear idea of how I solved the issue, but the my main point is that the code shouldn't rely on how the engines are added. It would be a system too rigid that would implode pretty soon.

you can read more about it here: http://www.sebaslab.com/ecs-1-0/ (the sequencer example is toward the end of the article)
> 0 votes

---
Tags: entity-system, entity-component
---


title: Move Animation in LibGdx

text:
# Question
Title: Move Animation in LibGdx
I'm trying move animation within screen, here's the code

```
Animation<TextureRegion> animation_run = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP,
    Gdx.files.internal("run.gif").read());
    float elapsedTime += (Gdx.graphics.getDeltaTime()) * 2;
    float playablePosition = (Gdx.graphics.getWidth()) / 2 - 200;
    float currentPosition = 0;
    for (int i = 0; currentPosition <= playablePosition; i++) {
    currentPosition += i;
    batch.begin();
    batch.draw(animation_run.getKeyFrame(elapsedTime), currentPosition, 0, 200, 300);
batch.end();
}

```

but I got not exactly what I want

Does anybody know how fix my code to make movement from left edge to the center properly?

# Answer
Your problem lies in this code

```
for (int i = 0; currentPosition <= playablePosition; i++) {
    currentPosition += i;
    batch.begin();
    batch.draw(animation_run.getKeyFrame(elapsedTime), currentPosition, 0, 200, 300);
    batch.end();
}

```

Instead of looping through adding the animation we want to just draw the animation once in the batch and draw it in different position each frame. Below I change the position of the animation by incrementing position

```
Animation<TextureRegion> animation_run = GifDecoder.loadGIFAnimation(Animation.PlayMode.LOOP,
Gdx.files.internal("run.gif").read());
float elapsedTime += (Gdx.graphics.getDeltaTime()) * 2;
float playablePosition = (Gdx.graphics.getWidth()) / 2 - 200;
// float currentPosition = 0; // <-- this needs set outside ouside of the render method.
currentPosition += 1;
batch.begin();
batch.draw(animation_run.getKeyFrame(elapsedTime), currentPosition, 0, 200, 300);
batch.end();

```
> 1 votes

---
Tags: libgdx, animation
---


# Question
Title: Approaches on 2D top-view racing game track design
I've finished programming the car (acceleration, etc) and now I'll start developing a track editor of some sort. The thing is: I have no idea how I'm going to do that. How would you do it? Perhaps design the tracks on GIMP and use some sort of pixel collision detection, or perhaps use multidimensional arrays to store track data like walls and "dirt". I'm open to suggestions.

# Answer
The way I would approach this is to create at least two tiles (dirt and road) on GIMP as you suggested (pixel size depending on the size of your car). Then I would keep track of the "board" of a certain size, where the number represents the number of tiles, using a matrix or a list of lists (IDK what engine/language/platform you are using so I'm keeping it vague). This would let me lay out the board pseudo-randomly with just a couple of for loops. By pseudo-random I am referring to the fact that the road must be connected. Maybe even consider laying out the road and then filling up the rest of the matrix with dirt.

for example an 10x10 board gives you 8x8 tiles to work with and it would look like this (s=start; e=end; d=dirt; r=road):
_ _ _ _ _ _ _ _ _ _
| d d d d d d d **e** |
| d d d d d d d **r** |
| d d d d d d **r r** |
| d d d d d d **r** d |
| d d d d **r r r** d |
| d d **r r r** d d d |
| d d **r** d d d d d |
| d **s r** d d d d d |
| _ _ _ _ _ _ _ _ |

This Unity 2D tutorial is where I got the idea: https://www.youtube.com/watch?v=bvvaqAbpPjc&t=321s

TBH I am pretty new to this myself... just started to learn recently, but i thought I could be helpful here.
> 2 votes

---
Tags: game-design, map-editor, racing
---


title: Unity detect tap on 3d object

text:
# Question
Title: Unity detect tap on 3d object
I have a simple game object (3d object) and I want to detect and run some code when gets clicked/tapped.

I tried `OnPointerDown/Up/Click` but seems to not be working for 3D Objects. With 2d objects (images with raycast targets) it works fine.

How can I do it with a 3d objects in a simple way? Thanks!

# Answer
> 4 votes
1. Make sure your object has a 3D collider component attached with a suitable shape & size

Ensure it's not in a layer that ignores raycasts (the defaults will work fine)
2. Add a script using one of these MonoBehaviour methods:

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


# Question
Title: How to get NPC to Find and Follow Path to other NPC?
# Problem:

I am using **Skyrim Creation Kit** to create a very simple mod. I want the mod to make one NPC follow another NPC. My first problem is that I am not really 100% sure where to start. The second problem is which functions I should use. I have been reading the documentation at www.creationkit.com. In other words:

```
LOOP: {
  // move Bob to Mike's current position with speed of 0.5
  (npc_Bob.moveToPosition( npc_Mike.getPos(), 0.5 )
} // end loop

```

---

# My Attempt:

I tried making a quest but to no avail. So then I made 2 custom actors (`member` and `leader`) and I put this script in `member`:

```
Scriptname NpcFollowNpc extends ObjectReference
//***put a loop once you get this part working
// moves member to leader with speed of 0.5
member.PathToReference(leader, 0.5)

```

but it didn't compile. I don't really know if this is the right way to implement what I want. I know how to code and make algorithms and a bunch of that computer science stuff, but I don't know how to move the actor `member` to the location of actor `leader` in Skyrim and loop it while the actor `leader` is alive.

Any ideas how I could go about doing this? thanks for any help/feedback!

# Answer
> 1 votes
As stated in this forum, you will need to Spawn a path point, attach it to an NPC. Then press U with the pathpoint selected to open the parameters. In the first text field, the one called Type, replace "Stand" with whatever (has to be written with a capital letter)

---
Tags: path-finding, skyrim-modding
---


# Question
Title: Using 2D Heightmap Data to generate terrain with the Marching Cubes Algorithm
The Marching Cubes (MC) algorithm works by taking 8 points of a cube with different density values and converting them into vertices and triangles based on a given iso level (threshold above which is considered solid area). It can create quite a smooth result. For example the following picture shows MC generating polygons using a 3D noise perlin function.

However 3D perlin noise is not very useful for generating terrain. 2D perlin noise is much better. One could use the following function to generate the density values at each corner of each cube sent through the marching cubes algorithm with an iso level of 0:

```
float IsoValue(Vector3 pos) {
    float gap = maxHeight - minHeight;
    float perlin = (Mathf.PerlinNoise(pos.x * frequency, pos.z * frequency) * gap) + minHeight;
    if(pos.y > perlin) {
        return -1f;
    }
    else {
        return 1f;
    }
}

```

It produces a jagged-looking result:

This is because unlike the 3d-noise function, the density values go straight from 0 to 1, and MC always generates vertices along a grid instead of at different heights in between the grid. How do I modify the above IsoValue function to not always give values between 0 and 1 (to make smoother looking terrain) depending on how close the generated noise is to the grid?

# Answer
> 1 votes
You need to set a positions density to

```
Mathf.clamp(perlin - pos.y, 0, 1);

```

Instead of setting the values to either 1 or 0, this makes the top a bit more smooth. The clamp is required to make range of thr values inside the mesh lie between 1 and 0.

You should always pass a value between 1 and 0 to the marching cubes algorithm

# Answer
> 0 votes
Check out this GPU gems article an making nice looking terrain with marching cubes.

The trouble is that what you want is a *continuous 3D function* over which to compute the isosurface. In other words, you want a signed distance field representation of the map. Not a heightmap. 3D perlin noise is already representing a signed distance field in 3D, so it works with marching cubes.

Note that Marching Cubes needs continuous gradients in 3D to represent smooth surfaces. The function you provided does not have continuous gradients in 3D (there is a hard cutoff in x and y based on the height value, and no gradient in z).

In the GPU gems article, we get a nice way of generating a 3D signed distance field based on terrain which is mostly 2 dimensional. You simply *add together* the results from 3D perlin noise with a simple modulating function that goes from 0 to 1 from the minimum to maximum height of the world.

From the article:

> For example, for a flat plane at a height of y = 0

```
 `float density = -ws.y;`

```

Then you can add noise to this simple density function:

`density += noiseVol.Sample(TrilinearRepeat, ws).x;`

Where in your case the "noiseVol.Sample" would be your 3D perlin noise function.

---
Tags: c#, procedural-generation, heightmap, marching-cubes
---


# Question
Title: How to simulate explosions vehicle parts?
I've downloaded some 3D vehicle models that I bought from the Asset Store, because I don't know how to create 3d models.

These objects have different meshes for different vehicle parts: steering wheel, doors, body, lamp lights, hood etc.

I would like to simulate an explosion and apply physics impulses to each of the parts.

I've tried this flow:

* Create a rigidbody for each vehicle part, set its weight and set:
`isKinematic = true; useGravity= false;`
* Create a mesh collider for each part and disable it
* Create a main box collider for vehicle

When a bullet, or other explosive object, hits my vehicle, I've tried to use a script to enable these components on the parts: rigidbody (isKinematic = false, useGravity=true) and mesh collider, and, obviously, apply a force explosion.

The problem is that it's not possible to enable a mesh collider at runtime for performance reasons (it lags a lot, and this does not depend on PC/Hardware power, but depends from graphics pipeline).

So my question is: how can I simulate an explosion by applying forces to individual vehicle parts?

# Answer
maybe my solution might not be good at all but worked for me
create three empty objects then put your car parts in two of them like this :

Holder = NotDestroyed , Destroyed
NotDestroyed = wheels , body , doors etc...
Destroyed = wheels , body , doors etc...

add ridgidbody and colliders to your mesh parts one by one.

then put NotDestroyed and Destroyed objects in your main object "Holder" , after that write a script and attach it to the Holder object that when anything like bullet or rocket touch collider of your car disable NotDestroyed and enable Destroyed ( be careful that position of NotDestroyed and Destroyed must exactly same as each other to achieve maximum result.
I have a script too you can use or try to read for better understanding of my answer.

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

public class DestroyObjects : MonoBehaviour {

// When aggresive object come touch collider
void OnTriggerEnter(Collider other)
{
    // compare tag to see if is correct object or not
    if (other.CompareTag("Player") || other.CompareTag("Cop"))
    {
        Obj_Destroy();
    }

}
// a function for disabling first holder and enbaling second holder (destroyed objects )
void Obj_Destroy()
{
    var Obj_Stand = transform.GetChild(0).gameObject;
    Obj_Stand.SetActive(false);
    var Obj_Des = transform.GetChild(1).gameObject;
    Obj_Des.SetActive(true);
}

```

}

I hope it helps.
> 2 votes

---
Tags: unity, physics
---


# Question
Title: How can I improve on this engine design?
I am trying to come up with a terrain visualization system and I am writing a simple graphics engine for this. For some reason, I wanted to try a new idea. Rather than using dynamic polymorphism and derive from a `GameObject` like class for all the entities in the screen, I go for something like this.

First, I want to have a very simple scene graph, very non-sophisticated. For this, I am using a heterogeneous vector like given here. My scene graph will be just a heterogeneous vector of possible renderable items. I will iterate through each item using visitors.

For example my Terrain class looks like following

```
template <typename RenderAPI>
class HeightmapTerrain
{
public:
    // constructor like things
    void render();
    void input();
    // imagine the rest
private:
    Heaightmap hm;
    Transformation tm;
    TerrainInputHandler tih;
};

```

Then I will have a specialization of this for OpenGL as follows

```
template <> class HeightmapTerrain<OpenGLAPI> {
public:
    // as an example
    void render()
    {
        BasicTerrainGLSLShader ts;
        ts.bind();
        hm.generateVBO();
        // etc.
    }
private:
};

typedef Terrain<OpenGLAPI> HeightmapOpenGLTerrain;

```

Assume all of these are in a file called `Terrain.h`. I am planing to include that file and I will add an instance of `HeightmapOpenGLTerrain` to my scene graph. This way, I can call `render_visitor()` in the render function of my scene graph and since it is a heterogeneous vector all will work, I hope.

The reason I am doing this is because if I want to extend the system with new graphics APIs, I will just create a new specialization and implement render etc. methods as

```
template <> class HeightmapTerrain<VulkanAPI> {
public:
    // as an example
    void render()
    {
        // Vulkan implementation
    }
private:
};
typedef Terrain<VulkanAPI> HeightmapVulkanTerrain;

```

With this, I can use same scene graph to render and input handle etc. but now using Vulkan. It feels like I can easily change the Input mechanism as well, with this system.

Now, what I am asking is this; I am not really that great at template programming. Is this approach feasible? What are the performance and design disadvantages compared to dynamic polymorphism approach we all know and love? Is this design downright obtuse? Lastly, can I have different private members for different specializations? Let's say I wanted to also have `HeightmapTerrain<OfflineRendering>` to render using path tracing. Can I add an extra private member to this specialization, like `Canvas cs`?

# Answer
> 1 votes
The templates here buy you nothing. You can achieve the same effect by writing one `HeightmapTerrain` class that has the data you need, using the preprocessor to cordon off Vulkan variables from OpenGL variables:

```
struct HeightmapTerrain {
  void render();
private:
  #ifdef USE_VULKAN
     // Vulkan-specific variables here.
  #endif

  #ifdef USE_OPENGL
     // OpenGL-specific variables here.
  #endif
};

```

You can then implement `render()` in a source file; either using the preprocessor again to control which actual code gets compiled, or by putting the Vulkan implementation in one file and the OpenGL implementation in another, and feeding the appropriate one to the compiler based on build configuration.

Not only is the same net effect (compile-time selection of the rendering backend used by `HeightmapTerrain`), you're also gaining the advantage of having the bulk of the implementation tucked away in a source file like normal, and you don't have to duplicate the API-agnostic parts of the class either.

The template approach requires all your code to be in a header file (if you want anybody else to be able to use it), which means everything referencing that header file recompiles any time you change the implementation. In a larger project or over a long enough time, this can really add up.

The template approach also requires you to fully re-implement the specialized version of the class. You don't get to "inherit" anything from the non-specialized template when you specialize, so if all you're changing is the `render()` function, you're really duplicating a lot of code.

---

The idea of compile-time selection of your rendering API is fine; in fact, I tend to always argue in favor of that over the "polymorphism approach we all know and love," which I find absurd and overly complex in nearly all cases. But you don't need to involve templates to make it work. The preprocessor, and/or leveraging your build system, is a much simpler way to achieve the same goal.

---
Tags: architecture, software-engineering
---


title: Nested reference problem

text:
# Question
Title: Nested reference problem
I have an array of objects tied to a global array in GMS2 When I try to reference the variable used to position the object I get errors saying the variable hasn't been declared. The error also says the object and variable that cause the error are unknown. I feel like I'm using the nested reference to point to the current target of the for loop incorrectly.

```
//Place is a local variable used as a index for the array
 Global.hand[place] = noone;
 //The array global.hand is elsewhere set as a 1d array that's 8 items tall
 For(i = place + 1; i < 8; i++)
 {
     Global.hand[i] = global.hand[i + 1];
     Global.hand[i].place -= 1;
 }
 Place = instance_count(card);

```

The snippet is supposed to take an item in the array and move it to the end

The line that's causing the error is Global.hand\[i\].place -= 1;

# Answer
> 1 votes
Does the `hand` object have a member called `place`? I doubt it. `place` looks like a local variable. This is where the error is coming from.

# Answer
> 0 votes
"Solved" this by adding a global variable that gives me something I can reference later

In the left pressed trigger

```
    global.bookmark = place;

    global.hand[place] = noone;
    for (i = place + 1; i < 7; i++)
    {
        global.hand[i] = global.hand[i + 1];
    }
    //place=instance_number(basic_card);
    shuffling = 1;
}

```

In the end step

```
if place > global.bookmark && place != instance_number(basic_card) && shuffling = 1
{
    place -=1;
    shuffling = 0;
}

```

It's not perfect but I don't get crashes anymore

---
Tags: game-maker
---


title: Pygame set_repeat() issue

text:
# Question
Title: Pygame set_repeat() issue
I want a single key press to result in the sending of one event in my game loop. As a toy example, if the player presses and holds LEFT, I want the sprite to move 1 pixel left and then stop until the player releases the key and presses it again.

Pygame allows you to set the repeat characteristics of key presses using

```
 set_repeat().

```

Not calling this method at all, calling it without parameters, or specifying 0 as its delay parameter are all supposed to result in the behavior I want.

From the documentation:

> **pygame.key.set\_repeat()**
>
> control how held keys are repeated
>
> set\_repeat() -\> None
>
> set\_repeat(delay, interval) -\> None
>
> When the keyboard repeat is enabled, keys that are held down will generate multiple pygame.KEYDOWN events. The delay is the number of milliseconds before the first repeated pygame.KEYDOWN will be sent. After that another pygame.KEYDOWN will be sent every interval milliseconds. If no arguments are passed the key repeat is disabled.
>
> When pygame is initialized the key repeat is disabled.

Unfortunately, I can't get this to work. I tried not calling the method at all, calling the method without parameters, and calling the method with a delay set to 0 (which is, strangely, supposed to disable key repeating -- see the comments in the documentation).

Here's a minimal example:

```
import pygame as pg
import sys

# colors
WHITE = (255, 255, 255)
GREY = (100, 100, 100)

class Game:

    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((640, 640))
        self.clock = pg.time.Clock()
        pg.key.set_repeat()

    def new(self):
        self.all_sprites = pg.sprite.Group()
        self.player = Player(self, 100,100)

    def run(self):
        self.playing = True
        while self.playing:
            self.clock.tick(60)
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()
        sys.exit()

    def update(self):
        self.all_sprites.update()

    def draw(self):
        self.screen.fill(GREY)
        for sprite in self.all_sprites:
            self.screen.blit(sprite.image, sprite.rect)
        pg.display.flip()

    def events(self):
        for self.event in pg.event.get():
            if self.event.type == pg.QUIT:
                self.quit()

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((32,32))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.pos = [x, y]

    def get_keys(self):
        if self.game.event.type == pg.KEYDOWN:
            if self.game.event.key == pg.K_LEFT:
                self.pos[0] -= 1
                print("This should only be printed once per key press")

            elif self.game.event.key == pg.K_RIGHT:
                self.game.player.pos[0] += 1
                print("This should only be printed once per key press")

    def update(self):
        self.get_keys()
        self.rect.centery = self.pos[1]
        self.rect.centerx = self.pos[0]

g = Game()
while True:
    g.new()
    g.run()

```

This does not result in the behavior I want. Pressing the LEFT key will continuously move the sprite left, and continuously print my test message. I have tried calling the method at various other spots in my code (for example, during the events() method of the game class and during the get\_keys() method of the player class). No luck.

My question is simple: **What am I doing wrong?**

---

**ADDITIONAL INFO**

For what it's worth, when I call

```
pygame.key.get_repeat(),

```

which is supposed to tell you the repeat characteristics for the current instance of pygame, the value returned is (0,0).

I am working on a MacBook 2010, running macOS Sierra 10.12.6.

I am interested to know if others can replicate this issue.

I know that I can create a workaround using booleans to track keydowns and keyups, but this would be a nuisance (the project relies on a lot of single key presses).

# Answer
I tried your code on Linux, using the pygame\_sdl2 module.

The set\_repeat() works fine, you just have an issue with your code. You keep seeing the same old event, because you keep a reference to it.

After running Game.events() func, the game.event will still point to the last event.

Just iterate over the events as you retrieve them from the queue, and handle them right then and there, without keeping a reference to it.

You can use a secondary handler in Player class to do the actual work for keypresses if you want, as show below.

```
import pygame_sdl2 as pg

# colors
WHITE = (255, 255, 255)
GREY = (100, 100, 100)

class Game:

    def __init__(self):
        pg.init()
        self.screen = pg.display.set_mode((640, 640))
        self.clock = pg.time.Clock()
        pg.key.set_repeat()

    def new(self):
        self.all_sprites = pg.sprite.Group()
        self.player = Player(self, 100,100)

    def run(self):
        self.playing = True
        while self.playing:
            self.clock.tick(60)
            self.events()
            self.update()
            self.draw()

    def quit(self):
        pg.quit()

    def update(self):
        self.all_sprites.update()

    def draw(self):
        self.screen.fill(GREY)
        for sprite in self.all_sprites:
            self.screen.blit(sprite.image, sprite.rect)
        pg.display.flip()

    def events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.quit()
            if event.type == pg.KEYDOWN:
                self.player.handle_keydown( event.key )

class Player(pg.sprite.Sprite):
    def __init__(self, game, x, y):
        self.groups = game.all_sprites
        pg.sprite.Sprite.__init__(self, self.groups)
        self.game = game
        self.image = pg.Surface((32,32))
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.pos = [x, y]

    def handle_keydown( self, key ) :
        if key == pg.K_LEFT:
            self.pos[0] -= 1
            print("This should only be printed once per key press")
        elif key == pg.K_RIGHT:
            self.pos[0] += 1
            print("This should only be printed once per key press")

    def update(self):
        self.rect.centery = self.pos[1]
        self.rect.centerx = self.pos[0]

g = Game()
while True:
    g.new()
    g.run()

```

Note that I get a crash when I close the window, so your code needs more work than this.
> 2 votes

---
Tags: input, pygame, events, keyboard
---


# Question
Title: Take an image and cut it up into a tile map
So I am attemping to make a game in Phaser.

I am trying to think of the best way to cut this image up and make it in to a tile map OR do I try and lay this entire image as a back ground to the game and just determine where the mouse was clicked.

I believe the images have a width of 140 and a height of 160 or 162. Then I would have to make the four corners of the image transparent so I can overlay them to create the map.

If I want to go with a scrollable background, I am not sure how to proceed, would I overlay hot spots on to the screen and would I have to do a point to hex conversion as I would not have the tile coordinates

# Answer
Take a look at Tiled. It's a tool for creating 2D tile maps including hex-based maps like the example in your post. Phaser allows you to load tile map data generated by this tool.

Once you've created and exported your map you would do something like this in your preload script:

```
this.game.load.tilemap('SweetTileMap',
                       '/images/maps/sweetMap.json',
                        null,
                        Phaser.Tilemap.TILED_JSON
                      );
this.game.load.image('tiles', '/images/terrain_atlas.png');

```

Then use it as you would use any other tile map in Phaser. There's a basic tutorial here.
> 2 votes

---
Tags: tools, phaser, tiled, tilesets
---


# Question
Title: Do I have to keep all my UI elements within the safe area defined by the iPhone X?
Suppose this is my game's screen for the iPhone 8:

I have 7 blue buttons, and one blue bar at the bottom which is used to display commentary text.

I understand that the iPhone X has a safe area. In this case, there would be a bottom inset because of the home indicator and the swiping gestures.

The swiping and the home indicator pose no issue to my players. The game does not use any sort of gestures, and the center button is large enough that the home indicator doesn't really affect its aesthetics.

Given that, **do I still have to avoid the bottom inset?** Am I supposed to keep all my buttons within the safe area defined by the iPhone X even when it doesn't affect my user experience?

If I were to stay within the safe area, then I would have to push the bar and the buttons upwards by several pixels, then the leftmost buttons have to be pushed to the right, and the rightmost buttons to the left. That wouldn't look really great with my game art.

Would my game be rejected if I don't keep my elements inside the safe area?

It ***seems*** like I must indeed keep all my UI elements within that area, based on this image from the keynote:

# Answer
There are a number of problems caused by placing UI elements outside the safe area. Note that many of these are not unique to iPhone X, and would also apply to CRTs, projectors, or smart watch screens for which a safe area is defined.

Touch handling (input) problems:

* The user may initiate a swipe gesture accidentally while intending to tap your button.
* Inversely, the user may initiate a tap gesture accidentally while intending to swipe the home indicator.
* The user's ability to reach buttons or other controls comfortably, without having to readjust their grip, is hindered.

Design and layout (output) problems:

* As you point out, your buttons would be partially occluded by the home indicator. If you had them at the top (in portrait orientation) or sides (in landscape orientation), they could become occluded by the sensor housing.
* Inversely, the home indicator would be obscured by your button. Looking at the example screenshot from the keynote, you can probably picture how a confused user might not see how to leave the app.
* Being close to the physical edge of the device can hinder the readability of your UI (much like when text is laid out with insufficient margins).
* It will look inconsistent with most other apps, and may give the impression that you didn't take the user's device into consideration when you designed the UI.

Having said that, if your buttons have (for instance) text or icons within the safe area, and the circles are effectively just part of the background (with low contrast against the rest of the background, such as your game scene), that would probably be OK. You'd still have to be careful not to obscure the home indicator, though.
> 1 votes

---
Tags: iphone, ui-design, user-experience
---


# Question
Title: Merging multiple image with DirectX D3DImage best approach?
I'm currently rendering up to 6 images (7440 x 7440) together via a series of colorizing shaders (one each image) and then merging shaders (5 to merge colorizer result). I'm not getting the performance I would expect. I'm using D3DImage to render into a WPF application. The rendering is appearing to be very slow. However, the shaders are rendering in .005 secs each. This is currently rendered on one quad...

Is it better to flush between image and merge or send on flush at the end?

Are C# for loop slowing it do? The benchmarks are not showing that but...

Also I use the colorize shader to change color in near real time the UI locks up...

Windows 7 I know is limited to 1 device. Windows 10 I know support multiple instances of devices... is there a way to use that capability? is it worth it?

Here is the kicker I will need to eventually do this on 20 quads.

Thank you in advance!

# Answer
The Pixel Shader and Texture Array are your friends.

I removed any C# architecture the was not absolutely necessary (Loops and Collections). I was able to get this working very well with smooth color transitions.

I also limited my layers to 15 which still meets my initial requirements.

Windows 10 and Windows 7 are running in single device mode at 60fps.
> 1 votes

---
Tags: c#, directx, directx11, sharpdx
---


# Question
Title: SharpDX C#, Quad renderer not rendering as expected
I've been working on a Quad Renderer and have gotten close. However, It still does not render correctly. Can anyone spot what I'm doing wrong or give me a better option. See the rendered results below the Code.

I'm about at wits end with this thing.

```
    public void Initialize(DeviceManager deviceManager, string vertexShaderFile, string pixelShaderFile = null)
    {
        m_DeviceManager = deviceManager;

        VertexShaderFile = vertexShaderFile;
        PixelShaderFile = pixelShaderFile ?? vertexShaderFile;

        RemoveAndDispose(ref m_VertexShader);
        RemoveAndDispose(ref m_PixelShader);
        RemoveAndDispose(ref m_InputLayout);
        RemoveAndDispose(ref m_ShaderResourceView);
        RemoveAndDispose(ref m_SamplerState);

        using (var vertexShaderByteCode = SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(VertexShaderFile, "VSMain", "vs_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug))
        {
            m_VertexShader = AddDisposable(new SharpDX.Direct3D11.VertexShader(m_DeviceManager.Direct3DDevice, vertexShaderByteCode));

            m_InputLayout = AddDisposable(new SharpDX.Direct3D11.InputLayout(m_DeviceManager.Direct3DDevice,
                vertexShaderByteCode.Bytecode.GetPart(SharpDX.D3DCompiler.ShaderBytecodePart.InputSignatureBlob),
                new[]
                {
                    new SharpDX.Direct3D11.InputElement("SV_Position", 0, SharpDX.DXGI.Format.R32G32B32A32_Float, 0, 0),
                }));
        }

        using (var pixelShaderByteCode = SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(PixelShaderFile, "PSMain", "ps_5_0", SharpDX.D3DCompiler.ShaderFlags.Debug))
        {
            m_PixelShader = AddDisposable(new SharpDX.Direct3D11.PixelShader(m_DeviceManager.Direct3DDevice, pixelShaderByteCode));
        }

        var samplerStateDescription = new SharpDX.Direct3D11.SamplerStateDescription
        {
            AddressU = SharpDX.Direct3D11.TextureAddressMode.Wrap,
            AddressV = SharpDX.Direct3D11.TextureAddressMode.Wrap,
            AddressW = SharpDX.Direct3D11.TextureAddressMode.Wrap,
            Filter = SharpDX.Direct3D11.Filter.MinMagMipLinear
        };

        m_ShaderResourceView =
            AddDisposable(TextureLoader.CreateShaderResourceView(m_DeviceManager.Direct3DDevice, "backgroundDefault.jpg"));

        m_SamplerState =
            AddDisposable(new SharpDX.Direct3D11.SamplerState(m_DeviceManager.Direct3DDevice, samplerStateDescription));

        m_VertexBuffer =
            AddDisposable(SharpDX.Direct3D11.Buffer.Create(m_DeviceManager.Direct3DDevice,
                SharpDX.Direct3D11.BindFlags.VertexBuffer, new SimpleVertex[]
                {
                    /*  Position: float x 3 */
                    new SimpleVertex(-1.0f, -1.0f, 0.5f), new SimpleVertex(-1.0f, 1.0f, 0.5f),
                    new SimpleVertex(1.0f, -1.0f, 0.5f), new SimpleVertex(1.0f, 1.0f, 0.5f),
                }));

        m_VertexBufferBinding = new SharpDX.Direct3D11.VertexBufferBinding(m_VertexBuffer, SharpDX.Utilities.SizeOf<SimpleVertex>(), 0);

        // Triangle strip:
        // v1   v3
        // |\   |
        // | \ B|
        // | A\ |
        // |   \|
        // v0   v2
    }

    public void Render()
    {
        var direct3DContext = m_DeviceManager.Direct3DDeviceContext;

        using (var shaderRestore = new ShaderRestore(direct3DContext))
        {
            direct3DContext.PixelShader.SetShaderResource(0, m_ShaderResourceView);

            direct3DContext.PixelShader.Set(m_PixelShader);

            direct3DContext.VertexShader.Set(m_VertexShader);

            //direct3DContext.InputAssembler.InputLayout = null;
            direct3DContext.InputAssembler.InputLayout = m_InputLayout;

            direct3DContext.InputAssembler.PrimitiveTopology = SharpDX.Direct3D.PrimitiveTopology.TriangleStrip;

            direct3DContext.InputAssembler.SetVertexBuffers(0, m_VertexBufferBinding);

            direct3DContext.Draw(4, 0);

            shaderRestore.Restore();
        }

    }

    private DeviceManager m_DeviceManager;

    private SharpDX.Direct3D11.VertexShader m_VertexShader;
    private SharpDX.Direct3D11.InputLayout m_InputLayout;

    private SharpDX.Direct3D11.PixelShader m_PixelShader;

    private SharpDX.Direct3D11.ShaderResourceView m_ShaderResourceView;
    private SharpDX.Direct3D11.SamplerState m_SamplerState;

    private SharpDX.Direct3D11.Buffer m_VertexBuffer;
    private SharpDX.Direct3D11.VertexBufferBinding m_VertexBufferBinding;

    public string VertexShaderFile { get; private set; }
    public string PixelShaderFile { get; private set; }

```

Shader Code. I could get it to format correctly.

# Answer
> 0 votes
This turned out the quad points were in the wrong order. Once figuring out my issue, I created a static method to create Quads from now on.

```
public static Quad CreateQuad(IDevice3DManager device3DManager, float x = -1, float y = 1)
    {
        var baseVector = new Vector2(x, y);

        var vertices = new[]
        {
            new TexturedVertex(GetVectorP1(baseVector), new Vector2(0,0)),
            new TexturedVertex(GetVectorP2(baseVector), new Vector2(1,0)),
            new TexturedVertex(GetVectorP3(baseVector), new Vector2(1,1)),
            new TexturedVertex(GetVectorP4(baseVector), new Vector2(0,1)),
        };

        var indices = new[] { 0, 1, 2, 2, 3, 0 };
        var quad = new Quad(device3DManager)
        {
            VertexBuffer = Buffer.Create(device3DManager.Device, BindFlags.VertexBuffer, vertices.ToArray()),
            IndexBuffer = Buffer.Create(device3DManager.Device, BindFlags.IndexBuffer, indices.ToArray()),
            VertexSize = Utilities.SizeOf<TexturedVertex>()
        };

        quad.MeshSubsets.Add(new MeshSubset()
        {
            DiffuseColor = new Vector4(1, 1, 1, 1),
            IndexCount = indices.Count()
        });

        return quad;
    }

/// <summary>
/// Textured Vertex
/// </summary>
public struct TexturedVertex
{
    /// <summary>
    /// Position
    /// </summary>
    public Vector3 Position;

    /// <summary>
    /// Texture coordinate
    /// </summary>
    public Vector2 TextureCoordinate;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="position">Position</param>
    /// <param name="textureCoordinate">Texture Coordinate</param>
    public TexturedVertex(Vector3 position, Vector2 textureCoordinate)
    {
        Position = position;
        TextureCoordinate = textureCoordinate;
    }
}

private static Vector3 GetVectorP1(Vector2 vector, float size = 2)
    {
        return new Vector3(vector.X, vector.Y, 0);
    }

    private static Vector3 GetVectorP2(Vector2 vector, float size = 2)
    {
        return new Vector3(vector.X + size, vector.Y, 0);
    }

    private static Vector3 GetVectorP3(Vector2 vector, float size = 2)
    {
        return new Vector3(vector.X + size, vector.Y - size, 0);
    }

    private static Vector3 GetVectorP4(Vector2 vector, float size = 2)
    {
        return new Vector3(vector.X, vector.Y - size, 0);
    }

```

No more problem...

---
Tags: c#, shaders, sharpdx
---


# Question
Title: Why is the for loop more efficient than the for each loop in Unity?
During a Unity talk about performance, the guy told us to avoid `for each` loop to increase performance and use the normal for loop instead. What's the difference between `for` and `for each` in implementation point of view? What makes `for each` inefficient?

# Answer
> 14 votes
A foreach loop ostensibly creates an IEnumerator object out of the collection you pass it, and then walks over that. So a loop like this:

```
foreach(var entry in collection)
{
    entry.doThing();
}

```

translates to something a bit like this:
(eliding some complexity around how the enumerator is disposed of later)

```
var enumerator = collection.GetEnumerator();
while(enumerator.MoveNext()) {
   var entry = enumerator.Current;
   entry.doThing();
}

```

If this gets compiled naively/directly, then that enumerator object gets allocated on the heap (which takes a little time), even if its underlying type is a struct - something called boxing. After the loop is done this allocation becomes garbage to clean up later, and your game can stutter for a moment if enough garbage piles up for the collector to run a full sweep. Lastly, the `MoveNext` method and `Current` property could involve more function call steps than just grabbing an item directly with `collection[i]`, if the compiler doesn't inline that action.

The Unity docs Hellium links above indicates that this naive form is exactly what happens in Unity *prior to version 5.5*, if iterating over anything other than a native Array.

In version 5.6+ (including 2017 versions), this unnecessary boxing is gone, and you shouldn't experience unnecessary allocation if you're using any concrete type (eg. `int[]` or `List<GameObject>` or `Queue<T>`).

You will still get an allocation if the method in question only knows that it's working with *some kind* of IList or other interface \- in those cases it doesn't know what specific enumerator it's working with so it has to box it into an IEnumerator object first.

So, there's a good chance this is old advice that's not so important in modern Unity development. Unity devs like us can be a bit superstitious about things that *used* to be slow/hairy in old versions, so take any advice of that form with a grain of salt. ;) The engine evolves faster than our beliefs about it.

In practice, I've never had a game exhibit noticeable slowness or garbage collection hiccups from using foreach loops, but your mileage may vary. Profile your game on your chosen hardware to see if it's even worth worrying about. If you need to, it's pretty trivial to replace foreach loops with explicit for loops later in development should a problem manifest, so I wouldn't sacrifice legibility and ease of coding early in development.

# Answer
> 0 votes
If a for each loop used for collection or array of object (i.e. array of all elements other than primitive datatype), GC (Garbage Collector) is called to free space of reference variable at the end of a for each loop.

```
foreach (Gameobject temp in Collection)
{
    //Code Do Task
}

```

Whereas for loop is used to iterate over the elements using an index and so primitive datatype will not affect performance compared to a non-primitive datatype.

```
for (int i = 0; i < Collection.length; i++){
    //Get reference using index i;
    //Code Do Task
}

```

---
Tags: unity, performance
---


# Question
Title: How can I create Portrait game assets to have same with gap for both iPhone 7 Plus and iPhone X?
In my Unity game I made changed my Pixel Per Unit value to 243 since the height of a Portrait game for iPhone X is 2436. The game looks great and the asset sizes look just right on the iPhone X simulator. But when I change to iPhone 7 Plus I get considerable space on the sides and it gets worse when I change to the iPad. How can I make my game have the same width gaps for iPhone 7 Plus and iPhone X without making assets look stretched horizontally or vertically?

**UPDATE**

The images below give an idea of my game on both 1080x1920 (for iPhone 7 Plus) and 1125x2436 (for iPhone X). It's not a match3 game. All the game objects below are static and have colliders. The gaps between are quite significant for other dynamic objects to move between. Reducing the gaps significantly would alter the movement of the dynamic objects and their sizes too, making the ratio in object sizes look wrong. I haven't started worked on scores or menus yet, so I haven't added a UI canvas yet.

# Answer
This Script writes on your Camera Setup and runs it. It used for Portrait mode only. Count Width of Object it is our WorldWidth.

**Then Follow this Script:**

```
    public float worldWidth = mainObjectWidth;
    void Awake()
    {
        float x = worldWidth;
        float y = x * Screen.height / Screen.width;
        Camera.main.orthographicSize = y * 0.5f;
    }

```

It will work for sure. :)
> 1 votes

---
Tags: unity
---


title: Vulkan Storage Buffers, loss of data

text:
# Question
Title: Vulkan Storage Buffers, loss of data
I have been passing glm::vec3's in an array to a storage buffer to be processed by a compute shader, but once it has been modified I am getting some malformed data back.

Shader

```
#version 450

#extension GL_ARB_separate_shader_objects : enable

layout(binding = 0) buffer DataObject {
    vec3[] floatArray;
} data;

void main()
{
    data.floatArray[gl_GlobalInvocationID.x].x = 45.0123f;
    data.floatArray[gl_GlobalInvocationID.x].y = 45.0123f;
    data.floatArray[gl_GlobalInvocationID.x].z = 45.0123f;
}

```

Data being passed

```
struct DataObject
{
    glm::vec3 payload[2];
};

...

Buffer payload_buffer;
VkDeviceSize buffer_size = sizeof(DataObject);
CreateBuffer(engine, buffer_size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, payload_buffer);

// Create the data that will be saved
DataObject payload;

// Move the data to the GPU
memcpy(payload_buffer.mapped_memory, &payload, (::size_t)buffer_size);

```

The data that is returned is as follows

```
v1 x:45.0123f y:45.0123f z:45.0123f
v2 x:0 y:45.0123f z:45.0123f

```

Has anyone else come across this issue? and if so how would i resolve it?

# Answer
> 1 votes
It's alignment. `Vec3`s in storage buffers must be aligned to 16 bytes (same as `vec4`).

replace DataObject with:

```
struct DataObject
{
    glm::vec4 payload[2];
};

```

---
Tags: vulkan, compute-shader
---


title: Unity frame-rate drops / stall

text:
# Question
Title: Unity frame-rate drops / stall
I have an issue where my game suddenly stops for a second and then continues. And I think it has something to do with my performance so I took at look at the profiler:

I tried to take a screenshot as soon as the crack happened:

However, since I am a bit new to optimization could anyone give me a helping hand on what might be the problem here?

# Answer
> 3 votes
As Nico says, your profiler seems to show a big spike of garbage collector activity, which is consistent with the symptom of a sudden isolated stall.

This happens when your scripts allocate and then discard heap memory frequently. When a heap allocation request comes in and there's no longer enough untouched space left on the game's heap to fulfill it, the .Net/Mono runtime puts everything on hold while the garbage collector checks which previous allocations are no longer being used and clears them out, compacting the used portion heap to leave a nice big open space again. In a large & complicated game, a full sweep can take a significant amount of time.

To avoid this, take a look into which scripts are allocating lots of heap memory managed by the garbage collector — that's the GC Alloc column in the profiler, where I notice one line there allocated 2.0 MB in this frame. If that's happening frequently then it will definitely add up.

2.0 MB could be two 512 x 512 uncompressed RGBA textures, for instance. If you're allocating big blocks of memory like this, see if there are ways you can re-use them like a circular buffer or object pool, rather than continually allocating new ones. If you need temporary RenderTextures in particular, Unity has a built-in pool you can tap into with RenderTexture.Get/ReleaseTemporary.

Also watch for cases where two different scripts make a modified copy of a source asset each, even if the modification they needed was the same — you can cache and re-serve the existing copy instead of re-doing the work on a new one.

Creating new instances of reference types like Arrays/Lists, instantiating GameObjects, attaching Components, or modifying strings without a pre-allocated StringBuilder all create heap allocations too, though typically on a much smaller scale than textures, and more easily reclaimed.

If you're using Unity methods that return new arrays, like RaycastAll, check to see if they have a NonAlloc variant that lets you pass in your own buffer to populate, letting you re-use the same memory between calls.

For more information about reducing problems from garbage collection, see this Unity tutorial which goes into a lot of detail. :)

---
Tags: unity, optimization, frame-rate
---


# Question
Title: How can you make custom direct3D11 calls in Unreal Engine 4?
I have some custom code that renders to Direct3D11 texture. Is it possible to use this texture on an object in unreal 4? Or alternatively, is it possible to draw custom geometry directly to the scene in unreal 4 using raw Direct3d?

So far, it seems like I need to make a custom instance of `UPrimitiveComponent` which creates and returns an `FPrimitiveSceneProxy`. In the `FPrimitiveSceneProxy::CreateRenderThreadResources` I can call `RHIGetNativeDevice` and cast its return to `ID3D11Device` and use it to create Direct3D instances, however, I'm not sure where to put my per-frame draw calls.

# Answer
I figured out a way to render to texture.

1. Create a new c++ component that has a `UTextureRenderTarget*` property
2. Create a render target in unreal. I followed the steps in this short tutorial create a render target, but instead of assigning it to the screen capture camera, I assigned it to the component I made in step 1.
3. Call `ENQUEUE_UNIQUE_RENDER_COMMAND_ONEPARAMETER` from `TickComponent` (or some other game thread function). In my case, my queued code just calls a `Render` method on a class that has a pointer to the `UTextureRenderTarget` named `renderTarget`.
4. In my `Render` method, I can access the `ID3D11Texture2D` as follows:

`FTextureRenderTarget2DResource* rtRes = static_cast<FTextureRenderTarget2DResource*>(renderTarget->Resource);
 ID3D11Texture2D* d3dTexture = static_cast<ID3D11Texture2D*>(rtRes->GetTextureRHI()->GetNativeResource());`

Then you can create an `ID3D11RenderTargetView` that maps to the `ID3D11Texture2D` and render. In my case, I got it working by using the `DXGI_FORMAT_R16G16B16A16_FLOAT` and also setting my render target to the equivalent setting in unreal.
> 3 votes

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


# Question
Title: Synchronizing "token" between players(multiplayer)
I am implementing the multiplayer(client-server architecture) of a game, and I came to doubt about entities common to players.

I understand how to share information such as the position of the players among themselves. However I am caught up in the logic of how to do for the common entities between them.

Imagine: Two players and a chicken, how would you share the position of the chicken between them? because it needs to move, and can not move in different places in the two clients, the two clients should see the chicken in the local place, but if I send the position of the chicken of one client, and also the other, there may be conflicts.

What should I do. Choose one of the clients to be the "master" who will send the chicken position to the other players? How do they handle this in online games?

I am thinking of doing the following:

I can not imagine the calculations being done on the server working properly, I will use the example of the hens, my hens would have an AI maybe too complex to stay on the server. I thought the following, one of the clients of the update area, as it is a big map, the clients are receiving updates being in chunks of the map, then one of the clients would be the master (the first one that entered the channel) , the others would just listen to it, the "master" client would then send to the server the chicken positions/states and the server would send to all the clients enrolled in the channel the chicken position/status.

It works similar to a "token" who is at the top of the channel users list is going to deal with the chicken's calculations.

advantages: \- Less work for the server to handle.

Disadvantages: \- Poorly trained players could change the position of the hen and make the game experience unpleasant.

What could you do to avoid this disadvantage?

# Answer
The vast majority of online games handle all game mechanics on the host. The host can be either a dedicated server or it can be the same computer a player is playing on. The situation described in the question, with "an AI too complex to stay on the server", is a very exotic requirement. Most games spend only a very small fraction of their computing resources on game mechanics. The vast majority is used for visualizing them.

But if you are indeed creating a very unusual game where the game mechanics are extremely computational expensive, but their results still small enough to send via network in real-time, then you could distribute the work evenly between hosts. When there are 10 players in the game, have each one manage one tenth of the game world.
> 2 votes

# Answer
From what I have seen so far, the most common approaches for multiplayer are either peer-to-peer connections (with a master client and connecting clients) or a client-server structure.

Regarding client-server, I would say (like Nico) that you should calculate the movement of the chicken on the server, and send the information (calculations) to both connected clients. This way, there is no real client 'owner' as both clients are recieving the data from the server (the server is the owner in this case).
> 1 votes

---
Tags: multiplayer, gameobject, online
---


# Question
Title: How to programmatically place objects in an arc and rotate them?
I have created an arc of circles from the inspector without any issues, but I need to create them programmatically. The image below shows what I'm looking for.

How can I get the positions at which to instantiate them, and how would I easily rotate them around the circle path, so that the arc ends up on the other side of the circle?

# Answer
Positioning those is fairly trivial once you're familiar with circle-math (or trigonometry):

```
int objectCount = 7;
float angle = 90.0f; // Initial angle.
float increment = 180.0f / objectCount;
float radius = <distance from center>;
for (int i = 0; i < objectCount; i++)
{
    // Make sure angle-units match up.
    float x = cos(angle) * radius;
    float y = sin(angle) * radius;

    Vector2 pos = new Vector2(x, y);
    // Instantiate with pos.

    angle -= increment;
}

```

We simply start with an angle, position the object correctly, and then increment the angle correctly. This solution works for any number of objects (well, depending on how you'd want those to be positioned).

For animating these, all you have to do is to update the initial angle value, so for an example, move the `angle` from 90 to 270. This could possibly also be done by rotating a parent object, whose children the balls are, without having to manually reposition the children, which you would have to do if you go with the angle-sliding approach.
> 3 votes

---
Tags: unity
---


# Question
Title: Unity how to have a ghost 3d game object
I want to have a 3d game object (player) who converts to ghost.

That means that the user must not collide with other players, but must not pass walls, trees, and must take care about terrain height levels (I mean, I can't put it as kinematic and remove the collider because the Vector3.MoveTowards which moves the player will ignore the height dimension and will pass the mountains, etc)

My was thinking about tagging the players and in some way try to skip the collider between them.

Any idea? Thanks

# Answer
You can implement this using Layers.

* Create two new layers "Ghost" and "Player".
* Assign the "Ghost" layer to the players who are ghosts.
* Assign the "Player" layer to the players who are not ghosts and to any other objects which are not supposed to interact with ghost players.
* Keep anything which is supposed to interact with players and ghosts equally (like walls, trees and terrain) on the already existing "Default" layer.
* Set the layer collision matrix under *Edit -\> Project Settings -\> Physics -\> Physics Manager* as follows:

+ "Ghost" collides with "Default" but not with "Player" and "Ghost" (unless, of course, you want ghosts to interact with each other)
    + "Player" collides with "Default" and "Player" but not with "Ghost"
> 3 votes

# Answer
You can make use of the Unity collision layer. With this you can tag which layers can collide with which. In the edit you can select that players can not collide with ghosts by untagging the layer for it. You can add a layer for let's say environment\_objects for doors and such with which they collide. Applying the layer to the gameobjects by selecting it will activate the given settings to the layer. I think this will achieve the results you desire.
> 0 votes

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


# Question
Title: How much freedom should my players have regarding naming characters?
I'm currently developing a text based adventure game (original, eh?). I'm not sure how much freedom they should have in character naming.

I've thought of three options:

*Option 1:* Predetermined names for all characters. The player is told of people's names.

*Option 2:* Predetermined names for most characters. They are introduced in certain situations. The player picks their own name, and their best friend's name, etc.

*Option 3:* The player picks everyone's name that they meet. If the person is killed before they are introduced (e.g. if someone is held at gunpoint and you pull the trigger), then their name is not needed to be known.

If you have any better ideas, say them. The easiest would be the first, but the second will make the player feel more involved but I think the third is too much and would become tedious.

# Answer
It depends on the use of the names. If they have a sense of humor or something eye catching about it then I'd go with option 2 as it would feel a bit rewarding to be rewarded a newer "cooler" or "funnier" name. If the names are bland and hold no significance I'd go with option 1.

Option 3 is very interesting though. But depending on the list of names the player would spend a lot time into naming NPC's instead of the actual game (unless that is your goal then go with this option).

Option 2 would give more variaty to names though with different characters having different names as at some point the player would like to use the "unlocked" name. While with option 1 the player would eventually get bored of the list and just pick them at random or name all the same.
> 0 votes

---
Tags: game-design
---


# Question
Title: How to set max string length on my EditorGUI.TextArea?
How to set max string length on a `EditorGUI.TextArea`? A `GUILayout.TextArea` has a `maxLength` property but sadly the editor-version doesn't.

# Answer
This proved to be a bit more tricky that I originally thought. Here is my test code :

```
using UnityEditor;
using UnityEngine;

public class MyWindow : EditorWindow {

   string textAreastring =" ";
    int stringLimit = 3;
   [MenuItem("Test/My Window")]
    static void Init()
    {

        // Get existing open window or if none, make a new one:
        MyWindow window = (MyWindow)EditorWindow.GetWindow(typeof(MyWindow));
        window.Show();
    }

    void OnGUI()
    {
        EditorGUI.BeginChangeCheck();
        textAreastring = EditorGUI.TextArea(new Rect(0, 0, 250, 25), textAreastring);
        if (EditorGUI.EndChangeCheck())
        {
            if (textAreastring.Length >= stringLimit)
            {
                textAreastring = textAreastring.Substring(0, stringLimit);
                GUI.FocusControl(null);
            }
        }

    }
}

```

As you can see the trick is in the `EditorGUI.BeginChangeCheck();` and if `(EditorGUI.EndChangeCheck())`. After we check for a change we can truncate the string anyway we want. Now the problem is this only takes affect when the window looses focus so this is why I put `GUI.FocusControl(null);` at the end. Not the best solution by far but I can only come up with this on the fly. If anyone can figure out a better way please do!
> 0 votes

---
Tags: unity
---


# Question
Title: Entity Component System: system and components relation
I'm planning to develop a game in C# (but I don't think that language matters) and I'll be using Entity Component System since I know by design that my game will have a lot of different game items with different twisted behaviours and logics. I have some experience using Unity ECS which I find very easy and intuitive. I've also programmed games in the past using the old "inheritance approach" and I found that pattern very not scalable.

As far as I know, a pure ECS (which is not what Unity implements) works like this:

> A **GameObject** is just a collection on Components, it may be seen as a wrapper class or as a shared index in some parallel arrays of Components.
>
> A **Component** is a collection of data (basically a record) which holds the data needed by its relative System to handle it. It does not implements game logic itself.
>
> A **System** is a world object which loop through each GameObject which has a component it can process and update game logic of that component.

My point is: if the Systems are the ones responsible for the actual game logic update (practically speaking, the game logic code is written inside the system), is there a **1:1 relation between every component and every system** ? Let me explain with an example: let's say I have 2 components:

* RenderSpriteComponent
* RenderLightSourceComponent

The first one does a simple 2D sprite rendering (using OpenGL or whatsoever); the second one send a light source to the rendering shaders. They do similar operations but with some actual differences. My question is: since they behaviour is different, should I implement two different Systems which will handle them separatly? If not, should I add a bunch of `IF` statements or *overloads* to handle those two components inside the same System?

From my point of view both ways seem unnecessary, especially if the ECS should improve code scalability. Using one of those approach would force me either to **implement a different system** for each component I have (implying a lot of GameObjects loops) or either to fill my Systems with *if* and overloads making them impossibile to understand after a certain point.

Furthermore, from what I can see and understand, Unity implements a different version of this pattern in which every component implements its own logic (in the Update method) and the GameObject is a wrapper class which has an internal list of components to update. Systems don't exist at all (or if they do they do, they do so for other reasons). This implementation looks easier and more "elegant" from my point of view, but I can't understand why it's not so spread and everyone sticks to the "classic" ECS implementation which has those "*problems*" I've described above. At the same time, I do not have control over the priority of the components updates, which can be useful in some cases.

I understand there isn't an "absolute" better way to design your game structure, but I'd like to know how is generaly implemented. Or which factors would make a way better than the other.

# Answer
One of the big reasons some ECS proponents favour a strict separation of components and systems is that it helps architect game functionality in a data-oriented style.

In the ideal data-oriented flow, all your major systems work like particle systems: churning through big batches of data at a time that all need the same kind of operation performed on them. Each of these batch operations can be scheduled to run in a clear dependency order, to minimize doubling-back over the same content when something changes.

When done right, this can make excellent use of the processor's cache, for both instructions (the same few functions are called many times in a row, so you don't have to stall to look up the next step in the process), and data (working through a big batch of contiguous memory in-order means you're fully using the cache lines you pull in instead of taking one item from them and discarding the rest, and the access pattern is easy for the caching systems to predict to keep ahead of the processor).

This is important because one of the biggest bottlenecks in modern PCs is waiting on data that's not in the cache - main memory, fast as it is, just hasn't kept up to increases in CPU speeds & data bandwidth. See this excellent article on data locality for a more in-depth discussion of this topic.

This is in contrast to something like the Unity component system, where your component updates might be interleaved in an almost random order, so lots of memory gets pulled into the cache to be used once, then discarded because a series of unrelated components needed something different, then pulled back in when you get to another component with similar dependencies. In theory, we'd expect this to lead to a lot of CPU time burned waiting for needed memory to come in, though I'm not aware of any specific profiling that shows how much this manifests in typical Unity games.

The advantage of Unity's component-centric approach is that it's easy for even a novice to jump into without thinking deeply about architecture & dependencies, so it's fast to prototype and iterate within. And fortunately, modern hardware makes it "fast enough" for many kinds of games we want to make, on an impressive range of platforms. So I don't want to imply that this is a "wrong" way to do ECS - it's just a style that favours flexibility & expressiveness over absolutely maximizing throughput.

You can also selectively implement a more systems-focused style inside a Unity-style ECS for some subset of behaviour you've deemed to be a bottleneck - assigning one "master" component the role of updating a big batch of components of the same type. Or you could implement a Unity-style component-focused update loop inside a more strict ECS system, using it for gameplay scripts that need more flexibility than your main physics & rendering systems. So it's not an all-or-nothing decision, and many games hybridize these and other ECS strategies to make a style that works best for their developers.

---

Circling back to your earlier question about 1:1 relationships between systems and components: often we'll have a many-to-many relationship instead.

Take for example a Transform component that holds the location/orientation of an object in space.

* Your physics system will want to act on collision representation & rigid body components to compute an updated Transform for each dynamic object
* Your AI & game logic systems will want to query the Transform components of various objects to react to & interact with nearby objects and their gameplay components like health, collectable items, switches, etc.
* Your rendering systems will want to read the final Transform of each object for the frame in order to draw it in the correct place, along with mesh and sprite components to be able to draw the right content for it, and lighting components to shade it correctly.

So here's a single component, shared by many systems, each of which also uses other components too.

One system using multiple component types does not necessarily imply branch-heavy code though: just because the system uses multiple component types does not mean they need to be delivered to it in one big unstructured blob. Your sprite rendering system might first...

* ask for a list of all active sprites to frustum cull,
* then ask for a list of all point lights that might affect them to subdivide them into batches by which lights are in play,
* then ask for a list of all directional lights...

At each stage it's working through a collection of similarly-typed objects, performing similar actions, rather than trying to interleave all of these behaviours based on each component it encounters in some random order.

Some of these stages could be delegated to a distinct system, but you can choose to do that only to the degree that it helps make your code clear and enjoyable to work with - you're not under any strict obligation to define a new system for absolutely every sub-process. As long as the dependency order of each system's tasks are clear, you should be in good shape to get a smooth data-oriented flow, if that's what you're aiming for.
> 8 votes

# Answer
> My point is: if the Systems are the ones responsible for the actual game logic update (practically speaking, the game logic code is written inside the system), is there a 1:1 relation between every component and every system ?

There are few ECS frameworks, like Svelto.ECS (which I wrote), where there isn't a direct correlation between Systems and Components. I first saw this concept in the Ash ECS and I extended it in Svelto.ECS. In Svelto.ECS Entities group components, but Engines know the entities components only through a node mapping. So it would be absolutely wrong to write a System for each component. Usually Systems query entities (and you can get the components from the entities), but with nodes you can do even better.

A similar question was asked before and someone actually gave a very good answer that I now use to save time:

> It is common for "systems" (or "engines" as they are known in svelto) to need to access multiple components per entity. For example an EnemyEngine might need to access a Health component, an Ammo component and a Positioning component. This creates at least a 1-to-many relationship between Engines and Components. (In fact once you share components among several engines that turns into a many-to-many relationship - but only the 1-to-many side of it need be modeled).
> Their solution to this problem is the Nodes concept. They represent that 1-to-many relationship as a Node object and that object might hold several components within it. Then they simply have a 1-to-1 relationship between Engines and Nodes. It also means an Engine need only manage a single object which fully embodies the relevant aspects of an entity.

I wrote a lot of articles about Inversion of Control and how ECS is the definitive pattern to exploit the principle. If you have the time, you may want to have a look a these articles. If you have questions, I will be happy to answer:

//Dissertation on how to exploit the ECS pattern to achieve Inversion of Control

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-i-dependency-injection/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-ii-inversion-of-control/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-iii-entity-component-systems/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-iv-dependency-inversion-principle/

http://www.sebaslab.com/the-truth-behind-inversion-of-control-part-v-drifting-away-from-ioc-containers/

//how my ECS framework works in practice

http://www.sebaslab.com/ecs-1-0/

http://www.sebaslab.com/svelto-ecs-svelto-tasks-new-example-plus-whats-coming-and-optimization-related-thoughts/
> 1 votes

---
Tags: entity-system, entity-component
---


# Question
Title: Is A* efficient even when the obstacles are moving?
I'm just starting to learn about path-finding and have been looking into the A\* algorithm and my main concern is that it all of the examples I have seen show static obstacles that it computes around.

If I have moving obstacles, say other characters for example, moving around as well that the character must find their way around, I'm assuming I'll have to run the algorithm each frame, but I'm worried that will become rather expensive for the hardware to process each frame for each moving actor.

So is A\* still efficient enough to use whenever the obstacles are moving too, or is there another method of path-finding that handles moving obstacles more eloquently?

# Answer
> 27 votes
There are multiple algorithms that are much faster than A\* when you need to recalculate a path with moving obstacles. See here under "Simple Recalculations".

However, you're not likely going to find an off-the-shelf solution for any of them, so in 99% of cases they're overkill for a game. Your time would be better-spent using an existing, fully-optimized A\* solution, and using the common existing tricks for speeding up pathfinding in games:

* Only recalculating the best path in infrequent intervals
* Sharing best-paths among multiple units *(example)*
* Creating a hierarchical graph so you only need to recalculate part of the path

etc. You can find more info about these tricks and more all over this site, or on Amit's A\* pages

# Answer
> 10 votes
Yes. A\* is still the way to go in almost every case. It's your **node cost calculation that becomes dynamic** and therefore more complex to calculate and track.

If you already know where the moving obstacles will be in the future your A\* can take the temporality of obstacles into account in the cost function.

E.g.: This node will be reached in 4 ticks, occupied from tick #3 until tick #6, so travel cost on this node is 6 - 4 = +2 ticks. That may still be the best path.

The travelling direction of the obstacle also has to be taken into account.

If you don't know in advance then you can assume no obstacles and recalculate the path when obstacles are reached but you will need to do something about deadlocks and livelocks. (The same applies if you can predict where obstacles will be but that in itself is a type of deadlock/livelock avoidance and that can be good enough for your purpose.)

A deadlock is when both wait for the other to move and none move.

A livelock is when both (**or more** \<- this is important to consider) move to avoid the other in the same direction and end up going back and forth with no progress.

Solving livelocks can become very complex and that depends entirely on your game's collision rules and mechanics (e.g.: should they fight and destroy the obstacle?).

It often comes back to having your moving objects schedule node/path reservations (don't forget cancellations when they change path or die) so other moving objects can plan ahead.

Once you have this information you can also plan interceptions.

---
Tags: algorithm, path-finding, memory-efficiency
---


# Question
Title: What could I use to search tiles in a game
I'm creating a tile based game similar to Minesweeper. When a user clicks on a tile and its not a mine or a number space I need to search and expose the adjacent tiles that are empty and stop when it hits a number or the edge of the board. I have it working right now so that it will clear the row of the tile clicked and stop at a numbered tile or the edge of the board. What I have is going to get ugly quickly and I am sure there is a easier way of doing this. Is there a searching algorithm I can use that will find all adjacent tiles to the one the player click only stopping once it hits the edge of the board or hit a numbered tile?

# Answer
> 2 votes
The search algorithm you're looking for is called Flood Fill

Every empty tile is colour A. Every non-empty tile is colour B. Then you apply the flood fill with the modification that you also stop filling in that direction when there's an adjacent non-empty tile.

Alternatively: every empty-with-no-adjacent-non-empty tile is colour A, all the others colour B, and you apply a flood fill then enlarge the filled area mask by 1 tile in all directions.

---
Tags: algorithm, unreal-4, search, minesweeper
---


title: Bike game - following a road path

text:
# Question
Title: Bike game - following a road path
I am writing a game in java which has a bike riding down a road. I intend to add some obstacles on the road which are structures having a slope, which the biker must negotiate. In other words, the bike must climb and run along the slope whenever it encounters one so obviously it must be aligned accurately with the slopy path. Im currently doing this using trig functions to find the angle of rotation, x y coordinates for the bike when it is climbing, descending etc. Can someone suggest a better algorithm to achieve this please ?

# Answer
I don't' think you can avoid the trig really, but what you can do is improve just how you calculate the angle.

Your question mentions the "x y coordinates for the bike", but in fact the bike doesn't have one coordinate. It has two coordinates - the two wheels.

Specifically, don't base it on the bike's location and a single point. If you use just a single fixed point (like at the bike middle), it's not going to work when the bike first crosses into a slope - the bike's front wheel won't tip up until the mid point crosses onto the slope.

Here's a picture of what it will look like if you calculate from the middle and just enter a slope...

Instead, calculate the rotation based on where the front and back wheels touch the ground. Calculate Y at back wheel, then Y at front wheel, then what the angle is between the two points. Then you can make it work with uneven ground, and the motion will be a lot more believable, and will look like this...

This also will let you handle smaller bumps nicely. Based on wheel to wheel slope, you'll actually have your bike front wheel go over the bump, come down the other side, then have the rear wheel go over it. Calculating based on one point (middle of bike), you'll get this...

But calculating based on the bike wheels, you'll get this...
> 2 votes

# Answer
That's more or less how I would do it too. One thing you can try is to have the ground pieces contain a normal vector that you can quickly query to align the bike to the slope.

---

Vector normalization is mostly used when you want the vector to have a length of 1. Another use is if you want the vector to have a specific length then you would normalize the vector which guarantees the vector has a length of 1 and then multiply by the number you want it's length to be.
> 0 votes

---
Tags: movement, path
---


title: Moving object with preset timelapse

text:
# Question
Title: Moving object with preset timelapse
I am a newbie game developer.

I have one problem. Consider the following case.

I have a simple game with only one object - a ball. A ball can move only up and down from one side to another.

A User is allowed to set the game time and ball iteration count. An iteration is when the ball goes up to the topmost point and goes back to the bottommost point.

It should complete all iterations for the time user has set.

Here is an example.

Consider that a user has set the game time to **60** seconds, and the ball iterations option to **30**.

We can find how much time do we have for an iteration **60/30 = 2** seconds. So the ball should complete the iteration for two seconds.

Let's assume we have a known frame rate and it is **30ms** (update and drawing). So a single loop iteration takes **2000ms**.

Next find iterations per a complete ball movement **2000/30 = 66** iterations. Also let's imagine that a distance from one side to another is **2000px**.

So the ball need to complete **4000px** per iteration.

Finally we can find out our movement delta **4000px/66 = 60 px** . So ball will move 60px per a loop iteration.

But what to do if I don't frame rate, but what is more interesting what to do when the framerate is not static and we need to correlate it every time.

Please suggest an algorithm or an approach to solve this problem.

It seems that there should be a function, that will calculate position of a ball by the time passed from the game start, like sin (because ball is bouncing)

Thanks.

# Answer
> 0 votes
This is usually called a "time step"

One simple way to handle this is to track the total \[game\] time elapsed since the start of the game. Then you can find how much time the current frame needs to account for with a simple subtraction:

```
currentTime = GetTimeSinceStartup();
realDeltaTime = currentTime - lastFrameTime;
lastFrameTime = currentTime;

```

This "delta time" (often abbreviated `dt` or `dT`) represents the time that's passed since the previous frame - often in units of seconds for convenience.

(Note that subtracting two floating point numbers very similar in value can cause "catastrophic cancellation" leading to precision loss, so consider using an integer or double-precision type for your time since startup. Your `deltaTime` can safely use single-precision)

You can also combine your delta time with a multiplier between zero and one, to make the game run in slow-mo, or pause updates when a menu is displayed.

```
gameDeltaTime = realDeltaTime * gameSecondsPerRealSecond;

```

Now you can scale your game updates by this value:

```
myPosition += myMovementSpeedPerSecond * gameDeltaTime;

```

Or for something like your bouncing ball:

```
phase += gameDeltaTime * cyclesPerSecond * 2f * PI;
myPosition = new Vector2(0, sin(phase) * (ceiling - floor)/2f + floor);

```

Note that many games combine both a variable time step like we've calculated above - for smooth visual animations - and a fixed time step that's always the same in each update (the game just runs more or fewer updates depending on how much time it needs to account for). This can make it easier to control the results of the game simulation and scale the game to different hardware without changing the experience.

---
Tags: 2d, physics, mathematics, game-loop
---