# Question
Title: Mechanics to keep mobs and environment alive without using tons of memory?
I'm working on a server for a little mobile MMORPG. This consists mainly of two important features: mobs and environment resources like trees, rocks etc.

The world is randomly generated and each time a player jumps to another grid, the server generates new mobs and resources for that area. Those are simply getting stored in dictionaries or lists, but are kept permanently in memory.

The problem here is that we need to find a way to save and load those entities without keeping them alive in memory for the rest of the day. This just causes huge memory usage which breaks the server at some point.

We also can't destroy those entities once a player leaves the area because players could abuse this by leaving/joining an area until rare mobs or resources spawn.

What mechanics would you recommend for dealing with this issue?

# Answer
> 37 votes
First of all, are you sure you really need that? Have you calculated the memory footprint?

A small back-of-the-envelope calculation: A single mob and its state should fit into 100 byte of data. Let's give it a whole kByte, in case you are doing something extraordinary. When a cell has 1000 such entities, it requires a MByte. If your world is 100x100 cells, you would need 10 GByte of RAM. That's a lot, but still within a reasonable order of magnitude. The hoster where I hosted my last multiplayer project offers servers with up to 768 GB of RAM. And that's still not the limit of what's *technically* possible RAM-wise (if you have a deep budget). But I am just inventing numbers here. You should have much better data about the planned size of your world, its entity density, the memory footprint of each entity and the memory footprint you need for any other features of your game.

But let's say that you did the math on your own and come to the conclusion that the memory footprint will be too much for the kind of server you budgeted for. So you indeed have to get that memory footprint down. In that case you can save a lot of memory by only having those cells in memory which have active players and storing the data of all others on the hard drive.

When you have areas without any online characters in them, suspend that area by persisting the state of all entities to hard drive and removing it from memory. You can store that data in a database or by inventing your own file format.

When a player enters a suspended area, reload it from file/database and initialize all entities according to the suspended data. If you have any timed processes which are supposed to continue even when there is no player nearby (like regrowth of resources), determine how much time elapsed since the cell was suspended and simulate that time accordingly.

# Answer
> 14 votes
One way you could solve this problem is not actually storing state on disk, but just setting up your generation code to use a seed for the random number generator, so it generates the same thing for a given area every time the area is generated, deterministically.

Then you just keep the 1000 or so most recently visited areas in memory. When areas are evicted from that cache, they will reset to their default state the next time someone goes there, but it will be the *same* default state every time without you needing to have saved it anywhere. You can't game the system to force rare things to appear, but the things that do appear will eventually "recharge" if left alone long enough.

If you don't want the rare stuff to always be in the same places, you could mix in the date with your random seed, so that every day each area gets a new default state with different stuff in it.

# Answer
> 4 votes
# Save it to the hard drive instead.

Saving large quantities of data in a non-volatile fashion is literally why hard drives were invented. If a player isn't interacting with it anymore, you won't need to rapidly access it, so why keep it in the RAM? Just save it to the your server's hard drive in a text file or something.

# Answer
> 1 votes
Option A: For a project that we worked on, we had utilized grouping. It was one creature (with a model of many creatures), but had many hitboxes. When a hitbox HP became 0, it would divide the creature and create a second or third model.

Option B: Utilize low-poly models. We had to use this a long time ago for massive battles with multiple mobs.

Option C: If you are very invested in keeping multiple mobs with multiple movements then you could move the issue to IT by use elastic servers. Amazon, Google, and Microsoft Azure all offer it; however, you would have to have a more sophisticated area/zoning mechanism. Additionally, the prices for server costs can also increase.

---
Tags: unity, android, server, memory
---


title: Add impulse and torque to a cube

text:
# Question
Title: Add impulse and torque to a cube
I would like to spawn a cube if I press space and apply a short impulse of force and torque to make the cube rotate. I have some calculations for the impulse but I think they are wrong since the cube only gets faster over time and not fast on the impulse. The formular for the impulse is p = m · v. In my case I decided to give the cube a mass of 1.

At the moment I calculate the whole impulse thing this way in c++:

```
                f = 8.f / dt; //force = impulse / dt
                a = f / 1; //acceleration = force / mass
                v += dt * a; //velocity = velocity + a * dt
                p = m_pObject1->getPosition()[0];
                p += v * (float)event.dt; //position= position + v * dt
                m_pObject1->setPosition(glm::vec3(p,m_pObject1->getPosition()[1], m_pObject1->getPosition()[2]));

```

I am sure I am doing something wrong here also I am a little bit lost in implementing the torque here. I hope my code and question is clear and I would be happy to see some suggestions. :)

Kind regards

# Answer
Torque is just a rotational version of the same principle as linear impulses:

Let us look at

```
F = ma

```

To compute the change in velocity, we change it to

```
a = F/m

```

Likewise we can say:

```
T = Iw

```

Where T is torque, I is inertia, and w is angular acceleration. Let's rearrange that:

```
w = T/I

```

Now we can use torque to compute the change in rotation. However, angular acceleration is a vector, and inertia is a *tensor*, that is a matrix, representing the resistance to change in velocity along 3 axes. This creates a small issue, in that we cannot divide a vector by a matrix directly. but let's construct our tensor first:

```
float ix = cube.height * cube.height;
//cube so all dimensions equal,
//but other objects may not be
ix = (cube.mass * (ix + ix + ix) )/12.0f;
matrix3x3 inertia = {{ix, 0.0f, 0.0f},
                     {0.0f, ix, 0.0f},
                     {0.0f, 0.0f, ix}};

```

But first, we need to compute T. To compute T we need to know where on the cube, the linear impulse is being applied (point p). Once we know this, we can calculate the level vector, t:

```
vec3 t = p-cube.centre();
// the lever is defined as a vector from the centre of mass, to the point of impulse

```

Now we can compute the torque:

```
T = F X t

```

where T is the cross product of the linear force (F) and the lever(t)

Now, in order to perform our division, we use a little trick. We multiply the torque impulse by the *inverse* of the inertia tensor, in order to get the change in angular velocity:

```
w = inertia.inverse() * T;

```

This will give us our final value. This is a vector, who's magnitude is the amount of acceleration, and the normalized vector is the axis of rotation.

Update:

A final point on updating position/orientation, and calculus. They are not directly changed by forces. An impulse, or force, translates to a change in velocity, or acceleration. It then follows that velocity is a change in position. Calculus is the mathematics of change.

Once you have computed your change in linear velocity, you simply add it to your cubes current velocity. Same with angular velocity.

```
cube.velocity += a; //a is acceleration: a=F/m
cube.angularVelocity += w; //w is angular acceleration: w = T/I

```

Then, during each frame, or update, you perform *integration* on the velocities to make changes to position/orientation, thusly:

```
position+=velocity * deltaTime; //deltatime is a very small interval (~60th of a second)
orientation+=angularvelocity*deltaTime;

```

This is known as Euler integration. It is very useful, but not the only way of doing this. You can also look into Verlet integration, which I will not go into here.
> 1 votes

---
Tags: c++, physics, torque
---


title: No AA support in Godot 3.1?

text:
# Question
Title: No AA support in Godot 3.1?
I'm using Godot 3.1.1 and just realized that there is no available AA options. According to some post, Godot 2 supports FXAA, but some reason it's took out from 3. So I try to get FXAA for Godot 3.1, but couldn't find any.

I don't want to publish my game without Anti Aliasing. Is there a way to apply FXAA in Godot 3.1.1 which using GLES3?

# Answer
> 5 votes
Still Godot 3.1 doesn't support FXAA, however there are some user implemented version.

If you are using GLES3, use this: https://gist.github.com/cart/7d2da58eb28c75c0952787f29f3e562f

If you are using GLES2, use this: https://github.com/atomius0/Godot-3.1-FXAA-Shader/blob/master/project/fxaa/fxaa.shader

Steps to apply FXAA:

1. Create ColorRect Node
2. Set Layout to "Full Rect" so that it covers whole screen
3. Create new Shader Material and assign shader script in your ColorRect node you just created.
4. Run the game.

Tested with Godot 3.1.1 with GLES3 in 3D scene.

---
Tags: godot, antialiasing, post-processing
---


title: Unity Build Failed - Duplicate Class

text:
# Question
Title: Unity Build Failed - Duplicate Class
I'm here struggling for hours to build my game (android) and 'Execution failed for task : checkReleaseDuplicateClasses'

```
Duplicate class androidx.annotation.AnimatorRes found in modules androidx.annotation.annotation-1.0.0.jar (androidx.annotation.annotation-1.0.0.jar) and androidx.annotation.annotation-1.1.0.jar (androidx.annotation.annotation-1.1.0.jar)
Duplicate class com.google.android.gms.auth.api.signin.zaa found in modules classes.jar (:com.google.android.gms.play-services-base-17.0.0:) and classes.jar (:com.google.android.gms.play-services-base-17.1.0:)

```

... are just two examples of the 486 warnings I'm getting. Can anyone help a noob out? Thanks so much for your time!

# Answer
To solve this I deleted com.google.android.gms.play-services-base-17.0.0 and androidx.annotation.annotation-1.0.0 from Plugins/Android folder.
> 1 votes

---
Tags: unity, android
---


title: Make a game from a TV game show

text:
# Question
Title: Make a game from a TV game show
I'm an indie developper and I'm planning to do a game based on a TV game show. I would like to know if I could have problems with the law if I do it. I know I should consult a lawyer but I can not afford to do it. For example, can I make a game called "Ninja Warrior, the game", and try to reproduce the game show? Since this isn't a copy of an existing video game, but an adaptation of a game show, I'm confused of what I can do or not. Any help is appreciated.

# Answer
You cannot use anything that is subject to copyright, trademark, patent, et cetera without permission.

TV show titles are typically trademarks, so using them is potentially treading on dangerous ground. If your game is similar enough to the Ninja Warrior show that one could make a case that somebody would confuse your product for theirs, you will likely lose any resulting legal action.
> 3 votes

---
Tags: copyright, trademark, intellectual-property
---


# Question
Title: How to run code selectively only when a specific trigger collider has been hit
I have 2 objects both with trigger colliders. The first object has only 1 trigger collider (imagine this to be a sword).

The second object (a person) has multiple colliders. One is a non-trigger collider (used for collision detection for walls, ground) and then multiple trigger colliders on different parts of the body (the purpose is for hurt box).

Now when the sword hits the person, I want to only process code for those trigger colliders and to be able to detect which of those trigger colliders got hit (arm, leg, etc.).

But the event only exposes a parameter hit for the other collider:

```
void OnTriggerEnter(Collider other)
{
    if (other.gameObject.layer == LayerMask.NameToLayer(Constants.LAYER_HITBOX_PLAYER))
    {
        // Run code here
    }
}

```

I want to run code only when certain trigger collider are hit, like for example, when the head is hit, or the body, etc. How do I get this info to be able to run conditional code on this method?

# Answer
> 1 votes
I haven't found any information related to this. So the best solutions I can think of are only workarounds and there probably isn't any built in solutions to do this. It is very inconvenient indeed.

```
[SerializeField] private GameObject _hammerHeadGameObject;

[SerializeField] private LayerMask _impulseLayerMask;
[SerializeField] private CinemachineImpulseSource _cinemachineImpulseSource;
[SerializeField] private GamepadHapticSettings _hapticSettings;

private void OnCollisionEnter(Collision other)
{
    if ((this._impulseLayerMask & (1 << other.collider.gameObject.layer)) != 0)
    {
        for (int a = 0; a < other.contactCount; a++)
        {
            if (other.contacts[a].thisCollider.gameObject == this._hammerHeadGameObject)
            {
                this._cinemachineImpulseSource.GenerateImpulse();

                InputSystem.GetDevice<Gamepad>().TriggerHaptic(this._hapticSettings);
            }
        }
    }
}

private void OnTriggerEnter(Collider other)
{
}

```

This is an example of how I get colliders from `Collision`. Not the most efficient solution, but it works. The problem with `Collider` \- there is a high chance that it's not possible to get contacts from it, at least I haven't found how to.

---

**1.**

We can simulate our own collision to get information. The process is pretty straightforward:

1. Trigger collision.
2. Work out what type of collider it is.
3. Simulate collision with same settings (bounds, size, offset...).
4. Get colliders that were hit (those will be the ones you are looking for).

Small example:

```
private void OnTriggerEnter(Collider other)
{
    if ((other as BoxCollider) != null)
    {
        BoxCollider boxCollider = (other as BoxCollider);

        Collider[] colliders = Physics.OverlapBox(boxCollider.center, boxCollider.size / 2f, boxCollider.transform.rotation); // I am not sure about (/ 2f) - not tested.
    }
}

```

Basically we solve this from another perspective from original. We take the collision information from other colliders that hit the colliders we need information about.

Same approach is taken in second solution.

**2.**

In this approach we process collision in reverse. Instead of finding the collision in the original object. We have the script attached to other objects that can collide with it. And upon collision we notify that object that it has been hit and pass it a collider that was hit.

```
private void OnTriggerEnter(Collider other)
{
    if (other.TryGetComponent<ObjectThatCanBeHit>(out ObjectThatCanBeHit objectThatCanBeHit))
    {
        objectThatCanBeHit.CollisionHappened(other); // There we process that collision.
    }
}

```

---

All in all, the first solution is more flexible, but requires more processing power if there are lots of collisions. Although, the second one can be intense as well, it all depends on quantity of objects in the scene and number of collisions. So some kind of benchmark would be required, I am just saying that first one would require more processing power from the first look and intuition.

# Answer
> 1 votes
If you don't mind just create children to the object that would be hit. Let the children's names be indexes for your hit registry. In my example, I named the head hitbox as "0", chest as "1", arms as "2" and legs as "3".

Attach a script for "Hit Registry" to them. Then you should have a public function in the parent object (the object that would be hit) to determine the damage, the bleed, the punch values (if you need). The function has to have an "int" input for the registry.

```
public void Hit(int registry, float damage, float punch)
{
    //Run the code here
}

```

Then you can have the damage and punch values from the collider if you want. In my example, I declared them as constants.

```
float damage = 10;
float punch = 10;

void OnTriggerEnter2D(Collider col)
{
    transform.parent.GetComponent<HitBox>().Hit(int.Parse(gameObject.name), damage, punch);
}

```

So you will send the parsed int data for your hit function to know where has been hit. And in the final you can add switch to your hit function to deliver the damage to the object.

```
public void Hit(int registry, float damage, float punch)
{
    switch (registry)
    {
        case 0:
            //Run the hit code for head.
            break;
        case 1:
            //Run the hit code for chest.
            break;
        case 2:
            //Run the hit code for arms.
            break;
        case 3:
            //Run the hit code for legs.
            break;

    }
}

```

# Answer
> 0 votes
you can make `other` colliding GameObject to define its own Event Function. for example other Object hast Enemy Class Component that has `Die()` function. so you have to write:

```
Action myAction;
void OnTriggerEnter(Collider other)
{
    myAction= Other.GetComponent<Enemy>().Die;
myAction.Invoke();
}

```

if you want to check function of different classes you can use polymorphism and get component by interface and those classes should implement the same Die Function form interface. you can getComponent like this:

```
IAttribute attribute = GetComponent(typeof(IAttribute)) as IAttribute;

```

but best practices is to instead of making you OnTriggerEnter check for different types of triggers, make those triggers to implement their own OnTriggerEnter and Run their own function.

---
Tags: unity
---


# Question
Title: How can I use websockets in a Unity WebGL project?
There are plenty of good Websocket APIs for C#, but I run into trouble when targeting Unity WebGL due to this restriction described in the Unity documentation:

> **No direct socket access**
>
> Due to security implications, JavaScript code does not have direct access to IP Sockets to implement network connectivity. As a result, the .NET networking classes (ie, everything in the `System.Net` namespace, particularly `System.Net.Sockets`) are non-functional in WebGL. The same applies to Unity’s old `UnityEngine.Network*` classes, which are not available when building for WebGL.
>
> If you need to use Networking in WebGL, you currently have the options to use the `WWW` or `UnityWebRequest` classes in Unity or the new Unity Networking features which support WebGL, or to implement your own networking using WebSockets or WebRTC in JavaScript.

How can I work around this restriction for networking in my Unity WebGL game?

# Answer
> 8 votes
As the documentation says, The Unity scripting API does not expose direct WebSocket access itself. But you can access the native web browser API by calling JavaScript from Unity C# scripts.

1. Create a JavaScript file which defines the functions you need and implements them by calling native browser functionality.
2. Give it the file extension `.jslib`
3. Put it into the directiory `Assets/Plugins` of your Unity project
4. Import them into a C# script by defining a class-level method with the prefix `[DllImport("__Internal")] private static extern`.

Example for a websocket.jslib:

```
mergeInto(LibraryManager.library, {

  WebSocketInit: function(url, protocol) {
         this.socket = new WebSocket(url, protocol);
  },
  WebSocketSend: function(message) {
         this.socket.send(message);
  }

});

```

Example of a C# script using those methods:

```
using UnityEngine;
using System.Runtime.InteropServices;

public class WebSocketSender : MonoBehaviour {

    [DllImport("__Internal")]
    private static extern void WebSocketInit(string url, string protocol);

    [DllImport("__Internal")]
    private static extern void WebSocketSend(string message);

    void Start() {
        WebSocketInit("wss://example.com/gameserver", "mygameprotocol");
    }

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
                WebSocketSend("Pew!Pew!Pew!");
        }
    }
}

```

But please keep in mind that **WebSockets are not native TCP/IP sockets**. The protocol adds some framing and masking to the messages which makes them unable to implement any raw TCP/IP protocols. So you won't be able to use WebSockets to interface with any server which doesn't implement the WebService protocol.

---
Tags: unity, c#, unity-networking, websocket, unity-webgl
---


# Question
Title: KinematicBody returns null to try get collided Rigidbody
Player is a KinematicBody and enemy is a Rigidbody. I'm using move\_and\_slide() to move player. When they collided, each both push them opposite direction, so it seems like physics stuffs working, however when I try to get collided object, it always returns null.

Using move\_and\_collide() returns null, and try this way also returns null:

```
for index in get_slide_count():
    var collision = get_slide_collision(index)
    print(collision)

```

However when I changed the type of enemy to StaticBody, now it gives me enemy. But I don't want to use StaticBody to enemy, they needed to move! Why get collided is always null even it's collided with Rigidbody?

# Answer
You need to pass `false` for the `infinite_inertia` parameter of `move_and_collide`. From the docs:

> If infinite\_inertia is true, body will be able to push RigidBody nodes, but it won’t also detect any collisions with them. If false, it will interact with RigidBody nodes like with StaticBody.
> 1 votes

---
Tags: physics, rigidbody, godot, kinematic
---


# Question
Title: How can I simple use global or individual bool flag/s?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DoorsManager : MonoBehaviour
{
    public bool globalDoorsLockState = false;
    public bool[] doorsLockState;
    public GameObject[] doorsShieldFX;

    // Start is called before the first frame update
    void Start()
    {
        doorsShieldFX = GameObject.FindGameObjectsWithTag("ShieldFX");
        doorsLockState = new bool[doorsShieldFX.Length];

    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < doorsLockState.Length; i++)
        {
            if (globalDoorsLockState == true)
            {
                doorsLockState[i] = true;
            }
            else
            {
                doorsLockState[i] = false;
            }
        }
    }
}

```

I want to be able to change all the doors flags to true/false or each door individually. Now in the Update it's working only for the global.

How can I add code or change it so it will also be able to change each door lock state individually?

# Answer
First of all I recommend not checking the `doorLockState` and `globalDoorLock` state in the update method. That method gets called on **every frame** (which impacts performance) and is better reserved for functions that actually needs to be checked constantly. (Like player movement)

Now back on topic you want to be able to change the lock state of every door individually as well as being able to change the lock state of every door at once. I recommend instead of storing the `lockStates` of every door in the `DoorsManager` (`public bool[] doorsLockState`) that you make a `Door` object that stores his own lock state. For that Door Object you can also create two methods that can change the `lockState` to either locked or unlocked.

To unlock (or lock) all doors at once you can still keep the *`globalDoorsLockState`* variable and control it using two methods similar to the `Door` object one that unlocks all doors and one that locks all doors. You can access these doors by storing the doors (instead of its lock states) in the `DoorsManager`.

Here is a simple example of how you can do it:

```
public class DoorsManager : MonoBehaviour
{
    public bool GlobalDoorsLockState = false;
    // Assign these in the inspector
    public Door[] DoorList;

    public void UnlockDoors()
    {
        GlobalDoorsLockState = false;
        UpdateDoorsLockState();
    }

    public void LockDoors()
    {
        GlobalDoorsLockState = true;
        UpdateDoorsLockState();
    }

    public void UpdateDoorsLockState()
    {
        foreach(door in DoorList)
        {
            if (GlobalDoorsLockState)
            {
                door.LockDoor();
            }
            else
            {
                door.UnlockDoor();
            }
        }
    }
}

public class Door : MonoBehaviour
{
    private bool lockState = true;

    public void UnlockDoor()
    {
        // Inside this method you can also do more stuff like play a sound effect
        lockState = false;
    }

    public void LockDoor()
    {
        lockState = true;
    }
}

```

Keep in mind that the `Door` class is supposed to be in a separate file.
> 2 votes

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


# Question
Title: Can't open scripts in Unity 2019.2.11.f1 version
I'm using Visual Studio 2017, Unity Hub to 2.1.3 and just created a project using Unity's 2019.2.11.f1 version.

Once trying to open a script in Unity, it doesn't open and then I'm forced to use Task Manager to End Unity's task because can't even close it normally due to not being able to interact with the screen. **No errors or warnings, VS doesn't open, can't interact with Unity anymore.**

This doesn't block me from working, it just isn't as convenient as before.

# Answer
I managed to solve it by going through all the next steps.

1. Did some research and found a thread where people write about going through similar or the same problem but didn't really gave me an answer.
2. Restarted Unity and ensured all packages are updated, but the problem remained.

3. Downgraded the project to 2019.2.7f2 and to 2019.2.1f1 (in Unity Hub), but this wasn't enough.

4. I tried to open the script in VS 2017 and it opens fine.
5. Checked possible updates in VS 2017 and ensured it's up-to-date.

***To note***: It's possible that the problem could have been solved right away just by updating the VS 2017.
> 1 votes

---
Tags: unity, visual-studio
---


# Question
Title: How to display and hide complex object part in 2.5D
I am working on a 2.5D mechanical app. I use 3D software like Blender to render the 3D model to create the 2D assets for the 2D game engine (which's cocos-creator , but it doesn't matter for this case).

How can I hide a part of object which's covered by another object with in the game engine? A sort of mask or something else, I am not sure.

For it has hundreds of object in the scene, like a car engine with all parts. So the solution I am looking for need to be automatic or half-automatic generated by 3D software (eg.Blender, etc), instead of full manual work like using Photoshop to create the mask.

# Answer
> -1 votes
Since you wanted an agnostic answer, This answer will deal with how to *integrate* this in any 2D game framework.

You have supplied orthographic projection models. What you can do is, say, you have an origin for each of those models, and each pixel on the model itself will correspond to a *depth value* based on that offset. Blender apparently allows the z buffer value to be output directly to an image. The alternative is to create another program, say in opengl, webgl, directx, metal, or vulkan which does the same, but using the geometry you've generated. Once you have this depth value, it will probably be normalized between zero and 1.0, so you'll need to get the near and far clipping plane information. In blender you can get this from 3D view area properties. If you used a custom solution, you would have set this yourself in your orthographic transform matrix.

You can then use the far and near values to re-normalize the depth information if you wish, or you could skip this process if you are sure every model will be rendered using the same near and far values.

Re normalizing would look like this:

```
renormalized_depth = near + (far - near) * depth;

```

depth is then calculated, once you have your image, as the depth texture you've just created, offset by the current position of the image and offset where it was rendered originally to get the depth value (since depth starts at zero at your camera face, not at the origin of the object).

To account for the original position you placed it at for rendering you would need to do the following:

```
renormalized_depth = renormalized_depth - object_centroid_distance;

```

and then a simple offset for the current centroid would work for current depth.

Once you have this information, you can then go to your 2D rendering, and have a separate depth image you write to at the same time you write to your rendered image. For each pixel you are rendering your texture to, check if the value in the depth buffer is closer than the currently being written value (you should have a texture, depth pair at thispoint) if it is, don't write the color value out. Continue this for every image with depth.

Note In openg, vulkan, webgl, any of the other APIs, this is taken care of automatically in 3d rendering. Cocos does have shader support where this can be easier to manage if you have the depth information. Cocos may have 3D support, but i'm not sure to what extent, the documentation is very light on it.

Such a shader would look like this (I can't tell whether Cocos uses opengl ES 3.1 or not, which uses a newer shader version, but I'll be using similar syntax here) (note in opengl there are issues with reading and writing to the same texture):

# Vertex Shader

```
#version 300 es
// vertex points for texture drawn can replace this with generated coordinates if using glDrawArrays(...) with no attached vertex buffer https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glDrawArrays.xhtml
in vec2 position_attribute;
in vec2 texture_coord_attributes;
in mat4 mvp_matrix;

out vec2 texture_coordinates
void main(){
    texture_coordinates = texture_coord_attributes
    gl_Position = mvp_matrix * vec4(position_attribute, 0.0,1.0);
}

```

# Fragment Shader

```
#version 300 es
uniform vec3 texture position;
uniform sampler2D texture_depth;
uniform sampler2D texture_color;
uniform sampler2D current_depth_texture;
//location of first color output attachment
layout(location = 0) out vec4 render_color;
//location of second depth output attachment
layout(location = 1) out vec4 render_depth;

in vec2 texture_coordinates;
in vec2 screen_coordinates;

void main(){
    float depth = texture(depth, texture_coordinates).r;
    float current_depth = texture(current_depth_texture, screen_coordinates);
    if(depth < current_depth){
        render_depth = depth;
        render_color = texture(texture_color, texture_coordinates);
    }else{
        render_depth = current_depth;
    }
}

```

Of course, this can all be replicated on the CPU if you don't have access to these facilities for what ever reason.

# Answer
> -2 votes
In Unity this would be very easy to do that, but my question is, do you have actual 3d models? if yes, than you can go for orthographic projection and do what you want to do. No need to worry about the depth or masking. Even if you don't have 3d models, i would waste time in creating simple models and when everything will start working fine, than i will start playing with the shaders to make models look like how you wanted them to look like.

if you don't want to use unity, than you have to split your all images(assets) into tiles, and work like a tile game, or there's another possibility to swap images when they join.

If I were you, i would have done this using former approach.

---
Tags: 2d, sprites
---


# Question
Title: What is the status of Monogame now that XNA has been discontinued?
XNA has officially been discontinued, with support no longer being offered by Microsoft. Does this mean that Monogame has died also? I see that the site still says it is based upon XNA 4. What is the official status of Monogame?

# Answer
> 7 votes
Quite the opposite. MonoGame stands to be the perfect replacement for existing XNA developers. It doesn't do everything that XNA did yet but there's no good reason why it can't. Coupled with the fact that it sports many more platforms and it's already being used in many reputable games I'm confident it will be great for some time to come.

Edit: I wrote this answer on my phone, let me elaborate a little more.

Firstly, MonoGame does not depend on XNA, it's an open source implementation of the XNA API and does *not* use Microsoft's implementation in any way. They make it clear in the Contributing to MonoGame instructions that no code from the XNA framework is actually used in the implementation, only the public API. Therefore, MonoGame exists on it's own without XNA.

Secondly, the MonoGame project is being actively developed. You can see on github there is plenty of commit activity going on. The most recent post on their website was 2 days ago announcing 2 MonoGame titles coming to PS4.

Third, the MonoGame forums are active. The most recent posts are today, and plenty of discussions going on around development, new game announcements, new platform support and solving problems. They also have other active social feeds like twitter and as Noctrine pointed out an "official status"

So, there's plenty of evidence to indicate that MonoGame has not died.

# Answer
> -1 votes
hmm i have been working on a project for 4 years now, 4 years ago i put it aside, because there were too many bugs in Monogame. I continued the work 2 month ago, only to struggle with the exact same issue i did back then (4 years ago), it still doesnt work, and its still full of bugs and memory leaks. :( - Many of the bugs has been found years ago (2016), and reported and even talked about by the developers, but they are still not fixed. I have a hard time seeing how this will ever be production ready, im planning to switch to Unity, as the majority. - Too bad my new 3D Engine (writte in XNA, attempted ported to Monogame will never be a reality) :( as im 98% done with it.

---
Tags: xna, c#, xna-4.0, monogame
---


# Question
Title: DirectX12 root signature error while using compute shader with ConsumeStructuredBuffer
I am getting this error: I do not have CBV, but it looks like I am forgetting to bind a CBV.

D3D12 ERROR: ID3D12Device::CreateComputePipelineState: Root Signature doesn't match Compute Shader: Shader CBV descriptor range (BaseShaderRegister=0, NumDescriptors=1, RegisterSpace=0) is not fully bound in root signature \[ STATE\_CREATION ERROR #882: CREATECOMPUTEPIPELINESTATE\_CS\_ROOT\_SIGNATURE\_MISMATCH\]

the hlsl is very small..it's just add to a particle system

```
struct Particle
{
    float3 Position;
    float3 Velocity;
    float3 Acceleration;
};
float TimeStep = 1.0f / 60.0f;
ConsumeStructuredBuffer<Particle> gInput : register(u0);
AppendStructuredBuffer<Particle> gOutput : register(u1);
[numthreads(16, 16, 1)]
void CS()
{
// Consume a data element from the input buffer.
    Particle p = gInput.Consume();
    p.Velocity += p.Acceleration * TimeStep;
    p.Position += p.Velocity * TimeStep;
// Append normalized vector to output buffer.
    gOutput.Append(p);
}

```

And the application is

```
#include "../../Common/d3dApp.h"
#include "../../Common/UploadBuffer.h"

using Microsoft::WRL::ComPtr;
using namespace DirectX;
using namespace DirectX::PackedVector;

#pragma comment(lib, "d3dcompiler.lib")
#pragma comment(lib, "D3D12.lib")

struct Particle
{
    XMFLOAT3 Position;
    XMFLOAT3 Velocity;
    XMFLOAT3 Acceleration;
};

class ParticleAddCSApp : public D3DApp
{
public:
    ParticleAddCSApp(HINSTANCE hInstance);
    ParticleAddCSApp(const ParticleAddCSApp& rhs) = delete;
    ParticleAddCSApp& operator=(const ParticleAddCSApp& rhs) = delete;
    ~ParticleAddCSApp();

    virtual bool Initialize()override;

private:
    virtual void OnResize()override;
    virtual void Update(const GameTimer& gt)override;
    virtual void Draw(const GameTimer& gt)override;

    void DoComputeWork();

    void BuildBuffers();
    void BuildRootSignature();
    void BuildShadersAndInputLayout();
    void BuildPSOs();

private:

    ComPtr<ID3D12RootSignature> mRootSignature = nullptr;

    std::unordered_map<std::string, ComPtr<ID3DBlob>> mShaders;
    std::unordered_map<std::string, ComPtr<ID3D12PipelineState>> mPSOs;

    std::vector<D3D12_INPUT_ELEMENT_DESC> mInputLayout;

    const int NumDataElements = 16*16;

    ComPtr<ID3D12Resource> mInputBufferA = nullptr;
    ComPtr<ID3D12Resource> mInputUploadBufferA = nullptr;
    ComPtr<ID3D12Resource> mOutputBuffer = nullptr;
    ComPtr<ID3D12Resource> mOutputBuffer1 = nullptr;
    ComPtr<ID3D12Resource> mReadBackBuffer = nullptr;

};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
    PSTR cmdLine, int showCmd)
{
    // Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
    _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

    try
    {
        ParticleAddCSApp theApp(hInstance);
        if(!theApp.Initialize())
            return 0;

       // return theApp.Run();
        return 0;
    }
    catch(DxException& e)
    {
        MessageBox(nullptr, e.ToString().c_str(), L"HR Failed", MB_OK);
        return 0;
    }
}

ParticleAddCSApp::ParticleAddCSApp(HINSTANCE hInstance)
    : D3DApp(hInstance)
{
}

ParticleAddCSApp::~ParticleAddCSApp()
{
    if(md3dDevice != nullptr)
        FlushCommandQueue();
}

bool ParticleAddCSApp::Initialize()
{
    if(!D3DApp::Initialize())
        return false;

    // Reset the command list to prep for initialization commands.
    ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), nullptr));

    BuildBuffers();
    BuildRootSignature();
    BuildShadersAndInputLayout();
    BuildPSOs();

    // Execute the initialization commands.
    ThrowIfFailed(mCommandList->Close());
    ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
    mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);

    // Wait until initialization is complete.
    FlushCommandQueue();

    DoComputeWork();

    return true;
}

void ParticleAddCSApp::OnResize()
{
}

void ParticleAddCSApp::Update(const GameTimer& gt)
{
}

void ParticleAddCSApp::Draw(const GameTimer& gt)
{
}

void ParticleAddCSApp::DoComputeWork()
{
    // Reuse the memory associated with command recording.
    // We can only reset when the associated command lists have finished execution on the GPU.
    ThrowIfFailed(mDirectCmdListAlloc->Reset());

    // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
    // Reusing the command list reuses memory.
    ThrowIfFailed(mCommandList->Reset(mDirectCmdListAlloc.Get(), mPSOs["particleAdd"].Get()));

    mCommandList->SetComputeRootSignature(mRootSignature.Get());

    mCommandList->SetComputeRootUnorderedAccessView(0, mInputBufferA->GetGPUVirtualAddress());
    mCommandList->SetComputeRootUnorderedAccessView(1, mOutputBuffer->GetGPUVirtualAddress());

    mCommandList->Dispatch(1, 1, 1);

    // Schedule to copy the data to the default buffer to the readback buffer.

    //D3D12_RESOURCE_STATE_COPY_SOURCE: The resource is used as the source in a copy operation.
    //D3D12_RESOURCE_STATE_COPY_DEST: The resource is used as the destination in a copy operation.

    mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(mOutputBuffer.Get(),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE));

    //We need to read the data back from the GPU after computer shader does its calculation
    //mCommandList->CopyResource(Destination: CPUData, Source: GPUData);
    mCommandList->CopyResource(mReadBackBuffer.Get(), mOutputBuffer.Get());

    mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(mOutputBuffer.Get(),
        D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));

    // Done recording commands.
    ThrowIfFailed(mCommandList->Close());

    // Add the command list to the queue for execution.
    ID3D12CommandList* cmdsLists[] = { mCommandList.Get() };
    mCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);

    // Wait for the work to finish.
    FlushCommandQueue();

    // Map the data so we can read it on CPU.
    Particle* mappedData = nullptr;
    ThrowIfFailed(mReadBackBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mappedData)));

    std::ofstream fout("results.txt");

    for(int i = 0; i < NumDataElements; ++i)
    {
        fout << "(" << mappedData[i].Acceleration.x << ", " << mappedData[i].Acceleration.y << ", " << mappedData[i].Acceleration.z <<
            ", " << mappedData[i].Position.x << ", " << mappedData[i].Position.y << ", " << mappedData[i].Position.z <<
            ", " << mappedData[i].Velocity.x << ", " << mappedData[i].Velocity.y << ", " << mappedData[i].Velocity.z << ")" << std::endl;
    }

    mReadBackBuffer->Unmap(0, nullptr);
}

void ParticleAddCSApp::BuildBuffers()
{
    // Generate some data.
    std::vector<Particle> dataA(NumDataElements);
    for(int i = 0; i < NumDataElements; ++i)
    {
        dataA[i].Acceleration = XMFLOAT3(1.0f, 1.0f, 1.0f);
        dataA[i].Position = XMFLOAT3((float)i, (float)i, (float)i);
        dataA[i].Velocity = XMFLOAT3(10.0f, 10.0f, 0);
    }

    UINT64 byteSize = dataA.size()*sizeof(Particle);

    // Create some buffers to be used as SRV.
    //mInputBufferA = d3dUtil::CreateDefaultBuffer(
    //  md3dDevice.Get(),
    //  mCommandList.Get(),
    //  dataA.data(),
    //  byteSize,
    //  mInputUploadBufferA);

    // Create the actual mInputBufferA buffer resource.
    ThrowIfFailed(md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
        nullptr,
        IID_PPV_ARGS(&mInputBufferA)));

    // In order to copy CPU memory data into our mInputBufferA buffer, we need to create
    // an intermediate upload heap.
    ThrowIfFailed(md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize),
        D3D12_RESOURCE_STATE_GENERIC_READ,
        nullptr,
        IID_PPV_ARGS(mInputUploadBufferA.GetAddressOf())));

    // Describe the data we want to copy into the default buffer.
    D3D12_SUBRESOURCE_DATA subResourceData = {};
    subResourceData.pData = dataA.data();
    subResourceData.RowPitch = byteSize;
    subResourceData.SlicePitch = subResourceData.RowPitch;

    // Schedule to copy the data to the mInputBufferA buffer resource.  At a high level, the helper function UpdateSubresources
    // will copy the CPU memory into the intermediate upload heap.  Then, using ID3D12CommandList::CopySubresourceRegion,
    // the intermediate upload heap data will be copied to mBuffer.
    mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(mInputBufferA.Get(),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_DEST));

    UpdateSubresources(mCommandList.Get(), mInputBufferA.Get(), mInputUploadBufferA.Get(), 0, 0, 1, &subResourceData);

    mCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(mInputBufferA.Get(),
        D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS));

    /*D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc;
    uavDesc.Format = DXGI_FORMAT_UNKNOWN;
    uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
    uavDesc.Buffer.FirstElement = 0;
    uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_APPEND;
    uavDesc.Buffer.NumElements = mNumElements;*/

    // Create the buffer that will be a UAV.
    ThrowIfFailed(md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS),
        D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
        nullptr,
        IID_PPV_ARGS(&mOutputBuffer)));

    //Specifies a heap used for reading back. This heap type has CPU access optimized for reading data back from the GPU,
    //but does not experience the maximum amount of bandwidth for the GPU. This heap type is best for GPU-write-once,
    //CPU-readable data. The CPU cache behavior is write-back, which is conducive for multiple sub-cache-line CPU reads.
    //Resources in this heap must be created with D3D12_RESOURCE_STATE_COPY_DEST, and cannot be changed away from this
    ThrowIfFailed(md3dDevice->CreateCommittedResource(
        &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_READBACK),
        D3D12_HEAP_FLAG_NONE,
        &CD3DX12_RESOURCE_DESC::Buffer(byteSize),
        D3D12_RESOURCE_STATE_COPY_DEST,
        nullptr,
        IID_PPV_ARGS(&mReadBackBuffer)));
}

void ParticleAddCSApp::BuildRootSignature()
{

    // Root parameter can be a table, root descriptor or root constants.
    CD3DX12_ROOT_PARAMETER slotRootParameter[2];

    // Perfomance TIP: Order from most frequent to least frequent.
    slotRootParameter[0].InitAsUnorderedAccessView(0);
    slotRootParameter[1].InitAsUnorderedAccessView(1);

    // A root signature is an array of root parameters.
    CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(2, slotRootParameter,
        0, nullptr,
        D3D12_ROOT_SIGNATURE_FLAG_NONE);

    // create a root signature with a single slot which points to a descriptor range consisting of a single constant buffer
    ComPtr<ID3DBlob> serializedRootSig = nullptr;
    ComPtr<ID3DBlob> errorBlob = nullptr;

    HRESULT hr = D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1,
        serializedRootSig.GetAddressOf(), errorBlob.GetAddressOf());

    if(errorBlob != nullptr)
    {
        ::OutputDebugStringA((char*)errorBlob->GetBufferPointer());
    }
    ThrowIfFailed(hr);

    ThrowIfFailed(md3dDevice->CreateRootSignature(
        0,
        serializedRootSig->GetBufferPointer(),
        serializedRootSig->GetBufferSize(),
        IID_PPV_ARGS(mRootSignature.GetAddressOf())));
}

void ParticleAddCSApp::BuildShadersAndInputLayout()
{
    mShaders["particleAddCS"] = d3dUtil::CompileShader(L"Shaders\\ParticleAdd.hlsl", nullptr, "CS", "cs_5_1");
}

void ParticleAddCSApp::BuildPSOs()
{
    D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
    computePsoDesc.pRootSignature = mRootSignature.Get();
    computePsoDesc.CS =
    {
        reinterpret_cast<BYTE*>(mShaders["particleAddCS"]->GetBufferPointer()),
        mShaders["particleAddCS"]->GetBufferSize()
    };
    computePsoDesc.Flags = D3D12_PIPELINE_STATE_FLAG_NONE;
    ThrowIfFailed(md3dDevice->CreateComputePipelineState(&computePsoDesc, IID_PPV_ARGS(&mPSOs["particleAdd"])));
}

```

# Answer
In the computer shader code, I had to declare the type as "static const", otherwise this would override it from the app via constant buffer.

static const float TimeStep = 1.0f / 60.0f;
> 2 votes

---
Tags: directx12
---


# Question
Title: Resetting variables when starting a new game
What is the best practice when implementing a way to start a game when a previous game has been played and the game's variables have already some kind of values assigned to them?

The most naive answer would be to create a method that would set all the variables and objects the game uses to their default value.

However that would be obviously error prone in cases when some time later a new variable is added to the game and not added to the method where it's set to a default value - such cases could lead to impossible to track bugs when a game would work ok if started first time, but not thereafter.

This would also violate DRY principle as a variable would have a default value at two different places - in the place where it's used and in the method where it's reset.

# Answer
> 0 votes
For those that might ran into same question in the future:

I've decided to go with wrapping the entire logic of my game in a class that gets instantiated when the game starts. When the game ends I just destroy the existing object and create a new one, thus avoiding any chance of bugs when resetting the game.

# Answer
> 4 votes
> The most naive answer would be to create a method that would set all the variables and objects the game uses to their default value.

Do that thing. In the spot where you create a new game (for the first time or are resetting variables), call that function. It will set all of your variables to default and its called from both places. This is perfectly DRY.

> when some time later a new variable is added to the game and not added to the method

Put an invalid value into it when you declare it. Set it to `null` or `-1` or whatever. Something that will absolutely cause a problem if the value isn't set to its proper starting value by your function.

If some of your variables are objects and those objects hold values too...discard them and create `new` ones. Don't bother resetting them, just delete and recreate: the constructor *is* that create-defaults method. If you wanted to, you could do this for your main collection of variables (rather than having them as fields on your `Game` class, make them fields on your `GameData` class and then just create a `new GameData` whenever you start a new game).

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


title: Pybox2d Collision detection explanation

text:
# Question
Title: Pybox2d Collision detection explanation
Hi I am working on a PyBox2D game and it became quite complex and I need to learn about collisions, so I made this very simple script in order to learn collision setting more effectively, however I am completely stuck, I really do not know how to detect whether the collision occurred and how to use that information

I have been stuck on this topic for about a week now. I googled it, looking for tutorials but nothing helped (mostly because these tutorials were not written in python).

So... I would be more than grateful if you showed me on my script for example how to change color of the rectangle when it hits the ground (I am not showing you what I have already tried because there were various ways using e.g. memory locations and I want to make this example as simple as possible.

```
import pygame
import numpy as np
from Box2D.b2 import world, polygonShape, circleShape,edgeShape, staticBody, dynamicBody, kinematicBody, revoluteJoint, wheelJoint, contact
from Box2D import b2Vec2, b2FixtureDef,b2PolygonShape, b2CircleShape, b2Dot,b2EdgeShape, b2Contact,b2ContactFilter,b2Filter, b2ContactListener

pygame.init()

PPM = 15
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pos_X = SCREEN_WIDTH/PPM/3
pos_Y = SCREEN_HEIGHT/PPM

Box_2_World = world(gravity = (0.0, -9.81), doSleep = True)

Rectangle = Box_2_World.CreateDynamicBody(position = (pos_X+5, pos_Y + 5),
                                    angle = np.pi/4,
                                    fixtures = b2FixtureDef(
                                        shape = b2PolygonShape(box= (5,5)),
                                        density = 1000,
                                        friction = 1000,
                                                            ))
Ground = Box_2_World.CreateStaticBody(position = [0,0],
                                    angle = 0,
                                    fixtures = b2FixtureDef(
                                        shape = b2PolygonShape(box= (50,1)),
                                        density = 1000,
                                        friction = 1000,
                                                            ))

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
colors = {dynamicBody: (133, 187, 101, 0),  staticBody: (15, 0, 89, 0)}
FPS = 24
TIME_STEP = 1.0 / FPS
running = True

def my_draw_polygon(polygon, body, fixture):
    vertices = [(body.transform * v) * PPM for v in polygon.vertices]
    vertices = [(v[0], SCREEN_HEIGHT - v[1]) for v in vertices]
    pygame.draw.polygon(screen, colors[body.type], vertices)
polygonShape.draw = my_draw_polygon

while running:
    # Draw the world
    screen.fill((255, 255, 255, 255))

    for body in Box_2_World.bodies:
        for fixture in body.fixtures:
            fixture.shape.draw(body, fixture)

    # Simulate dynamic equation in each step
    TIME_STEP = 1.0 / FPS
    Box_2_World.Step(TIME_STEP, 10, 10)

        # Flip the screen and try to keep at the target FPS
    pygame.display.flip() # Update the full display Surface to the screen
    pygame.time.Clock().tick(FPS)

pygame.quit()

```

Thank you VERY much for any response. I cannot move forward in my game without this...

P.S. I have posted almost identical question on Stack Overflow because the answer is really important to me, I apologize for spamming

EDIT: I have found a link which solves exactly what I want to do, but it is written in C++ and I do not understand it :( http://www.iforce2d.net/b2dtut/collision-callbacks

# Answer
warning: I don't know any python programming but I may help you a little bit? As per your code example it seems that the only thing you are missing is the b2ContactListener which will tell you when two fixtures collide:

**from iforce2d:**

> Now, we want Box2D to tell us when the contact state changes. Make a subclass of b2ContactListener and implement the BeginContact/EndContact functions as follows:

**I don't know how you make listener in python but in c++:**

```
//at global scope
MyContactListener myContactListenerInstance;
//in FooTest constructor
m_world->SetContactListener(&myContactListenerInstance);

```

**In lua it's (gideros engine example):**

```
world = b2.World.new(0, -9.81, true)
world:addEventListener(Event.BEGIN_CONTACT, self.onBeginContact, self)
world:addEventListener(Event.END_CONTACT, self.onEndContact, self)

```

And then you do stuff in the contact listeners on bodyA and bodyB.

Now the question is how do you call listeners in python. Hope this will guide you in the right direction.
> 0 votes

---
Tags: collision-detection, box2d, python, pygame
---


# Question
Title: How to play two 2D animations at the same time?
I have a "burn" animation and a "poison" animation for when the player is burnt or poisoned respectively. I want to play both animations at the same time when the player is both burnt and poisoned. From what I've read this is supposed to be possible with layers, but I can't get it to work.

# Answer
Yes indeed it is possible with Layers.

1. First create two layer in animator.
2. Then increase layer "Wight" to 1.
3. Now set animators like this.
4. Not Add Two triggers to parameters for may be "Poison" and "Burn":
5. And assign those parameters to Transitions buy click on transition arrow And also do Transition setting to your need.
6. Now At last step set triggers like:

---

> -If poison then:
>
> ```
>      NPCAnimator.SetTrigger("Poison");
>
> ```

---

> -If Burn then:
>
> ```
>      NPCAnimator.SetTrigger("Burn");
>
> ```

---

> -If Both then:
>
> ```
>      NPCAnimator.SetTrigger("Poison");
>      NPCAnimator.SetTrigger("Burn");
>
> ```

I hop this will help.

If you need more information please let know.
> 1 votes

---
Tags: unity, mecanim
---


# Question
Title: Mob generation design - is creating a class for each mob efficient?
I'm working on an RPG game for my coursework project. Everything is going fine but I've reached a stage where I do think that my project's code is not the most efficient.

Here I have a constructor of my class `AbstractMob`

```
public AbstractMob (String name, int hp, int attack, int defense, int magicAttack,
                        int magicDefense, int expBound, int goldBound, String folder, String idleAtlas, String attackAtlas) {

        abilities = new ArrayList<>();
        //setting variables
        this.attack = attack; //and so on

        idleAnimation = new Animation<>(
                0.070f, new TextureAtlas(Gdx.files.internal(
                        "sprites\\mobs\\" + folder)).findRegions(idleAtlas),
                Animation.PlayMode.LOOP);

        attackAnimation = new Animation<>(
                0.070f, new TextureAtlas(Gdx.files.internal(
                        "sprites\\mobs\\"+ folder)).findRegions(attackAtlas),
                Animation.PlayMode.LOOP);
    }

```

And here is an example of a class that inherits `AbstractMob`

```
public class FireElemental extends AbstractMob {
    public FireElemental() {
        super("Fire Elemental",
                400,
                12,
                10,
                18,
                15,
                50,
                20,
                "fireElemental\\fire.atlas",
                "firesprite",
                "firesprite"
        );
        //from AbstrctMob, declares any abilities the mob has
        abilities.add(new Fire()); //same design pattern as these mob creations,
        //I have a separate class for Abilities, and subclasses such as Fire
        //that inherit from Abilities

        setAbilities(abilities);
    }
}

```

Now, my question is - does it make sense to create a multitude of separate classes (i.e make more classes like `FireElemental` for different mobs) for each entity (whether that be abilities or mobs) for this game? How about utilising files/scripts to load them?

Thank you so much!

# Answer
> 3 votes
Typically for a pure data change like this, we would not use separate classes.

Instead, you could make your class non-abstract (say "BasicMob" to leave room if you need more complex mob classes in future) and give it one or several Factory Methods that populate the data of your mob to make a specific variant. eg..

```
public static BasicMob CreateFireElemental() {

    BasicMob mob = new BasicMob(
         "Fire Elemental",
          400,
          12,
          10,
          18,
          15,
          50,
          20,
          "fireElemental\\fire.atlas",
          "firesprite",
          "firesprite"
      );

       mob.abilities.add(new Fire());
       mob.setAbilities(mob.abilities);

      return mob;
}

```

If many of these properties are constant for all instances of a given "kind" of mob, then you could abstract them out to a Type Object, then construct a mob from a type object.

```
// For brevity I'll make this all public.
// In practice you'll likely want these parameters to be immutable.
public class MobType {
    public int maxHP;
    public int attack;
    public int defense;
    public Ability[] abilities;
    // You probably don't want to look up
    // sprites by name every time — do that once.
    public SpriteSet sprites;
}

public BasicMob(MobType typeToCreate) {
    mobType = typeToCreate;
    currentHP = mobType.maxHP;
}

```

Now each new mob type needs no new class or method at all. You can just keep a library of type objects to pass when you want to spawn a mob.

Once you've separated your "type" of mob into its own object, you can even deserialize it from a human-readable text file like JSON. Then you can just have a folder of mob definitions like "fireElemental.json" "earthElemental.json" that you read on start-up or on demand whenever a new mob ID is requested in your level.

The advantage of doing it this way is if you have non-technical team members, like game designers and level designers who don't write code. If they can experiment with new combinations of stats & abilities for mobs just by editing text files, even adding new mob types to the game with no dependency on coders and no need to even recompile, then your team's iteration speed gets a massive boost.

It also opens the door to a player modding community, if you choose to make this serialized format user-editable in the released version.

---
Tags: java, libgdx, software-engineering, oop
---


title: Tile based game data structure

text:
# Question
Title: Tile based game data structure
I've been working on a top down 2d game and the character moves freely around the map, like zelda link to the past.

How would you model the data structure for such a game in order to implement pathfinding, astar, etc.

As far I understood one could go with this approach:

```
Tile {
 sprite,
 walkable,
 position,
}

Board {
  width
  height
  tiles: Tile[]
}

```

In a board of 5x5 there will be a sprite rendered for each tile. But here comes the problem:

The player is at position (+1,+1). Now it moves to the right side (+2,+1). This will mean that the player is moved immediately from one tile to another. So, we could make the player move pixel by pixel. How would you translate this back to the grid position?

If player moves pixel by pixel (using floating point instead of integers) and is at position (1.5,1),doest it means we need a separated data to store player position and later on round its current position (1.5, 1) to find its current cell in the grid?

I'm kind lost in this subject, i would love if you could share some thoughts on it, articles, videos, books, etc.

Thanks!

# Answer
I'd probably use those three variables:

```
Vector2i previousTile
Vector2i nextTile
float transition

```

Previous and next tile are pretty self explainatory. If player wants to move, nextTile is set to his target coordinates (eg. \[2, 1\]). Player is in "moving" state if previous and nextTile are different. The "transition" field is used to tell where the player is now, from 0 (not started moving) to 1 (finished moving). Anything lower than 0.5 would mean that, as far as game logic carse, the player is still at previousTile. Anything greater or equal -\> player is at nextTile. You might want to introduce additional field, or helper function that will tell you where the player is at the moment:

```
currentTile = (transition<0.5) ? previousTile : nextTile;

```

With that approach, you can play with how fast player moves between tiles (by changing how much you add to "transition" variable per frame).

```
function Update(float timeStep)
    if(previousTile==nextTile)
        return

    transition += timeStep * 2
    // *1 => distance between adjecent tiles in 1 second
    // *2 => ^ twice as fast, in 0.5s

    // Make sure we do not exceed 1, otherwise player will overshoot his target
    if(transition>1)
        transition=1

    currentTile = (transition<0.5) ? previousTile : nextTile;

```

As for the drawing, you'll have to interpolate player's sprite position:

```
function Draw()
    Render.DrawAt(previousTile*(1-transition) + nextTile*transition)

```

Probably you'll want to change previousTile and nextTile in above example to locations of those tiles on the screen.
> 0 votes

---
Tags: 2d, tilemap, grid
---


# Question
Title: Why is my player not giving a knock back when it stays at the right side of the enemy?
So, I have this problem I am facing, for some reason my player does not get a knockback when it stays at the right side of the enemy but when it stays at the left side it gives a knockback. What's the problem?

---

**PLAYER MOVEMENT**

---

```
void Movement()
    {

        //THIS IS FOR WALKING
        if (isControlesEnabled)
        {
            moveInput = Input.GetAxisRaw("Horizontal") * runSpeed;
            myBody.velocity = new Vector2(moveInput, myBody.velocity.y);
        }

```

---

**PLAYER KNOCKBACK**

---

```
private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Enemy"))
        {
            health -= 0;

            if (health <= 0)
            {
                gameObject.SetActive(false);
            }
            else
            {
                ContactPoint2D contactPoint = collision.GetContact(0);
                Vector2 playerPosition = transform.position;
                Vector2 dir = contactPoint.point - playerPosition;

                dir = -dir.normalized;

                myBody.velocity = new Vector2(0, 0);
                myBody.inertia = 0;

                isControlesEnabled = false;
                Invoke("EnablePlayerControles", controlesDisablePeriod);

                myBody.AddForce(dir * knockBackForce, knockBackForceMode);
            }
        }
    }

    private void EnablePlayerControles()
    {
       isControlesEnabled = true;
    }

```

# Answer
Do your entities both use box colliders?

When two axis-aligned box colliders collide, then there isn't really a single collision *point* but rather a collision *line* on which the colliders touch. Unity is supposed to return multiple collision points in such a situation. That's why Collision2d.contacts is an array and not a single value. But your code only cares about the very first collision point in that array (`ContactPoint2D contactPoint = collision.GetContact(0);`).

That point happens to be the lowest point on left collisions and the highest point on right collisions. So a left-collision launches your player upwards (when it *should* get launched horizontally) while a right-collision launches the player downwards. The downwards trajectory pushes the player into the ground where friction kills most of its momentum, so it seems like right-collisions do almost nothing at all.

How do you fix that problem?

Instead of comparing the player position with the contact point, compare the player position with the center of the collider.

```
else
{
    Vector2 enemyPosition = collision.transform.position;
    Vector2 playerPosition = transform.position;
    Vector2 dir = enemyPosition  - playerPosition;

```

When the positions of both objects are on the same height then you will get a horizontal motion. If you would like to maintain the slight upwards trajectory (I personally think it's quite neat), subtract a little from the height of the enemy position. This example subtracts 0.5 units. You might have to experiment a bit with the value to find the one which gives you the best results:

```
Vector2 enemyPosition = collision.transform.position - new Vector3(0.0f, 0.5f);

```

I am looking forward to playing your game.
> 1 votes

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


title: Only one triangle drawn

text:
# Question
Title: Only one triangle drawn
I am trying to render a quad with gl render mode GL\_TRIANGLES with using element array buffer. Here is some code to explain process. Only the first 3 elements of indices array are drawn as expected. But following indices doesn't drawn at all.

Mesh Creation

```
glm::vec3 vertices[] = { glm::vec3(-1, 1, 0),
                          glm::vec3(-1, -1, 0),
                          glm::vec3(1, -1, 0),
                          glm::vec3(1, 1, 0)
                        };

glm::vec2 textures[] = { glm::vec2(1, 0),
                          glm::vec2(0, 0),
                          glm::vec2(0, 1),
                          glm::vec2(1, 1)
                        };

unsigned int indices[] = { 0, 1, 3, 3, 1, 2};
Mesh* mesh = new Mesh(vertices, sizeof(vertices) / sizeof(glm::vec3), textures, sizeof(textures) / sizeof(glm::vec2), indices, sizeof(indices) / sizeof(unsigned int), texture);

```

Mesh Class

```
Mesh::Mesh(...){
    InitMesh(...);
}

void Mesh::InitMesh(vec3* vertices, unsigned int numVertices, vec2* textureCoords, unsigned int numTextureCoords, unsigned int* indices, unsigned int numIndices) {
     this->numIndices = numIndices;

    // Generate VAO and bind
    glGenVertexArrays(1, &vaoID);
    glBindVertexArray(vaoID);
    // Generate VBOs
    glGenBuffers(3, vboIDs);
    // Bind Position Buffer, Buffer Position Data
    glBindBuffer(GL_ARRAY_BUFFER, vboIDs[0]);
    glBufferData(GL_ARRAY_BUFFER, numVertices * sizeof(vec3), vertices, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
    // Buffer TextureCoord Data
    glBindBuffer(GL_ARRAY_BUFFER, vboIDs[1]);
    glBufferData(GL_ARRAY_BUFFER, numTextureCoords * sizeof(vec2), textureCoords, GL_STATIC_DRAW);
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0);
    // Buffer Indices Data
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vboIDs[2]);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, numIndices * sizeof(unsigned int), indices, GL_STATIC_DRAW);
    // Unbind VAO
    glBindVertexArray(0);
}

void Mesh::Draw() {
    glBindVertexArray(vaoID);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);
    glDrawElements(GL_TRIANGLES, numIndices, GL_UNSIGNED_INT, 0);
    glDisableVertexAttribArray(1);
    glDisableVertexAttribArray(0);
    glBindVertexArray(0);
}

```

# Answer
> 2 votes
SOLUTION

After several hours of searching found the issue on creation of vboIDs\[\]. I was creating it by size 2, changed it to 3 and fixed the issue.

---
Tags: opengl, c++, shaders, rendering
---


# Question
Title: Why are Visual Studio and VSCode not giving me a dropdown list of methods and options etc?
I am using VSCode but I have also tried Visual Studio 2019 to write code for Unity, but when I'm writing the lines I don't get dropdown menus with for example the methods this class holds. Or objects. Or it's properties. etc.: basically, IntelliSense is not working.

Is there a setting that I need to enable in order to get those? Since I've seen everyone who use VSCode and visual studio get these dropdown menus.

# Answer
> 1 votes
Here are the things I have had to do to solve this issue before:

* Make sure you have Visual Studio Code set as your editor in the unity preferences.
* Make sure you have the C# Visual Studio Code extension installed.
* Check the VSCode OmniSharp logs for any errors.

Let me know if this helps.

---
Tags: unity, c#, visual-studio, visual-studio-code
---


# Question
Title: How to completely stop the camera from clipping into the ground
Hi I'm trying to do a basic Camera Collision in unity, for convenience, here's the entire script (I actually got most of it from someone else who wrote the comments, if that's necessary to know):

```
///
///
/// CameraControllercs.cs
/// Camera Controller in CSharp v2.1
///
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;

public class CameraController : MonoBehaviour
{
    public GameObject target;                           // Target to follow
    public float targetHeight = 1.7f;                         // Vertical offset adjustment
    public float distance = 12.0f;                            // Default Distance
    public float offsetFromWall = 0.7f;                       // Bring camera away from any colliding objects
    public float maxDistance = 20f;                       // Maximum zoom Distance
    public float minDistance = 0.6f;                      // Minimum zoom Distance
    public float xSpeed = 200.0f;                             // Orbit speed (Left/Right)
    public float ySpeed = 200.0f;                             // Orbit speed (Up/Down)
    public float yMinLimit = -80f;                            // Looking up limit
    public float yMaxLimit = 80f;                             // Looking down limit
    public float zoomRate = 40f;                          // Zoom Speed
    public float rotationDampening = 3.0f;                // Auto Rotation speed (higher = faster)
    public float zoomDampening = 5.0f;                    // Auto Zoom speed (Higher = faster)
    public int collisionLayers;     // What the camera will collide with
    public bool lockToRearOfTarget = false;             // Lock camera to rear of target
    public bool allowMouseInputX = true;                // Allow player to control camera angle on the X axis (Left/Right)
    public bool allowMouseInputY = true;                // Allow player to control camera angle on the Y axis (Up/Down)

    private float xDeg = 0.0f;
    private float yDeg = 0.0f;
    private float currentDistance;
    private float desiredDistance;
    private float correctedDistance;
    private bool rotateBehind = false;
    private bool mouseSideButton = false;
    private float pbuffer = 0.0f;       //Cooldownpuffer for SideButtons
    private float coolDown = 0.5f;      //Cooldowntime for SideButtons

    GameObject main;
    void Start()
    {
        collisionLayers = LayerMask.GetMask("Default");
        var temp = GameObject.Find("main");
        if(temp != null)
        {
            main = temp;

        }

        Vector3 angles = transform.eulerAngles;
        xDeg = angles.x;
        yDeg = angles.y;
        currentDistance = distance;
        desiredDistance = distance;
        correctedDistance = distance;
        Camera.main.nearClipPlane = 0.001f;

        if (lockToRearOfTarget)
            rotateBehind = true;
    }
    void Update()
    {
        if (target == null)
        {
            target = GameObject.FindGameObjectWithTag("Player") as GameObject;
            Debug.Log("Looking for Player");
        }

    }

    //Only Move camera after everything else has been updated
    void FixedUpdate()
    {
        // Don't do anything if target is not defined
        if (target == null)
            return;
        //pushbuffer
        if (pbuffer > 0)
            pbuffer -= Time.deltaTime;
        if (pbuffer  currentDistance ? Mathf.Lerp(currentDistance, correctedDistance, Time.deltaTime * zoomDampening) : Mathf.Lerp(currentDistance, correctedDistance, Time.deltaTime * zoomDampening * 3);

        // Keep within limits
        currentDistance = Mathf.Clamp(currentDistance, minDistance, maxDistance);

        // Recalculate position based on the new currentDistance
        position = target.transform.position - (rotation * Vector3.forward * currentDistance + vTargetOffset);

        //Finally Set rotation and position of camera
        transform.rotation = rotation;
        transform.position = position;

    }

    private void RotateBehindTarget()
    {
        float targetRotationAngle = target.transform.eulerAngles.y;
        float currentRotationAngle = transform.eulerAngles.y;
        xDeg = Mathf.LerpAngle(currentRotationAngle, targetRotationAngle, rotationDampening * Time.deltaTime);

        // Stop rotating behind if not completed
        if (targetRotationAngle == currentRotationAngle)
        {
            if (!lockToRearOfTarget)
                rotateBehind = false;
        }
        else
            rotateBehind = true;

    }

    private float ClampAngle(float angle, float min, float max)
    {
        if (angle  360f)
            angle -= 360f;
        return Mathf.Clamp(angle, min, max);
    }

}
```

As you can see in the start function, I also set the near clipping to a low value (the camera has a MainCamera tag BTW).

The problem: as you can see in this picture

even with the low nearClipping value, and the high offsetFromWall value (0.7f when it's normally 0.1f), the camera is still clipping the ground when moving it with the mouse semi-fast (when it's moved kind of slow it's not a problem).

I have no idea how to fix this, if I make the nearClipping lower the whole render gets messed up, and even then it doesn't work, so what else can I do to ensure that the user **never** sees underneath the ground?

# Answer
> 2 votes
# Near Clip Plane

It sounds like you've misunderstood what a camera's near clip plane is. The official unity scripting manual describes the clip planes as:

* Clipping Planes: Distances from the camera to start and stop rendering.
* Near Plane: The closest point relative to the camera that drawing will occur.

These planes create the camera's view frustum. The view frustum is essentially a box in front of the camera's position which lets the camera know what to render. Anything inside that frustum gets displayed to the screen. So when you set `camera.nearClipPlane` your adjusting how close to the camera's position that box is.

The frustum only controls what the camera sees, **NOT** how it moves. If you want to prevent the camera from moving through solid objects you would need to set up some kind of collision between the camera and anything you want to avoid tunneling into (in this case the ground).

# Fixed Update

Unity has several update functions which each do different things. Fixed update occurs at a fixed rate. This update is normally used for physics and math updates which require a fixed timestep. According to your comment `//Only Move camera after everything else has been updated`, you want the camera to update last. I would recommend using `LateUpdate()` instead of `FixedUpdate()`. Unity3D's update order is described as:

* Fixed Update is often called more frequently than Update. It can be called multiple times per frame, if the frame rate is low and it may not be called between frames at all if the frame rate is high. All physics calculations and updates occur immediately after FixedUpdate. When applying movement calculations inside FixedUpdate, you do not need to multiply your values by Time.deltaTime. This is because FixedUpdate is called on a reliable timer, independent of the frame rate.
* Late Update is called once per frame, after Update has finished. Any calculations that are performed in Update will have completed when LateUpdate begins. A common use for LateUpdate would be a following third-person camera. If you make your character move and turn inside Update, you can perform all camera movement and rotation calculations in LateUpdate. This will ensure that the character has moved completely before the camera tracks its position.

# Answer
> 1 votes
You can just cast a ray from, say, knees of the player model to the camera POV. If it intersects terrain - constrain the camera's vertical movement to current level.

---
Tags: unity, c#, physics, camera, clipping
---


title: Find angle to a point

text:
# Question
Title: Find angle to a point
I'm trying to find the angle between a point and the left side of my camera's fov.

In the picture below the camera (Red dot) is looking towards a polygon (Green) with the fov of the camera represented as the blue lines.

I've tried to butcher some code together from my limited understanding of linear so I havent gotten far. I've tried atan2 as well, but it seems to give incorrect answers for what im looking for.

the info i have is:

```
the point(x,y) I'm evaluating
the camera(x,y)
line segment and angle representing the left side of the cameras fov
same for the right

```

How would i find the angle between the left angle and the point? I'm going to use the calculation to find the angle to each of the points making up the polygon.

Below is a rough mock up ive been using to try to figure this out the blue angle with the question mark is what im looking for

# Answer
> 0 votes
The angle can be computer with **atan2()** function from **math**.

```
import math
dx = tgtx - camx
dy = tgty - camy
ang = math.atan2( dy, dx )

```

Note that this angle will be in radian units.

# Answer
> 0 votes
I've solved my own issue. If anyone in the future is looking for the same answer below is the code witha short write up.

```
def get_angle(e, f, p):
    """
    :param e: Entity we're measuring from
    :param f: Fov arm endpoint
    :param p: Point we're getting the angle to
    :return:
    """
    a = np.array([e.pos.x, e.pos.y])
    b = np.array([f.x, f.y])
    c = np.array([p.x, p.y])
    ba = b - a
    bc = b - c
    cos_ang = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
    return np.arccos(cos_ang) * 10

```

This will create a line intersecting "e" and "f" then return how close point "p" is to that line. I am running this in tandem with another solution to detect if the point is in view as you will recieve the same value if your camera angle is flipped 180

---
Tags: python, pygame
---


# Question
Title: Data structure for multiple Textures in materials in assimp
I'm going through assimp documentation regarding materials. Each material can have multiple textures containing various data (color maps, height maps, etc.) and blending data, etc. I'm trying to understand how to model this efficiently in a data structure, without storing textures for each mesh separately (meaning generating textures and loading the texture (bind and upload to GPU) for each and every mesh in a redundant manner, ignoring that they are re-used).

In this tutorial, they simplify the situation, by just caring about the "1st diffuse color maps". This simplifies the data structure immensely. But, theoretically at least, there can be multiple texture maps for a single material, and textures can be re-used across materials.

I'm trying to understand whether it's common practice to not share any textures between different meshes in a single scene/model.

I have a couple of questions regarding this:

1. What is the best way to store textures when loading models through assimp? I understand that you can store each texture per mesh per scene (space inefficient but simple). Is there a better way?
2. I found a few free fbx model that only contains one diffuse color map as a material (similar to the tutorial). Is it common practice for this to happen or did I come across a simplified model?

PS: I understand openGL quite well and I have no problem getting things to render. This question is only concerned about what's practical, efficient and considered best practice.

# Answer
I have run into this problem for my own game engine currently being designed. The method I used was to store the all the loaded textures into a hash table with the path as its key: `std::unordered_map<std::string, Texture>`. This data structure will be managed by a `ResourceManager` or whatever you want to call. Every time you want to retrieve a texture you query the `ResourceManager` with the key. If it doesn't exist, the `ResourceManager` is responsible for instantiating the texture and return a pointer. Basically something looks like this

```
Texture *ResourceManager::getTexture(const std::string &path, const TextureType& type)
{
    auto t = m_textures.find(path);
    if (t == m_textures.end())
    {
        return loadTexture(path, type);
    }
    return &t->second;
}

```

And the relationship between Texture, Material and Mesh (and shaders) can be as follow:

Meshes contain pointers to the material, and materials will have the shader program object and pointers to the textures whom the fragment shader will use. And all three kinds of objects can be stored using the method we discussed above. So when you import from Assimp you will load all the resources separately and only reference each other. The above structure will be useful when you want to dynamically use material and meshes. for example, you can give your brick material to the human mesh or the wall mesh.
> 1 votes

# Answer
Generally speaking, rendering engines uses some kind of singleton to manage loaded textures and avoid duplication.

This kind of singleton is often called an asset manager.

Meshes are assigned a material. Materials are composed by example of diffuse color, specular color, diffuse texture, normal maps, glow maps, specular maps, height maps, ...

These material values are often called material parameters. The ones that are related to texture hold a reference to the texture in the asset manager. That means that all meshes that share the same texture only share the same reference to the asset manager, avoiding duplication.

It means that you organised your shaders in a way that a shaders that uses a particular kind of asset uses the exact same name or position for this in all the other shaders.

Before rendering a mesh, you make bindings using the reference held by the asset manager. Some renderers use the same reference in the asset manager than the OpenGL internal reference.

Lastly, using this kind of material management allows you to actively sort meshes before rendering based on their material parameters in order to reduce OpenGL state changes that are costly.

Of course, material is only one of the sorting criteria, along with transparency, z order, ...

Hope it helps!
> 0 votes

---
Tags: assimp
---


# Question
Title: Parts of 3D model disappear during animation
I'm trying to properly play an animation done in Blender 2.8 inside my OpenGL application. When the animation is running, it happens that at some particular frames, some parts of the 3D model "disappear", by "disappear" I mean that they obviously get relocated at some incorrect position and rotation in the 3D scene.

The model is an FBX file.
Has anyone got an idea about what could be the possible reasons for that?
Maybe some wrong settings in Blender?

Thanks in advance!

# Answer
I think I've found something, the idle animation got some really really slight offsets of movements, I've printed the matrices being used on frame 1 and for all the parts not appearing on screen the matrices got the following pattern:

(0 0 0 a) (0 0 0 b) (0 0 0 c) (0 0 0 1)

Those are glm matrices (column major).

Maybe due to the really slight difference of movement between two consecutive frames, the float precision isn't enough and the value is set to zero ?

Thus, all I got to do is doing some larger movements for the corresponding keyframes ? I'll try that if that works, but I'm still open to some suggestions !
> 0 votes

# Answer
sorry I'm a bit late !

Yes the errors did always happened on the same frames for the exact same model parts across each test iterations, but I've managed to solve the issue.

So basically, I took a glance at the number of position, rotation and scaling keys, and I had noticed that some keys were missing. For instance, the idle animation must have 48 keys, and for the parts that caused troubles, some animation keyframes were missing. In my code I did a trick for that case, to just take the last known computed keyframe as the current keyframe and chain multiply it with all its parent joints matrices, but it didn't worked great.

So I eventually found on the web a nice addon for Blender which properly export 3D Blender files to the collada file format, and then all the keyframes were set the right way and all the weird things were gone.
> 0 votes

---
Tags: opengl, c++, blender, skeletal-animation, fbx
---


title: SDL2 Block collision with player Bug

text:
# Question
Title: SDL2 Block collision with player Bug
I am currently working on a small 2D Games Engine with SDL2 for fun. The engine works in a way, that you can define a tileset, which accesses the engine and allows you to place tile by tile on the predefined window and specify what type of tile you want to place. If it should have collision or if it should rotate. My bug occurs by the collision with the player.

I seperate the block i want the player to collide with into 8 blocks(4 side-blocks and 4 Corner-blocks).If my player now collides with an tile, the program checks,which part of the tile the player has collided with and then pushes the player in a certain direction dependend on the block of the tile it collided with.

This is the code for the collision:

```
int Editor::Collision(EDITOR_BODY body)
{
    int rect = 0;
    for (int i = 0; i < tile_type.size(); i++)
    {
        if (tile_type.at(i) == ITEM_HITBOX)
        {
            #define COL(a,b) (a.x+a.w>b.x&&a.x<b.x+b.w&&a.y+a.h>b.y&&a.y<b.y+b.h)

            SDL_Rect corner_ur, corner_ul, corner_dr, corner_dl, side_l, side_r, block_u, block_d;

            corner_ul = {
                tiles.at(i)->GetX(),
                tiles.at(i)->GetY(),
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight() / 8
            };
            corner_ur = {
                tiles.at(i)->GetX()+tiles.at(i)->GetWidth()*7/8,
                tiles.at(i)->GetY(),
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight() / 8
            };
            corner_dr = {
                tiles.at(i)->GetX()+tiles.at(i)->GetWidth()*7/8,
                tiles.at(i)->GetY()+tiles.at(i)->GetHeight()*7/8,
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight() / 8
            };
            corner_dl = {
                tiles.at(i)->GetX(),
                tiles.at(i)->GetY() + tiles.at(i)->GetHeight() * 7 / 8,
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight() / 8
            };
            side_r = {
                tiles.at(i)->GetX() + tiles.at(i)->GetWidth() * 7 / 8,
                tiles.at(i)->GetY() + tiles.at(i)->GetHeight()/ 8,
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight()*6 / 8
            };
            side_l = {
                tiles.at(i)->GetX() ,
                tiles.at(i)->GetY() + tiles.at(i)->GetHeight() / 8,
                tiles.at(i)->GetWidth() / 8,
                tiles.at(i)->GetHeight() * 6 / 8
            };
            block_u = {
                tiles.at(i)->GetX()+ tiles.at(i)->GetWidth()/ 8 ,
                tiles.at(i)->GetY(),
                tiles.at(i)->GetWidth()*6 / 8,
                tiles.at(i)->GetHeight() /2
            };

            block_d = {
                tiles.at(i)->GetX() + tiles.at(i)->GetWidth() / 8 ,
                tiles.at(i)->GetY()+ tiles.at(i)->GetHeight() / 2,
                tiles.at(i)->GetWidth() * 6 / 8,
                tiles.at(i)->GetHeight() / 2
            };
            if (COL(corner_ul, body))rect=1;
            if (COL(corner_dl, body))rect = 2;
            if (COL(corner_ur, body))rect = 3;
            if (COL(corner_dr, body))rect = 4;

            if (COL(side_r, body))rect = 5;
            if (COL(side_l, body))rect = 6;
            if (COL(block_u, body))rect = 7;
            if (COL(block_d, body))rect = 8;
            //Release the next comment for testing purposes..
            SDL_SetRenderDrawColor(setup->GetRenderer(), 255,0, 0, 255);
            SDL_RenderFillRect(setup->GetRenderer(), &corner_ur);
            SDL_RenderFillRect(setup->GetRenderer(), &corner_ul);
            SDL_RenderFillRect(setup->GetRenderer(), &corner_dr);
            SDL_RenderFillRect(setup->GetRenderer(), &corner_dl);

            SDL_SetRenderDrawColor(setup->GetRenderer(), 0,255,  0, 255);
            SDL_RenderFillRect(setup->GetRenderer(), &side_r);
            SDL_RenderFillRect(setup->GetRenderer(), &side_l);

            SDL_SetRenderDrawColor(setup->GetRenderer(), 0, 0,255,  255);
            SDL_RenderFillRect(setup->GetRenderer(), &block_u);
            SDL_RenderFillRect(setup->GetRenderer(), &block_d);

            SDL_SetRenderDrawColor(setup->GetRenderer(), 255, 255, 255, 255);
            if (COL(corner_ul, body))SDL_RenderFillRect(setup->GetRenderer(),&corner_ul);
            if (COL(corner_dl, body))SDL_RenderFillRect(setup->GetRenderer(), &corner_dl);
            if (COL(corner_ur, body))SDL_RenderFillRect(setup->GetRenderer(), &corner_ur);
            if (COL(corner_dr, body))SDL_RenderFillRect(setup->GetRenderer(), &corner_dr);

            if (COL(side_r, body))SDL_RenderFillRect(setup->GetRenderer(), &side_r);
            if (COL(side_l, body))SDL_RenderFillRect(setup->GetRenderer(), &side_l);
            if (COL(block_u, body))SDL_RenderFillRect(setup->GetRenderer(), &block_u);
            if (COL(block_d, body))SDL_RenderFillRect(setup->GetRenderer(), &block_d);

        }
    }

    return rect;
}

```

My problem ist, that when the player stands on the right coordinats, that he is paralell to a tile, but hits a corner block first, he is able to clip through an block.

Here is a picture, that shows the bug:

Maybe you can tell me how to avoid this Problem, or if there is a better way to handle such collisions

# Answer
> 1 votes
Instead of showing you code, I will just outline an abstract way to perform AABB (axis aligned bounding box) vs AABB collision detection, that you can translate to any language. It may require some changing of how you store your character/tile data.

First, construct your AABB (player & tile):

```
cornersA = vec2[4];
halfwith = player.width/2;
halfheight = player.height/2;
cornersA[0] = player.position+vec2(-halfwidth, halfheight); //upper left corner
cornersA[1] = player.position+vec2(-halfwidth, -halfheight); //lower left corner
cornersA[2] = player.position+vec2(halfwidth, -halfheight); //lower right corner
cornersA[3] = player.position+vec2(halfwidth, halfheight); //upper right corner

Repeat for tile

```

Now that we have useful data, lets define the Cartesian axes that you will use to tell if they are colliding:

```
axes[0] = vec2(1.0,0.0);
axes[1] = vec2(0.0,1.0);

```

This may seem superfluous but, I will revisit this later.

Now that we have two AABB and two axes defined, we can perform the detection proper in pseudocode:

```
minA, minB = MAX_VALUE // A is player, B is tile
maxA, maxB = MIN_VALUE
for each axis loop:
    for each corner in cornersA loop:
        position = dot(axis, corner);
        if position < minA
            minA = position
        end if
        if position > maxA
            maxA = position
        end if
    end loop
    // repeat for tile
    if minA > maxB
        exit //no collision
    else if maxA < minB
        exit //no collision
    else if (maxA-minB) < (maxB - minA)
        //collision: perform a simple correction
        player.position+=axis * (maxA-minB);
        continue;
    else if (maxB-minA) < (maxA - minB)
        //collision: perform a simple correction
        player.position+=axis * (maxB-minA);
        continue;
    end if
end loop

```

This will detect and correct the players position on the x and y axes, should a collision take place.

The reason I stated the pseudocode as a loop through a set of axis, is that you could expand it to 3D very easily.

If you want to handle something more complex, like rotating (orientated) bounding boxes, you will need something a little smarter. I recommend looking into separating axes theorem for collision detection. It's not the fastest collision detection algorithm, but it is easy to understand and implement.

# Answer
> 0 votes
Find the origin of the player, like a circle in the center say 0.0 is the origin of the circle. With that your character is colliding and stopping within the collided region which is (0.0) of the source of the player. If that character is a circle then its outer radius shouldn't be hard to calculate, as you can get it with (x,y) using radius. What you have to do is do make a lot of collision checks number ranging from (x-\>x1,y-\>y1) and have it stop at that point if any object passes through it.

---
Tags: c++, movement, sdl2
---


# Question
Title: How do I make dialogue text appear with a beeping effect?
I'm interested in old-school RPG dialogue boxes, where text appearing in dialogue boxes is accompanied by a subtle beeping sound. This is demonstrated in a video here.

Is this morse code translated to audio?

How can I achieve such an effect?

# Answer
Assuming the text is displayed letter by letter, you can have a single 'beep' sound, and play it every time a letter is added to the text.

You can make some exceptions, for example, play a beep only if the letter is not a symbol, or to make it more dynamic, add an additional delay when a comma (or dot) is added to the text.
> 1 votes

# Answer
I use this in my game, wich is in Java.

```
public static String GetWords(String text, float wordCount)
{
    float words = wordCount;
    int soundcounter = 0;
    boolean IS_MARKUP = false;
    Random rand = new Random();
    // loop through each character in text
    for (int i = 0; i < text.length(); i++)
    {

        if(i == text.length() - 1 && SceneHandler.lineFinished == false){
            SceneHandler.lineFinished = true;
        }
        words--;
        if (words <= 0)
        {
            return text.substring(0, i);
        }

    }
    return text;
}

```

You just draw your text in your render/update method, I assume you have one, and you feed it the String you want to typewrite, the time elapsed (wich is just deltatime++) and at what character speed per second you want it to type.

```
GameTools.fontText.draw(fontbatch, GameTools.GetWords(fullText, timeElapsed * wordsPerSecond), 204, 143);

```
> 1 votes

# Answer
This is not morse code.

You don't need a library to do this.

You could achieve the same effect by having a sound file that has different lengths of beeps interleaved with silences. The sound file must be *loopable*. When the text starts to be written to the screen, you start the looping sound. And when the text is done being 'typed' to the screen, you stop the sound.

I would suggest you find a web site that offers free to use sound effects, load it in your favourite audio editor (Audacity could do the trick) and modify it until it fits your needs.
> 0 votes

# Answer
This little JavaScript code might help you

```
var textSpeed = 50;
var textHolder = document.getElementById('id');
var sound = new Audio(...);
var timer = setInterval(function(){
  textHolder.innerHTML += string[i];
  if(string[i]!=' '){   //if space sound doesnt play
    sound.pause();
    sound.currentTime = 0;
    sound.play();
  }
  i++;
  if(i>=string.length){
    clearInterval(textTimer);
  }
},textSpeed);

```
> 0 votes

---
Tags: text, sound-effects
---


title: Positioning a Window to Fill the Screen

text:
# Question
Title: Positioning a Window to Fill the Screen
I'm using Pygame (just started), and I'm struggling to find how I set the position of the window to fill my entire monitor screen.

I can move things around within the screen / surface. I can make the screen the right size to fill my monitor (can drag it with my mouse to the right place), but can't find how to set the top-left corner of the surface to the top-left corner of my monitor. I'm using sprites.

# Answer
> 1 votes
I haven't tried that but a web search suggests that you need to use the underlying SDL layer to achieve this.

You need to set an environment variable before you initialize the window:

```
x = 100
y = 0
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (x,y)

import pygame
pygame.init()
screen = pygame.display.set_mode((100,100))

```

<sup>(Source)</sup>

Now, if you want to have the app running in fullscreen, there is another way to do that: use `pygame.FULLSCREEN` flag when calling `set_mode`:

```
pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

```

More details on StackOverflow, and in the official documentation.

---
Tags: pygame, window-management, fullscreen
---