# Question
Title: Which consoles may I target with OpenGL?
I'm thinking on technical design for a game/game engine using OpenGL, and I wonder if there is any recent consoles (Xbox360, PS3, Wii U, Xbox one and PS4) that I could work with if I do so.

I found plenty of conflicting answers through forums. The only straight answer seems that it is impossible for Xboxes because Microsoft forbid to use something else than DirectX, its own product.

So, finally, does anyone know for sure which consoles can support an OpenGL-based game?

# Answer
Probably the easiest answer: Don't bother, instead pick what works best for you to work with now (i.e. whatever you're more proficient with.

If you think you should write an engine with portability in mind ("create games, not engines!"), create a renderer abstraction layer, so you're able to plug in any back end you'd need.

While most desktop systems understand/have OpenGL, you'll need OpenGL ES for most mobile platforms. As such it would be just a small additional step to add DirectX as well later.

More specific details are, as far as I know, really hard to get, since most specifics are hidden behind NDAs and stuff like that (for whatever reason).

It's pretty much known that Microsoft favors (and only supports?) DirectX, while I think Sony offers support for OpenGL (although I'm not sure about the feature level/version). Since both require a developer license, I guess they're out of question for now anyway.

No idea about Nintendo, possibly OpenGL or some proprietary stuff? They want you to sign contracts first as well, anyway.

Many other (micro) consoles (such as the Ouya, Amazon's FireTV, etc.) use Android and as such support OpenGL ES 1.1 as well as OpenGL ES 2.0.

Windows PCs usually offer DirectX as well as OpenGL, OpenGL ES is indirectly supported through wrappers (like Google's ANGLE project).

Linux and Mac based systems usually provide OpenGL and OpenGL ES. Wrappers for DirectX exist, although I'm pretty sure this is really just exclusive to emulation. Haven't seen any used elsewhere.

Unfortunately, as you can see, there's no "one interface fits them all" solution.

If you want to limit yourself to one interface for now (which you definitely should IMO), go with (modern) OpenGL. It allows you the easiest/biggest cross-platform use right now, and also makes debugging pretty easy. With some adjustments (to use OpenGL ES rather than OpenGL), this code will run on most phones and micro consoles as well.

If you favor programming under Windows with Microsoft Visual Studio, DirectX might be an option for the Visual Studio integration (graphics debugger, etc.). Just keep in mind this won't work anywhere else (except XBox, which requires a developer license anyway).
> 6 votes

# Answer
None of the consoles you list use OpenGL as their native rendering API. The PS3 used to support a proprietary variant of OpenGL called PSGL but it was never the preferred API and I'm not sure it's even supported any more. To my knowledge none of the others have any kind of official support for OpenGL although you could in theory use ANGLE on Xbox 360 and Xbox One with some slight modifications.

If you want to target consoles with a custom engine you will need to support multiple rendering back-end APIs since there is no one API that you can use across all of them. In fact, of the consoles you list no two even share the same rendering API. The PS4 and PS3 have different APIs as do the Xbox 360 and Xbox One.
> 2 votes

# Answer
The Nintendo Switch is the first console which supports OpenGL (even desktop OpenGL!) natively. Source: https://www.tweaktown.com/news/55537/nintendo-switch-certified-vulkan-opengl-4-5/index.html
> 2 votes

---
Tags: opengl, console, porting
---


# Question
Title: How to calculate plane corner vertices from plane origin point and plane normal?
I have an origin point, and normal vector of a 3D plane. I want to calculate 4 vertices to use as the corners of a 2 triangle quad to render the plane.

# Answer
Here's one way that I can think of to do it.

Find a point on the plane `a` other than the origin, `o`. The vector `a - o` lies on the plane, so is guaranteed perpendicular to the plane normal. Normalise the vector `a - o` and call it `x`.

Take the cross product of `x` and the plane normal and call it `y`. `y` is guaranteed to be perpendicular to both `x` and the plane normal.

The four points of a square are now `o + x`, `o + y`, `o - x`, `o - y`.
> 2 votes

# Answer
I had to go through a similar situation lately, and here is something that might be more complete than the provided answer.

You provide a *normal* and the *origin*. Using *the origin* is a very specific case, so I'll use "point on the plane", or simply *point*, which is a bit more generic.

Let's start by going into standards and finding the plane equation parameters. According to the Internet and a few books out there, we have:

```
ax + by + cz + d = 0

```

where `a`, `b` and `c` represent the normal of the plane, `x`, `y` and `z` represent a point on the plane, and `d` is the shortest distance from the origin to the plane, or the distance you'd have to move the plane toward the normal so that plane passes by the origin.

We can easily find `d` with this:

```
d = -(normal.x * point.x + normal.y * point.y + normal.z * point.z)

```

Now the tricky part is to "place a quad on the plane". Keep in mind that there is an infinite possibility of having that, as you don't specify an "axis around which you'll place it". We'll start by placing our quad on the XY plane, and rotate and move it according to the parameters we have above.

The following function is based on ODE's function `dxPlaneSpace`. There was comments lacking so if any of those can help anyone, it's all good.

```
void getPlaneSpace( const Vec3& aNormal, Vec3& aP, Vec3& aQ )
{
  // This is an arbitrary way to avoid a division by zero (this guarantees that z > 0,
  //  used when computing a).
  if ( std::abs( aNormal.z() ) > ( 1.0 / std::sqrt( 2.0 ) ) ) // 0.707106781186547524...
  { // Note: the "else" part is a bit easier to follow as it projects on the x-y plane.
    // choose p in y-z plane, where the magnitude of x is zero
    // a is the length^2 of the normal projected onto the plane
    float a = aNormal.y() * aNormal.y() + aNormal.z() * aNormal.z();
    // k is 1 / length of the normal vector projected onto the y-z plane.
    float k = 1 / std::sqrt( a );
    aP.x() = 0;
    aP.y() = -aNormal.z() * k;
    aP.z() = aNormal.y() *k;
    // set q = n x p
    aQ.x() = a * k;
    aQ.y() = -aNormal.x() * aP.z();
    aQ.z() = aNormal.x() * aP.y();
  }
  else
  {
    // choose p in x-y plane, where the z = 0
    // get the length^2 of the normal projected onto the plane.
    float a = aNormal.x() * aNormal.x() + aNormal.y() + aNormal.y();
    // k is 1 / length; used to adjust the size of the new vectors so that they're "unit"
    // vector.
    float k = 1 / std::sqrt( a );
    aP.x() = -aNormal.y() * k;
    aP.y() = aNormal.x() * k;
    aP.z() = 0;
    // set q = n x p
    aQ.x() = -aNormal.z() * aP.y();
    aQ.y() = aNormal.z() * aP.x();
    aQ.z() = a * k;
  }
}

```

```
void getRotationMatrixFromZAxis( Matrix3& aRot, float aX, float aY, float aZ )
{
  Vec3f normal { aX, aY, aZ };
  Vec3f p;
  Vec3f q;

  normal.normalize();
  // This will create a reference frame for the supplied normal:
  getPlaneSpace( normal, p, q );

  aRot.set(
    p.x(), q.x(), normal.x(),
    p.y(), q.y(), normal.y(),
    p.z(), q.z(), normal.z()
  );
}

```

This will generate a vertex array that can be used to produce two triangles of the quad, and the normals for that quad.

```
std::pair<Vec3Array, Vec3Array> GetQuadCoordinatesOnPlane(
    Vec4d aPlane
  , float aQuadHalfSize )
{
  // The normals is easy:
  Vec3Array vec3ArrayNormals  = new Vec3Array( 6 );

  Vec3 normal {
      static_cast<float>( aPlane.x() )
    , static_cast<float>( aPlane.y() )
    , static_cast<float>( aPlane.z() ) };

  float d = static_cast<float>( aPlane.w() );

  ( *vec3ArrayNormals )[0] = normal;
  ( *vec3ArrayNormals )[1] = normal;
  ( *vec3ArrayNormals )[2] = normal;
  ( *vec3ArrayNormals )[3] = normal;
  ( *vec3ArrayNormals )[4] = normal;
  ( *vec3ArrayNormals )[5] = normal;

  // We need 4 vertices, we'll use those to form 2 triangles; we start off assuming
  // they're in the XY plane
  Vec3Array vec3ArrayVertices = new Vec3Array( 4 );
  ( *vec3ArrayVertices )[0] = Vec3f(  aQuadHalfSize,  aQuadHalfSize, 0.0f );
  ( *vec3ArrayVertices )[1] = Vec3f( -aQuadHalfSize,  aQuadHalfSize, 0.0f );
  ( *vec3ArrayVertices )[2] = Vec3f( -aQuadHalfSize, -aQuadHalfSize, 0.0f );
  ( *vec3ArrayVertices )[3] = Vec3f(  aQuadHalfSize, -aQuadHalfSize, 0.0f );

  Matrix3 rotationMatrix;
  getRotationMatrixFromZAxis(
    rotationMatrix
    , static_cast<float>( aPlane.x() )
    , static_cast<float>( aPlane.y() )
    , static_cast<float>( aPlane.z() ) );

  // We need a matrix4 for the vector transformation.
  Matrix4 rotat;
  for ( int i = 0; i < 3; ++i )
  {
    for ( int j = 0; j < 3; j++ )
      rotat( i, j ) = rotationMatrix( i, j );
  }

  // Transform the vertices.
  Vec3f planeOrigin = normal * -d;
  for ( int i = 0; i < 4; ++i )
  {
    Vec4f vec { ( *vec3ArrayVertices )[i], 1 };
    vec = rotat * vec;
    ( *vec3ArrayVertices )[i].x() = vec.x() + planeOrigin.x();
    ( *vec3ArrayVertices )[i].y() = vec.y() + planeOrigin.y();
    ( *vec3ArrayVertices )[i].z() = vec.z() + planeOrigin.z();
  }

  // Build the triangles.
  Vec3Array trianglesArrayVertices = new Vec3Array( 6 );
  ( *trianglesArrayVertices )[0] = ( *vec3ArrayVertices )[0];
  ( *trianglesArrayVertices )[1] = ( *vec3ArrayVertices )[1];
  ( *trianglesArrayVertices )[2] = ( *vec3ArrayVertices )[2];
  ( *trianglesArrayVertices )[3] = ( *vec3ArrayVertices )[2];
  ( *trianglesArrayVertices )[4] = ( *vec3ArrayVertices )[3];
  ( *trianglesArrayVertices )[5] = ( *vec3ArrayVertices )[0];

  return std::pair( trianglesArrayVertices, vec3ArrayNormals );
}

```
> 1 votes

---
Tags: 3d, mathematics, geometry, computational-geometry
---


# Question
Title: For deferred rendering and SSAO, what coordinate system are the normals actually in?
So, I'm following the very helpful LearnOpenGL online tutorials, and I'm working on implementing SSAO. I don't have a deferred rendering pipeline, but I need to collect normals during my depth pass so that I can sample them for the SSAO effect. I'm following this tutorial: https://learnopengl.com/Advanced-Lighting/SSAO, and referencing this one when needed: https://learnopengl.com/Advanced-Lighting/Deferred-Shading.

However, neither of these tutorials really explain what's going on with the normals. What is the normalMatrix being used in the shader?

```
mat3 normalMatrix = transpose(inverse(mat3(view * model)));
Normal = normalMatrix * (invertedNormals ? -aNormal : aNormal);

```

I'm not worried about the invertexNormals conditional, that's probably just something weird the author added for handling different conventions, but what the heck is going on with that normalMatrix? Why would we invert the view * model matrix? If we're starting with aNormal in object space (whether it's coming directly from a vertex buffer or from a normal map TBN calculation), I can't for the life of me figure out what coordinate system that resulting normal is going to end up in!

So, long story short, what coordinate frame should my normals be in if I'm to use them for SSAO? World space? View Space? Clip space? None of the above? If it's some weird coordinate system, can somebody help me get there? I'm probably more confused than I should be.

# Answer
The particular example you've shown here isn't particularly specific to deferred rendering or SSAO.

We want to transform normals by the inverse transpose matrix anytime our model matrix might contain non-uniform scale. A scale that flattens the object along the y-axis should have somewhat the opposite effect on the normals: as the model flattens into a pancake in the xz plane, the normals should gradually turn perpendicular to this plane, ie. parallel to the y axis.

That's what the inverse transpose matrix does: it preserves the rotation of the original matrix, but inverts the scale so that normal vectors stay perpendicular to the surface they stick out from.

Here, because it's the model-view matrix you're taking the inverse-transpose of, your normals end up in **view space**. (ie. x+ points to the camera's right, y+ points to the camera's up, and a normal parallel to the z axis is pointing directly toward or away from the camera, depending on your coordinate conventions) This is a reasonably common choice for deferred rendering.
> 0 votes

---
Tags: opengl, maps, ssao
---


# Question
Title: Using several render textures at the same time during runtime
I want to achieve a system where I can use render textures as portraits/icons. So when I select something I want to show it in my UI, currently I do:

1. Spawn my prefab with the model (I have one of these prefabs for each model), in my case this prefab has a camera (for render texture), a model, and a spotlight.
2. Show this render texture in my UI

This is fairly straight forward when I only need one render texture at a time. But say I select a house and want to see all residents, now I need 6-10 render textures all showing different models.

Should I create/destroy render texture assets at runtime for this type of feature, since each camera would need its own render texture? Im worried its an expensive feature that costs more than its worth perhaps.

Or do I need to create one render texture asset for each model in my game, and simply point to it in the prefab mentioned above?

Is there a smarter way?

# Answer
This likely comes down to a design choice. Given the system you described, it sounds like you are using pretty small render textures, maybe 256x256 or 512x512 at the worst, and you currently expect 6-10 textures at a time (lets say 20 in case you need some for the future). Personally I would consider one of the following options:

1.) Creating and destroying render textures as needed is technically okay (you may run into a small frame drops depending on resolution and number for render textures). So you can probably keep going as is so long as you are not using HDRP (cameras get expensive fast in HDRP).

2.) Use render texture pools to avoid the frame drop in creating up to 20 render textures. This doesn't solve the HDRP camera issue but should be okay in URP so long as you don't get too crazy with additional cameras (think I tested up to 50 or with a 1080 on Windows). There should be many examples of how to do **object pooling** online, combine this with a **singleton pattern** so you can grab them from anywhere in your game as needed.

3.) Create **one** dedicated camera that renders only game objects on the **portraits layer** and have a script that moves special character **portrait prefabs** into position so you can render out a **single render texture Atlas** of all portraits needed at the moment. This should eliminate all costs associated with creating new render textures, new cameras, and most camera render time (you still need one). This is the approach I normally take for HDRP projects when I need to do stuff like rendering text in Visual Effect graphs. It's tricky to setup but should work in most cases. Just make sure your render texture is the size of *"portraitResolution.X x textureAtlasColumnCount, portraintResolution.Y x textureAtlasRowCount"*. So for 20 rendertextures at 256x256 that would be roughly 1280x1024 or 2560x2048 at 512x512 with 5 images per row and 4 rows. To use these images you can adjust the UV offset on any materials that take the texture atlas as a texture.
> 1 votes

---
Tags: unity
---


# Question
Title: Bandwidth cost / hour for one MMORPG player
I am trying to calculate / guesstimate the costs of running an MMORPG for a client. And now I need a pretty accurate estimate for the monthly bandwidth cost so I can calculate the possible revenue of the investor / client. So what is a pretty reasonable bandwidth cost for each player per hour?

The MMORPG I'm trying to make is a virtual conference with gamification. We can go to booths, see other people, make a transaction in the booths. And we will also have a quest and mini-game system for the gamification.

We will be making it using Unity + Forge. We were thinking of using Photon before, but when I reached out to them, they said I need to subscribe for Photon Industries since it's not a game, per se, which is like 2.5x the cost of PUN.

We will split the server into two: the game server and the REST API server. I'm in charge of the game side of the project so the REST API and backend is not my jurisdiction. I this is the specs of the game that I had in mind:

1. The event will be held for 10 days, possibly running 24 hours straight.
2. Max customer that we have anticipated is around 1000-2000 CCU
3. There will be multiple scenes / rooms that the customer can go to (e.g. Commerce area, Lobby area, Mini-Game area, etc)
4. The quest system, booth transactions, and other features that doesn't need real time update will be handled by the backend.

So that leaves these data that needed to be synced:

Player:

* position : 4 bytes * 3 (X, Y , Z) = 12 bytes
* currentScene: 1 byte
* avatarModel: 4 bytes (will use bitmasking to handle the current type of clothing and accessories of the player model)
* playerAction: 4 bytes (player's enumerated action type)
* playerActionTarget: 4 bytes (player's action's target)

Scene:

* sceneStatus: 16 bytes (any status of the current scene e.g. the current quest. Still unsure how many bytes I need to sync)

So, this is what I have calculated so far using AWS EC2 (possibly wrong):

# Answer
> 26 votes
Your calculation makes a couple mistakes which might change your actual traffic and bandwidth requirements a lot.

## Not every information needs to be updated with the same frequency

For example, the look of the avatar. You only need to tell clients how an avatar looks when they either encounter that avatar for the first time or when that avatar changed its appearance. So those 4 bytes which describe the character appearance don't need to be sent 15 times per second, because most of the time they won't have change since the last update.

The only information which *might* always requires 15 updates per second is position and rotation. In action-oriented games, players will often spend more time moving than standing, so those games often don't bother checking and just send continuous position updates. But considering the target demographic for your application, I would expect that the majority of users will stay idle most of the time. So even position and rotation might be something you only need to send when someone is actually moving.

## The amount of data you need to send increases quadratically with the number of users in the same room.

When there are 100 users in a room and one user does something, then you receive that action once, but you need to send it to all 100 users in the room. If all users do something at once, you need to distribute 100 x 100 = 10,000 messages.

So people distributed over many smaller rooms will generate a lot less traffic than the same number of people in the same room.

## You assume people will be online for 24 hours

This is very unlikely in this context. When it is a virtual conference, you can assume that the time every participant spends online on average is about the length of a regular work day (~8 hours). But keep in mind that there will very likely be peaks where almost all participants will want to be online at once. So this affects the traffic requirements, but not the bandwidth requirements.

## What you really need to worry about is media streaming

When this is a virtual conference, then I assume people will want to communicate and present. They will want to have voice chat. They will want to show powerpoint slides or even videos to other participants. The traffic requirements for that will eclipse anything you could do to sync up the users avatars.

## Conclusion

You need to do testing to check how your end-users will interact with your product, optimize your netcode for their behavior patterns and then see how much traffic your product actually generates.

# Answer
> 19 votes
> **Note:** This answer was written for an earlier version of the question which lacked any details about what the project was actually about. While it does not answer the new version of the question properly, I will leave it up, as it might help others.

I'm sorry, but you can't do such an estimate without having a prototype. Not every MMORPG is the same. Depending on various implementation details and your game mechanics, your bandwidth can differ a lot.

For example, how often are you going to send position updates to the clients? When you have an action-oriented combat system where players are expected to act and react quickly, you ideally want to send 100 updates per second for maximum precision. But if the combat system is a bit slower, then perhaps just 10 updates per second and letting the clients interpolate between them are OK. In a very slow-paced system, you might even get away with just 1 update per second.

So this simple design choice about how your combat system works can affect your bandwidth requirements by factor 100. And that was just one feature. MMORPGs are very complex games. There are lots and lots of features which could require a lot of bandwidth depending on what you want them to do and how you implement them.

Further, that number might not scale linearly with the number of players. It in fact usually increases quadratically with the number of players in the same area. When there are 10 players, then you need to update 10 clients each about what happens to 10 different players. Which means you don't need to send 10 times but 100 times the data. So depending on how the players in your game will distribute themselves around your game world, you might have very different traffic requirements. Sure, there are ways to influence that. And there are workarounds for too many people being in the same area and bogging down the server (like instancing). But do you *want* to use them? And if you do, *when* and *how* exactly? These are all very complex design questions you might not be able to answer yet.

---

However, you could take a different approach. Set a budget for how much bandwidth the game is allowed to consume. Then take that budget into account while you develop your game. When some feature of the game breaks the bandwidth budget, either drop or redesign it.

But if it turns out that your budget was too low, then a lot of features you considered essential to the vision of your game might end up getting cut. So this approach could lead to frustration for you and your investors.

So you need some experience to judge how much bandwidth you will need in order to make those essential core features possible. One way to gain that experience is by creating a prototype.

# Answer
> 3 votes
I think you are mixing a few things together that have very different properties and requirements on communication.

Scene, its state, and items in the scene are slow changing. They may require rather large amount of data, but the data are mostly constant. You need an effective way to broadcast partial updates, a diff, of what changed. Players then can keep track of the changes and update their copy of the scene state. It is a good idea to broadcast the full state from time to time, for example, in form of a hash or a version number, because the players may get out of sync due to a bug.

Chat messages, trades, emotes and similar things are changing relatively slowly, but you must not loose them. You also need to preserve history of the chat messages. You want transactional consistency here.

Player position and movement is changing quickly and there is no need to keep history. It is fine to drop a few updates, just make sure you get the last one. You want eventually consistent state here, i.e., state may be temporarily inconsistent, but after a while, the clients sync again. These updates also depend on the distance between players. If player is far away or out of sight, you don't need to know his exact position, but you need an update when you get close to him again, even if he does not move. Notice how players disappear in the games when they are in distance.

Spells, actions, and similar stuff is somewhere between these two. You need to broadcast them only to nearby players, there is no need for keeping the history, but you should not loose the event. The state update should be distributed separately from these events, because if you loose such an event, other player will not see the action, e.g., a spell cast, but they must keep their local state in sync with the global state.

---

Then there is a TCP connection. It sends packets again if they are lost and there are buffers on the way. You need to take into account that. You need to watch for the communication, response times and buffer usage. If you use UDP, the situation is easier, but you will have troubles with firewalls, and you cannot use WebSockets in a web browser.

---

Anyway, you need to figure out how to update the world. There are scene state, player state, NPC state, chat messages, and effects. Each have different requirements. You need to utilize eventual consistency, keep the updates localized, and reduce communication that is not relevant.

There is no need to assign bytes to a scene state or player features. You need to have items, instances, and properties. Then send a message when a property changes. The world state needs to be a tree with partial updates. A client needs to know that given data are obsolete (and how much), but it may not need to know the current state. It may just ask later when player actually takes a look.

This brings us to the one more feature: AFK. Users are often away from keyboard, not paying attention, not looking. The game may be minimized and the player is only listening to the talk. When user is online for 24/7, it does not mean he actually is there. If a player does nothing for a while there is no need to send or receive updates that often.

---

So, back to the original question: How much bandwidth do we need?

I really like the budget idea from the other answer. Calculate the size of the state update messages, assume about 5 to 20 updates per second. You should get a few kilobytes per second. Then set the budget and throttle the updates to fit the desired frequency and the budget. Limit updates between players that do not see each other and are far away. Your problem will be latency.

---
Tags: mmo, costs
---


# Question
Title: Find projectile initial velocity, and air time, given projectile elevation, distance, angle
I have a target X position (D). I have a turret Y elevation (E). Turret is always pointed at 45 degrees (A). I need to calculate the initial projectile velocity required to hit the target, with an arbitrary gravity constant (G).

# Answer
> 3 votes
If your projectile is fired on a 45 degree angle, that's:

$$ \vec v = (c, c)$$

...for some scalar component \\$c\\$.

Gravity doesn't affect the horizontal axis, so the time it takes this projectile to cross the horizontal distance to your target is:

$$T = \frac D c$$

Now we can plug that into the equation of our parabola on the vertical axis, tracking the height at time \\$T\\$, \\$h\_T\\$ as a function of time, our initial height \\$h\_0\\$, our upward speed \\$c\\$, and our acceleration due to gravity \\$g\\$:

$$h\_T = h\_0 + c \cdot T + \frac g 2 T^2\\ h\_T = h\_0 + c \frac D c + \frac g 2 \frac {D^2} {c^2}\\ h\_T - h\_0 - D = \frac {g D^2} { 2 c^2}\\ c^2 (h\_T - h\_0 - D) = \frac {g D^2} 2\\ c^2 = \frac {gD^2} {2 (h\_T - h\_0 - D)}\\ c = \sqrt{\frac {gD^2} {2 (h\_T - h\_0 - D)}}\\ c = \sqrt{\frac {-gD^2} {2 (E + D)}}$$

...taking only the positive root because by construction our vector has to point up and to the right.

Don't be alarmed by the negative sign inside the square root. Because gravity points downward, your acceleration constant \\$g\\$ in this formula is negative, canceling out to a positive.

---
Tags: mathematics, projectile-physics
---


# Question
Title: How to disable pause() in game_loop() once game_over() function is called?
How can I disable pause() in game\_loop() once game\_over() function is called?

# game loop

```
def game_loop():
    global playerX, playerY, playerX_change, playerY_change, bulletX, bulletY, bulletY_change, bullet_state
    global score

    # background music
    mixer.music.load('bg music.mp3')
    mixer.music.play(-1)

    running = True

    while running:

        # set background image(bg)
        bg = pygame.image.load('bg 2.PNG')
        screen.blit(bg, (0, 0))

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                if event.key == pygame.K_p:
                    pause()
                    game_loop()

            # movement of player L, R , U & D
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    playerX_change -= 7

                if event.key == pygame.K_RIGHT:
                    playerX_change += 7

                if event.key == pygame.K_UP:
                    playerY_change -= 7

                if event.key == pygame.K_DOWN:
                    playerY_change += 7

                # update bullet position when shift in player position + bullet sound
                if event.key == pygame.K_SPACE:
                    if bullet_state == "ready":
                        bullet_sound = mixer.Sound('bullet.wav')
                        bullet_sound.play()
                        bulletX = playerX
                        fire_bullet(bulletX, bulletY)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    playerX_change = 0

                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    playerY_change = 0

        playerX += playerX_change
        # for player stay inside game window (L & R)
        if playerX >= 650:  # R
            playerX = 650
        elif playerX <= 20:  # L
            playerX = 20

        playerY += playerY_change
        # for player stay inside game window (U & D)
        if playerY >= 370:  # D
            playerY = 370
        if playerY <= 350:  # U
            playerY = 350

        # for enemies to stay inside game window & enemies movement
        for i in range(no_of_enemies):
            # game over
            if enemyY[i] >= 340:
                for j in range(no_of_enemies):
                    enemyY[j] = 1000
                game_over()
                break

            enemyX[i] += enemyX_change[i]
            if enemyX[i] >= 720:  # R
                enemyX_change[i] -= 5
                enemyY[i] += enemyY_change[i]
            elif enemyX[i] <= 20:  # L
                enemyX_change[i] += 5
                enemyY[i] += enemyY_change[i]

            # collision for every enemy
            result = collision(enemyX[i], enemyY[i], bulletX, bulletY)
            if result:
                enemy_to_blast(enemyX[i], enemyY[i])
                explosion_sound = mixer.Sound('explosion.wav')
                explosion_sound.play()
                score += 1
                bulletY = 445
                bullet_state = "ready"
                enemyX[i] = random.randint(20, 720)
                enemyY[i] = random.randint(20, 150)

            # call enemy func
            enemy(enemyX[i], enemyY[i], i)

        # bullet movement
        if bullet_state == "fire":
            fire_bullet(bulletX, bulletY)
            bulletY -= bulletY_change
            # re-appearance of bullet at start point
            if bulletY <= 0:  # U
                bulletY = 445
                bullet_state = "ready"

        # call funcs 'player' & 'score'
        player(playerX, playerY)
        display_score()
        display_pause()

        pygame.display.update()

```

# pause()

```
def pause():
    global running

    # background music for paused screen
    mixer.music.load('start.mp3')
    mixer.music.play(-1)

    paused = True

    while paused:

        txt_on_screen(paused_text_font_1, "PROJECT ANNIHILATION", 0, (-120), white, black)
        txt_on_screen(paused_text_font_2, "0N HOLD", 0, (-70), red, black)
        txt_on_screen(paused_text_font_3, " RESUME >> esc ", 0, 0, black, light_purple)
        txt_on_screen(start_text_font_3, " SETTINGS >> s ", 0, 50, black, light_purple)
        txt_on_screen(start_text_font_4, " QUIT >> Delete ", 0, 100, black, light_purple)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                paused, running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:  # RESUME GAME
                    paused = False
                    mixer.music.stop()
                    break
                if event.key == pygame.K_DELETE:
                    paused, running = False
                # if event.type == pygame.K_s >>>>> volume settings
        pygame.display.update()

```

# game over

```
def game_over():
    global bullet_state
    # centering game-over text
    txt_on_screen(game_over_font, "GAME-OVER!", 0, 0, light_purple, None)
    # centering game-over 'instructions' text
    txt_on_screen(below_txt_font, "Press 'Delete' to QUIT, 'r' to RESTART", 0, 50, white, black)

    # game-over sound effect
    end_sound = mixer.Sound('end.wav')
    end_sound.play()
    mixer.music.set_volume(0)

    # unable shooting bullets
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                bullet_state = "ready"
            if event.key == pygame.K_r:
                game_loop()

```

# Answer
You call `game_over()` inside `game_loop()`, and `game_loop()` again inside `game_over()`, and I *think* that could eventually reach an OverFlowError if you restart the game too many times (though I am not 100% sure).

What if you did something similar to `pause()` and write a while loop inside the `game_over()` function that leads you back to `game_loop()` once it's over? That way you would also disable `pause()` from being called.

e.g.

def game_over():
    global bullet_state
    # centering game-over text
    txt_on_screen(game_over_font, "GAME-OVER!", 0, 0, light_purple, None)
    # centering game-over 'instructions' text
    txt_on_screen(below_txt_font, "Press 'Delete' to QUIT, 'r' to RESTART", 0, 50, white, black)

    # game-over sound effect
    end_sound = mixer.Sound('end.wav')
    end_sound.play()
    mixer.music.set_volume(0)

    game_over = True
    while game_over:
        # unable shooting bullets
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    bullet_state = "ready"
                if event.key == pygame.K_r:
                    game_over = False

```

> 0 votes

---
Tags: architecture, game-loop, pygame, logic, game-state
---


# Question
Title: Game Architecture: Class leaking into almost all files
We currently have the problem that our main class GameController is being pulled into every backend file in our game. We're wondering what are common solutions to this problem.

Here's a bit more about the game architecture. The game is a board game, so since ~90-95% of the time there isn't anything happening, the game is set up more like a rest API. It waits for a user prompt, when received, the msg is distributed to the respective components of the game and the proper logic is executed. No large update loops, just executes logic when prompted.

The problem is that as this msg cascades through the system, GameController acts more like a relay point between the systems. It's how the nodes communicate to each other so that all game components are updated properly. The problem is that it's created this system where all new/old classes contain a pointer to parentGame, so GameController is everywhere.

Are there any simple architectural solutions to avoid having every class contain a pointer to parentGame? Is this necessarily a bad thing?

Some example code:

class GameController {
    bank: Bank
    action: Action
    ...
}
class Bank {
    parentGame: GameController

    constructor(game: GameController) {
        this.parentGame = game
    }
}
class Action {
    parentGame: GameController

    constructor(game: GameController) {
        this.parentGame = game
    }
}
```

# Answer
I've encountered systems like this; hell, I've even written some when I was in a hurry during prototyping. It is not specifically *wrong*, it is just one way in which systems can evolve. Reasons systems evolve this way include:

* The root controller class / instance *needs* to be privy / proxy to much or all of what other actors in the system, are doing (perhaps even before it is done); maybe it needs to take some secondary action.
* The root controller is the only one who is *authorised* to use this message to issue imperatives to other sub-controllers, i.e. the usual Hierarchy of Control we see in most programs. So by this manner of thinking, messaging in this system *has to* go via the root controller.
* The lack of time, willingness, or knowledge as to how to improve the system.

...the reality is the first two are just ways of thinking about the system. This kind of "deep propagation" up *and* down through a control tree gets increasingly tedious to manage explicitly, as the tree deepens... and deepens... as it tends to do in an app as complex as the typical game.

`Is this necessarily a bad thing?`

As someone else said, Yes, usually. Under most conditions, tight coupling is to be avoided. The reason is that the cost of modifying the code becomes large, *quickly*.

`Are there any simple architectural solutions to avoid having every class contain a pointer to parentGame?`

**One way is to pass methods** from super-controllers downward, let sub-controllers call them. This breaks encapsulation; but it is a relatively quick solution. Ultimately though, if these methods are modifying state on the parent, it still acts as a sort of messaging hub, just as you describe.

I would not recommend this except as an interrim measure on the road to a better architecture.

**Another way is the observer pattern**, A.K.A. **pub(lish)-sub(scribe)**. This prevents your having a direct link to an instance of a specific class; rather, you have indirect, generic links to instances of a specific *interface* from which your classes *inherit*. As subscriber, you can now listen to the messages which the publishers broadcast, or broadcast your own message to those subscribed to you. A given class can even be both a publisher and a subscriber, provided it inherits or implements both sets of functionality!

Anything that needs to know when *something else* changes, but doesn't want to create a specific, typed link to the *something else* in question, should use this pattern.

One of the reasons it works so well is the observer has a list of these abstract / interface-derived objects. If there are no objects, the iterator does nothing, and there is no null reference error (which you will get plenty of, in your current project). If there is one object, or many objects which the observer is listening to, it treats them all similarly. Lists / Arrays are powerful this way, and it is one reason language design is headed in this direction; avoiding dreaded NREs / NPEs completely.

The essence is that you can have multiple observer arrays and multiple response styles (callbacks) for those different sorts of objects observed by each array. Different objects may subscribe, for example, to messages from both children and global services, with each type of child, and each type of service, being intercepted and handled in a different manner.
> 1 votes

# Answer
I think the most important question is: why are all your modules/systems accessing GameController?

Are they interacting with GameController so that they can access data or functionality provided by this class? If that's the case, your GameController is probably accumulating too much responsibility and you might benefit from applying the single responsibility principle (https://en.wikipedia.org/wiki/Single-responsibility\_principle). You might want to refactor GameController into multiple classes so that concentrated functionality/data is naturally diluted away and your systems start depending less on GameController and more on other classes. However, you mentioned GameController works as a relay to your systems, so I believe that you already have an architecture that is not so monolithic.

Are your systems interacting with the GameController so that they can access other systems? If that's the case, your GameController is probably behaving like a module/system container, exposing all modules - high or low level - to any module, and so you might benefit from applying the dependency inversion principle (https://en.wikipedia.org/wiki/Dependency\_inversion\_principle). You might want to inject the system's dependencies (via ctor or setters) from GameController instead of acquiring them from each system via GameController's getters. That way they won't have to have any knowledge about the GameController and the other modules/systems that they don't need to know about. You could even use a DI container implementation, but I fear that might be too much for your current needs.

In the end, it can also be a bit of both. You might have to break down your solution into smaller modules/systems and you might want to decouple them from GameController.

> Is \[accessing the GameController from all other classes\] necessarily a bad thing?

I'd say yes. That couples most of your classes to the GameController class, meaning that if you change GameController's public interface, you'd probably need to recompile those classes. And if GameController is the corner-stone of your solution, how frequently would that happen?

How you're going to tackle that, however, depends on how you got to this situation which is what I tried to get to with the questions above.
> 1 votes

---
Tags: architecture, software-engineering, design-patterns
---


# Question
Title: Modern Compilers Inlining and Header and Implementation Practices in Game Development
I was taught that in general practice its best not to try to beat the compiler, at least until its proven to be stupid. So in general, and since I was told that its generally only used as a suggestion to the compiler, the inline tag has never been a priority for me to use because I was taught that the compiler is pretty good when it comes to understanding the trade offs your system will have to make when it comes to inlining vs. looped calls to a function pointer for example.

But then I just read that functions cannot be inlined unless they are defined in the header file because otherwise the compiler won't see it when it starts to work on other header and cpp files. I did some more research and I found that some people were saying that this is the old way things worked and that modern compilers perform "Whole Program Optimization" or "Link-Time Code Generation" which is responsible for the construction of the obj files that I'm used to seeing which can then be linked together and optimized further such as allowing the compiler to see functions in the obj file that were once "hidden" in the cpp file and then inline optimize them where appropriate. This sounds great but I'm wondering which source to trust and was wondering if I could get an additional opinion on the matter.

On the other hand I was reading up on header only implementations and how they tend to be used in libraries to increase compiler optimizations and was wondering if its was also a standard practice in game development or if it was typical to separate declaration and implementation into different files when developing a game engine.

# Answer
> \[I\] was wondering if its was also a standard practice in game development

<sup>(I'll cover only this because it's the only part that is on-topic here.)</sup>

The standard practice in game development is to *ship* a game that can be played in a decent way on the *target hardware*.

This means that developers have to find the right balance between time it takes to produce a game (including a decent compile time -- `developer's time == money`) and how smooth it plays on the hardware (rightly optimized).

Given this angle, there is not really a way to define a standard practice w.r.t. creating header-only libraries in the game development industry. And I suspect that applies to other industries too.
> 3 votes

# Answer
If you're really working at sufficiently critical parts of the engine, I recommend `noinline` to help optimizers instead of `forceinline`. BTW, the compiler is stupid in its own way just as we are. It doesn't know in advance what is a common case execution path and rare case one unless you use PGO, and that's very tricky with an interactive game unless you write all sorts of tests that simulate what users commonly do. We're stupid about things like register allocation (and maybe instruction selection if we're really ignorant about computer architecture), but we certainly know better (or we should anyway) than the compiler about how users are going to use the software.

Tell the compiler, "This function isn't going to be called repeatedly in a loop. So never inline it." That can help a lot, and I recommend reaching for this over forceful inlining if people are tempted towards the latter. It helps even with inlining because say we have a function like this:

```
void some_func(...)
{
    if (common_case)
        f1();
    else // rare case
        f2();
}

```

The optimizer, absent PGO, has no idea whether f1() or f2() is a common case even though you know upfront. So if they're both reasonably small functions, the optimizer will tend to inline both. Then `some_func` may cease to be inlined, and that can cut into performance and show hotspots in profiling sessions that can disappear if you `noinline` the rare case. Mark f2() with `noinline` and then both `some_func` and `f1` will likely be inlined. So I actually recommend making `noinline` your best friend if you are tuning at this level, not `forceinline`.

It's also more intuitive. There's probably some legitimacy to the adage that optimizers know better than we do about what to inline. They have a lot of information like precisely how many machine instructions will result and how many registers are allocated that is very difficult for a human to anticipate. But we certainly know better what to definitely *not* inline which they will tend to inline otherwise.

As for what compilers inline, linkers can inline things since the late 90s (maybe before but that's the first time I became really aware of it). Shoving everything into a header file as a way to encourage inlining seems silly to me. Besides, if these things are really critical, I don't see why a dev wouldn't at least profile these things with profiler in hand. It's very quick to tell what is and isn't inlined there. The benefits of header-only files are predominantly convenience as I see it (I'll be happy to change my mind if someone shows me a case where inlining every single thing in a header file actually boosted performance).
> 1 votes

---
Tags: c++, optimization
---


# Question
Title: How to make my sun appear far away in VR
I am attempting to add VR compatibility to my game, please could you help me figure out how to better control the multiple cameras in my scene regarding the head tracking and movement from VR devices?

I’m using Unity v2019.4, and not using the new VR Plugin system. In my XR Settings I have Virtual Reality Supported ticked and have the Oculus and OpenVR virtual reality SDKs.

I have three cameras in my scene, at the following Depth levels:

2 = Main Camera (Depth only) which shows everything except my sun and skybox

1 = A Sun Camera (Depth only) showing only my sun layer

0 = A Background Camera (SkyBox) showing my custom skybox

The reason I render the sun on a separate camera is to give the effect of a very distant object. The sun camera is sat close to the sun, but when I move in the scene the sun never gets any closer giving the illusion of it being far out there in space. This works great in non-VR, but in VR if I move my head forward or to the side, the sun camera also moves and so breaks the illusion of the distant sun.

I have tried playing around with settings and done a lot of searching, but I cannot figure out how to stop the "local" movement in my sun camera. Any ideas?

# Answer
If you can modify the shaders used by your sun, you can neutralize the parallax of your camera in the vertex shader.

Here's the default vertex shader you get from Unity when making a new unlit effect (I presume the sun is unlit since it's a source of light, not something that reflects light significantly):

```
v2f vert (appdata v)
{
    v2f o;

    // This line combines the object's transform, the camera's viewpoint,
    // and the perspective projection into one step.
    o.vertex = UnityObjectToClipPos(v.vertex);
    // That's the only part we're going to change.

    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
}

```

We can change that to this:

```
v2f vert (appdata v)
{
    v2f o;

    // First, apply the object's transformation in the world.
    float4 pos = mul(unity_ObjectToWorld, v.vertex);

    // Zero out the w component, so we're not affected by the camera position
    // in the next step - we behave as though the camera is always at (0, 0, 0).
    pos.w = 0;
    // Then apply the camera's rotation.
    pos = mul(UNITY_MATRIX_V, pos);

    // Restore the w component so we project correctly...
    pos.w = 1;
    // ...and apply the perspective projection.
    o.vertex = mul(UNITY_MATRIX_P, pos);

    // The rest of the shader can remain unchanged.
    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
}

```
> 0 votes

---
Tags: unity, virtual-reality
---


title: How can I draw filled triangles in C++?

text:
# Question
Title: How can I draw filled triangles in C++?
**VERY IMPORTANT NOTE:** Im trying to fill a triangle. I have already made the 3D part. Sorry if this wasn't understandable.

I'm currently trying to create a simple 3D-Engine. Well, I have successfully drawn a triangle using this method.

```
void DrawTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
  drawLine(x1, y1, x2, y2); //Usage: drawLine(x, y, x1, y1)
  drawLine(x2, y2, x3, y3);
  drawLine(x3, y3, x1, y1);
}

```

After this method worked surprisingly well and a cube appeared very convincing, I tried to add lighting. Now I'm facing a pretty big problem. After a long thought I found this method of filling a triangle but here is the problem. It paints a few triangles but not all. Unfortunately I cannot show any pictures because I do not have a camera and a screenshot would not work (as I explain later). My theory is that it only draws bottom flat triangles (or the other way around). What should I change about my method so that it works? Thanks in advance.

This is my filling code:

```
void FillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
 drawLine(x1, y1, x2, y2);
 drawLine(x2, y2, x3, y3);
 drawLine(x3, y3, x1, y1);
 for(int x = x1; x<=x2; x++) {
    for(int y = y1; y<=y2; y++) {
     drawLine(x3, y3, x, y);
    }
  }
}

```
* I'm currently working with an Arduino UNO
* I'm using the Nokia 5110 display
* I'm using C++
* I'm using this library for displaying
* Do not downvote, just comment what you need to know.
* I have already tried this code but it wasn't working.

# Answer
There's plenty of different rasterization algorithms, but many articles you find these days are optimized for systems with fast floating point math. For your use case, the ones on this page would probably work better: http://www.sunshine2k.de/coding/java/TriangleRasterization/TriangleRasterization.html.

If you already have a function to draw lines, you can use the Bresenham triangle algorithm to do the job:

> 1. Draw the line V1V2 using the bresenham algorithm, but stop if the algorithm moves one pixel in y-direction.
> 2. Draw also the line V1V3 using the bresenham algorithm, and stop if the algorithm moves one pixel in y-direction.
> 3. At this point we are on the same y-coordinate for line V1V2 as well as for line V1V3.
> 4. Draw the horizontal lines between both current line points.
> 5. Repeat above steps until you triangle is completely rasterised.
> 1 votes

# Answer
A relatively fast algorithm in pseudocode:

```
function fill_a_triangle(x1,y1,x2,y2,x3,y3)
  //get length of all sides
  d1 = sqrt(((y2-y1)**2)+((x2-x1)**2))
  d2 = sqrt(((y3-y2)**2)+((x3-x2)**2))
  d3 = sqrt(((y1-y3)**2)+((x1-x3)**2))
  if(((d1<d2)or(d1=d2))and((d1<d2)or(d1=d2)))
    tx = x1
    ty = y1
    vx = (x2-x1)/d1
    vy = (y2-y1)/d1
    counter = 0
    while(counter<d1)
      draw_a_line(x3,y3,tx,ty)
      //drawing a line from point(x3,y3) to point(tx,ty).
      tx = tx + vx
      ty = ty + vy
      counter = counter + 1
  else if((d2<d3)or(d2=d3))
    tx = x2
    ty = y2
    vx = (x3-x2)/d2
    vy = (y3-y2)/d2
    counter = 0
    while(counter<d2)
      draw_a_line(x1,y1,tx,ty)
      tx = tx + vx
      ty = ty + vy
      counter = counter + 1
  else
    tx = x3
    ty = y3
    vx = (x1-x3)/d3
    vy = (y1-y3)/d3
    counter = 0
    while(counter<d3)
      draw_a_line(x2,y2,tx,ty)
      tx = tx + vx
      ty = ty + vy
      counter = counter + 1

```

Note that how accurately this algorithm performs is affected by how you implement it. If it doesn't work, try drawing the individual dots in a line rather than using a built in function.
> 1 votes

---
Tags: c++, graphics, rasterization
---


# Question
Title: Isometric tiles on wrong positions if the mouse points at a negative world coordinate
I am using this approach:

http://clintbellanger.net/articles/isometric\_math/

Basically, you can calculate the iso coordinates based on the screen coordinates. What I am doing is, getting the actual world position the mouse is pointing at using get\_mouse\_global\_position() and convert this position to isometric values.

Then I translate those coordinates back to world space coordinates to actually display the sprite.

Problem is, that when the world coordinates come from a negative position, the tiles get offset by almost an entire tile amount. Here is the relevant code.

The get\_coord() function returns the actual world position of the tile used to display the Sprite

```
func get_coord(pos : Vector2):
    var t = Vector2()
    var e = screen_to_iso(pos)
    t = iso_to_screen(e)
    print(pos)
    print(e)
    print(t)
    return t
    pass
var buildings

func screen_to_iso(pos :Vector2):
    var flipx = 0
    var flipy = 0
    var t = Vector2()
    var x_size = size/2
    var y_size = size/4
    t.x = int((pos.x/x_size) + (pos.y/y_size))/2
    t.y = int((pos.y/y_size) - (pos.x/x_size))/2
    return t
    pass

func iso_to_screen(pos : Vector2):
    var t = Vector2()
    var x_size = size/2
    var y_size = size/4
    t = Vector2((pos.x-pos.y)*x_size, (pos.x+pos.y)*y_size)
    return t
    pass

```

I can't seem to figure out a way

# Answer
> 1 votes
I'm not familiar with the language you're using (GDScript?) but the usual reason for negative sides of a grid to be off by one is that you're using an operation that rounds towards zero, where you want one that rounds down.

```
t.x = int((pos.x/x_size) + (pos.y/y_size))/2
t.y = int((pos.y/y_size) - (pos.x/x_size))/2

```

I looked for documentation and this page says

> int int ( float from )
>
> Cast a float value to an integer value, this method simply removes the number fractions, so for example int(2.7) will be equals to 2, int(.1) will be equals to 0 and int(-2.7) will be equals to -2.

That will explain your error: you want -3 and you get -2.

One solution is to use the floor function, which always rounds towards negative numbers, before converting to int.

However, I notice that you're dividing by 2 after converting to int; dividing by 2 will also round towards zero, so you can't just insert `int(floor(...))` into your existing expression. I haven't studied your code enough to understand it completely, but it's possible this would work (spaces and bold inserted to highlight differences):

```
t.x = **int(floor( (** (pos.x/x_size) + (pos.y/y_size) **)/2 ))**
t.y = **int(floor( (** (pos.y/y_size) - (pos.x/x_size) **)/2 ))**
```

---
Tags: mathematics, isometric, godot, projection
---


# Question
Title: How to get neigbor pixel coordinates in Unity HLSL shader
I am writing Mandelbrot set shader for Unity.

I wrote an Image Effect shader and it works.

Unfortunately, each point "shimmers" on translate scale. This is because, for each shader call I compute value for only one mathematical point, which is infinitesimal. On even small translation, the value can change drastically.

So, I would like to compute math value not for one point, but for several. But for this I need to know, which aother points belong to my pixel, and for this I need to know the distance to neighbor pixel. Unfortunately, my incoming values are float and I don't know, how to step to next pixel.

How to accomplish?

# Answer
Somewhere in your shader you'll have a declaration of your texture sampler, something like this:

```
sampler2D _MainTex; // This is the sampler.
float4 _MainTex_ST; // This is the scale/offset parameters set in the material widget.

```

Add one extra line below these:

```
float4 _MainTex_TexelSize;

```

This gives you a variable you can access in your shader, that Unity will pre-populate as described in the docs:

> **Texture size** {TextureName}\_TexelSize - a float4 property contains texture size information:
>
> * x contains 1.0/width
> * y contains 1.0/height
> * z contains width
> * w contains height

Now you can use this in your shader. Where the "current" pixel being drawn is...

```
float2 thisPixel = i.uv;

```

We can shift this to get...

```
float2 rightNeighbour  = i.uv + float2(_MainTex_TexelSize.x, 0);
float2 leftNeighbour   = i.uv - float2(_MainTex_TexelSize.x, 0);
float2 topNeighbour    = i.uv + float2(0, _MainTex_TexelSize.y);
float2 bottomNeighbour = i.uv - float2(0, _MainTex_TexelSize.y);

```

And of course you can scale this by a scalar to reach over only half a pixel, or two pixels, or combine both x & y to access a neighbouring point in any diagonal direction.
> 2 votes

---
Tags: unity, shaders, hlsl, image-effects
---


# Question
Title: A* heuristic for a map that can have roads
I have a 2D grid which I am performing A\* pathfinding on. Nodes are connected via a value of **3** in most cases (some connections are more expensive). In some (depends on the gameplay) circumstances the node may have a **road** to another node though, bringing the connection cost down to **1**.

The heuristic cost is determined by multiplying the heuristic value (as stated below) with the minimum connections to take (this is known).

If I use a **heuristic of 0** per connection then A\* will always find the shortest path, due to just performing a Dijkstra search. Not ideal.

If I use a **heuristic of 1** per connection then A\* will still always find the shortest path, but will not be very efficient even when the path is straightforward. This is my fallback.

If I use a **heuristic of \>1** per connection then A\* may not always find the shortest path, but will be more efficient. I am kind of scared of this "not always the shortest path".

I'm considering using a heuristic of 1 (or just always lower the heuristic score by a set amount without letting it get below 1) for connections heuristically close to the target (and maybe close to the start too?) to have "perfect" pathfinding in the regions where it may matter most. Useful or wrong thinking?

What would be a good way to handle this setup? Any tips?

Edit: I just found http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html and wanted to mention it, quite helpful.

# Answer
> 1 votes
The point of the A\* is to exploit the structural constraints present in most real-world path-finding applications. The heuristic just needs to give a meaningful lower-bound to the total cost of reaching the end-node.

For example, for a graph modeling real-life roads, we know the shortest possible distance between two cities is the bird's-eye straight-line, and teleporters don't exist, so we can safely say that no path between those cities (no matter what roads are taken) will have a shorter distance than that. This extra information doesn't come from the *graph*, it comes from the thing we're using a graph to represent.

You haven't told us anything about the *physical* constraints of the problem you're using a graph to model, so we have no way of knowing whether your idea will work or not. If you somehow *know* that the path from **start** to **finish** will take at least **n** hops, and each hop has weight of at least 1, then **n\*1 = n** is a reasonable heuristic. However, if you don't have a lower-bound on the number of hops, then "minimum weight per connection" isn't really helpful.

---
Tags: path-finding, heuristics
---


title: delta_time with discrete movement

text:
# Question
Title: delta_time with discrete movement
I have a basic snake game movement system with Pygame:

```
clock = pygame.time.Clock()
if timer == MOVE_TICK_INTERVAL:
    timer = 0
    move_snake()

timer += 1
clock.tick(MAX_FPS)

```

The issue is that the higher `MAX_FPS` is, the faster `timer` iterates and thus the faster the snake moves. I'm aware of using some form of `delta_time` variable to calibrate and adjust the velocity of an object moving continuously but I don't know how to implement this method with discrete, grid-based movement.

In short, I want to move my snake the same amount of units in a direction every interval with frame rate considered but I don't want to modify said distance.

# Answer
> 1 votes
It's fairly straightforward to convert this to use the real-time clock. The PyGame `time` object has a `get_ticks()` member function which returns a continuously updating count of milliseconds. It's quite handy for timing objects in games.

Basing your movement on a number of milliseconds makes the updating completely independent of the frame rate. So if your FPS drops a fraction because the device needs to do something in the background, the movement is still constant.

```
MOVE_TICK_INTERVAL = 300   # milliseconds between player movements
next_move_at       = 0     # time in future when player move occurrs

clock = pygame.time.Clock()

# in main loop
time_now_ms = pygame.time.get_ticks()

# is it time to move the player?
if ( time_now_ms > next_move_at ):
    new_move_at = time_now_ms + MOVE_TICK_INTERVAL   # future time of next move
    move_snake()

clock.tick(MAX_FPS)

```

---
Tags: python, pygame
---


# Question
Title: Stop mouse joint from dragging current rigidBody without mouse-up?
I have a hero, I drag him with-mouse joint attached to his rigidBody. But I want to stop dragging him when he hits a trap.

I want the mouse-joint stop working without event "touch-end" being fired. But I've tried to remove even the mouseJoin-Component from the hero node without luck.

Please any one with any suggestion ?

I'm using Cocos Creator with JS Thanks!

# Answer
I've tried to trigger a fake event "touch-end" on the node without luck. But a minute later I found the answer (It was pretty simple)

```
node.active = false;
node.active = true;

```

When node is inactive, it stop dragging.
> 1 votes

---
Tags: cocos2d-x-js
---


# Question
Title: Moving objects in a circular path, and also moving the whole group
I have eight elements distributed in a circle, with a common center.

All of them move along a circular path, just like the poster in this question asked:

Moving an object in a circular path

This solves half of my question, however I also need to oscillate the whole group of units from side to side, with an easing, or linearly, depending on the design.

I've been playing around with it, but I can't figure how to add or modify what I assign to the X and Y value so the objects move like if they were contained inside a Sprite, and I would be moving that Sprite.

Edit.:

I found that this:

```
var newX:Number = Math.cos(_angle) * 100;
var newY:Number = Math.sin(_angle) * 100;

y = _startingY + newY;

x = _startingX + newX + _incrementX;

_angle += 2 * Math.PI / 180;

_incrementX += 1 + Math.sin(_angle);

```

Gets close enough to what I need, however it still doesn't work. In theory, if I subtract the sin f the angle it should fix the rotation compensation.

Edit2: The stars moving in circle:

What happens when I just add a linear increment to each element: (it would represent in the code above doing `_incrementX++`)

# Answer
This is the concept: You add "rotation movement" and "linear movement" together, and you get "rolling movement". Once you calculated all vectors for rotation movement, then you can simply add linear vectors to your results.
> 2 votes

# Answer
All you have to do to be able to freely move your items in a circle around the screen is:

1. Measure the x and y distance from 0, 0 to the center of the circle. Put the values into variables.
2. Set the x and y positions based off of the sin and cos values.
3. Add the x and y from the first step to the current positions.

Is this what you're looking for?
> 2 votes

# Answer
Check this out, it may help: http://gizma.com/easing/

The best way to do this, if you're not changing the destinations every frame, is to once calculate the positions, and store it in an array. Then use the values from that array. This is a great optimization because you won't have to call the math functions every frame.
> 0 votes

# Answer
I note that your stars appear one after the other on your second animation. It suggests you indeed create them at different time, and let that be the cause of your objects be at different angles at some time.

Unfortunately, that means they will have individual `_incrementX` values. You made `_incrementX` be a function (mathematically speaking) of the angle, while you want it to be a function over time, and have each object have its own time-to-angle relationship.

Try initializing them all at the same time, but with different values for `_angle`.

If that doesn't work for you, I suggest you introduce an invisible 'group center' that provides base (x,y) coordinates and each object then does

```
y = _center.Y + newY;
x = _center.X + newX;

```

and let `_center.X` be the things that increments over time.
> 0 votes

---
Tags: mathematics, actionscript-3
---


# Question
Title: How can I customize Unity editor controls (hotkeys)?
I have been using blender for quite some time so I know pretty much how it works, and I have just recently started using Unity.

I find the unity UI to be very confusing and hard to use, and I was wondering if there was a way to change the controls to be more blender-like. What I mean is, "shift + scroll" to pan, or just "scroll" to orbit.

# Answer
> 1 votes
You can rebind them: just go to Edit-\> shortcuts and then look at the command you want to rebind in the search box, **double click on it**, and then press the key or combination of keys you want on your keyboard There is a helper at the top right showing you the assigned keys

---
Tags: unity
---


# Question
Title: How would I go about adding a tooltip to a Unity UI Image?
I'm going to try out the community here once more, I haven't had very good look in the past with getting help.

I'm iterating through a series of List() and I'm creating a bar graph and a line graph based on those values, Later I'll replace the List with a file which it retrieves the values from. I'm having a problem though with creating a tooltip. I know how to add them to buttons created under OnGui() but that's about it. I've spent the past 2 days trying to figure this out and I'm just not sure how to go about making the bar images and dot's show up under public void OnPointerEnter(PointerEventData eventData) {} and OnPointerExit() I know that print(eventData.pointerCurrentRaycast.ToString()); will display the item I'm hovering over and it seems to work fine for everything except the GameObjects that are created by my script:

```
        private GameObject CreateBar(Vector2 graphPos, float barWidth)
    {
        GameObject gameObject = new GameObject("bar", typeof(Image));
        gameObject.transform.SetParent(graphContainer, false);
        gameObject.GetComponent<Image>().color = barColor;
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();
        rectTransform.anchoredPosition = new Vector2(graphPos.x, 0f);
        rectTransform.sizeDelta = new Vector2(barWidth * barWidthMultiplier, graphPos.y);
        rectTransform.anchorMax = new Vector2(0, 0);
        rectTransform.anchorMin = new Vector2(0, 0);
        rectTransform.pivot = new Vector2(.5f, 0f);

        return gameObject;
    }

```

If anyone could give me a hand on how to make this show up under eventData I can figure the rest out from there. Or if you have a better method you wouldn't mind sharing I would appreciate that.

# Answer
Here is an easy solution for how you get it styled right and working without any need to write extra code.

1. create the Image/ Tooltip you want as a child of your element that should have the tooltip.
2. disable the element
3. attach a Event Trigger component to your ui element that should have the tooltip
4. add new event type: PointerEnter
5. select your component that should be displayed and the bool enabled, click the checkbox
6. add new event type: PointerExit, should be prefilled with the same values as from PointerEnter, just deselect now the checkbox

While this does not generate the toolbox via code, you have a lot more control and possibility to fine tune it.
> 2 votes

---
Tags: unity, gameobject, events, unity-ui
---


# Question
Title: Unable to create Shader Object for Geometry Shader (GL_GEOMETRY_SHADER)
I am just starting with OpenGL using c++ on Ubuntu 18.04. The problem I have is that when I try to link Geometry Shader in my main program, the following function call is unable to create an object (and hence returns 0)

```
GLuint ShaderObj = glCreateShader(ShaderType);

```

when ShaderType = GL\_GEOMETRY\_SHADER. The error log thrown is: "Error creating shader type 36313". Here, 36313 is the enum value for GL\_GEOMETRY\_SHADER.

NOTE: My program runs successfully (with a differing functionality) when I remove the geometry shader, while keeping the fragment & vertex shaders intact.

The following is the source code for my geometry shader:

```
#version 130

layout (triangles) in;
layout (triangle_strip, max_vertices = 4) out;

void main() {
    gl_Position = gl_in[0].gl_Position;
    EmitVertex();
    gl_Position = gl_in[1].gl_Position;
    EmitVertex();
    gl_Position = gl_in[2].gl_Position;
    EmitVertex();
    EndPrimitive();
}

```

The flow of the main code is as follows:

During `CompileShaders()`, the code calls `AddShader(ShaderProgram, gs.c_str(), GL_GEOMETRY_SHADER)`. The following are the first few lines in this function.

```
static void AddShader(GLuint ShaderProgram, const char* pShaderText, GLenum ShaderType) {
    GLuint ShaderObj = glCreateShader(ShaderType);
    if (ShaderObj == 0) {
        fprintf(stderr, "Error creating shader type %d\n", ShaderType);
        exit(0);
    }
...
}

```

Here `glCreateShader()` returns 0 which is why in the following if condition an error is thrown as mentioned previously.

The following are the version details of my setup.

```
    GLX version: 1.4
        Max core profile version: 4.6
        Max compat profile version: 3.0
        Max GLES1 profile version: 1.1
        Max GLES[23] profile version: 3.1
    OpenGL core profile version string: 4.6 (Core Profile) Mesa 20.0.8
    OpenGL core profile shading language version string: 4.60
    OpenGL version string: 3.0 Mesa 20.0.8
    OpenGL shading language version string: 1.30
    OpenGL ES profile version string: OpenGL ES 3.1 Mesa 20.0.8
    OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.10

```

The following is my hardware information.

```
00:02.0 VGA compatible controller: Intel Corporation HD Graphics 5500 (rev 09)
    Subsystem: Dell HD Graphics 5500
    Kernel driver in use: i915
    Kernel modules: i915
--
08:00.0 3D controller: NVIDIA Corporation GF117M [GeForce 610M/710M/810M/820M / GT 620M/625M/630M/720M] (rev a1)
    Subsystem: Dell GeForce 820M
    Kernel driver in use: nouveau
    Kernel modules: nvidiafb, nouveau

```

I think this might be some version error. But I am not sure. I would be really, really grateful if someone could help me out with this.

# Answer
This is less a specific answer to the question, but a general hint on how to set up an OpenGL context because I feel it will answer the question automatically. The same procedure is used for instance by 'learnopengl.com' and possibly others I don't know. My system is a Debian 10, but it should work on Windows as well.

We'll setup an OpenGL context and enable debug messages. This works from OpenGL 4.3 on, which should not be a problem even on old systems. I'll use GLFW3 (www.glfw.org) as the windowing and input event handling api to avoid messing with system specific C-apis, glad as the GL library loader (glad.dav1d.de/), and the code snippets are plain C. I installed glfw via the package manager (Windows users will have to read the installation documentation), and glad comes as a header and a c file.

1 - Headers to be included:

```
#include "glad/glad.h"
#define GLFW_NO_INCLUDE_API
#include <GLFW/glfw3.h>

```

Note you will have to link to glfw and under Linux to dl for dynamic loading.

2 - Initialize glfw, load opengl functions:

```
glfwSetErrorCallback( glfw_error_callback );
if( GL_TRUE != glfwInit() ) {
    // didn't work, can't carry on
}
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 4 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 5 );
glfwWindowHint( GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE );
glfwWindowHint( GLFW_CLIENT_API, GLFW_OPENGL_API );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );

```

Set other specific hints if needed, then open the window:

```
window = glfwCreateWindow( width, height, title, NULL, NULL );
if( !window ) {
    // didn't work, but there should be an error message by the error callback
    glfwTerminate();
    return false;
}
glfwMakeContextCurrent( window );
// Load gl function pointers
if( !gladLoadGLLoader( (GLADloadproc)glfwGetProcAddress ) ) {
    // glad couldn't load the function pointers, cleanup and get out
    glfwDestroyWindow( window );
    glfwTerminate();
    return false;
}

```

Now initalize debug output:

```
GLint flags;
glGetIntegerv( GL_CONTEXT_FLAGS, &flags );
if( flags & GL_CONTEXT_FLAG_DEBUG_BIT ) {
    glEnable( GL_DEBUG_OUTPUT );
    // Envoke callback directly in case of error
    glEnable( GL_DEBUG_OUTPUT_SYNCHRONOUS );
    glDebugMessageCallback( glDebugOutput, NULL );
    glDebugMessageControl( GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE );
} else
    // say that debug context could not be created but life goes on without it

```

Now two things are still missing, the `glfw_debug_callback` and the `glDebugCallback`. I leave the function body out because mine is pretty verbose:

```
void error_callback( int error, const char *msg ) {
    // format and output/log the message
}

```

as well as

```
void APIENTRY glDebugOutput( GLenum source, GLenum type, GLuint id, GLenum severity,
    GLsizei length, const GLchar *message, const void *userParam ) {
// Ignore non-significant error/warning codes
// pseudcode: if( id == 131169 || id = whateverelse ) return;
/* stitch togehter and format a msg from source:
   GL_DEBUG_SOURCE_API, GL_DEBUG_SOURCE_WINDOW_SYSTEM,
   GL_DEBUG_SOURCE_SHADER_COMPILER, GL_DEBUG_SOURCE_THIRD_PARTY,
   GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_SOURCE_OTHER
   type:
   GL_DEBUG_TYPE_ERROR, GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR;
   GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR, GL_DEBUG_TYPE_PORTABILITY,
   GL_DEBUG_TYPE_PERFORMANCE, GL_DEBUG_TYPE_MARKER,
   GL_DEBUG_TYPE_PUSH_GROUP, GL_DEBUG_TYPE_POP_GROUP,
   GL_DEBUG_TYPE_OTHER
   and severity:
   GL_DEBUG_SEVERITY_HIGH, GL_DEBUG_SEVERITY_MEDIUM,
   GL_DEBUG_SEVERITY_LOW, GL_DEBUG_SEVERITY_NOTIFICATION */
   // add the message text and eventually add userdata
   // log/output
}

```

With this one receives meaningful messages on error conditions. Checking `glError` is not necessary any more and parameterized one can run with a debug context and without, saving a bit of performance.
> 2 votes

---
Tags: opengl, c++, geometry-shader
---


# Question
Title: Unity Unable to blend 2D Light renderers
I've followed the documentation on Unity regarding 2D lighting. It said to turn on Alpha blending in the options. But this is how it turns out: If Alpha blending is off:

If Alpha blending is on:

I'm not entirely sure why it's turning black. These are my settings for the 2D light:

I've checked my layers, specifically the tile map floor, and it's on the Default layer.

I just want my lights to blend well.

# Answer
Found the problem. Apparently, 2D lights should have their intensity to be set at least `1` or higher. Otherwise, dark pixels will be drawn onto the 2D light renderer.
> 0 votes

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


title: Unwanted jump when landing

text:
# Question
Title: Unwanted jump when landing
I managed to make my 3D player character jump (hurrah!) but I get an unwanted jump upon landing.

It's not a mid-air double-jump. If I press space mid air, then after it get backs to ground it immediately jumps again.

How can I prevent this?

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

public class PlayerMovement : MonoBehaviour
{
    bool jumpKeyIsPressed;
    float horizontalMovement;
    bool isGrounded ;
    Rigidbody rb;
    [SerializeField] float playerJumpForce;
    [SerializeField] float movementSpeed;

    void Start()
    {   //sustituye GetComponent<Rigidbody>() por rb!!!
         rb = GetComponent<Rigidbody>();
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            jumpKeyIsPressed = true;
        }

        horizontalMovement = Input.GetAxis("Horizontal");
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isGrounded = true;
        }
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector3(horizontalMovement * movementSpeed, rb.velocity.y, 0);

        if (jumpKeyIsPressed && isGrounded)
        {
            rb.AddForce(Vector3.up * playerJumpForce, ForceMode.VelocityChange);
            isGrounded = false;
            jumpKeyIsPressed = false;
        }
    }
}

```

# Answer
What you have here is called input queuing. When the player presses the jump button, if you can't act on it right away, you store-up that button press to fire again when it's applicable.

This can be a good thing in many games. Celeste, as one example, queues a jump input up to a few frames before you land, so if you press the jump button just a moment too early it "snaps" to a perfect moment-of-landing rebound, improving game feel and making it easier to pull off some of the fast-paced precision platforming challenges in that game.

It's also important when you're gathering your input in Unity's `Update()` method, but acting on it in `FixedUpdate()`. If the player is running at a very high framerate, you might not get a physics step the first frame after a button press, so if we clear `jumpKeyIsPressed` back to `false` in the next `Update()` then we might erase it before we had a chance to apply it.

The trick is that you don't want to queue the input infinitely! Right now you keep `jumpKeyIsPressed == true` eternally until we touch the ground and are allowed to jump again and finally consume that input.

A quick and simple fix if you don't want to keep the input queuing at all is to act on the jump input as soon as it's received:

```
void Update()
{
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(Vector3.up * playerJumpVelocity, ForceMode.VelocityChange);
        isGrounded = false;
    }

    horizontalMovement = Input.GetAxis("Horizontal");
}

```

(I changed your variable name from `playerJumpForce` to `playerJumpVelocity` because the way you're using it, it's not actually a force measured in Newtons. It's a delta-v measured in m/s)

You want to apply any continuous movement changes in `FixedUpdate()` to make sure they're always consistent, no matter how the rhythm of display frames and physics steps interleave. But for an instantaneous change like a jump, there's no harm in applying it eagerly in `Update()` \- it won't kick in until the next physics step anyway, the same as if we queued it up.

If you'd like to keep the input queuing behaviour, we'll just want to give it a time window it's valid for. Instead of tracking a Boolean for whether it's pressed or not, we'll keep a float tracking how long ago it was pressed.

```
float jumpQueueWindow = 2.0f/30.0f; // Queue for up to 2 frames at 30 FPS.
float secondsSinceJumpPressed = float.PositiveInfinity;

void Update()
{
    secondsSinceJumpPressed += Time.deltaTime;

    if (Input.GetKeyDown(KeyCode.Space))
    {
        secondsSinceJumpPressed = 0f;
    }

    horizontalMovement = Input.GetAxis("Horizontal");
}

void FixedUpdate() {
    rb.velocity = new Vector3(horizontalMovement * movementSpeed, rb.velocity.y, 0);

    if (isGrounded && secondsSinceJumpPressed <= jumpQueueWindow )
    {
        rb.AddForce(Vector3.up * playerJumpVelocity, ForceMode.VelocityChange);
        isGrounded = false;
        secondsSinceJumpPressed = float.PositiveInfinity;
    }
}

```

You could also store a timestamp when jump is pressed and compare it against the current time. That saves accumulating `deltaTime` into your variable each frame, but it means the precision of your jump window is limited to the precision of your timestamp, and the precision of `Time.time` in Unity loses precision if your game's been running for many hours continuously. So I like to err on the side of using frame deltas which keep their precision no matter how long your game's been running.
> 1 votes

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


title: How to import three.module.js

text:
# Question
Title: How to import three.module.js
I'm looking at this three.js cubemap example, and it runs fine in my browser when loaded from that page.

After much strain to find and download the files - it does not run?

What am I doing wrong, with this "module" stuff?

I got it to work by changing:

```

<script type="module">
import * as THREE from 'three.module.js';
...

```

Into:

```
<script src="three.js"></script>
<script>
...

```

Can anyone explain how to properly import three.module.js? Why is this change necessary when I run the project on my machine?

# Answer
> 1 votes
you should try changing this line:

```
import * as THREE from 'three.module.js';

```

to this line:

```
import * as THREE from './three.module.js';

```

so the browser understand that it is a **Relative Import** and it works.

---
Tags: javascript, three.js
---


# Question
Title: If i make a game in Unity where a player can host their own servers, will it still cost me more money?
I know that with Unity's networking system, you will have to pay Unity if you have more than X players on your servers at the same time. I believe this is because that Unity is hosting the servers, and it costs them internet service? But if the players are hosting their own servers, this wouldn't cost Unity any internet. Is it possible to host your own servers using Unity networking, and if so, will it still cost extra money? thanks. :)

# Answer
> 1 votes
You have answered your own question.

Unity charges you for two things:

1. **Licensing their engine**, proportional to your number of seats (employees in your organization using the software simultaneously), once your revenue exceeds a particular threshold.
2. **Use of Unity's online services**, proportional to your consumption of those services.

If you are not consuming their online services, then point 2 doesn't apply, and the only payment you owe them is the licensing of the engine, if your revenue is enough to exceed the Personal tier.

You can write whatever network code you want in order to synchronize your game clients without using a Unity-hosted server as an intermediary.

# Answer
> 1 votes
In fact, you could use unity as a client programming. Meaning totally as a game client distribute to players.

Elsewhere the game clients connect to any kind of game server written with other platform and other programming language. For example a game server written in .net offering Rest API interface. Or maybe a nodejs server offering socket.io / websocket . You're free to pick surely there are advantages and disadvantages.

It may cost a lot lesser than using what's provided by unity. E.g. those game server could be hosted on AWS, Heroku, etc.

---
Tags: unity-networking, costs, hosting
---


# Question
Title: Raycasting - weird lines on walls when ray is facing up or right
I am trying to make a raycasting game. Everything is rendered correctly except when the ray is facing up (angle \> PI) or facing right(angle \> 0.5PI and \< 1.5PI) lines are drawn on walls. I am not sure what is causing it to happen but I know that the lines are not affected by the rotation of the player only by the players position. I also tried rounding the rays position but that did not help.

Right and up ray walls.

The walls up close.

Left and down ray walls.

Code:

```
        let rayX, rayY, rayAngle, rayDeltaX, rayDeltaY

        for (let i = 0; i < this.screen.width; i ++) {
            rayAngle = this.angle - this.fov / 2 + i * (this.fov / this.screen.width)

            if (rayAngle < 0) {
                rayAngle += Math.PI * 2
            }
            else if (rayAngle > Math.PI * 2) {
                rayAngle -= Math.PI * 2
            }

            rayX = this.x
            rayY = this.y

            let stepY

            if (rayAngle > Math.PI) {
                stepY = -this.tileSize
                rayY = Math.floor(rayY / this.tileSize) * this.tileSize - 1
            }
            else {
                stepY = this.tileSize
                rayY = Math.floor(rayY / this.tileSize) * this.tileSize + this.tileSize
            }

            rayX = this.x  + (rayY - this.y) / Math.tan(rayAngle)

            rayDeltaY = stepY
            rayDeltaX = stepY / Math.tan(rayAngle)

            while(true) {
                if (this.Map.map[Math.floor(rayY / this.tileSize) * this.Map.width + Math.floor(rayX / this.tileSize)] == '#') {
                    break
                }

                rayX += rayDeltaX
                rayY += rayDeltaY
            }

            let rayHorizontalX = rayX
            let rayHorizontalY = rayY
            let rayDistanceHorizontal = Math.sqrt((this.x - rayHorizontalX) ** 2 + (this.y - rayHorizontalY) ** 2)

            rayX = this.x
            rayY = this.y

            let stepX

            if (rayAngle > 0.5 * Math.PI && rayAngle < 1.5 * Math.PI) {
                stepX = -this.tileSize
                rayX = Math.floor(rayX / this.tileSize) * this.tileSize - 1
            }
            else {
                stepX = this.tileSize
                rayX = Math.floor(rayX / this.tileSize) * this.tileSize + this.tileSize
            }

            rayY = this.y + (rayX - this.x) * Math.tan(rayAngle)

            rayDeltaY = stepX * Math.tan(rayAngle)
            rayDeltaX = stepX

            while(true) {
                if (this.Map.map[Math.floor(rayY / this.tileSize) * this.Map.width + Math.floor(rayX / this.tileSize)] == '#') {
                    break
                }

                rayX += rayDeltaX
                rayY += rayDeltaY
            }

            let rayVerticalX = rayX
            let rayVerticalY = rayY
            let rayDistanceVertical = Math.sqrt((this.x - rayVerticalX) ** 2 + (this.y - rayVerticalY) ** 2)

            let rayFinalDistance

            if (rayDistanceHorizontal < rayDistanceVertical) {
                rayFinalDistance = rayDistanceHorizontal
                ctx.fillStyle = 'darkblue'
            }
            else {
                rayFinalDistance = rayDistanceVertical
                ctx.fillStyle = 'blue'
            }

            let rayCorrectedDistance = rayFinalDistance * Math.cos(rayAngle - this.angle)

            let lineHeight = this.tileSize * (this.screen.width / 2 / Math.tan(this.fov / 2)) / rayCorrectedDistance
            let lineBottom = this.projectionPlane.centerY + lineHeight * 0.5
            let lineTop = this.projectionPlane.height - lineBottom

            ctx.fillRect(i, lineTop, 1, lineHeight)
        }

```

Any help would be appreciated.

# Answer
I fixed the problem. When the ray was facing up or right I was substracting 1 from the rounded position of the ray to get the first intersection. Substracting a smaller number like 0.001 fixed it.
> 2 votes

---
Tags: javascript, raycasting
---


# Question
Title: Is naming convention a good base for a sorting and tagging system for game assets?
TLDR: what are the pros and cons of using a naming convention for tagging and sorting game assets?

1. for the UI to search and handle it
2. for devs and gamers to move files around

I am building a game that is designed to be moddable under UE4.

I am going to have tons of assets (clothes, hairs, jewleries and their textures materials and whatnot) to deal with.

This has to be organised well to avoid issues later on, and for the UI to be able to handle it in a user friendly way.

Eventually the game has to be localized for a bunch of non-latin character systems, too.

The easiest way would be to use a prefix/suffix system when naming the assets, which would come in the game in as Blueprints, containing the asset and some extra data as well. This would be a requirement for modders.

For example:

```
tag_othertag_clothname.uasset
tag          |name

```

And then all I do is just search tru the name of the asset. I feed it the text the user typed for the name part, and the tags as strings for the tag part, and than hide the tag part from the user.

I set up a test scene and it does work ok with 500 assets, running the search every time you hit a button.

Later on I can store tag data in json or just as a plain string in the Blueprint.

The issue is that as the number of tags grow, the length of the string grows too, which can be a problem later on.

I thought about using strings and json files to store the tagging data in the Blueprint as well.

I would like to have 2 categories of tags by default

1. region or body part: head, torso etc ---\> makes searching and categorizing very easy but not as efficient, can be appied to nearly all asset types
2. asset type: cloth, jewlery, armour, etc

My questions are:

In your experience

* are there pitfalls of using a prefix suffix system, for example security, performance, ease of use etc? if yes what are they?
* what are the alternatives - I thought of using databases, but I don't have much experience with them, not sure which one works best with a high number of Blueprints, I saw quite a few on the Marketplace...

I 'd like to make it as simple as it can be, no overcomplication or overengineering.
I just want it to be usable, user friendly and easily extendable as the project grows.

# Answer
> 0 votes
Conventions like that will tend to become very long 'sentences'. Naming conventions like that, within a filename, will tend to be nasty for the users too. Also filenames have a maximum size, on Windows 10 I believe it is 260 (by default). On Linux it is 256.

About non-latin characters, I know nothing about other then they exist.

Maybe a consideration for you could be to pack the hair and cloth items in their own zip-file. For curly\_blond\_hair.zip it would need a mesh file, texture and a small simple configuration textfile. For other game objects, whatever they are, too.

Or to ignore zip-files, just use a folder. Thus curly\_blond\_hair and i\_dont\_like\_to\_name\_files (see example below) are folders too and you search the directories for the files: mesh, texture.png and config.txt.

Since you have a config file, tags won't be a problem. It's not unlimited but more then enough. A filename is limited in size.

Users, or gamers, you can't control - they can destroy the application entirly, I know as I did way back. So having folders with some files will invite a mess made by users. From within your application or editor, let users pick a folders and pack it into the zip (or your own format) and it is for the user very clear they belong to eachother. This way you force them to work along with the application.

Next is just an example. If you apply the above you could get:

* Application path\
    + Resources\ // your default items
        - Hair\
            * lame\_hair.zip // it is default, right?
    + Modding\
        - Hair\
            * curly\_blond.zip
                + mesh
                + texture
                + material // if they need to make these
                + config.txt // for body part, size, location, rotation
            * brown\_grease.zip
                + idem
            * black\_long\_loose.zip
                + idem
        - Jewelry\
            * readme.txt // ignored by your program as it is looking for zip-files or folders
            * Rings\
                + golden\_with\_diamond.zip
                    - mesh
                    - texture
                    - material
                    - config.txt
                + i\_dont\_like\_to\_name\_files.zip
                    - idem
                + who\_cares\_for\_a\_name\_when\_we\_have\_configfile.zip
                    - idem
            * Necklesses\
                + silver.zip
                    - idem

---
Tags: unreal-4, data-structure, modding, asset-management, pipeline
---