# Question
Title: Is it worthwhile to use particle pools in managed languages?
I was going to implement an object pool for my particle system in Java, then I found this on Wikipedia. To rephrase, it says that object pools aren't worth using in managed languages like Java and C#, because allocations take just tens of operations as compared to hundreds in unmanaged languages like C++.

But as we all know, every instruction may hurt game performance. For example, a pool of clients in an MMO: the clients won't enter and exit the pool too fast. But particles may get renewed tens of times in a second.

The question is: **is it worth it to use an object pool for particles (specifically, those that die and get recreated fast) in a managed language?**

# Answer
> 14 votes
Yes, it is.

Allocation time isn't the only factor. Allocation can have side-effects, such as inducing a garbage collection pass, which can not only impact performance negatively it can also impact performance unpredictably. The specifics of this will depend on your language and platform choices.

Pooling also generally improves locality of reference for the objects in the pool, for example by keeping them all in contiguous arrays. This can improve performance while iterating the contents of the pool (or at least the live portion thereof) because the next object in the iteration will tend to already be in the data cache.

The conventional wisdom of trying to avoid any allocations whatsoever in your innermost game loops still applies even in managed languages (especially on, for example, the 360 when using XNA). The reasons for it just differ slightly.

# Answer
> 1 votes
For Java it's not so helpful to pool objects\* since the first GC cycle for objects still around will reshuffle them in memory, moving them out of "Eden" space and potentially losing spatial locality in the process.

> * It is always useful in any language to pool complex resources which are very expensive to destroy and create like threads. Those can be worth pooling because the expense of creating and destroying them has almost nothing to do with the memory associated with the object handle to the resource. However, particles do not fit this category.

Java offers fast burst allocation using a sequential allocator when you rapidly allocate objects into Eden space. That sequential allocation strategy is super fast, faster than `malloc` in C since it's just pooling memory already allocated in a straight sequential fashion, but it comes with the downside that you can't free individual chunks of memory. It's also a useful trick in C if you just want to allocate things super fast for, say, a data structure where you don't need to remove anything from it, just add everything and then use it and toss the whole thing away later.

Because of this downside of not being able to free individual objects, the Java GC, after a first cycle, will copy all the memory allocated from Eden space to new memory regions using a slower, more general-purpose memory allocator that does allow memory to be freed in individual chunks in a different thread. Then it can toss away the memory allocated in Eden space as a whole without bothering with individual objects which have now been copied and live elsewhere in memory. After that first GC cycle, your objects can end up being fragmented in memory.

Since the objects can end up being fragmented after that first GC cycle, the benefits of object pooling when it's primarily for the sake of improving memory access patterns (locality of reference) and reducing allocation/deallocation overhead are largely lost... so much so that you'll get better locality of reference typically by just allocating new particles all the time and use them while they're still fresh in Eden space and before they become "old" and potentially scattered in memory. However, what can be extremely helpful (like getting performance rivaling C in Java) is to avoid using objects for your particles and pool plain old primitive data. For a simple example, instead of:

```
class Particle
{
    public float x;
    public float y;
    public boolean alive;
}

```

Do something like:

```
class Particles
{
    // X positions of all particles. Resize on demand using
    // 'java.util.Arrays.copyOf'. We do not use an ArrayList
    // since we want to work directly with contiguously arranged
    // primitive types for optimal memory access patterns instead
    // of objects managed by GC.
    public float x[];

    // Y positions of all particles.
    public float y[];

    // Alive/dead status of all particles.
    public bool alive[];
}

```

Now to reuse memory for existing particles, you can do this:

```
class Particles
{
    // X positions of all particles.
    public float x[];

    // Y positions of all particles.
    public float y[];

    // Alive/dead status of all particles.
    public bool alive[];

    // Next free position of all particles.
    public int next_free[];

    // Index to first free particle available to reclaim
    // for insertion. A value of -1 means the list is empty.
    public int first_free;
}

```

Now when the `nth` particle dies, to allow it to be reused, push it to the free list like so:

```
alive[n] = false;
next_free[n] = first_free;
first_free = n;

```

When adding a new particle, see if you can pop an index from the free list:

```
if (first_free != -1)
{
     int index = first_free;

     // Pop the particle from the free list.
     first_free = next_free[first_free];

     // Overwrite the particle data:
     x[index] = px;
     y[index] = py;
     alive[index] = true;
     next_free[index] = -1;
}
else
{
     // If there are no particles in the free list
     // to overwrite, add new particle data to the arrays,
     // resizing them if needed.
}

```

It's not the most pleasant code to work with, but with this you should be able to get some very fast particle simulations with sequential particle processing being very cache-friendly always since all the particle data will always be stored contiguously. This type of SoA rep also reduces memory usage since we don't have to worry about padding, the object metadata for reflection/dynamic dispatch, and it splits hot fields away from cold fields (for example, we're not necessarily concerned with data fields like a particle's color during the physics pass so it'd be wasteful to load it into a cache line only to not use it and evict it).

To make the code easier to work with, it might be worth writing your own basic resizable containers that store arrays of floats, arrays of integers, and arrays of booleans. Again you can't use generics and `ArrayList` here (at least since the last time I checked) since that requires GC-managed objects, not contiguous primitive data. We want to use contiguous array of `int`, e.g., not GC-managed arrays of `Integer` which won't necessarily be contiguous after leaving Eden space.

With arrays of primitive types, they're *always* guaranteed to be contiguous, and so you get the extremely desirable locality of reference (for sequential particle processing it makes a world of difference) and all the benefits that object pooling is intended to provide. With an array of objects, it is instead somewhat analogous to an array of pointers which start out pointing to the objects in a contiguous fashion assuming you allocated them all at once into Eden space, but after a GC cycle, can be pointing all over the place in memory.

---
Tags: performance, design-patterns, particles
---


title: Unity 2d how to stop infinite jump

text:
# Question
Title: Unity 2d how to stop infinite jump
So my problem is very common but as far I am able to find tutorial on how to stop game object to do infinite jump is make a bool then set if y velocity == 0 then set bool to true else its false but doing this makes object movement very jittery , so what is most efficient and pro ways= to make object stop jumping infinitely?

I m using Rigidbody2d not CC so isgrounded is not applicable

```
if (Input.GetKey(KeyCode.D))
{
    Vector2 velocity = box.velocity;
    velocity.x = Xvelocity;
    box.velocity = velocity;
}
if (Input.GetKey(KeyCode.A))
{
    Vector2 velocity = box.velocity;
    velocity.x = -Xvelocity;
    box.velocity = velocity;
}
if (Input.GetKey(KeyCode.W))
{
    if (toJump)
    {
        Vector2 velocity = box.velocity;
        velocity.y = Yvelocity;
        box.velocity = velocity;
    }
}

if (box.velocity.y < 0f)
{
    Vector2 velocity = box.velocity;
    velocity.y = -gravity;
    box.velocity = velocity;
}
if(box.velocity.y == 0f)
{
    toJump = true;
}
else
{
    toJump = false;
}

```

# Answer
> 1 votes
Ok, so, a few things:

1) You should be using `Input.GetButton()` and `Input.GetButtonDown()`, this allows players to modify their keybindings (what if they want to use IJKL instead of WASD?)

2) This code:

```
if (box.velocity.y < 0f)
{
    Vector2 velocity = box.velocity;
    velocity.y = -gravity;
    box.velocity = velocity;
}

```

This doesn't make sense. If the player's falling (velocity y is negative) you set their velocity to `negative gravity` which is either going to make them go up again (which is not good) or is going to replace their downward velocity--whatever it is--*with* a gravitational speed, making their fall *linear* (also not good). In either case you're enforcing this instead of letting the physics engine Do Its Thing.

3) y-velocity of 0 is not indicative of being grounded. At the top of the player's jump, y-velocity will *also* be zero. And this is ignoring the problem of floating point values hardly ever equaling anything. You should be using some kind of raycast or overlap check to see if your character is standing on something instead.

4) It is unclear if this code is in `Update()` or `FixedUpdate()` (it should probably be in the latter)

5) You should probably be using `MovePosition()` for your left/right walking code.

# Answer
> 0 votes
To build upon Draco's answer a little bit, when using a Rigidbody of any kind (2D or otherwise) it tends to be better practice to use the built in Physics functions, such as Rigidbody2D.AddForce() and Physics2D.Raycast() in this case which is basically the two main functions used by the Character Controller Asset.

In the case of stopping "Infinite Jump" using a Raycast will do the trick. The following function can be called whenever the character attempt to jump, it will return true if the ground is under the character and false if not allowing for it to only jump when it hits the ground. Make sure to put this check within `FixedUpdate()` as it is a physics function.

```
/// <summary>
/// Check if the Character is Grounded using a Raycast. Passing the Distance from the Center of the Character and the tag name of the ground
/// </summary>
/// <param name="rayDistance"></param>
/// <param name="groundLayerName"></param>
/// <returns></returns>
private bool IsGrounded2D(float rayDistance, string groundLayerName)
{
    //Can be used to visualize the Ray from scene view
    Debug.DrawRay(transform.position, -Vector2.up * rayDistance, Color.red);

    //Use a Raycast down from the Character to find any object of the Ground Layer
    //This also requires the distance from where the ray starts to the bottom of the Character
    RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, rayDistance);

    if (hit.collider && hit.collider.tag == groundLayerName)
        //If it hits, return true
        return true;

    //else return false
    return false;
}

```

This requires the ground to have a tag on it you can parse to the function to detect the correct object. Alternatively you could use Layer detection within the `Raycast` but its really up to you.

Remember that this will work for detecting `Collider2D` components, if you want to detect a 3D object your will be required to change it to do `RaycastHit` and `Physics.Raycast` instead.

As a bit of a side note from the question. When using the Rigidbody it would be better to use something similar to the following in order to control the left and right movement of the character, this will allow for it to be used in both a PC and Controller environment by using force and input which will not add any jitter to the movement.

```
[RequireComponent (typeof(Motor))]
public class Player : MonoBehaviour
{
    private Motor motor;

    private void Start()
    {
        motor = GetComponent<Motor>();
    }

    void Update()
    {
        motor.HorizontalInput = Input.GetAxisRaw("Horizontal");
    }
}

[RequireComponent (typeof(Rigidbody2D))]
public class Motor : MonoBehaviour {

public float speed;
public float jumpForce;

private float horizontalInput;
private Rigidbody2D rigidBody;

private void Start()
{
    rigidBody = GetComponent<Rigidbody2D>();
}

/// <summary>
/// Use Fixed Update for Physics Math
/// </summary>
private void FixedUpdate()
{
    //Add a force depending on the input value (Between -1 for left an 1 for right) and times it by the required character speed.
    //This will allow the User to ramp up their own speed with a controller but also allow the character to slow itself down.
    rigidBody.AddForce((Vector2.right * horizontalInput) * speed);

    //Check if the character is grounded
    if (IsGrounded2D(0.5f, "Ground"))
    {
        //Add Force to make the character jump
        rigidBody.AddForce(Vector2.up * jumpForce);
    }
}

/// <summary>
/// Check if the Character is Grounded using a Raycast. Passing the Distance from the Center of the Character and the tag name of the ground
/// </summary>
/// <param name="rayDistance"></param>
/// <param name="groundLayerName"></param>
/// <returns></returns>
private bool IsGrounded2D (float rayDistance, string groundLayerName)
{
    //Can be used to visualize the Ray from scene view
    Debug.DrawRay(transform.position, -Vector2.up * rayDistance, Color.red);

    //Use a Raycast down from the Character to find any object of the Ground Layer
    //This also requires the distance from where the ray starts to the bottom of the Character
    RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, rayDistance);

    if (hit.collider && hit.collider.tag == groundLayerName)
        //If it hits, return true
        return true;

    //else return false
    return false;
}

/// <summary>
/// Set the Horizontal Input and Clamp it between -1 for left and 1 for right
/// </summary>
public float HorizontalInput
{
    get
    {
        return horizontalInput;
    }

    set
    {
        horizontalInput = Mathf.Clamp(value, -1, 1);
    }
}

```

This typically requires you to split your `Character` script into a `Motor` and `Character` script as the `Motor` just controls any movement whilst the `Character` tells it what to do (useful if you want to get into AI).

Sorry about the long answer and maybe some unneeded information just a bit of a tip.

---
Tags: unity, physics
---


title: Turning off Perspective Divide

text:
# Question
Title: Turning off Perspective Divide
Is there a way, in OpenGL, to switch off the automatic perspective divide? I'd like to see the effect a perspective projection has by itself.

# Answer
You can "turn off" the perspective divide easily enough by putting 1.0 in the `W` component of `gl_Position`. However, I don't think you fully understand what this will do.

Perspective projection is based on doing such a division. Simply removing that math from the equation, while still using a perspective projection matrix, will not yield reasonable results.

So merely "turning off" the division will not allow you to "see the effect a perspective projection has by itself". It will create a generally nonsensical mess of triangles.

What you probably want to do is switch to using an orthographic projection instead of a perspective projection. That is a matter of what projection matrix you use.
> 2 votes

---
Tags: opengl
---


title: Game Engine & Language for beginners?

text:
# Question
Title: Game Engine & Language for beginners?
It would be great if someone who is experienced at game development would give me some insight and advice about game development. I'm studying computer science for 2 years now and game development is my biggest interest. Which is the best engine and programming language to start on? For indie game development, what engine would you recommend. I've been using Unity and C# for a month but I don't know if its the best option. Some tips or guidance on the topic would be thanked!

# Answer
I'd recommend GameMaker. It's simple to use, but can do pretty well as your demands go up. It's not a high end, super fancy 3D game engine, but that's not what making games is about necessarily.

Personally I'd start with a 2D style of game - something simple, like a side scroller or top down view game. You'll learn a lot about the development and design, and then later you can move into 3D if you'd like. GameMaker can handle 3D, but if you want to go "fancy", you can move up to Unity.

The other suggestion I might make is to look into modding. Get HalfLife 2, and start reading up on how to create mods for it. Modding lets you leverage all the art and other resources that companies like Valve have made and shared, while using a decent game engine. You can put your time into just level design if you'd like, or modelling and art (2D textures, 3D models), or even coding to extend the game if you'd like.
> -3 votes

# Answer
In my opinion Unity3D is the best game engine, it has very good tools and optimization settings, I totally agree with you it’s a bit hard to learn “, but it can give you large area of options , if you seriously interested in GameDev but you don’t want to write your own engine , Unity3d would be the best one.
> -3 votes

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


title: Player Movement

text:
# Question
Title: Player Movement
I started developing games recently, teaching myself using a german book about C++ and Direct3D 9.

The author states, player movement should be implemented using a time delta, like this

```
player.position.x += time.delta * movementFactor

```

as opposed to an implementation without incorporating the time passed since last frame; i.e like this

```
player.position.x += movementFactor

```

Latter solution would cause other players to move faster, since the expression above would be executed more often on faster CPUs. (More explanation on Tayacan's answer below)

Is there any other solution to this problem?

---

**Old, poorly phrased question I wrote when I was young**:

> I'm reading on a Book that's about Gamedevelopment with C++ and DirectX 9.
>
> There is something that interrests me: It says that playermovements are increasing with the power of the CPU. Becouse a faster CPU will move the player with every frame ( better CPU = better FPS ) To bypass it, it says you have just to multiplicate time\*movementfactor .
>
> I'd like to know is there an another way to bypass it ?

# Answer
Why do you want another way? The one you describe is what you'd use in any kind of game development, whether or not you use DirectX.

The problem is this: In (most) games you have a main loop. This loop runs as fast as the hardware allows. However, people use different hardware, so on some computers, this will be faster than on others. So in order to make an object in a game move with the same speed on any hardware, you multiply the movement vector with the time, in seconds, since last time the loop was run. This also has the benefit that if you're moving the object, say, `5 * time` units in some direction, that's the same as saying "move it 5 units/seconds".
> 2 votes

# Answer
If you need another way, there is an another way, as mentioned by DMGregory too. In main loop where an update is called after every frame, you can make your fixed update function which should be called after every fixed interval of time. Many games (I think all multiplayer games) uses this concept. As it's called after a fixed interval so you don't have to worry about time.delta and just make your movement factor according to that fixed time interval and you are good to go.
> 1 votes

---
Tags: c++, physics, game-loop, timestep
---


# Question
Title: OpenGL ES 2.0 Shadow Mapping - depth only FBO not working due to GL_FRAMEBUFFER_INCOMPLETE_ATTACHMEN
I am trying to add simple shadow mapping to my friends gles 2.0 app. It is based on gles 2.0 and PowerVR SDK.

The problem I encounter is that FBO is not valid due to GL\_FRAMEBUFFER\_INCOMPLETE\_ATTACHMEN (0x8CD6) error checked with glCheckFramebufferStatus() function.

I also checked call to glTexImage2D() function with glGetError() and it returns GL\_INVALID\_OPERATION (0x0502).

Here is my code:

```
GLuint framebuffer;
glGenFramebuffers(1, &framebuffer);
glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);

GLuint depthTexture;
glGenTextures(1, &depthTexture);
glBindTexture(GL_TEXTURE_2D, depthTexture);

GLenum error = glGetError(); // no error
// I tried also various combination of GL_DEPTH_COMPONENT16 formats and internal formats
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);
error = glGetError(); // GL_INVALID_OPERATION (0x0502) error

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);

GLenum framebufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);

if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
{
    GLenum framebufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); // GL_FRAMEBUFFER_INCOMPLETE_ATTACHMEN(0x8CD6)
    printf("Invalid framebuffer\n");
}

```

I have no idea what is wrong. I tested in on integrated Intelu GPU and Nvidia 1080 Ti GPU so this in probably not a driver bug.

# Answer
> 4 votes
You will need to implement multiple alternative solutions depending on the GPU.

Not only are there many choices (GL\_DEPTH\_COMPONENT16, GL\_DEPTH\_COMPONENT24, GL\_DEPTH\_COMPONENT32, GL\_DEPTH\_COMPONENT32F, and GL\_DEPTH24\_STENCIL8, GL\_UNSIGNED\_INT\_24\_8\_OES) every GPU has different levels of support and fallbacks must be implemented.

It is possible the GPU does not support depth textures at all and you'll have to encode depth into a color texture.

You must check for presence (or absence) of the GL\_OES\_depth\_texture extension and other extensions.

In case it is missing you must render the depth to a color texture and use a regular depth buffer (not a depth texture) to do your depth testing while drawing the depth values to a color texture. This is wasteful but the only way some GPUs can do it.

The most likely supported values for a depth texture would be `glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0);`

(Don't forget the **GL\_UNSIGNED\_SHORT**: the driver may not accept GL\_FLOAT and you're not sending any values anyway.)

Make sure to call `glBindTexture (GL_TEXTURE_2D, 0);` **before** calling `glFramebufferTexture2D`.

You can't have the texture bound to both the framebuffer and a texture unit at the same time and the driver may see this as an error even if you unbind the texture later before rendering.

To create a depth buffer instead use:

```
        glGenRenderbuffers(1, &depth_buffer);GL_ERROR_CHECK;
        if(depth_buffer){
            glBindRenderbuffer(GL_RENDERBUFFER, depth_buffer);GL_ERROR_CHECK;

            glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height);GL_ERROR_CHECK;

            glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depth_buffer);GL_ERROR_CHECK;
        }

```

You can encode the depth as an RGB value (for example: `r = depth; g = fract(depth * 256);` ) and write those to a color texture also attached to the same frame buffer. Then decode those values back into a depth value when reading the color texture `depth = r + (g * (1.0/256.0));`

The shadow test will then have to be done as shader code rather than using a depth sampler. You may need to tweak the encoding due to the (de)normalisation of the color values.

# Answer
> 0 votes
You have to tell OpenGL that you are not going to use the color component by calling `glDrawBuffer(GL_NONE);`. So, the updated code would look like this:

```
...
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
glDrawBuffer(GL_NONE);

GLenum framebufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
...

```

That should complete your framebuffer attachments!

If it does not, it could be that your current framebuffer configuration is not supported for whatever reason. You could try if a combined depth-stencil-buffer would work:

```
...
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_STENCIL, 1024, 1024, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, 0);
...
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, depthTexture, 0);
glDrawBuffer(GL_NONE);
...

```

# Answer
> 0 votes
To solve this problem I must use normalized unsigned integer (or short ) for depth texture type: GL\_UNSIGNED\_INT

```
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, 1024, 1024, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, 0);

```

I am not sure why Nvidia drivers doesn't support floating point depth buffer, still, everything works now.

---
Tags: opengl-es, opengl-es2, depth-buffer, shadow-mapping, frame-buffer
---


# Question
Title: Recognising when a user is clicking below a particular sprite
I have a game, built using pixi.js, where I want to run some code every time the user presses below a certain sprite. I am handling the press event using hammer.js. The problem is that the y attribute of the sprite and the y attribute of the user’s touch event don’t match what I can see on my screen.

As, an example, consider the code below:

```
if (touchPointer.clientY > this.children.marker1.position.y) {
  console.log("******* Clicked Below the Line ********: ");}
else{
  console.log("******* Clicked Above the Line ********: ");}

```

The problem I have is that, when I click slightly above the sprite, the first section of code will run (which prints “Clicked Below the Sprit”), even though on the screen, I can clearly see the pointer is above the sprite. I am guessing, what’s going on is that the y positions for the pointer and the sprite are being calculated differently, but I don’t know how to go about ensuring they’re calculated consistently, so I can properly compare sprites against the pointer. Any suggestions?

# Answer
> 0 votes
The coordinates of the mouse/touch are in screen coordinates. To translate to world coordinates, you need to convert to world coordinates by adjusting for the current transform and rotation of your camera.

# Answer
> -1 votes
Instead of using

```
this.children.marker1.position.y

```

I used

```
this.children.marker1.worldTransform.ty

```

and then it worked properly.

---
Tags: javascript
---


# Question
Title: Can not connect HTC Vive headset - Steam VR plugin error Failed to load IVRRenderModels
When I add SteamVR plugin I receive error Failed to load IVRRenderModels interface version IVRRenderModels\_005.

The plugin works for my other projects, camera and controllers are detected and work fine.

# Answer
> 1 votes
I did a few things:

First was to try this answer.

Editing the settings file worked OK. It removed the error message and kicked Steam to stay open, but my cameraRig was still not connecting to the headset in the imported scene and in the project it was coming from.

In the end I copied a camera object tree from working scene - one combining VRTK + steamVR cameraRig and it connected

Reconstructing camera object in Other scenes with problems works again too.

In the meantime I updated Viveport, changed back and forth usb ports, rebooted headset, restarted pc, removed and re-imported SteamVR plugin and VRTK and many others.

Hope my experience helps someone else too.

---
Tags: unity, camera, steam, htc-vive
---


# Question
Title: How to rotate an object around one end of line till its lies on the line
From the image below, I would like to rotate a game object C around a point A of a line (made using a line renderer) by an angle d to position p1 till C is on the same line joining points A and B over a given period of time. Preferably using a coroutine. Please note that the angle d is not known. How can I achieve this?

# Answer
> 0 votes
Try the following script :

```
using UnityEngine;
using System.Collections;

public class RotateScript : MonoBehaviour
{
    public float rotationSpeed;

    public void StartAlign( Vector3 pointA, Vector3 pointB )
    {
        StartCoroutine( Align(pointA, pointB) );
    }

    private IEnumerator Align( Vector3 pointA, Vector3 pointB )
    {
        // Compute the rotation axis
        Vector3 axis = Vector3.Cross( pointB - pointA, transform.position - pointA );

        // Compute the rotation angle
        float totalAngle = -Vector3.SignedAngle(pointB - pointA, transform.position - pointA, axis );
        float sign = totalAngle < 0 ? -1 : 1;
        float angle = 0;

        // Rotates smoothly the object
        for ( float cumulativeAngle = 0 ; sign * cumulativeAngle < sign * totalAngle ; cumulativeAngle += angle )
        {
            angle = sign * Mathf.Min( sign * (totalAngle - cumulativeAngle), Time.deltaTime * rotationSpeed );
            transform.RotateAround( pointA, axis, angle );
            yield return null;
        }
    }

}

```

---

If your `pointC` must be a vector, try the following script:

```
using UnityEngine;
using System.Collections;

public class RotateScript : MonoBehaviour
{
    public float rotationSpeed;

    // This is an example function to show how StartAlign must be called
    // The last parameter must be a function taking a Vector3 as only parameter
    public void Foo()
    {
        StartAlign( pointC, pointA, pointB, OnPointCChanged );
    }

    public void StartAlign( Vector3 pointC, Vector3 pointA, Vector3 pointB, System.Action<Vector3> SetNewPointCPosition )
    {
        StartCoroutine( Align( pointC, pointA, pointB, SetNewPointCPosition ) );
    }

    private IEnumerator Align( Vector3 pointC, Vector3 pointA, Vector3 pointB, System.Action<Vector3> SetNewPointCPosition )
    {
        // Compute the rotation axis
        Vector3 direction = pointC - pointA;
        Vector3 axis = Vector3.Cross( pointB - pointA, direction );

        Quaternion startRotation = Quaternion.identity;
        Quaternion endRotation = Quaternion.FromToRotation( direction, pointB - pointA );

        Debug.Break();

        // Rotates smoothly the object
        for ( float time = 0 ; time < 1 / rotationSpeed ; time += Time.deltaTime )
        {
            Quaternion rotation = Quaternion.Slerp( startRotation, endRotation, time * rotationSpeed );
            Vector3 d = rotation * direction;
            SetNewPointCPosition( d + pointA );

            yield return null;
        }
    }

    private void OnPointCChanged( Vector3 newPosition )
    {
        Debug.Log( newPosition );
    }
}

```

# Answer
> 0 votes
The signed angle between two 2d vectors A and B is

```
angle = atan2(-B.y * A.x + B.x * A.y, B.x * A.y + B.y * A.y)

```

If you have a signed angle between the point and the line, then rotating the former towards the latter is as simple as checking for the sign of the angle. If it's positive, then subtract from the current angle. If it's negative, then add to it.

In code (`step` is the angle the point rotates in one frame):

```
IEnumerator Rotate(Vector2 A, Vector2 B) {
    float angle;
    do {
        angle = Mathf.atan2(-B.y * A.x + B.x * A.y, B.x * A.y + B.y * A.y);
        if (angle < 0) {
            // Rotate the point by 1 step in the positive direction
        } else {
            // Rotate the point by 1 step in the negative direction
        }
    } while (angle > step);
    // Set the angle of the point to the angle of the line
}

```

---
Tags: unity
---


# Question
Title: How to make a boss control multiple object spawners in Game Maker Studio 2
I'm working on a boss fight for a 2D platformer/shooter game in the vein of the Megaman franchise. I expect part of the fight to include this boss causing large boulders to fall from certain points on the ceiling to possibly crush the player, which serve both as an attempt to harm the player and a possible means by which the player may harm the boss. I am having some difficulty, however, with conceptualizing how to tie these randomly-falling rocks to an action on the boss's part. I can make spawner objects to drop the boulders when prompted, my issue mainly lies in how to give the boss object the ability to trigger this action, especially given there will be several such spawners in the level, which may be selected at random.

Are there any functions or techniques that may be useful in allowing a single "boss" object to trigger one or more of a set of other "spawner" objects as a part of an action the "boss" takes, rather than simply automating the spawners to work on their own timing?

# Answer
For ways to let him trigger actions on his own, try using gamestates.

Game states is an form of using enums that describes different kinds of movement or actions. by using a switch statement to seperate the gamestates and a timer to change the gamestates, you can give your boss patterns on his own.

To give an example of a timer-based gamestate:

In the Create Method:

```
int timer = 0;
public enum GameState
{
     MOVE,
     THROWROCKS
     STANDSTILL,
};
GameState gameState = GameState.MOVE;

```

And in the Step method:

```
public void Update
{
    timer -= 1;
    switch (gameState)
    {
        case MOVE:
        {
            //moves
            if (timer <= 0)
            {
                timer = 10;
                gameState = GameState.THROWROCKS;
            }
            break;
        }
        case THROWROCKS:
        {
            //do another action
            if (timer <= 0)
            {
                timer = 10;
                gameState = GameState.THROWROCKS;
            }
            break;
        }
    }
}

```

This is just a raw example to explain properly what I mean, try playing around and see if this can fit you.

(I remember this better from XNA experience than Gamemaker, but they almost work the same way, so be aware that a few parts might work differently in GML, it's mostly to show an example)
> 1 votes

---
Tags: game-maker, gameobject
---


# Question
Title: Issue giving object player's hand position
I'm trying to put an object (for example a sword) in my player's hand. To do so i set the player's hand transform as the object's parent, in order to have the same movement for the object and the hand. No problem here.

The real issue starts as soon as i set the sword position to the hand position. My player starts to move backward.

One of my doubt was that my sword has a rigid body and my player too, so it could have an impact on it because I know that you can set a rigid body as a rigid body child.

So I was wondering if it's the right way to do it.

**Edit**

Here is my script to pickup an item:

```
 public void PickupItem()
    {
        Ray interactionRay = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit interactionHit;

        if (Physics.Raycast(interactionRay, out interactionHit, InteractionMaxDistance))
        {
            if (interactionHit.collider.tag == "LootableItem")
            {
                Item item = interactionHit.collider.gameObject.GetComponent<Item>();
                GetComponent<CharacterStats>().AddStats(item.Stats);

                _hand = TransformUtil.FindChild("mixamorig:RightHandMiddle1", _player);
                item.GetComponent<Rigidbody>().isKinematic = true;
                item.GetComponent<Rigidbody>().useGravity = false;

                item.transform.parent = _hand;
                item.transform.position = _hand.position;
                item.transform.rotation = _hand.rotation;
            }
        }
    }

```

My script for player movement :

```
void Update()
    {
        float translation = (Input.GetAxis("Vertical") * Speed) * Time.deltaTime;
        float rotation = (Input.GetAxis("Horizontal") * RotationSpeed) * Time.deltaTime;
        transform.Translate(0, 0, translation);
        transform.Rotate(0, rotation, 0);

        if (Input.GetButtonDown("Jump"))
        {
            _animator.SetTrigger("triggerJump");
            return;
        }

        if (Math.Abs(translation) < 0.01 && Math.Abs(rotation) < 0.01)
        {
            Speed = 1;
        }
        else
        {
            if (Input.GetKey(KeyCode.LeftShift))
            {
                Speed = 4;
                RotationSpeed = 150;
            }
            else
            {
                Speed = 2;
                RotationSpeed = 200;
            }
        }

        _animator.SetFloat("speed", Speed);
        _animator.SetFloat("rotation", rotation);
        _animator.SetFloat("translation", translation);
    }

```

I took my character from Mixamo, same for the animaitons.

# Answer
I found a solution, it's not the best but it works.

When I equip my sword I destroy the `Rigidbody` and set it's `Collider` to `isTrigger` in order to detect collisions.

```
Destroy(item.getComponent<RigidBody>);
item.getComponent<Collider>().isTrigger = true;

```

And once I drop it, i add a new rigid `Rigidbody` and I switch `isTrigger` to false.

```
item.addComponent<RigidBody>();
item.getComponent<Collider>().isTrigger = false;

```

ps: If anyone has a better solution I would really appreciate.
> 0 votes

# Answer
It sounds like the physics engine might be finding a collision between the player's dynamic collider and the sword's, and is trying to move them apart to resolve the collision.

If you want the player to ignore self-collisions with objects they've picked up, you can call:

```
Physics.IgnoreCollision(playerCollider, itemCollider, true);

```

Once you've dropped the item, you can re-enable collisions between it and the player using:

```
Physics.IgnoreCollision(playerCollider, itemCollider, false);

```
> 0 votes

---
Tags: unity, transformation, rigidbody
---


title: Gravity well shader for Unity2D

text:
# Question
Title: Gravity well shader for Unity2D
I'm trying to find or create a gravity well distortion shader for Unity. I've been looking around and all I can find are "lenses" which bend space around a black hole.

I'd rather have a distortion that "pulls" or "bends" the image behind into a small hole. Essentially, what this would look like if viewed from above (ignoring the sphere):

I can't seem to find any examples or a common terminology for it.

# Answer
> 1 votes
This should, at least, give you a starting point, if not be exactly what you want:

I believe I modified the original shader I'd found to arrive at this, which appears to be from this tutorial.

```
Shader "Dvornik/Distort" {
    Properties{
        _Refraction("Refraction", Range(-10.00, 10.0)) = 0
        [HideInInspector][PerRendererData]_MainTex("Sprite Texture", 2D) = "white" {}
        _DistortTex("Distort (RG)",2D) = "gray" {}
    }

    SubShader{

        Tags{ "RenderType" = "Transparent" "Queue" = "Overlay" }
        LOD 100
        Blend SrcAlpha OneMinusSrcAlpha

        GrabPass{

        }

        CGPROGRAM
            #pragma surface surf NoLighting alpha
            #pragma vertex vert
            #pragma multi_compile ___ DISTORTION_OFF

            fixed4 LightingNoLighting(SurfaceOutput s, fixed3 lightDir, fixed atten) {
                fixed4 c;
                c.rgb = s.Albedo;
                c.a = s.Alpha;
                return c;
            }

            sampler2D _GrabTexture : register(s0);
            sampler2D _MainTex : register(s2);
            sampler2D _DistortTex : register(s3);
            float _Refraction;

            float4 _DistortTex_TexelSize;

            struct Input {
                float2 uv_MainTex;
                #if !DISTORTION_OFF
                float2 uv_DistortTex;
                float4 screenPos;
                #endif
                float3 color;
                INTERNAL_DATA
            };

            void vert(inout appdata_full v, out Input o) {
                UNITY_INITIALIZE_OUTPUT(Input,o);
                o.color = v.color;
            }

            void surf(Input IN, inout SurfaceOutput o) {
                float4 main = tex2D(_MainTex, IN.uv_MainTex);
                #if !DISTORTION_OFF
                    float4 dist = tex2D(_DistortTex, IN.uv_DistortTex);
                    float2 distort = float2(dist.r - 0.5, dist.g - 0.5);
                    float2 offset = distort * _Refraction * _DistortTex_TexelSize.xy;
                    //float4 bgColor = tex2Dproj(_GrabTexture, IN.screenPos);
                    #if UNITY_UV_STARTS_AT_TOP
                    IN.screenPos.y = 1 - IN.screenPos.y;
                    #endif
                    IN.screenPos.xy = offset + IN.screenPos.xy;
                    float4 refrColor = tex2Dproj(_GrabTexture, IN.screenPos);
                    o.Emission = main.rgb * main.a * main.a + (1 - main.a) * refrColor.rgb;
                #endif

                #if DISTORTION_OFF
                    o.Emission = main.rgb;
                    o.Alpha = main.a;
                #else
                    o.Alpha = 1;
                #endif
            }
        ENDCG
    }
    CustomEditor "DistortToggleInspector"
}

```

This, along with the right distortion texture (included below) results in this effect:

At you can see, the neighboring pixels from other shots and the background have been pulled in towards the center (but leaves the white arc shaped bullet alone). The white arc is the sprite this shader is attached to (no distortion comparison and effect on grid). It also looks a lot better in motion, the blurriness isn't really noticed as it blends in with everything moving around. I tuned the settings to be noticeable at the speeds I was working with, without being too overwhelming.

Settings:

Distortion map:

From what I recall, the way this shader works is that the screen is grabbed and passed into the shader, which determines how to drag the pixels around based on the distortion map (which I created for this specific effect, trying to create a "round" sort of bubble, although it ends up being more conical) and the `_Refraction` amount (higher values, strong effect, negative values pull inward instead of pushing outward--at least on *this* distortion map).

Note that the effect won't work properly in the scene view. This is due to scene view and game view having different UV coordinates and it didn't bother me enough to write compiler directives to account for it (but I did learn about the multi\_compile pragma!).

The effect can also be disabled at runtime (in case you want to disable flashy effects for people with weaker computers):

```
Material mat = Resources.Load<Material>("Distortion");
if(all_effects) {
    mat.DisableKeyword("DISTORTION_OFF");
}
else {
    mat.EnableKeyword("DISTORTION_OFF");
}

```

And via custom inspector script:

```
public class DistortToggleInspector : CustomMaterialEditor {
    protected override void CreateToggleList() {
        Toggles.Add(new FeatureToggle("Distortion Enabled", "Distort", "___", "DISTORTION_OFF"));
    }
}

```

---
Tags: unity, shaders
---


# Question
Title: How do components access one another in a component based entity system
---Most of the stuff I am talking about I read here---

I am currently tring to wrap my head around component based systems to make a simple game engine of sorts.

I am having a hard time understanding how its supposed to work. I get that there are components which all inherit from the same base, which provides basic functions (init, update, end) and lets all of the different kind of components be stored in the same array of pointers. I get that. However I dont get how any efficient interactions of the components in a game object are supposed to happen.

Lets say I made a component that stores the amount of gold in a treasure chest (lets call it dataComponent). Lets also assume I made a component that does something when its update function is called (lets call it logicComponent)

There is also a class called Entity

```
class entity{
private:
    vector<component*> components;
public:
    void addComponent(component* comp);
    void removeComponent(component* comp);
    void getComponent(int id);
}

```

Lets now say I plan to make treasureChest, without any functions. Its just a background model. Then I will make a new enitity and using addComponent I will add the dataComponent(and give it 100 gold pieces in its constructor) and a logicComponent(and give it nothing in its constructor). The player might take out, or put in as much gold as he likes. We dont know how much gold there is in the chest. There might even be multiple dataComponents storing how many jewels or weapons are in the chest.

Example:

```
void main(){
    Entity chest;
    chest.addComponent(new dataComponent<int>("gold",100)); //100 gold pieces
    chest.addComponent(new dataComponent<int>("guns",2)); //2 weapons
    chest.addComponent(new logicComponent()); //this is going to do the printing
    updateEnt(Entity);//simply iterates through all components of the entity and calls thier update functions.
}
EXPECTED OUTPUT:
This chest contains 100 gold and 2 guns

```

The logic components job is to somehow get its hands on the data and print it to the screen.

My question is: How can the logic component get access to the other components in the same object as it is in and access the approperate ones (the ones it needs to function) without looking through the entire array every single time?

# Answer
> 8 votes
Components are just a collection of data and logic. How you store and relate them to the logical entity is where you gain or lose performance depending on the strategy you choose.

My example and explanation is in Java, but the theory can be applied to any language.

The way I usually handle custom Component engines is with HashMap registries of components. This ends up with a game engine that looks a lot like a relational database. Lookups and data manipulation are fast, and it can easily handle millions of entities at a time in memory. It has been a while since I've built one, so I don't remember any cons to the approach, but maybe someone does and can improve this answer.

Essentially it boils down to HashMaps and GUIDs. Each Entity is nothing more than a Globally Unique Identifier (GUID) which serves as the key in each HashMap. A HashMap exists for every ComponentType in your game. There are ways to make this more general purpose, but I'm going with the naïve solution for simplicity of argument.

We first need to track existing Entities. I do this with a HashMap with a GUID as the Key, and a boolean as the Value which indicates whether or not the entity should be destroyed.

```
public class EntityManager
{
  HashMap<GUID,boolean> entities =new HashMap<GUID,boolean>();

  public EntityManager()
  {
  }

  public GUID createEntity()
  {
      GUID entity= new GUID();
      entities.put(entity,false);
      return entity;
  }

  public HashMap<GUID,boolean> getAll()
  {
      return entities;
  }

  public void markPurge(GUID entity)
  {
      entities.put(entity, true);
  }

  public void purgeReady()
  {
      //removes all entities that have a value of true,
      //only called once all other purges have been called
      for(GUID entity : entities)
      {
        if(entities.get(entity))
          entities.remove(entity);
      }
  }
}

```

Lets say the object needs health, lets start with creating a Health component. During the initialization of your game, you'd create a HashMap to register Entities that have the Health Component.

```
public class HealthComponentRegistry
{
  private HashMap<GUID,int> healths=new HashMap<GUID,int>();

  public HealthComponentRegistry(){}

  public void set(GUID entity, int health)
  {
      healths.put(entity, health);
  }

  public int get(GUID entity)
  {
      return healths.get(entity);
  }

  public void remove(GUID entity)
  {
      healths.remove(entity);
  }

  public void add(GUID entity)
  {
      healths.put(entity, 100);
  }

  public void add(GUID entity, int health)
  {
      healths.put(entity, health);
  }

  public void purge(ArrayList<GUID> entities)
  {
    for(GUID entity : entities)
       healths.remove(entity);
  }
}

```

To spawn a new Entity with 100 health in our game, we first generate a new Entity GUID, then assign it a Health component.

```
public void setup()
{
  //spawn an entity, and add a Health component in one step
  HealthComponentRegistry.add(EntityManager.createEntity());
}

```

To actually use the components and assign game logic to them, I use Systems. Each System performs a piece of game logic, like destroying an entity if its health reaches zero.

```
public class DeathSystem
{
  EntityManager entities;
  HealthComponentRegistry healths;
  public DeathSystem(EntityManager e, HealthComponentRegistry h)
  {
     entities=e;
     healths=h;
  }

  public void update()
  {
     for(GUID entity : health.keySet())
     {
       if(healths.get(entity)==0)
           entities.markPurge(entity);
     }
  }
}

```

Now we simply call our systems in our main game loop, after handling user input. Altogether yielding the following

```
EntityManager entities;
HealthComponentRegistry healthComps;
DeathSystem deathSystem;
GUID player;
boolean run = true;

public void main(String args)
{
    setup();
    while(run)
    {
      update();
    }
}

public void setup()
{
    entities= new EntityManager();
    healthComps = new HealthComponentRegistry();
    deathSystem = new DeathSystem(entities, healthComps);
    player=entities.create();
    healthComps.add(player);
}

public void update()
{
    handleInput();
    //attackSystem.update();
    //healSystem.update();
    deathSystem.update();
    //finally, call the function that calls purge on all the component registries to remove any destroyed objects
    purgeAll();
    if(entities.getAll().size()==0)
       run=false;
}

```

The beauty of this kind of structure is that all of your entity lookups are O(1) operations, and each System only operates on Entities currently registered as having the relevant components. Because of this, the systems only do what is absolutely necessary. If none of your entities have health, the death system has nothing to iterate over, and returns in constant time. This also keeps the memory footprint at an absolute minimum.

There are other approaches as well, but this is the one that I've had the most success with, and I think this illustrates that a component isn't so much an object, as a fuzzy collection of data and logic.

# Answer
> 4 votes
Your component entity system doesn't match that which was shown in the article. The article doesn't attach logic components to entities, it uses system objects which look for data components.

Additionally IDs are typically enumerations or bit keys instead of strings. You'd have a system component that would do something like:

```
function update(entities):
    for each entity in entities:
        for each component reference in entity:
            ... do computation with component

```

## Binary Search

With your method, yes the only way to find components is to linearly search through the array. If however you can sort your components by key, then this is less of an issue as long as you aren't constantly adding and removing components. With sorted lists you can perform binary search which has a runtime cost of `log2(n)` which if you have 128 components on an object means you need to go through only 7 comparisons per object at max. When you want to keep stuff sorted, you can use binary search to insert in the proper place as well.

## Lock and Key

There is however another way. Some entity component systems invoke a lock and key mechanism. What this affords us is a method to see if our entity even has a given component in the first place before searching in constant time via bit manipulation. Each component is given a single bit value (1, 2, 4, 8 ... 2^n) which you then `or` with your entities current "lock" and you get a bitfield of entity keys. When a system wants to use your entity to use its components it simply has to compare its set of components it needs (a key) and your entities lock via the `and` operator and comparing that value against the systems key. If your system has that key, you know you won't be wasting time by searching it to find your component

This system has some draw backs in that you can't have more components types of components than the size of your lock, and you might run into issues with adding multiple of the same component to a given entity (though 99% of the time it doesn't make sense to add two health bars, and your system wont be able to distinguish non unique components anyway)

## Array index equals Component ID

Another way besides that, if you don't have too many entities you could alternatively get constant time look ups with arrays of components that are simply the size of the number of components you could ever possibly have. You would get instant look up of components (where the index in the array would correspond to their ID) and you could lower the amount of memory used if you pushed common component ids towards the top (meaning that most of the time you could avoid allocating memory to the next N elements, with only checking the size of your array first to make sure you don't walk off the end when checking).

## Hash table for Components for each entity

An additional way to fix this is to use a hash table per entity which hashes component IDs to components (resulting in O(1) access amortized). With small sizes of N it may end up taking more space and being slower than per index ID array solutions or using binary search.

## System Observable Components.

A final method I've seen is that each system, each time a new entity is added (registered), adds pointers to the components to a personal list such that it doesn't even need to look up anything on the entity at all when calling the `update` function. All the system needs to do is iterate and apply its algorithm on each set of components in its internal list. When entities are destroyed we unregister them from each observer by searching through the list of components and removing them. If **components** are constantly removed and added, it may be beneficial to implement the binary search strategy I talked about earlier here with the component list, but if they are instead only removed sparingly, but added often it would be better to just do linear searches.

I've implemented a system that uses lock and key, binary search and the system observable method myself, though it won't necessarily be the best method for every situation.

---
Tags: c++, component-based
---


title: Synchronise events in Multiplayer Game

text:
# Question
Title: Synchronise events in Multiplayer Game
I am trying to make a fighting game where two characters are fighting with hands or can have some weapon in their hands. It's a multiplayer game targeting initially for mobile devices. In Game, there would be some animation and when that weapon hit other character body, its health will decrease.

I have two different updates implemented. One is Fixed update which calls after every 100ms and all game logic is implemented there and other update is for drawing, running at 60 fps. Now when two players are fighting and one player is animating to hit other, I need to show others player's decrease of health at the time of hit. Now as drawing update is different, I got a hit event in an update but when should I have to decrease the health?

As my all game logic is running in fixed update, I am updating characters' health in fixed update and decide whether it's still alive or dead but due to this, on screen, it shows some delay in decreasing health. I want to know am I doing something wrong? What is the standard way to achieve this?

# Answer
> 1 votes
First you need to assign the authoritative simulation. Who decides a score?

If you have a server and two clients, the server would be authoritative of course, and would be running the simulation. So the health of both players is recorded by the server.

If your game is peer-to-peer, it is trickier. Even if we ignore the fact of hacked clients. Do both peers run a simulation? Typically, yes. If so, how are differences resolved?

Consider this sequence of events:

*timestamp T0*

* Player A presses the "Jab" button.
* Client A starts "Jab" animation.
* Client A sends "Jab" event to client B.

*timestamp T1*

* Client B presses the "Block" button.
* Client B starts the "Block" animation.
* Client B sends "Block" event to client A.

*timestamp T2*

* Client A ends the "Jab" animation.
* Client A deals damage to player B, as **A is still unaware of the block**.

*timestamp T3*

* Client A receives the "Block" event from B.

*timestamp T4*

* Client B receives the "Jab" event from B, and decides there is no damage dealt, because of the block.

Now one clients thinks: "A Hit!" and the other client thinks: "No Hit!"

As you see, Online Multi Player is one big can of worms.

If your animation times are always longer than the latency of the network, it would make your life easier of course. But even then you would need to cancel the effect of a Block, even though its animation has played half-way through, if a Jab event is received.

Personally I've made an online tank game using peer-2-peer with a local simulation on each peer. The simulations on the clients unavoidably differ slightly. To resolve hits, I decided that if the scoring player's simulation shows a hit, it overrides what the victim's simulation says.

PS: With multiple clients, you could also make them asymmetric and have one run a simulation, and the other just plays back the results. This makes for a bad user experience of course, as the player running the sim is at a huge advantage with a 0ms latency.

---
Tags: multiplayer, game-loop, events, synchronization, fighting-game
---


# Question
Title: crashing generating fire-balls(bullets) with Box2D
I got crash, making fire-balls as bullets.

I guess I should not use "private Array fireballs" in player class. it seems like when I add one more fire as index of 1 into the list, the first index does not look working on destroying in for loop in player class. it seems only destrying index of 0.

in playscreen class,

```
 public void handleInput(float dt){
       if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){
            playerBlue.fire();
        }

```

in player class,

```
private Array<FireBall> fireballs;
public void update(float dt) {
  for (FireBall ball : fireballs) {
        ball.update(dt);
        if (ball.isDestroyed())
            fireballs.removeValue(ball, true);
    }

 }
public void fire() {
    fireballs.add(new FireBall(screen, b2body.getPosition().x, b2body.getPosition().y, Blue.runRightSide ? true : false));

}

```

in fire class,

```
public class FireBall extends Weapon {
private TextureRegion fireball;
private float rotate;
public FireBall(PlayScreen screen, float x, float y, boolean rightside) {
    super(screen, x, y, rightside);
    fireball = new TextureRegion(screen.getAtlas().findRegion("fireball"),0,0,40,40);
    setRegion(fireball);
    setBounds(getX(),getY(),getWidth()*2,getHeight()*2);

}

@Override
protected void defineWeapon() {
    BodyDef bdef = new BodyDef();
    bdef.position.set(rightside ? getX() + 12 / AlienAdvantrue.PPM : getX() - 12 / AlienAdvantrue.PPM, getY());
    bdef.type = BodyDef.BodyType.DynamicBody;
    if (!world.isLocked())
        body = world.createBody(bdef);//?
    FixtureDef fdef = new FixtureDef();
    CircleShape shape = new CircleShape();
    shape.setRadius(3 / AlienAdvantrue.PPM);
    fdef.filter.categoryBits = AlienAdvantrue.FIREBALL_BIT;
    fdef.filter.maskBits = AlienAdvantrue.GROUND_BIT
            |AlienAdvantrue.Enemy_Head_BIT
            |AlienAdvantrue.BRICK_BIT
            |AlienAdvantrue.COIN_BIT
            |AlienAdvantrue.Enemy_BIT;

    fdef.shape = shape;
    fdef.restitution = 1;
    fdef.friction = 0;
    body.setLinearVelocity(new Vector2(rightside ? 2 : -2, 2.5f));
    body.createFixture(fdef).setUserData(this);

}

public void update(float dt){
    stateTime += dt;
    rotate +=100; // flip faste// ?
    rotate(rotate);
    setPosition(body.getPosition().x - getWidth() / 2, body.getPosition().y - getHeight() / 2);

    if((stateTime > 3 || setToDestroy) && !destroyed) {
        world.destroyBody(body);
        destroyed = true;
        stateTime=0;
    }
    if(body.getLinearVelocity().y > 2f)
        body.setLinearVelocity(body.getLinearVelocity().x, 2f);
    if((rightside && body.getLinearVelocity().x < 0) || (!rightside && body.getLinearVelocity().x > 0))
        setToDestroy();
}

```

}

# Answer
> 2 votes
The issue is probably this loop:

```
  for (FireBall ball : fireballs) {
        ball.update(dt);
        if (ball.isDestroyed())
            fireballs.removeValue(ball, true);
    }

```

you're removing items while iterating on your loop. That plays funny with the internal iterator since the size of `fireball` changes: items are basically skipped, and other strange effects.

I'm not an expert, but what's recommended in this Stack Overflow answer is to handle the iterator manually:

```
public void update(float dt) {

for(Iterator<FireBall> i = fireballs.iterator(); i.hasNext();) {
       Fireball ball = i.next();
        if (ball.isDestroyed())
          i.remove()
 }

```

---
Tags: libgdx, box2d
---


title: How to handle assets in Unity?

text:
# Question
Title: How to handle assets in Unity?
Here's what I have in our little Unity game:

* If an asset (mostly a prefab or a texture) has to be accessed (e.g. to instantiate a game object), it is often passed as `[SerializeField]` to the script component. Scripts that are not components get their assets through the constructor so the assets are passed down until the class where they are needed. It's ugly.
* If a lot of assets are needed (like textures of an animation), they are moved into a folder called "Resources" and accessed through the `Resources` class. The documentation explicitly says "don't use it".

What I want:

* To access assets through a name or path to create objects at run-time.

What I found:

* The `AssetDataBase` class looked promising until I couldn't locate it and found out it is deprecated (and the documentation does not tell how to replace it).
* Nothing on Google but a lot of outdated things
* Asset bundles look promising too, but they are quite complicated and there are no really good migration tutorials and I don't know how to use them.

Any suggestions? How do small/mid sized/bigger Unity games handle their resources?

# Answer
There are a few main ways to handle *dependencies*:

---

# 1) Make the scripts handle their own dependencies.

This seems to be what you're doing, and is how most beginner programmers first learn to handle dependencies. It is probably the most intuitive way to do it, to a programmer familiar with passing parameters to methods, but not familiar with other methods of dependency handling.

As you are finding out, it quickly becomes apparent that it has many limitations on anything more advanced than classroom assignments or the simplest kinds of applications.

---

# 2) Dependency-handling using Singletons \- The art of making scripts with a simple global access point, responsible for holding all the dependencies throughout the project.

This is usually done using *singletons* as holders, and then "pulling" references from those singletons using

```
Singleton.instance.dependency1

```

Where:

* `Singleton` is the `type` of the class.
* `instance` is a `static` field in that class, holding a reference to an (the only) instance of that class.
* `dependency1` is a field holding a reference to one specific dependency.

You will often hear that *"singletons are evil"* or that *"you should never use singletons"*. Don't blindly trust such statements. As often is the case where similar generalized statements are involved, things are not so black-and-white.

Singletons do have their use-cases, and, although there *are* better methods for handling dependencies, singletons are a valid method, and they are an important stepping-stone to understand why other, better methods, are better.

I personally use singletons for many of my small-scale unity projects; finding more advanced methods more time-consuming for "advantages" that would never be used/required (aka overkill).

---

# 3) Dependency-injection (basically, singletons, but with Inversion of Control steroids):

This is pretty much the experienced programmers' *standard* way of handling dependencies. It does, however, present a steeper learning-curve in general (nothing too complicated, but you *probably* don't want to learn this while at the same time learning to make your first games).

Additionally, for Unity specifically, there are some caveats, which make DI *really* not appropriate for your first few projects. And if you don't step through dependency-handling based on singletons first, you will know *what* to do, but most likely, you will be doing DI without knowing *why* it's (most but not all times) better to do dependency-handling this way.

The easiest way of doing DI for Unity, at least to my knowledge, is like doing DI for any other project: **Use a DI framework.**

In Unity's case specifically, the one I have experience with and recommend is **Zenject**. You can also find explanations for everything I mention here on the Zenject project page. From the *theory* behind DI, to the *caveats* related to Zenject (and DI in general) on Unity.
> 1 votes

---
Tags: unity, c#, assets, asset-management
---


# Question
Title: Partially transparent surface over opaque surface causes strange artifacts
I have a world with many unit square tiles, each made up of a 3d terrain chunk and a 2d water chunk (a square). Each chunk stretches from \[0, 0\] to \[1, 1\] (inclusive) in its tile space. This means each pair of adjacent chunks shares an edge of vertices (although for sharing the visual I've curbed in the edges of the water chunks to make it obvious where the tile edges are).

I'm having a weird issue when I make water somewhat transparent (85% in my case). It looks like "walls" form between the water surface and the terrain surface below, along the edges of the tile. The walls reflect the water color, but with 100% opacity instead of 85%.

*This side has a problem:*

*This side looks fine:*

The weirdest part to me is that I can only see these walls from one side, as shown in the screenshots. I suspected maybe this had something to do with backface culling, so I turned it off, but that didn't change anything.

I did notice that the walls disappear if I stop rendering the terrain, and maintain the same level of water transparency.

*No walls from front:*

*And no walls from back:*

(The light blue in the second set of images is the sky color.)

Does anyone recognize this issue, know a name for it, or have an idea what I could change to fix it? Thanks!

# Answer
> 1 votes
The "walls" are not walls, they're **missing grass pixels** due to the **depth test**.

This problem is Transparency Sorting

From one angle the water plane is drawn **before** the next chunk behind it preventing the grass geometry from rendering over that little bit of screen-space overlap due to the depth test.

From a different angle the water plane in front is drawn **after** which does not cause the issue since the grass behind it has already been drawn.

To fix this easily you can **render all your grass** (all the opaque stuff) from all the chunks **first** then and **all your water** (all the transparent stuff) in all the chunks **last**.

Ideally for quality you want to render all transparent triangles sorted back-to-front or use other techniques such as Order-independent transparency but this can be a huge performance hit when sorting all those triangles or fragments at once so most games take various shortcuts (such as mentionned above: render opaque first, transparent last, unsorted, works well enough most of the time).

---
Tags: 3d, tiles, transparency
---


# Question
Title: Freeing texture memory in SharpDX - what am I missing?
I'm having a torrid time trying to resolve an issue whereby my total GPU memory consumption keeps rising throughout the course of my application, until the application fails with a DX out of memory exception.

I frequently load large textures, split into texture arrays (of type Texture2D). These are freed using .Dispose() before the next one is loaded, but memory is not seen to be freed when using Process Monitor (specifically, the "Committed GPU Memory" keeps rising with each new allocation).

1. I freely admit that I do not really know what the Committed GPU Memory metric in Process Monitor is telling me, but it is the case that the application will eventually fail through lack of memory - so the memory leak is real (and always when the memory hits the same amount in PM).
2. I do have object tracking enabled, and am able to see that no objects remain unaccounted for when the application closes normally (including after a number of texture loads).
3. I have created a synthetic example which simply allocates a texture and immediately calls Dispose() on a button click. This demonstrates the problem - memory usage increases until the application fails with an out of memory exception.

```
    public void d()
{
    texture = new Texture2D(Renderer.Device, new Texture2DDescription()
    {
        Width = 1024,
        Height = 1024,
        MipLevels = 1,
        Format = Format.R8_UNorm,
        BindFlags = BindFlags.ShaderResource,
        Usage = ResourceUsage.Default,
        CpuAccessFlags = CpuAccessFlags.None,
        OptionFlags = ResourceOptionFlags.None,
        ArraySize = 100,
        SampleDescription = new SampleDescription(1, 0)
    });
    texture.Dispose();
}

```
4. I did read somewhere on this forum that calling Flush on the context might have an effect, and in my synthetic example it does stop the memory build up - but not in my real app (?).

System is Windows 8.1, SharpDX 2.6.3.

Am I missing something really obvious here? I've Googled extensively but I can't find anything that suggests more than a Dispose is required when freeing textures.

thanks, Matt

# Answer
> 1 votes
Thanks for this question, I too was suffering the dreaded non-release of memory and when editing a 16Kx16K image that quickly kills your system.

To identify the problem I wrote a small app that loops around multiple times loading a Texture, creating a ShaderResourceView, then releasing the Texture and finally fixed the problem.

The link to Flush gave me the clue ...

> we recommend that the application release all its references, call ID3D11DeviceContext::ClearState, and then call Flush.

I found that when I referenced the ShaderResourceView using:

```
device.ImmediateContext.PixelShader.SetShaderResource(0, texture.srv);

```

Then I had to call both ClearState and Flush

```
device.ImmediateContext.ClearState();
device.ImmediateContext.Flush();

```

I expect the ClearState function is performing *PixelShader.SetShaderResource(0, null)* and more.

---
Tags: sharpdx
---


# Question
Title: How can i move the player randomly between the waypoints?
What i'm trying to do is once the random flag is true move the player between the waypoints randomly. but just calling the random method is not enough.

```
using UnityEngine;
using System.Collections;

public class Waypoints : MonoBehaviour
{
    public GameObject[] waypoints;
    public Transform target;
    public float moveSpeed = 10f;
    public float slowDownSpeed = 3f;
    public float reverseSlowDownSpeed = 3f;
    public float rotationSpeed = 1f;
    private int targetsIndex = 0;
    private Vector3 originalPosition;
    private GameObject[] players;

    public Transform reverseTarget;
    private int reverseTargetsIndex = 0;
    private Vector3 reverseOriginalPosition;

    public bool random = false;

    // Use this for initialization
    void Start()
    {
        waypoints = GameObject.FindGameObjectsWithTag("Blocks");
        players = GameObject.FindGameObjectsWithTag("Player");
        originalPosition = players[0].transform.localPosition;
    }

    // Update is called once per frame
    void Update()
    {
        if (random == true)
        {
            RandomWayPointsAI();
        }
        else
        {
            WayPointsAI();
        }
    }

    private void WayPointsAI()
    {
        if (targetsIndex == waypoints.Length)
            targetsIndex = 0;
        target = waypoints[targetsIndex].transform;
        float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
        players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);

        //move towards the player
        if (distance < 30)
        {
            players[0].transform.localPosition += players[0].transform.forward * slowDownSpeed * Time.deltaTime;
        }
        else
        {
            players[0].transform.localPosition += players[0].transform.forward * moveSpeed * Time.deltaTime;
        }
        if (distance < target.transform.localScale.magnitude)
        {
            targetsIndex++;
        }
    }

    private void ReverseWayPointsAI()
    {
        if (reverseTargetsIndex == 0)
            reverseTargetsIndex = waypoints.Length - 1;
        reverseTarget = waypoints[reverseTargetsIndex].transform;
        float distance = Vector3.Distance(players[1].transform.position, reverseTarget.transform.position);
        players[1].transform.rotation = Quaternion.Slerp(players[1].transform.rotation, Quaternion.LookRotation(reverseTarget.position - players[1].transform.position), rotationSpeed * Time.deltaTime);

        //move towards the player
        if (distance < 30)
        {
            players[1].transform.position += players[1].transform.forward * reverseSlowDownSpeed * Time.deltaTime;
        }
        else
        {
            players[1].transform.position += players[1].transform.forward * moveSpeed * Time.deltaTime;
        }
        if (distance < reverseTarget.transform.localScale.magnitude)
        {
            reverseTargetsIndex--;
        }
    }

    void RandomWayPointsAI()
    {
        if (random == true)
        {
            int index = Random.Range(0, waypoints.Length);
            target = waypoints[index].transform;
        }
    }

    void DrawLinesInScene()
    {
        // draw lines between each checkpoint //
        for (int i = 0; i < waypoints.Length - 1; i++)
        {
            Debug.DrawLine(waypoints[i].transform.position, waypoints[i + 1].transform.position, Color.blue);
        }

        // draw a line between the original transform start position
        // and the current transform position //
        Debug.DrawLine(originalPosition, players[0].transform.position, Color.red);
        Debug.DrawLine(reverseOriginalPosition, players[1].transform.position, Color.red);

        // draw a line between current transform position and the next waypoint target
        // each time reached a waypoint.
        if (target != null)
            Debug.DrawLine(target.transform.position, players[0].transform.position, Color.green);
        if (reverseTarget != null)
            Debug.DrawLine(reverseTarget.transform.position, players[1].transform.position, Color.green);
    }

    void AddColliderToWaypoints()
    {
        foreach (GameObject go in waypoints)
        {
            SphereCollider sc = go.AddComponent<SphereCollider>() as SphereCollider;
            sc.isTrigger = true;
        }
    }
}

```

Inside the Update i'm checking if random is true then calling the RandomWayPointsAI(); but it's not moving the player it's just keep picking up each frame a new random waypoint but that's it.

```
void Update()
    {
        if (random == true)
        {
            RandomWayPointsAI();
        }
        else
        {
            WayPointsAI();
        }
    }

```

# Answer
> 1 votes
Just change your update function to

```
void Update()
{
        WayPointsAI();
}

```

and your waypointsAI() to

```
private void WayPointsAI()
{
    if (targetsIndex == waypoints.Length)
        targetsIndex = 0;
    target = waypoints[targetsIndex].transform;
    float distance = Vector3.Distance(players[0].transform.position, target.transform.position);
    players[0].transform.localRotation = Quaternion.Slerp(players[0].transform.localRotation, Quaternion.LookRotation(target.position - players[0].transform.localPosition), rotationSpeed * Time.deltaTime);

    //move towards the player
    if (distance < 30)
    {
        players[0].transform.localPosition += players[0].transform.forward * slowDownSpeed * Time.deltaTime;
    }
    else
    {
        players[0].transform.localPosition += players[0].transform.forward * moveSpeed * Time.deltaTime;
    }
    if (distance < target.transform.localScale.magnitude)
    {
        if(random)
            targetsIndex = Random.Range(0, waypoints.Length);//you can do more
                     //logic here to prevent from same targetsIndex value.
        else
            targetsIndex++;
    }
}

```

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


title: Knockback when shooting

text:
# Question
Title: Knockback when shooting
I am currently working on a shooter and I could use some help with this. I want to make my character knock back when he shoots, but also the knock back should be different when the player uses a different weapon. How can I do this?

# Answer
It sort of depends on the game engine you're using, but you can accomplish this effect by adding some relative force in the opposite direction of your character.

For each weapon, you will designate some force for the variable, and when you fire, apply that amount of force to your actor.

To add a little more cool effect, you can even make the camera shake some, or add some recoil to the camera.

If you're using Unity, for instance, you can check out RigidBody.AddRelativeForce documentation. You'd add the force on the Z axis, in the opposite direction.
> 1 votes

# Answer
Just animate the knockdown behaviour, create different animations with different weapons in some software like maya, blender etc and use it directly in Unity.

Unity uses Mechanim in which you can blend different animations in a same state. Although blending is used to blend two or more similar motions but it can also be used to play different animation in same state in different scenarios.

Tutorial for blend trees can be found here.
> 0 votes

---
Tags: unity
---


# Question
Title: Cache misses and usability in Entity Systems
Lately I have been researching and implementing an Entity System for my framework. I think I read most articles, reddits and questions about it that I could find, and so far I think I am grasping the idea well enough.

However, it raised some questions about overall C++ behavior, the language I implement the entity system in, as well as some usability issues.

So, one approach would be to store an array of components in the entity directly, which I didn't do because it ruins the cache locality when iterating through data. Because of this, I decided to have one array per component type, so all components of the same type are contiguous in memory, which should be the optimal solution for quick iteration.

But, when I am to iterate component arrays to do something with them from a system on an actual gameplay implementation, I notice that I almost always am working with two or more component types at once. For example, the render system uses the Transform and the Model component together to actually make a render call. My question is, since I am not iterating linearly one contiguous array at a time in these cases, am I immediately sacrificing the performance gains from allocating components this way? Is it a problem when I iterate, in C++, two different contiguous arrays and use data from both at each cycle?

Another thing that I wanted to ask about, is how one should keep references to components or entities, since the very nature of how the components are laid in memory, they can easily switch positions in the array or the array could be reallocated for expanding or shrinking, leaving my component pointers or handles invalid. How do you recommend to handle these cases, since I often find myself wanting to operate on transforms and other components every frame and if my handles or pointers are invalid, its quite messy to make lookups every frame.

# Answer
First, I wouldn't say that in this case you are optimising too early, depending on your use case. In any case though, you've asked an interesting question and as I have experience with this myself, I'll weigh in. I'll try to just explain how I ended up doing things and what I found on the way.

* Each entity holds a vector of generic component handles which can represent any type.
* Each component handle can be dereferenced to yield a raw T\* pointer. \*See below.
* Each component type has its own pool, a continuous block of memory (fixed size in my case).

It should be noted that no, you won't be able to just always traverse a component pool and do the ideal, clean thing. There are, as you have said, inescapable links between components, wherein you really need to process things an entity at a time.

However, there are cases (as I have found) where indeed, you can literally write a for loop for a particular component type and make great use of your CPU cache lines. For those who are unaware or wish to know more, take a look at https://en.wikipedia.org/wiki/Locality\_of\_reference. On the same note, when possible, do try to keep your component size less than or equal to your CPU cache line size. My line size was 64 bytes, which I believe is common.

In my case, making the effort of implementing the system was well worth it. I saw visible performance gains (profiled of course). You'll need to decide for yourself whether it is a good idea. The biggest gains in performance I saw at 1000+ entities.

> Another thing that I wanted to ask about, is how one should keep references to components or entities, since the very nature of how the components are laid in memory, they can easily switch positions in the array or the array could be reallocated for expanding or shrinking, leaving my component pointers or handles invalid. How do you recommend to handle these cases, since I often find myself wanting to operate on transforms and other components every frame and if my handles or pointers are invalid, its quite messy to make lookups every frame.

I also solved this issue personally. I ended up having a system where:

* Each component handle holds a reference to a pool index
* When a component is 'deleted' or 'removed' from a pool, the last component within that pool is moved (literally with std::move) to the now free location, or none if you just deleted the last component.
* When a 'swap' occurs, I have a callback which notifies any listeners, so that they may update any concrete pointers (e.g T\*).

\*I found that trying to always dereference component handles at runtime in certain sections of high use code with the number of entities I was dealing with was a performance problem. Because of that, I now maintain some raw T pointers in performance critical parts of my project, but otherwise I do use the generic component handles, which should be used where possible. I keep them valid as mentioned above, with the callback system. You may not need to go as far as that.

Above all though, just try things. Until you get a real world scenario, anything anyone says here is just one way of doing things, which may not be appropriate for you.

Does that help? I will try to clarify anything that is unclear. Also any corrections are appreciated.
> 13 votes

# Answer
To answer just this:

> My question is, since I am not iterating linearly one contiguous array at a time in these cases, am I immediately sacrificing the performance gains from allocating components this way? Is it a problem when I iterate, in C++, two different contiguous arrays and use data from both at each cycle?

No (at least not necessarily). The cache controller should, in most cases, be able to deal with reading from more than one contiguous array efficiently. The important part is to try where possible to access each array linearly.

To demonstrate this, I wrote a small benchmark (the usual benchmark caveats apply).

Starting with a simple vector struct:

```
struct float3 { float x, y, z; };

```

I found that a loop summing each element of two separate arrays and storing the result in a third performed exactly the same as a version where the source data was interleaved in a single array and the result stored in a third. I did find however, if I interleaved the result with the source, the performance suffered (by around a factor of 2).

If I accessed the data randomly, the performance suffered by a factor between 10 and 20.

Timings (10,000,000 elements)

linear access

* separate arrays 0.21s
* interleaved source 0.21s
* interleaved source and result 0.48s

random access (uncomment random\_shuffle)

* separate arrays 2.42s
* interleaved source 4.43s
* interleaved source and result 4.00s

Source (compiled with Visual Studio 2013):

```
#include <Windows.h>
#include <vector>
#include <algorithm>
#include <iostream>

struct float3 { float x, y, z; };

float3 operator+( float3 const &a, float3 const &b )
{
    return float3{ a.x + b.x, a.y + b.y, a.z + b.z };
}

struct Both { float3 a, b; };

struct All { float3 a, b, res; };

// A version without any indirection
void sum( float3 *a, float3 *b, float3 *res, int n )
{
    for( int i = 0; i < n; ++i )
        *res++ = *a++ + *b++;
}

void sum( float3 *a, float3 *b, float3 *res, int *index, int n )
{
    for( int i = 0; i < n; ++i, ++index )
        res[*index] = a[*index] + b[*index];
}

void sum( Both *both, float3 *res, int *index, int n )
{
    for( int i = 0; i < n; ++i, ++index )
        res[*index] = both[*index].a + both[*index].b;
}

void sum( All *all, int *index, int n )
{
    for( int i = 0; i < n; ++i, ++index )
        all[*index].res = all[*index].a + all[*index].b;
}

class PerformanceTimer
{
public:
    PerformanceTimer() { QueryPerformanceCounter( &start ); }
    double time()
    {
        LARGE_INTEGER now, freq;
        QueryPerformanceCounter( &now );
        QueryPerformanceFrequency( &freq );
        return double( now.QuadPart - start.QuadPart ) / double( freq.QuadPart );
    }
private:
    LARGE_INTEGER start;
};

int main( int argc, char* argv[] )
{
    const int count = 10000000;

    std::vector< float3 > a( count, float3{ 1.f, 2.f, 3.f } );
    std::vector< float3 > b( count, float3{ 1.f, 2.f, 3.f } );
    std::vector< float3 > res( count );

    std::vector< All > all( count, All{ { 1.f, 2.f, 3.f }, { 1.f, 2.f, 3.f }, { 1.f, 2.f, 3.f } } );
    std::vector< Both > both( count, Both{ { 1.f, 2.f, 3.f }, { 1.f, 2.f, 3.f } } );

    std::vector< int > index( count );
    int n = 0;
    std::generate( index.begin(), index.end(), [&]{ return n++; } );
    //std::random_shuffle( index.begin(), index.end() );

    PerformanceTimer timer;
    // uncomment version to test
    //sum( &a[0], &b[0], &res[0], &index[0], count );
    //sum( &both[0], &res[0], &index[0], count );
    //sum( &all[0], &index[0], count );
    std::cout << timer.time();
    return 0;
}

```
> 5 votes

# Answer
**Short Answer:** Profile then optimize.

**Long Answer:**

> But, when I am to iterate component arrays to do something with them from a system on an actual gameplay implementation, I notice that I almost always am working with two or more component types at once.
>
> Is it a problem when I iterate, in C++, two different contiguous arrays and use data from both at each cycle?

C++ is not responsible for cache misses, as it applies for any programming language. This has to do with how modern CPU architecture works.

Your problem might be a good example of what might be called **pre-mature optimization**.

In my opinion you optimized too early for cache locality without looking at the program memory access patterns. But the bigger question is did you really need this kind (locality of reference) of optimization?

Agner's Fog suggests that you shouldn't optimize before you profile your application and/or know for sure where the bottlenecks are. (This is all mentioned in his excellent guide. Link below)

> It is useful to know how a cache is organized if you are making programs that have big data structures with non-sequential access and you want to prevent cache contention. You may skip this section if you are satisfied with more heuristic guidelines.

Unfortunately what you did was actually assume that allocating one component type per array will give you better performance, while in reality you might have caused more cache misses or even cache contention.

You should definitely look at his excellent C++ optimization guide.

> Another thing that I wanted to ask about, is how one should keep references to components or entities, since the very nature of how the components are laid in memory.

Personally I will allocate most used components together in a single memory block, so they have "near" addresses. For example an array will look like that:

`[{ID0 Transform Model PhysicsComp }{ID10 Transform Model PhysicsComp }{ID2 Transform Model PhysicsComp }..]` and then start optimizing from there if the performance was not "good enough".
> 2 votes

# Answer
> My question is, since I am not iterating linearly one contiguous array at a time in these cases, am I immediately sacrificing the performance gains from allocating components this way?

Chances are that you'll get fewer cache misses overall with separate "vertical" arrays per component type than interleaving the components attached to an entity in a "horizontal" variable-sized block, so to speak.

The reason is because, first, the "vertical" representation will tend to use less memory. You don't have to worry about alignment for homogeneous arrays allocated contiguously. With non-homogeneous types allocated into a memory pool, you do have to worry about alignment since the first element in the array could have a totally different size and alignment requirements from the second. As a result you'll often need to add padding, like so as a simple example:

```
// Assuming 8-bit chars and 64-bit doubles.
struct Foo
{
    // 1 byte
    char a;

    // 1 byte
    char b;
};

struct Bar
{
    // 8 bytes
    double opacity;

    // 8 bytes
    double radius;
};

```

Let's say we want to interleave `Foo` and `Bar` and store them right next to each other in memory:

```
// Assuming 8-bit chars and 64-bit doubles.
struct FooBar
{
    // 1 byte
    char a;

    // 1 byte
    char b;

    // 6 bytes padding for 64-bit alignment of 'opacity'

    // 8 bytes
    double opacity;

    // 8 bytes
    double radius;
};

```

Now instead of taking 18 bytes to store Foo and Bar in separate memory regions, it takes 24 bytes to fuse them. It doesn't matter if you swap the order:

```
// Assuming 8-bit chars and 64-bit doubles.
struct BarFoo
{
    // 8 bytes
    double opacity;

    // 8 bytes
    double radius;

    // 1 byte
    char a;

    // 1 byte
    char b;

    // 6 bytes padding for 64-bit alignment of 'opacity'
};

```

If you take more memory in a sequential access context without significantly improving accessing patterns, then you'll generally incur more cache misses. On top of that the stride to get from one entity to the next increases and to a variable size, making you have to take variable-sized leaps in memory to get from one entity to the next just to see which ones have the components you're interested in.

So using a "vertical" representation as you do of storing component types is actually more likely to be optimal than "horizontal" alternatives. That said, the problem with cache misses with the vertical representation can be exemplified here:

Where the arrows simply indicate that the entity "owns" a component. We can see that if we were to try to access all the motion and rendering components of entities that have both, we end up jumping all over the place in memory. That kind of sporadic access pattern can have you loading data into a cache line to access, say, a motion component, then access more components and have that former data evicted, only to load the same memory region again that was already evicted for another motion component. So that can be very wasteful loading the exact same memory regions more than once into a cache line just to loop through and access a list of components.

Let's clean up that mess a little bit so that we can see more clearly:

Note that if you encounter this kind of scenario, it's usually long after the game has started running, after many components and entities have been added and removed. In general when the game starts out, you might add all the entities and relevant components together, at which point they might have a very orderly, sequential access pattern with good spatial locality. After a lot of removals and insertions though, you might end up getting something like the above mess.

A very easy way to improve that situation is to simply radix sort your components based on the entity ID/index that owns them. At that point you get something like this:

And that's a much more cache-friendly access pattern. It's not perfect since we can see that we have to skip over some rendering and motion components here and there since our system is only interested in entities that have *both* of them, and some entities only have a motion component and some only have a rendering component, but you at least end up being able to process some contiguous components (more in practice, typically, since often you'll attach relevant components of interest, like maybe more entities in your system which have a motion component will have a rendering component than not).

Most importantly, once you have these sorted, you won't be loading data a memory region into a cache line only to then reload it in a single loop.

And this doesn't require some extremely complex design, just a linear-time radix sort pass every now and then, maybe after you've inserted and removed a bunch of components for a particular component type, at which point you can mark it as needing to be sorted. A reasonably-implemented radix sort (you can even parallelize it, which I do) can sort a million elements in about 6ms on my quad-core i7, as exemplified here:

```
Sorting 1000000 elements 32 times...
mt_sort_int: {0.203000 secs}
-- small result: [ 22 48 59 77 79 80 84 84 93 98 ]
mt_sort: {1.248000 secs}
-- small result: [ 22 48 59 77 79 80 84 84 93 98 ]
mt_radix_sort: {0.202000 secs}
-- small result: [ 22 48 59 77 79 80 84 84 93 98 ]
std::sort: {1.810000 secs}
-- small result: [ 22 48 59 77 79 80 84 84 93 98 ]
qsort: {2.777000 secs}
-- small result: [ 22 48 59 77 79 80 84 84 93 98 ]

```

The above is to sort a million elements 32 times (including the time to `memcpy` results before and after sorting). And I'm assuming most of the time you won't actually have a million+ components to sort, so you should very easily be able to sneak this in now and there without causing any noticeable frame rate stutters.
> 1 votes

---
Tags: c++, performance, entity
---