title: 2d Rectangle Collision Resolution

text:
# Question
Title: 2d Rectangle Collision Resolution
## My Journey...

I've long struggled with rectangle to rectangle collision resolution. I've been making games for almost 10 years and still have yet to find a foolproof, reliable strategy.

When doing research on 2d, rectangle to rectangle collision resolution, I find myself digging through piles of collision *detection*, or other topics that have nothing to do with my search for truth (circle to rectangle, other detection methods...) For me, detecting collision has never been the issue...

```
if player.x + player.width > box.x and
   player.x < box.x + box.width and
   player.y + player.height > box.y and
   player.y < box.y + box.height then
     // A collision has been detected...
     // But now I am lost.....

```

Assuming both the `player` and `box` objects are positioned at their upper left corner

---

## The Rectangular Paradox...

For those brave enough, there is the path of chaos, torture, and unknown horrors available... The road known as *"creating your own"*. I have chosen to walk this path many times, never to find the answers I'm looking for. I'm sure I share some quarrels of this road with fellow developers.

At first you might think it a simple task: "Once you know the rectangles are overlapping, how difficult can it really be to push one out of the other?" Oh boy, how I miss that sweet innocence...

Let us say, the player in the above example is falling down on top of the box, and we want it to stop and be pushed back to the top of the box. Easy, right? We can just do a simple check if the player is above the box, and if so, push him up to the top.

```
// We know the player is overlapping with the box..
if player.y < box.y then
  player.y = box.y - player.height

```

Done. Tested and proven to work. But, let's say now we want the player to stop at the left side of the box as well..

```
if player.x < box.x then
  player.x = box.x - player.width

```

Looks like it should work fine right? But no. Upon testing you move the player to collide with the left side of the box, and ***bam***. Suddenly, he has immediately moved to the top of the box.

*Why?* The player can be both above the box, and to the left of the box at the same time. So one seems to end up always being favored over the others. To mitigate this I have written 3 nested if statements, 50 line chunks of code for each side of the rectangle, and wasted near weeks of my life..

---

## Conclusion

Although I walk my journey alone - I know there are others, battling the same demonic mystery of *rectangle to rectangle collision resolution*. And also.. Those who have conquered it...

I'm hoping someone can help me understand their solidified, proven methods of resolution. To help me and any other developers reading this right now, become level 100 devs.

---

I made a codepen for anyone who is interested to use as a playground for showcasing resolution methods.

# Answer
> 2 votes
The challenge you're facing is how to determine where the moving rectangle came from by looking at the current position of the moving rectangle and the rectangle it's crashing into, and as you're finding positions alone don't give that information. You have to look at the last movement of the moving rectangle to be able to just push it outside of the other one.

Here is a simple example\* built into your codepen illustrating a simple way this can be done.

```
//*** DETECTING & RESOLVING COLLISION ***//
handleCollisions() {
  var player = this.player;

  // As long as they are colliding (Be careful for infinite loops)
  while (this.hasCollision()) {
    // get current x direction
    const xDir = this.getXDirection();
    // get current y direction
    const yDir = this.getYDirection();
    // move the player 1 unit back the direction it came from
    player.x -= xDir;
    player.y -= yDir;
  }
  ...
}
// returns true if the player is colliding with the box
hasCollision() {
  const player = this.player;
  const box = this.box;
  return (
    player.x + player.width / 2 > box.x - box.width / 2 &&
    player.x - player.width / 2 < box.x + box.width / 2 &&
    player.y + player.height / 2 > box.y - box.height / 2 &&
    player.y - player.height / 2 < box.y + box.height / 2
  );
}
// returns 1, -1, or 0 if not moving
getXDirection() {
  if (this.controls.isDown("right")) {
    return 1;
  } else if (this.controls.isDown("left")) {
    return -1;
  } else {
    return 0;
  }
}
// returns 1, -1, or 0 if not moving
getYDirection() {
  if (this.controls.isDown("up")) {
    return -1;
  } else if (this.controls.isDown("down")) {
    return 1;
  } else {
    return 0;
  }
}

```

Keep in mind this is just a starting point for the possibilities of resolving collisions like this. You could check direction and relative velocity of two moving rectangles to support both rectangles moving.

In response to a comment about not being able to slide along an edge here is a link to an enhanced version of this same method that allows sliding along edges when colliding. All that changed was to separate the X and Y checks into separate loops. I hope this helps demonstrate how easily this basic method can be enhanced to meet specific needs.

\*Please note that this is not a perfect implementation. Right now the player will clip into the box until you release the move command; however that is a matter of changing this check to happen before rendering, and I would consider that off topic for this question as of now.

# Answer
> 2 votes
I don't know if there is a perfect method, at least not anything I have found, but I can show you what I did that worked for me.

Start by getting the inside rectangle of the collision. This is the rectangle created by the two overlapping rectangles. If the language you are using doesn't have a function that returns this you will need to figure out how to get the value. You can use the connecting points and one corner from each colliding rectangle to get the data you will need for the inside rectangle.

If the inside rectangle's width is less then the hight then your going to adjust the x coordinate of the moving rectangle, else you will adjust the y coordinate. If you get a tie your going to have to pick one depending on whether you use (less then) or (less then or equals to) when comparing the inside rectangles width and hight.

Next figure out which corners of the moving rectangle are outside the intersecting rectangle. Based on that you will know if you have to adjust (up or down) or (left or right). For instance say the (width of the inside rectangle is less than the hight) and (the top right and bottom right points of the moving rectangle are outside the intersecting rectangle) then adjust the moving rectangle's x coordinate to the right.

You will run into a problem wall sliding like this depending on how you iterate over the tiles. If your wall sliding and collide with another tile it could push you back from the direction you are heading. To fix this calculate the areas of the inside rectangles created by the multiple collisions with the multiple tiles. Adjust for the largest area. Do not make all adjustments from all collisions. Only adjust for the collision that creates an inside rectangle with the largest area. Then check for more collisions after you update the location of the moving rectangle and only make further adjustments if there are collisions with the new location.

This method avoids having to deal with what direction things are moving and figures it out based on the collision points. If you have thin rectangles this method may not work for you. But if you're using tiles it can work well.

# Answer
> 1 votes
This is probably the problem I struggled with most in the development of both major versions of Scrolling Game Development Kit. So here I will try to describe what the central function that addresses your problem in SGDK2 is doing. It's all wrapped up in a function called `ReactToSolid`. This function actually doesn't deal strictly with rectangles because SGDK2 allows tiles that are shaped like slopes too.

Before diving into the code, I should explain some of the variables you'll see:

* `x` \- The raw horizontal coordinate of the left side of a sprite. I say raw because this is not an integer and can store a position between pixels to help track, for example, a slow moving sprite that hasn't reached the next pixel yet.
* `y` \- The raw vertical coordinate of the top of the sprite.
* `PixelX` \- The truncated horizontal coordinate (round down to integer)
* `PixelY` \- The truncated vertical coordinate
* `dx` \- The horizontal velocity of the sprite used to determine where the sprite should move next
* `dy` \- The vertical velocity of the sprite
* `ProposedPixelX` \- The next value of `PixelX` based on current values of `x` and `dx` (in other words, `x+dx` rounded down)
* `ProposedPixelY` \- The next value of `PixelY`

The rest of the variables will be explained afterward.

And a some general points about this function:

* This function alters the dx and dy properties of a sprite so that when it moves (adjusts its x and y properties by adding dx and dy) it will avoid solid areas of the background.
* This function assumes that the sprite is not already overlapping any solids because once the sprite is overlapping a solid, you've lost a lot of information about how you should avoid the solid based on where you came from. If it is already overlapping, the behavior tends to be that solid edges going through the sprite are ignored.

The code:

```
public virtual bool ReactToSolid()
{
   Debug.Assert(this.isActive, "Attempted to execute ReactToSolid on an inactive sprite");
   if (m_solidity == null)
      throw new System.ApplicationException("Attempted to execute ReactToSolid on sprite without solidity defined");
   bool hit = false;
   double dyOrig = dy;
   double dxOrig = dx;

   int ProposedPixelY2 = (int)Math.Ceiling(y + dy);
   int SolidPixelWidth = SolidWidth + (int)Math.Ceiling(x) - PixelX;
   if (dy > 0)
   {
      int ground = layer.GetTopSolidPixel(new System.Drawing.Rectangle(PixelX, PixelY + SolidHeight, SolidPixelWidth, ProposedPixelY2 - PixelY), m_solidity);
      if (ground != int.MinValue)
      {
         // Do integer arithmetic before double otherwise strange rounding seems to happen
         dy = ground - SolidHeight - y;
         hit = true;
      }
   }
   else if (dy < 0)
   {
      int ceiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(PixelX, ProposedPixelY, SolidPixelWidth, PixelY - ProposedPixelY), m_solidity);
      if (ceiling != int.MinValue)
      {
         // Do integer arithmetic before double otherwise strange rounding seems to happen
         dy = ceiling + 1 - y;
         hit = true;
      }
   }

   if (dx > 0)
   {
      int ProposedPixelX2 = (int)Math.Ceiling(x + dx);
      int PixelX2 = (int)Math.Ceiling(x);
      int rightwall = layer.GetLeftSolidPixel(new System.Drawing.Rectangle(PixelX2 + SolidWidth, ProposedPixelY, ProposedPixelX2 - PixelX2, SolidHeight), m_solidity);
      bool hitWall = false;
      if (rightwall != int.MinValue)
      {
         int maxSlopeProposedY = (int)(y + dy - dx);
         int slopedFloor = layer.GetTopSolidPixel(new System.Drawing.Rectangle(PixelX2 + SolidWidth, maxSlopeProposedY + SolidHeight, ProposedPixelX2 - PixelX2, ProposedPixelY - maxSlopeProposedY), m_solidity);
         if (slopedFloor != int.MinValue)
         {
            int ceiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(PixelX2, slopedFloor - SolidHeight, SolidWidth, ProposedPixelY + SolidHeight - slopedFloor), m_solidity);
            if ((ceiling == int.MinValue) && (RidingOn == null))
            {
               int rightwall2 = layer.GetLeftSolidPixel(new System.Drawing.Rectangle(PixelX2 + SolidWidth, slopedFloor - SolidHeight, ProposedPixelX2 - PixelX2, SolidHeight), m_solidity);
               if (rightwall2 == int.MinValue)
                  // Do integer arithmetic before double otherwise strange rounding seems to happen
                  dy = dyOrig = slopedFloor - SolidHeight - 1 - y;
               else
                  hitWall = true;
            }
            else
               hitWall = true;
         }
         else
         {
            maxSlopeProposedY = (int)(y + dy + dx);
            int slopedCeiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(PixelX2 + SolidWidth, ProposedPixelY, ProposedPixelX2 - PixelX2, maxSlopeProposedY - ProposedPixelY), m_solidity);
            if (slopedCeiling != int.MinValue)
            {
               slopedCeiling++;
               int floor = layer.GetTopSolidPixel(new System.Drawing.Rectangle(PixelX2, ProposedPixelY + SolidHeight, SolidWidth, slopedCeiling - ProposedPixelY), m_solidity);
               if ((floor == int.MinValue) && (RidingOn == null))
               {
                  int rightwall2 = layer.GetLeftSolidPixel(new System.Drawing.Rectangle(PixelX2 + SolidWidth, slopedCeiling, ProposedPixelX2 - PixelX2, SolidHeight), m_solidity);
                  if (rightwall2 == int.MinValue)
                     dy = dyOrig = slopedCeiling - y;
                  else
                     hitWall = true;
               }
               else
                  hitWall = true;
            }
            else
               hitWall = true;
         }
         if (hitWall)
         {
            // Do integer arithmetic before double otherwise strange rounding seems to happen
            dx = rightwall - SolidWidth - x;
         }
         hit = true;
      }
   }
   else if (dx < 0)
   {
      int leftwall = layer.GetRightSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, ProposedPixelY, PixelX - ProposedPixelX, SolidHeight), m_solidity);
      bool hitWall = false;
      if (leftwall != int.MinValue)
      {
         int maxSlopeProposedY = (int)(y + dy + dx);
         int slopedFloor = layer.GetTopSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, maxSlopeProposedY + SolidHeight, PixelX - ProposedPixelX, ProposedPixelY - maxSlopeProposedY), m_solidity);
         if (slopedFloor != int.MinValue)
         {
            int ceiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(PixelX, slopedFloor - SolidHeight, SolidWidth, ProposedPixelY + SolidHeight - slopedFloor), m_solidity);
            if ((ceiling == int.MinValue) && (RidingOn == null))
            {
               int leftwall2 = layer.GetRightSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, slopedFloor - SolidHeight, PixelX - ProposedPixelX, SolidHeight), m_solidity);
               if (leftwall2 == int.MinValue)
                  // Do integer arithmetic before double otherwise strange rounding seems to happen
                  dy = dyOrig = slopedFloor - SolidHeight - 1 - y;
               else
                  hitWall = true;
            }
            else
               hitWall = true;
         }
         else
         {
            maxSlopeProposedY = (int)(y + dy - dx);
            int slopedCeiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, ProposedPixelY, PixelX - ProposedPixelX, maxSlopeProposedY - ProposedPixelY), m_solidity);
            if (slopedCeiling != int.MinValue)
            {
               slopedCeiling++;
               int floor = layer.GetTopSolidPixel(new System.Drawing.Rectangle(PixelX, ProposedPixelY + SolidHeight, SolidWidth, slopedCeiling - ProposedPixelY), m_solidity);
               if ((floor == int.MinValue) && (RidingOn == null))
               {
                  int leftwall2 = layer.GetRightSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, slopedCeiling, PixelX - ProposedPixelX, SolidHeight), m_solidity);
                  if (leftwall2 == int.MinValue)
                     dy = dyOrig = slopedCeiling - y;
                  else
                     hitWall = true;
               }
               else
                  hitWall = true;
            }
            else
               hitWall = true;
         }
         if (hitWall)
         {
            // Do integer arithmetic before double otherwise strange rounding seems to happen
            dx = leftwall + 1 - x;
         }
         hit = true;
      }
   }

   dy = dyOrig;

   int ProposedSolidPixelWidth = SolidWidth + (int)Math.Ceiling(x + dx) - ProposedPixelX;
   if (dy > 0)
   {
      ProposedPixelY2 = (int)Math.Ceiling(y + dy);
      int ground = layer.GetTopSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, PixelY + SolidHeight, ProposedSolidPixelWidth, ProposedPixelY2 - PixelY), m_solidity);
      if (ground != int.MinValue)
      {
         // Do integer arithmetic before double otherwise strange rounding seems to happen
         dy = ground - SolidHeight - y;
         hit = true;
      }
   }
   else if (dy < 0)
   {
      int ceiling = layer.GetBottomSolidPixel(new System.Drawing.Rectangle(ProposedPixelX, ProposedPixelY, ProposedSolidPixelWidth, PixelY - ProposedPixelY), m_solidity);
      if (ceiling != int.MinValue)
      {
         // Do integer arithmetic before double otherwise strange rounding seems to happen
         dy = ceiling + 1 - y;
         hit = true;
      }
   }

   if (hit && !double.IsNaN(LocalDX))
      LocalDX += dx - dxOrig;

   return hit;
}

```
1. The first major check for `dy>0` and `dy<0` is to determine whether we should be looking for a floor versus a ceiling to determine whether the sprite will be blocked from moving downward or upward.
2. Inside that block, the sprite's vertical velocity is adjusted to stop at the floor or ceiling that it is about to hit. `GetTopSolidPixel` and `GetBottomSolidPixel` are functions that return the vertical coordinate of the topmost or bottom-most solid pixel within the specified rectangle. Notice that we're not including the sprite rectangle itself in the area being checked because the sprite should not be overlapping solid already. We're just checking the rectangle that the edge of the sprite is moving through. Also notice that we use a variation `ProposedPixelY2` because we want to be sure to check the bottom of the sprite's lowest pixel when looking downward to avoid rounding errors.
3. In the next blocks concerning `dx>0` and `dx<0` we are basically doing the same check horizontally instead of vertically. But because hills add a lot of complexity, there's a lot more code. Since you're probably not concerned with hills much, I'll try to focus on the rectangular portion of the code.
4. When we check for `int.MinValue` we're basically checking whether no solid pixel edge was found on the background layer in the requested rectangle. `int.MinValue` is returned when no solid pixel was found. So basically, if we skip all the slope logic, we are matching the edge of the sprite to the left or right wall toward which it is headed if one was found. (Technically we're adjusting the sprite's dx so that it will match after its position is next updated.) The vast majority of the code here deals with sloped floors and ceilings, which I will ignore.
5. Next we are restoring the original vertical velocity (`dy = dyOrig`) and re-applying the ceiling and ground check, but this time taking into account not only the vertical movement of the sprite, but also the corrected horizontal movement. We also account for the fact that the sprite is 1 pixel wider when sitting between pixels. Honestly, this code has gotten so refined over the weeks of trial and error that formed it that I can't necessarily explain in detail all the reasons this had to be done, but here's my best attempt:
    * The earlier ground/ceiling check needed to be done ignoring the horizontal velocity because we weren't sure what it would be yet. But we needed a good approximation of the corrected vertical velocity in order to compute a good horizontal velocity. Landing on a floor may cause the sprite to land at a height where it can hit a wall even though it would not have hit that wall if the floor weren't there (if the sprite is taller than 1 tile or is approaching a sloped ceiling).
    * The later ground/ceiling check needed to be done so that the sprite's vertical velocity would be properly adjusted after taking into account the effect of walls on the expected horizontal location of the sprite.
    * The original vertical velocity `dyOrig` is used as a starting point because the earlier check that was done was not conclusive and we want to basically start over now that we know a good horizontal velocity.
6. The last bit of code dealing with `LocalDX` only applies when the sprite is riding on top of another sprite (`LocalDX` is the velocity of the sprite relative to the sprite on which it is riding). The relative velocity is updated according the the change that was applied to the absolute velocity. This prevents platforms from being used as a means to travel through walls. (The vertical equivalent of this logic is in a different function because hitting a floor or ceiling while riding a platform causes the sprite to stop riding.)

# Answer
> 0 votes
> Why? The player can be both above the box, and to the left of the box at the same time.

Solve the collision at each axis separately:

* Object moved - test intersection.
* Solve the collision at the horizontal axis based on the direction the object came from, if the object was moving horizontally (`hspeed != 0`). If the object came from left to right, move the object to the left of the intersected rectangle, if the object came from right to left, move object to the right of the intersected rectangle.
* Horizontal axis solved. Now test intersection again, with the updated position (after solving the horizontal axis), but for the vertical axis.
* Repeat the process of solving the collision, but for the vertical axis.

Another problem is this approach:

> ```
> if player.x < box.x then
>       player.x = box.x - player.width
>
> ```

because:

```
.---.                  .---.
| A | - - - - - - >  .-|-A |
`---´                | B-|-´
                     `---´

```

See that object A collide with B, but A was so fast, that it went almost past B, ending up at the right of B. Since your solution doesn't take in consideration the direction the object comes from, only the relative position between the two objects, the result will be incorrect: your algorithm will result (wrongly) in this:

```
     .---.
.---.| A |
| B |`---´
`---´

```

Do like in the steps I mentioned, considering the motion of the object.

---
Tags: collision-resolution
---


# Question
Title: Getting solid black color when texture is added to GLSL
I'm trying to apply the default *badlogic.jpg* image to a .obj I have. I'm currently loading the texture from `AssetManager` and creating a material with a texture attribute (as a diffuse).

In my fragment shader, I try to get the texture value and output it but it just results in a solid black. I outputted `v_texCoord` (as a vec4) and I could see different colors that resemble what they should be (which should mean that the texture coordinates are correct). But yet I still get a solid black color.

I don't understand why the texture is not coming through. Am I missing something?

Code:

```
/.../
model = assetManager.get("mesh/Sting-Sword-lowpoly.obj", Model::class.java)
texture = assetManager.get("badlogic.jpg", Texture::class.java)

val m = ModelInstance(model)

val mat = Material()
mat.set(TextureAttribute.createDiffuse(texture))
m.materials[0] = mat

/.../

```

Vertex Shader:

```
attribute vec3 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord0;

uniform mat4 u_projViewWorldTrans;
uniform sampler2D u_diffuseTexture;

varying vec3 v_normal;
varying vec2 v_texCoord;

void main()
{
    v_texCoord = a_texCoord0;
    v_normal = normalize(a_normal);
    gl_Position = u_projViewWorldTrans * vec4(a_position, 1.0);
}

```

Fragment Shader:

```
uniform sampler2D u_diffuseTexture;
varying vec2 v_texCoord;

void main()
{
    //Get color
    vec4 color = texture(u_diffuseTexture, v_texCoord);

    gl_FragColor = color;
}

```

# Answer
> 1 votes
The OpenGL specification states:

> If a fragment shader uses a sampler whose associated texture object is not complete ... the texture image unit will return(R,G,B,A)=(0,0,0,1).

The first thing to check is therefore that your texture loaded successfully and is complete. A common cause of textures failing to load, when attempting to load them by name from the file system, is the source image file not being found. Using an OO wrapper around the native texture loading functions can often mask errors such as this, e.g. by providing default values, or fallbacks for bad parameters or non-existent files.

```
texture = assetManager.get("badlogic.jpg", Texture::class.java)

```

Depending on the facilities offered by your language and/or programming environment, you should perform some error-checking around this line. Does `assetManager.get` throw an exception that you need to catch? Do you need to check the returned value of `texture`?

```
mat.set(TextureAttribute.createDiffuse(texture))

```

This also merits some error-checking. Again, does `TextureAttribute.createDiffuse` throw an exception or return a value that you need to check?

Hopefully this should enable you to hunt down the cause.

---
Tags: opengl, libgdx, glsl, kotlin
---


# Question
Title: Handle states in character in functional programming way
How to handle any change of state of a character with functional programming?

If I'm using functional programming the character should be stateless, in my understanding. With that said, I should instantiate a new character every time a position, for example, is changed. Is this correct? This doesn't sound very efficient, but I might be wrong. I'm tinkering before start implementing and wanted to be sure this is the right way.

Thanks.

# Answer
> 1 votes
What your looking for is FRP game development.

**Some Video Introductions:**

It is 100% possible and preferable to make the core game logic in a purely functional way, the industry as a whole is simply behind, stuck in one paradigm of thinking.

Its possible to do it in Unity as well.

To answer the question a new game state will be updated/created every time something moves, as carmack says in his talk, it's not a problem. The drastic reduction in cognitive overhead that comes from a purely functional, highly maintainable, flexible architecture far out ways the performance hit, if it exists at all.

---
Tags: design-patterns
---


# Question
Title: Are abilities in online games better crafted in the main game backend language or a scripting language?
Scourge Healing: Hex Spell. (30 seconds.) Whenever target foe is healed, the healer takes 15...67...80 holy damage.

The above is one of Guild Wars 1's monk class skills.

My question is about what would be a good way of implementing abilities like this. In a realtime game, should I be implementing them in my game's backend language(golang) directly, interpreting them from a scripting language at runtime, or something else? How do most RPGs(online or otherwise) do this?

# Answer
My experience is limited to two "AAA MMORPGs". I was a "gameplay engineer" in both, writing C++... SOE's "Everquest Next", and ZOS's "Elder Scrolls Online".

Both used abilities defined in data in such a way that dedicated designers could create and modify them with (ideally) little or no direct programmer involvement. The more complex things got, the more likely a designer might need an engineer to debug something, to say nothing of feature requests.

Both supported a fixed variety of kinds of things they could do, conditions they could test for, events they could hook into, and so on. A vast array of them, but a fixed set that could only be expanded by engineering.

In one case this data became so baroque/complex that it became Turing Complete. It was a painful obtuse/user unfriendly scripting language... accidentally.

I think an ideal system would use a visual scripting language (scribble, blockly, etc,) and expose a variety of objects/methods to it. This system would need to enforce execution time limits(and possibly other resources), and flag potential troublemakers for engineering review, native reimplementation, or deletion.

It would support a debugger! People writing these scripts are programming. Give them some tools to do it right. Ideally you wouldn't have to restart your game to load a new version of a script. Iteration time is important, particularly when you might have to close down your client and multiple servers, then restart them all. With debug builds this can easily take \> 10 minutes.

If players were allowed to customize their GUI with this same language/objects, you would further need different layers of access. General Public, internal GUI only, and abilities-n-such.

Given a working C++ (or whatever) class, it should be trivial to expose that object and some or all of its public methods to the scripting language. "Tweak an XML file and rebuild", or perhaps add code annotations as in Java or C++.

But this all stems from my experience on big teams of developers working on MMORPGS. A smaller game with fingers-of-one-hand people working on it can probably get by with something much simpler.
> 2 votes

---
Tags: scripting
---


# Question
Title: How can I reference C# objects in GDScript (and vice versa)?
I am using Godot Engine 3.0.6 Mono for Windows x64. I am prototyping the majority of my project in C# before I rewrite the game in C++ for release. I installed this plugin mostly to help with testing and debugging value-sensitive functionality. To make this possible however, I will need to be able to make references to my C# classes from GDScript (or vice versa) for binding commands. I could not find any instructions on how to do this in the official documentation. Can this be done currently in either direction?

*Note: If the references are made from C# to GDScript classes, I need to be able to cast the Nodes respectively to make function calls.*

# Answer
I figured out how this works both ways after a couple of days.

It is not immediately obvious and the GDScript interpreter will yell at you, but as long as your C# objects are included in the .csproj file and the class itself extends Object, you can call any method in the C# script.

The C# API adds a nice way of calling GDScript instance functions, which is are the Godot.Object methods `Call()`, `CallDeferred()`, and `Callv()`.

E.G. given:

## SampleGD.gd

```
func from_csharp(content):
    print(content)

```

Then in C# you would obtain a reference to this object in the scene or use `ResourceLoader` to load a new instance. After such, you could do:

## SampleCS.cs

```
var sampleGD = FindNode("SampleGD");
sampleGD.Call("from_csharp", "Hello from C#!");

```
> 7 votes

---
Tags: c#, godot, mono
---


# Question
Title: Error in DRAW GUI event on android. (GameMaker)
Image of the game on a mobile phone:

As you can see the **maze** (draw event) has been resized correctly.

But the **yellow post-it** (draw GUI event) has not been scaled or displayed in the correct location (center of the screen). Same thing with **GUI layout** (draw GUI event).

Because this is a small stage/room (size) I do not use the artifice of views, I thought that could be because of that the problem, but I enabled the views and did not get any different result.

Picture of the game on a computer (like it should be on the phone):

OBS - One information that can help you to help me solve the problem, is that to draw the post- it I use the following code: **draw GUI event** `draw_sprite(spr_Post,0,640,360);`.

**640** is the half screen width of the game and also the room, **360** is half the height of the game screen and also the room.

It seems that somehow the room on the cell phone is different size than 1280x720.

I do not put the following code: **draw GUI event** `draw_sprite(spr_Post,0,room_width/2,room_height/2)`, because there are much larger phases that need views, so the post-it needs to be in the **center of the screen of the player**, and with this code it ends up being in the center of the phase.

I tested the game on Bluestacks and it did not happen the same as on the phone.

# Answer
> 0 votes
What worked for me was this:

(Draw GUI Event)

```
display_set_gui_size(1280,720);
draw_sprite(spr_Post,0,640,360);
```

Reference:

https://docs.yoyogames.com/source/dadiospice/002\_reference/windows%20and%20views/display\_set\_gui\_size.html

# Answer
> 0 votes
Here I am again to the rescue XD

Instead of using room\_width or room\_height that are the size of the room, use the size of the view, the variables are view\_xview, view\_yview, view\_wview and view\_hview that are related to the current view so use the index \[0\] with the number of the view on all variables.

`draw_sprite(sprite_index, view_xview[0]+view_wview[0]/2, view_yview[0]+view_hview[0]/2);`

It will make the object origin to be in the center of the screen/view.

Edit: The Draw\_GUI event is relative to the view coordinate system. Edit2: added some code to try

Check them in the manual to see examples.

---
Tags: gui, game-maker
---


# Question
Title: is this approach correct to make my game framerate indipendent in javascript?
this is what i did

my game loop is run every REFRESH milliseconds

```
loop = setInterval(tick,REFRESH);

```

in the loop i calculate how much time is passed since last tick and subdivide that for how much time i expected to be passed

```
var now = performance.now();
var elapsedTime = now - lastTick;
var delta = time / REFRESH;
lastTick = now;

```

and every time based action that should happen every tick is "scaled" with the ***delta*** factor, for example my movement code

```
var distance=ball.dest.x-ball.x;
var movement=distance/speed;
ball.x+=movement;

```

will have ***movement*** multiplied with ***delta***

# Answer
> 3 votes
Your approach is unfortunately not framerate independent. You correctly notice the need to factor in the amount of time passed between each update in your physics calculations. However, you still specify the amount of time passed in units of frames. If your framerate changes, now your speeds have all changed with respect to the passing of real time. What you should do instead is pass the actual time passed between each frame in units of seconds or ms or us or whatever.

In your first example, the change is simply passing elapsedTime rather than delta. In the second half you need to calculate the speeds of items with respect to the passing of real time, like pixels/second or meters/second rather than pixels/frame.

# Answer
> 1 votes
Don't use `setInterval` for game loops. Use `requestAnimationFrame`. See the simple example below.

```
console.clear();
const INTERVAL = 16; //16 ms animation interval
var frame = {
  start: null,
  delta: null,
  count: 0,
};

run(test);

function run(func) {
  if (!frame.start) frame.start = performance.now();
  frame.delta = performance.now() - frame.start;
  if (frame.delta >= INTERVAL) {
    func.call();
    frame.start = null; //reset
    frame.count++;
  }
  //for this example the loop will be repeated only 100 time
  if (frame.count < 100) requestAnimationFrame(run.bind(null, func));
  //without counting limit
  //requestAnimationFrame(run.bind(null, func));
}

function test() {
  //simple function for demonstration
  // avoid using console in animation loop, except for debugging
  // console operations are very slow
  console.log(`${frame.count}`);
}
```

---
Tags: javascript, game-loop
---


# Question
Title: How do I interact ads with Unity Button?
I'm new to Unity and I'm a beginner. Unity ads have completed, but instead of the letter "E" and "T" I want the ad to come out by clicking the button. how can I write a code for it?

using System.Collections.Generic; using UnityEngine; using UnityEngine.Monetization;

public class AdController : MonoBehaviour { private string store\_id = "3049359";

```
private string video_ad = "video";
private string banner_ad = "bannerAd";

void Start()
{
    Monetization.Initialize (store_id, true);

}

void Update()
{
    if (Input.GetKeyDown (KeyCode.E)) {
        if (Monetization.IsReady (video_ad)) {

            ShowAdPlacementContent ad = null;
            ad = Monetization.GetPlacementContent (video_ad) as ShowAdPlacementContent;
            if (ad != null) {
                ad.Show ();
            }

        }
    }
        if (Input.GetKeyDown (KeyCode.T)) {
        if (Monetization.IsReady (banner_ad)) {

            ShowAdPlacementContent ad = null;
            ad = Monetization.GetPlacementContent (video_ad) as ShowAdPlacementContent;
            if (ad != null) {
                ad.Show ();
}

```

} } } }

# Answer
Place the code in the if statements in a new void and call that void from the button

```
public void ShowAd(){
 [Your code here]
}

```

Then go to the button, by "On Click" click on the +.

Select the GameObject the ads-script is on. Then select \[your script name\] and the ShowAd function.
> 1 votes

# Answer
Go to unity ads page. Copy the c# script . Paste that. In project services enable unity ads. It is that much simple . Only 2 mins
> 0 votes

---
Tags: unity, advertisements, unity-ads
---


# Question
Title: Do inventory items have to live in the game world?
I'm trying to create an inventory system. There's a few parts to it:

* Item (scriptable Object just the data like name etc of the item)
* ItemDatabase which takes array of Item (scriptable object) and then on awake it looks through and populates a dictionary for ID,data
* ItemStack - Actual item holds an int for an ID so it can get data from the dictionary from it.

My inventory has a list of ItemStacks, but to be able to populate that array the script needs to be on a GameObject, so with how everything works, is it required for me to always have GameObjects in the game basically representing items? I'm new to inventories so is that how its suppose to be? Or am I missing something here? It seems kinda strange if I have 700 different item in my inventory that would require 700 GameObjects created to represent them.

Or maybe I'm overthinking it... but I feel like the inventory should only have "data" and not a GameObject, the GameObject would be for when you spawn an item in the world.

# Answer
> 3 votes
I've figured out that the reason that I couldn't populate the inventory with only data and needed to be on Gameobject was cause the class was inheriting from Mono-behavior which REQUIRES it to be on a gameobject the solution was just to make the class not inherit from it.

# Answer
> 0 votes
My solution for this in my last game was to have three different classes:

* **`ItemData`** which inherited from `ScriptableObject` and contained all the relevant data for a type of item, both mechanical and regarding its appearance, both in the game world and in the inventory.
* **`FloorItem`** which inherited from `MonoBehaviour` and represented an item laying on the floor in the game world.
* **`InventoryItem`** which inherited from `MonoBehaviour` and represented an item in my inventory system UI.

Both `FloorItem` and `InventoryItem` had an `itemData` property referencing the scriptable object determining its type. When that property changed, the behaviours also changed the sprite/mesh, description text etc. to match the new data. I made this an editor script so I was able to change the type of an item in the game world by simply dragging another ItemData asset into it.

The ItemData class could also serve as a factory. So when the player picks up an item, I could do `floorItem.itemData.createInventoryItem()` to create a new UI object to insert into my inventory UI. And vice versa, when the player dropped an item from the UI, I could do `inventoryItem.itemData.createFloorItem()` to instantiate a new GameObject in the world.

---
Tags: unity, gameobject, inventory
---


# Question
Title: MoveTowards object stuck with isTrigger Collider
I am trying to have a missile seek its target once it has entered the target's trigger. The code should be fine, I think it has something to do with how the colliders are operating.

I want the blue missile to move towards the turret object once it is in turret object trigger collider. However this is sticking to the sphere trigger collider.

```
void Update()
{
    if (Time.time > timeCreated + timeToLive)
    {
        Destroy(this.gameObject);
    }
    if (inTurretTrigger == true)
    {
        StartCoroutine("MoveToTurret");
    }
}

public void OnCollisionEnter(Collision collision)
{
    //Debug.Log("Collided with " + collision.gameObject.name.ToString()); // All this logic needs to go in Trigger not collision
    /*
    TurretController t = collision.gameObject.GetComponentInParent<TurretController>(); // Returning null as this was not applied in Prefab
    Debug.Log("Who am I? " + t.gameObject.name.ToString());

    if (t != null)
    {
        Debug.Log("This is coming from Bullet Script and t is not null " + t.gameObject.name.ToString());
        transform.position = Vector3.MoveTowards(transform.position, t.gameObject.transform.position, bulletVelocity * Time.deltaTime);
    }
    else {

    }
    */
    Destroy(this.gameObject);
}

public void OnTriggerEnter(Collider other) // over here above code should work, however the best case is find all instances, or through Raycase, and follow the object through hit target
{
    t = other.gameObject.GetComponentInParent<TurretController>(); // Returning null as this was not applied in Prefab
    Debug.Log("Who am I? - " + t.gameObject.name.ToString());

    if (t != null)
    {
        inTurretTrigger = true;
    }
    else
    {
        //
    }
}

IEnumerator MoveToTurret() // logic for coroutine provided from StackOverflow
{
    Debug.Log("This is coming from Bullet Script and t is not null");
    transform.position = Vector3.MoveTowards(transform.position, t.gameObject.transform.position, bulletVelocity * Time.deltaTime); // this needs to be handled in Update
    yield return new WaitForEndOfFrame();
}

```

# Answer
> 1 votes
I think the answer to your question is present in your own code:

```
transform.position = Vector3.MoveTowards(transform.position, t.gameObject.transform.position, bulletVelocity * Time.deltaTime); // this needs to be handled in Update

```

as you can see the comment says that the operation needs to be handled in Update, like in this example on unity's scripting API: https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html

Instead of calling a new coroutine every frame, you should call the MoveTowards operation directly in your Update function inside the if statement like this:

```
if (inTurretTrigger)
{
    transform.position = Vector3.MoveTowards(transform.position, t.gameObject.transform.position, bulletVelocity * Time.deltaTime);
}

```

\[Notice: I omitted writing " == true" in the *if*'s condition since *inTurretTrigger* returns a boolean value\]

What you want to achieve can be done with a coroutine but it would just be pointless and resource wasting in this case, since "Coroutines are best employed when dealing with long asynchronous operations, such as waiting for HTTP transfers, Asset loads or file I/O to complete." as reported by UnityDoc here https://docs.unity3d.com/Manual/BestPracticeUnderstandingPerformanceInUnity3.html

I hope this can help you solve this issue.

---
Tags: unity, collision-detection, collider
---


# Question
Title: How can I set my non-convex object's collision to a more detailed one to allow other objects to go underneath?
My problem is simple. I imported a 3D object (it's not convex) and I want the character to go under your legs.

But this does not happen:

There seems to be a way to do this, I just do not know which one.

Vision of what would be a complex collision:

I've already changed all these options, but it did not work out:

The closest I got was when I saw something about adding a physical material. But when I try only a circle appears, I still can not add one exactly equal to the Character:

Links where I've already looked for help:

https://docs.unrealengine.com/en-us/Engine/Content/FBX/StaticMeshes#collision https://docs.unrealengine.com/en-us/Engine/Physics/PhysicalMaterials/PhysMatUserGuide https://forums.unrealengine.com/development-discussion/content-creation/18509-how-can-i-make-this-have-a-more-precise-collision-box

# Answer
The collision box defined by the UE4 for any imported object will be as simple as possible.

To modify the collision box I had to follow the following steps:

Now just click collision and then Auto Convex Collision:

Now just set the parameters and then click Apply:

**OBS** \- These numbers come by default, I did not put those values to modify my character.

Clicking on apply you will get a preview of how the collision box is:

**Do not forget to save!**

I recommend not to greatly increase the first parameter if the third parameter is at 100000, otherwise this warning will appear. Certainly not good.

Result in game:

References:

https://answers.unrealengine.com/questions/389593/how-to-add-collision-to-a-complex-static-mesh.html

https://en.wikipedia.org/wiki/Ramer%E2%80%93Douglas%E2%80%93Peucker\_algorithm
> 0 votes

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


# Question
Title: Getting the same message while using Facepunch.Steamworks
I use Facepunch.Steamworks for P2P game made in Unity, so I send packets through it(UnreliableNoDelay sendtype), but I've got a problem, since I send message like this: Move:0 and get this: Move:00,994 The thing is that the previous sent message, before "Move:0" was -0,994, so there is a question: Why do I keep getting the last non zero message(I get 00,994 even if I sent some more "Move:0" messages)? I use the same encoding(UTF8, tried with Unicode) on both, receive and send. I also debugged the messages(in Unity, if it is important) just before sending and just after receiving it, so it couldn't change. I think it's because of Steamworks' way to send messages, but can't get the way to fix it(except the one, when I ignore the messages if it is equal to last one). Also if I stop sending messages receiving is also stopped, so there is no loop, as I see. That's the results what I get in console(1-sent, 2-received):

I also get parts of another message in this one, like this for example:  "p" is from another message "Jump:0".

The code I use to send:

```
        byte[] data = Encoding.UTF8.GetBytes(messageType+";"+message);
    Debug.Log(messageType + ";" + message);
    client.Networking.SendP2PPacket(steamId, data, data.Length, networkType, channel);

```

And to receive:

```
            client.Networking.OnP2PData = delegate (ulong steamId, byte[] bytes, int lenght, int channel)
        {
            ParseMessage(Encoding.UTF8.GetString(bytes), steamId);
        };

```

Appreciate any help

# Answer
I fixed it, I had to use this code to encode the data: `Encoding.UTF8.GetString(bytes, 0, dataLenght)`.
> 0 votes

---
Tags: c#, networking, steam, udp
---


# Question
Title: Unity Canvas hover image does not trigger event
So i have the following setup:

This produces the following UI:

Now on each of the "HudCircle"(Bottom/Right/Left/Top), I have the following components:

As you can see I have a script that has the following code:

```
    public class HUDAction : MonoBehaviour,  IPointerEnterHandler, IPointerExitHandler
{
    public Color StartColor;
    public Color SelectedColor;
    public Image Image;

    private void Awake()
    {
        Image = GetComponent<Image>();
        StartColor = Image.color;
    }

    public void OnPointerEnter(PointerEventData eventData)
    {
        Image.color = SelectedColor;
        Debug.Log("Over");
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Image.color = StartColor;
        Debug.Log("Not over");
    }
}

```

Sadly when playing this scene nothing happens when I hover either of the circles.

Can anyone tell me what I've done wrong?

# Answer
> 1 votes
The Image component needs to have the Raycast Target checkbox checked. I assume you have an EventSystem GameObject somewhere in the hierarchy to handle sending the events as well. If not, you’ll need one of those too.

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


# Question
Title: How can I create a random deck of 7 cards every time they are all used?
I'm trying to create a Tetris like game in C# (Unity) and I've run into quite a problem on how I can generate 7 cards (tetrominoes) of which none are the same and when I run out of cards, I regenerate more.

I can kind of see how I could do the regeneration part but I'm very unsure on getting 7 cards for which none are the same.

# Answer
As it happens, I was showing this method to my game mechanics students just this week. :)

One of my favourite ways to work with a deck is using an online version of a Fisher-Yates Shuffle (also called a Knuth shuffle)

```
IEnumerator<T> ShuffleBag<T>(params T[] items) {
    int remaining = items.Length;

    while(true) {
        // Choose a random item from what remains of our deck.
        // (That is, the entries 0...remaining-1)
        int drawIndex = Random.Range(0, remaining);
        T drawnItem = items[drawIndex];

        // Remove the item from the deck by swapping it to the end.
        remaining--;
        items[drawIndex] = items[remaining];
        items[remaining] = drawnItem;

        // Yield the drawn item as our new .Current item,
        // and wait until we're asked to draw again.
        yield return drawnItem;

        // If we're out of cards when we ask for a new one,
        // reshuffle the discards to make a fresh deck.
        if (remaining == 0)
            remaining = items.Length;
    }
}

```

You can set this up like so:

```
var bag = ShuffleBag(
             Tetromino.I,
             Tetromino.O,
             Tetromino.T,
             Tetromino.J,
             Tetromino.L,
             Tetromino.S,
             Tetromino.Z
         );

```

Then draw a new tetromino from the bag like so:

```
bag.MoveNext();
var tetromino = bag.Current;

```

There will always be a new tetromino ready: the bag will automatically reshuffle the discards whenever it gets empty, and give them out in a new random order.

---

Here's the same basic idea, but as a class rather than an iterator, so we can give it a somewhat richer API:

```
[System.Serializable]
public class Deck<T> {

    public int Remaining { get; private set; }
    public int TotalCount { get { return _items.Count;  } }
    public int DiscardCount { get { return TotalCount - Remaining; } }

    [SerializeField]
    private List<T> _items;

    // To create an empty deck and .Add() items to it as you go.
    public Deck() {
        _items = new List<T>();
    }

    // To create a deck from the elements passed as constructor arguments.
    public Deck(params T[] items) {
        _items = new List<T>(items);
        Remaining = items.Length;
    }

    // To create a deck from an existing list, array, or other finite enumerable.
    public Deck(IEnumerable<T> items) {
        _items = new List<T>(items);
        Remaining = _items.Count;
    }

    // Shuffle a new card into the deck.
    public void Add(T item) {
        _items.Add(_items.Count > 0 ? _items[_items.Count - 1] : item);
        _items[Remaining] = item;
        Remaining++;
    }

    // Add an item to the discard pile, so it doesn't come up till the next shuffle.
    public void AddToDiscards(T item) {
        _items.Add(item);
    }

    // Draw an item, shuffling if necessary.
    public T Draw() {
        PreDraw();

        int index = Random.Range(0, Remaining);

        return Draw(index);
    }

    // Draw an item, using your own random source.
    // Useful if you need determinism, or are generating stuff in a background thread.
    public T Draw(System.Random dice) {
        PreDraw();

        int index = (int)(dice.NextDouble() * Remaining);

        return Draw(index);
    }

    // Manually force a reshuffle of any discards.
    public void Shuffle() {
        Remaining = _items.Count;
    }

    // Remove an item, if present (true)
    // Returns false if the item is not in the deck or discards.
    public bool TryRemove(T item) {
        int index = _items.IndexOf(item);

        if (index < 0) return false;

        if (index < Remaining)
            Remaining--;

        _items.RemoveAt(index);
        return true;
    }

    // Ensures the deck is in a valid state to draw from, shuffling if needed.
    private void PreDraw() {
        UnityEngine.Assertions.Assert.IsTrue(_items.Count > 0,
            "Attempted to draw from an empty deck. " +
            "Add at least one item before calling Draw().");

        if (Remaining == 0)
            Shuffle();
    }

    // Do the actual work of pulling the selected item out of the deck,
    // placing it in the discard pile, and keeping the remaining items together.
    private T Draw(int index) {
        T selected = _items[index];

        Remaining--;
        _items[index] = _items[Remaining];
        _items[Remaining] = selected;

        return selected;
    }
}

```
> 6 votes

# Answer
Create a list of your tetrominoes, then get a random one out of it, do something with it, then remove it from the list:

```
List<Tetromino> m_list = new List<Tetromino>();

m_list.Add(/* put tetromino #1 here*/);
m_list.Add(/* put tetromino #2 here*/);
m_list.Add(/* put tetromino #3 here*/);
m_list.Add(/* put tetromino #4 here*/);
m_list.Add(/* put tetromino #5 here*/);
m_list.Add(/* put tetromino #6 here*/);
m_list.Add(/* put tetromino #7 here*/);

while(m_list.Count > 0)
{
    int rndNumber = Random.Range(0, m_list.Count);
    // do something with m_list[rndNumber]
    m_list.RemoveAt(rndNumber);
}

```

This way, each item can be used only once, and when the while loop exits, you're sure you've used each one once.
> 1 votes

---
Tags: unity, c#, random, tetris
---


title: UE4 - 2D puzzles in 3D game

text:
# Question
Title: UE4 - 2D puzzles in 3D game
I want to create a game where you walk around in 3D, and sometimes you can activate some kind of 2D puzzle. For example - you walk up to the door, and you can open it using lockpicks. The lockpick part is 2D. There's plenty of games which could be example of that, like Assassin's Creed 3, Skyrim or possibly the new Thief?

While lockpicking the door, you lose control of the character, you use mouse or buttons to move the lockpicks. The visible elements would be moving.

How would you do that? Should I use UMG objects like images and buttons, or should I use some other kind of 2D graphics drawing? Or something even else?

# Answer
I think I solved my own problem quite well... this is how I did it.

I used default UE4 third person character for walking around. When I'm inside specific colliders and press a button, I access the "lockpick mode". That involves unpossessing the default character, creating a very simple pawn (it only reacts to some buttons and mouse movements, but cannot move around) and possessing it.

The lockpick "target" has a transform where to create the lockpicking interface, and where to place the new player pawn.

The lockpicking puzzle is not UMG. While UMG is powerful, it's just not enough. I have a game object containing the lockpick (which is just a 2D actor that has a collider and is controlled by the mouse) and some pins which have physics turned on.

If anyone is interested and this is not clear enough, I will be happy to add details!
> 1 votes

# Answer
I would use UMG. All the functionality you need is in there and you can use Set Input Mode Game and UI blueprint and set the target to your new UMG. It also has a Boolean operator to Lock Mouse to Viewport.

I believe this will also deactivate player control in the background but haven't tested this so can't say for certain. Disabling character control is also one function in Blueprint though so setting and unsetting it (when the UMG is closed) won't be a problem.
> 0 votes

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


# Question
Title: How do I use the Minecraft Coder Pack on Linux
I downloaded the Minecraft coder pack to mod the game and decompile it, but how do I use it on Linux. Some sources seem to give specific directions, but they are not clear and they involve executing the .bat files. My Ubuntu does not recognize .bat file. How do I decompile a class file from changing a Minecraft version jar file to a zip and unzipping it? How do I decompile one of those class files using Minecraft coder pack? I have been wondering what at least some of the Minecraft source code looks like.

# Answer
I did not try this but you should be able to execute the sh files. In windows you have .bat and in linux .sh, try to execute the decompile.sh file.
You can do this in terminal, rightclick into an empty space in the folder where the sh file is, then click on "open in terminal".
Type `./decompile.sh`
> 0 votes

---
Tags: minecraft-modding
---


title: ECS - System calling other systems

text:
# Question
Title: ECS - System calling other systems
I'm trying to build my first (2D) game with ECS but I always end up with some system calling other systems. Here's an example.

There is a RegionSystem that manages RegionComponents. On each frame, this system loops through all the RegionComponents and checks if the player is inside any of them.

When the player enters the water, the player's sprite must be changed from PLAYER\_RUNNING to PLAYER\_SIWMMING.

When the player steps onto a teleporter, an animation will play around the player, he'll be rotating and a new level will be loaded.

When the player steps into a hole, he will lose some health and will be repositioned in the level.

So, first of all, it needs the coordinates of the player's body to check if it is in a region (check point in rectangle). Hence it will ask the RigidbodySystem to get the coordinates.

Then if the player is inside a region, it will call PlayerSystem\_OnInsideRegion(regionInfo).

In turn this function, PlayerSystem\_OnInsideRegion must react differently depending on the type of the region:

* for the water case, it needs to call the SpriteSystem to change a sprite, the PlayerSystem to set a boolean (m\_inWater = True;) and the RigidBodySystem to get the coordinates of the player's body;
* for the teleporter case, it needs to call the LevelSystem and tell him to switch to another level on the next frame;
* for the hole case, well, simply descrease the member m\_health of the player component, so no need to call another system here.

I have the feeling this is a horrible design and does not fit the ECS architecture. I read that people use a message system where systems can subscribe and unsubscribe to particular type of message. But I also read that it can be tricky to react to them in a proper order.

# Answer
> 1 votes
As you describe, this is usually solved by a message system.

The region system runs early in your frame update, say just after movement, and any time an object changes region, it issues a "region changed" message for that object.

Other systems can subscribe to that type of message. When their turn in the update comes, they can read the relevant messages for the objects they care about and react accordingly — say by swapping out an animation or sound set. They don't need to know anything about how regions are determined, they just use the region ID as a key to look up into their asset collection & find the matching entry.

> But I also read that it can be tricky to react to them in a proper order.

I don't think that's likely to bite you here. With an ECS you'll typically have your systems running in a fixed order, so you can ensure the animation & sound systems run after the region update system, which runs after the movement integration systems. That ensures there's a well-defined order in which the data gets processed and used.

You can use this to cut down on excess workload too. Rather than searching every region for every object that needs region information, you can use messages from your movement system to indicate just the objects that moved. The region system can then process them: "Oh, the player moved from 3,3 in region A to 4,3? That's still in regionA, so no change to report!" without looping over all regions or searching a partition structure to make that determination.

---
Tags: entity-system
---


# Question
Title: How to calculate turret position after rotation
I'm trying to make a tank character for my game but I couldn't do the math of firing bullets from turret instead of center of the tank.

I tried some Stack Overflow solutions but I couldn't understand them correctly or they weren't related to my issue.

```
this.angle = (rotation in radians) + Math.PI / 2
var x = -40 * Math.sin(this.angle) - -40 * Math.cos(this.angle);
var y = -40 * Math.cos(this.angle) + -40 * Math.sin(this.angle);

turretX = turretX - x;
turretY = turretY - y;

```

Now, as you can imagine, the position is always 40px wrong. That's expected since I try to change values of both x and y regardless of whether they're already correct or not.

How can I get the correct x, y?

# Answer
I found an answer in a random stackoverflow post, not sure if there's better ways to do this but it works. Feel free to post your way if you think that's better.

```
var turretX =
  (0 - 0) * Math.cos(rotation) - (40 - 0) * Math.sin(rotation) + 0;
var turretY =
  (40 - 0) * Math.cos(rotation) + (0 - 0) * Math.sin(rotation) + 0;

```
> 0 votes

# Answer
If you know the angle and position of the turret, then it's simply

```
x = turretPosX + cos(angle) * barrelLength
y = turretPosY + sin(angle) * barrelLength

```
> 0 votes

---
Tags: mathematics, javascript, rotation
---


title: How can I import a landscape mesh?

text:
# Question
Title: How can I import a landscape mesh?
I can export the landscape of UE4 (File -\> Export Selected -\> .obj / .fbx) and load a landscape, for example, in Maya. But how is the modified landscape loaded back into UE4? Otherwise, how to import terrain to UE4? Thank.

P.S.: Any format and any editor are interested.

# Answer
> 1 votes
You may export it as \*.fbx and import it again via the import dialog.

---
Tags: unreal-4
---


# Question
Title: How to implemement smooth side scrolling in a DOS game?
I'm about to develop (just for fun) a retro DOS game with Turbo C 2.01. Currently I'm wirting directly all the pixel information to `0xA0000000 + [y * 320 + x]` which is very slow. My vision is to build a game which scrolls very smoothly over the tile map - just like this one (to name one example): http://www.doshaven.eu/game/dark-quest/.

I researched a bit online and found out that there is a *attribute controller register* where you can write to 13h a 4-bit pixel offset value.

```
inp(0x3da);
outp(0x3c0, 0x13 | 0x20);
outp(0x3c0, offset_in_x);

```

But it scrolls my screen only about 16 pixels and I read that this number is limited by the graphics mode (which I confirmed in some tests).

**So how is this properly done?**

# Answer
> 1 votes
I may have to see if I can use the port call. As of now, I do it via software which is a lot of loop de doo. First I pre string 4 320x200 images together while slicing them into 10x200 segments, creating a 1280x200 buffer array. I can scroll the 10x200 slices, back and fourth. It works fine for the most part but struggles a little on slow machines. I am struggling to write it in assembly, as it is a bit complicated. In the mean time I am looking at other alternatives myself.

```
void makesigbuff(char *dest,int width,int height,int dir,int map ) {
register unsigned  long count=0,l=0,k=0;
register unsigned  long i=0,j=0,frames=0;

register long endsig=10;
register long startsig=0;
register long imgs=0;
register long startplace = dir;
 do {

    count = 0;

    k=0;

    for(j=0;j < height + startplace;j++) {

       for(i=0;i < endsig;i++) {

         if(i >= startsig) {  // i > ... to see it in sigments.

             if(j >= startplace) {

                  dest[count+i]=splicearray[frames + map][k];    //+map

             }
             k++;
        }

     }

     if(j>=startplace) {
          count += 320;    bitwidth;  //SCREEN_WIDTH;
     }
   }

   startsig +=10;
   endsig+=10;
   frames++;

 }while(frames < 32 ); //128

}

```

---
Tags: platformer, side-scroller, scrolling
---


# Question
Title: How do I make TextMesh Pro go invisible when at a distance from the camera?
I'm building a 4x game. I've rendered the galaxy, and I want the text below each star to disappear when I'm zoomed out, so it looks nicer.

My stars are Prefabs with a star sprite and a 'UI' gameobject with TextMeshPro underneath the 'UI' gameobject.

I've put this as the script on the TextMeshPro object, but it says there is no renderer for TextMeshPro:

```
    Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
    if (viewPos.z > 100F)
    {
        this.gameObject.GetComponent<Renderer>().enabled = false;
    }

```

# Answer
> 0 votes
Alright, Ed Marty's answer below is a MUCH better solution to my issue. However, I did figure out the specific issue I was asking about.

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

public class DistanceFromCamera : MonoBehaviour
{

Camera cam;

void Awake()
{
    cam = Camera.main;
}

// Update is called once per frame
void Update()
{
    Vector3 viewPos = cam.WorldToViewportPoint(transform.position); // Grab the distance from the camera
    if (viewPos.z > 200F) // How far away is it?
    {
        float fadeOut = (((viewPos.z - 300F)*-1) / 100F); // Get percentage away it is between 200 and 300 units
        if (fadeOut < 0) // if it's beyond 300 then make it disappear altogether.
        {
            this.gameObject.GetComponent<CanvasRenderer>().SetAlpha(0.0F);
        } else
        {
            this.gameObject.GetComponent<CanvasRenderer>().SetAlpha(fadeOut); // if it's between 200 and 300, fade it out
        }
    } else
    {
        this.gameObject.GetComponent<CanvasRenderer>().SetAlpha(1.0F); // if it's close enough, just set to full alpha
    }
}
}

```

Apparently, I was looking for the CanvasRenderer component for TMP objects, not just Renderer. But, Seriously, it's not a good solution when considering performance.

# Answer
> 1 votes
One way of achieving this is to use CanvasGroup on the TMP gameObject or its parent and play with its alpha value. Once your given distance between camera and text object is surpassed, set the alpha value to 0, and the text becomes invisible.

To further improve that, you can use your own script which fades in and out the alpha value smoothly. Meaning you just tell that script to FadeIn or FadeOut the CanvasGroup holding the TMP text.

Optionally you can disable the gameObject (not the script) if it is in FadeOut mode and reached 0 alpha.

In order to improve performance, you may want to use something that only checks the distance in higher intervals and/or preferably only when the camera has been moved (or the text gameObject). It's not necessary to run an Update method ~60 times a second for each single text gameObject. It can be reduced to ~2 times per second with 1 single method call, using a list of references to which the text objects automatically subscribe on creation and unsubscribe upon destruction.

# Answer
> 1 votes
If you are going to have lots and lots of these, I recommend you use a single manager class which controls all of them at once, and to help with this, use the CullingGroup API.

Something like this (untested):

This script would go on each text object:

```
class RegisterInCullingGroup : MonoBehaviour {
    void Start() {
        CullingGroupManager.Instance.AddObject(this);
    }

    void OnDestroy() {
        CullingGroupManager.Instance.RemoveObject(this);
    }
}

```

And another GameObject in the scene will have this component:

```
class CullingGroupManager : MonoBehaviour {
    public static CullingGroupManager Instance;

    public float radius = 1;

    private CullingGroup group;
    private BoundingSphere[] spheres;
    private RegisterInCullingGroup[] objects;
    private int count;

    void Awake() {
        Instance = this;
        group = new CullingGroup();
        group.targetCamera = Camera.main;

        objects = FindObjectsOfType<RegisterInCullingGroup>();
        spheres = new BoundingSphere[objects.length];
        count = objects.length;
        for (int i = 0; i < count; i++) {
            spheres[i] = new BoundingSphere(objects[i].transform.position, radius);
        }
        group.SetBoundingSpheres(spheres);
        group.SetBoundingSphereCount(count);
        group.SetBoundingDistances(new float[]{100});
        group.onStateChanged = OnStateChanged;
    }

    //to change the behavior when they disappear or appear, change this method
    private void OnStateChanged(CullingGroupEvent sphere) {
        if (sphere.hasBecomeVisible)
            objects[index].gameObject.SetActive(true);
        else if (sphere.hasBecomeInvisible)
            objects[index].gameObject.SetActive(false);
    }

    void OnDestroy() {
        group.Dispose();
        group = null;
    }

    public void RemoveObject(RegisterInCullingGroup obj) {
        int index = Array.IndexOf(objects, obj);
        if (index == -1)
            return;
        group.EraseSwapBack(index);
        CullingGroup.EraseSwapBack(index, objects, ref count);
    }

    public void AddObject(RegisterInCullingGroup obj) {
        int index = Array.IndexIf(objects, obj);
        if (index != -1)
            return;
        if (count == objects.length) {
            Array.Resize(ref objects, count * 3 / 2 + 1);
            Array.Resize(ref spheres, objects.length);
        }
        objects[count] = obj;
        spheres[count] = BoundingSphere(obj.transform.position, radius);
        ++count;
        group.SetBoundingSphereCount(count);
    }
}

```

Yes, it does look significantly more complicated, but it is also going to be significantly more efficient. You can also use this sort of system for supporting multiple levels of detail for your stars etc by passing in more than one value when calling SetBoundingDistances, and checking which band the object is in inside of OnStateChanged (with the sphere.currentDistance property).

# Answer
> 0 votes
You could get the gameObject of the text mesh pro and use the SetActive(bool b) method to disable it. Alternatively, you could get the text of the TextMeshPro and set it to String.empty.

A little side note: You should not use Camera.main often, because it is performance heavy. Get a refernce to the Camera.main object (e.g. in the Awake-method) and use the reference to that instead.

---
Tags: unity, 3d, 4x
---


# Question
Title: DirectX 11 generate normals for tessellated triangles
I've spent a couple days looking for an answer to this - How can I access the newly created triangles of tessellation and generate normals for them? I've followed much of the shader code from the following tutorial: http://www.richardssoftware.net/2013/09/bump-and-displacement-mapping-with.html

I would like to use these normals so that I can correctly light the new triangles as part of my displacement mapping implementation. Can this be done? My other idea was to use bump mapping as well as displacement mapping in order to get the correct normals and bi/tangents. Would this be overkill? Would it look right?

Any advice would be greatly appreciated.

Thank you

# Answer
> 0 votes
So after some further testing and research it is true that I am accessing the normals for the newly generated triangles - they are simply the same as the input normals because you need to calculate the new ones yourself. I was able to successfully produce correct normals for my tessellated mesh by passing a matching normal map (pre generated from the displacement heightmap) into my pixel shader and directly sampling the normals from there.

---
Tags: c++, directx11, tessellation
---


title: RaycastHit.point to local coordinates

text:
# Question
Title: RaycastHit.point to local coordinates
I'm trying to detect where approximately an enemy in my game has been hit. I have added a box collider with a height of 1.8 metres to the enemy.

When the player then shoots, I use a RaycastHit to check if the enemy has been hit. This works fine.

My code is this:

```
GameObject nHit = _LaserScript.hit.collider.gameObject;

if (nHit != null)
{
    Vector3 nHP = _LaserScript.hit.point; //"hit" is a RaycastHit
    Debug.Log("hit at x: " + nHP.x.ToString() + ", y: " + nHP.y.ToString() + ", z: " + nHP.z.ToString() + "\n");
}

```

I can relatively easy determine if the enemy has been hit at the head by checking

```
if (nHP.y > 1.5f)
{
    //headshot detected
}

```

However, I'm not sure if these coords have to be converted to "local" coordinates.

I tried to determine if I shot the enemy at the left side of his body or on the right side.

To my surprise, the "x" coord of the raycast was always around 1.2, and I have no idea why. I was expecting the x value of the hit to be somewhat between 0 and 0.5f as the collider is not wider than 0.5f.

Basically, I would like a hit at the left "border" of the enemy to have an x value between 0 and 0.1f.

Do I have to convert these hit coordinates (of which the docs say they're world coords) to "local" coords?

# Answer
Yes, as you found in the docs, raycast hits (as with most physics-related points) are specified in world space coordinates — ie. the coordinate system of your whole scene.

If you want to convert them to the local coordinate space of a particular transform, you'll want to run them through:

```
Vector3 localHit = transform.InverseTransformPoint(hit.point);

```
> 4 votes

---
Tags: unity
---


# Question
Title: Sending a shot left/right/up/down based on directional key press
I am trying to make a top-down shooter game with similar combat to the Binding of Isaac:

* when I press the up key the shot goes up
* when I press the right key the shot goes to the right

I have all the rest of the code such as the point where the projectile is instantiating and the if statement to check for the button press I just want to know where I should put the vector 2 to allow me to set the direction and what to write into the vector 2

```
private void Update()
{

    if (Input.GetKeyDown("up"))
    {
        if (Time.time >= shotTime)

        {
            Instantiate(projectile, shotPoint);
            shotTime = Time.time + timeBetweenShots;

        }
    }

}

```

This is my Projectile script (at least the parts that I think would be useful)

```
void Update()
{
    transform.Translate(Vector2.up * speed * Time.deltaTime);
}

```

I realized that if I change the `Vector2.up` to make it say `Vector2.down` it would now shoot down But I need that to be able to change depending on which direction I am shooting.

# Answer
> 2 votes
First, if you don't always want every projectile to move up, you should make the shot direction a variable:

```
public class Projectile : MonoBehaviour {
    public Vector2 direction;
    public float speed;

    void Update() {
        transform.Translate(direction * speed * Time.deltaTime);
    }
}

```

Then you can make a firing method to spawn a projectile going in a particular direction:

```
// Assign this in the Inspector to hold your projectile instance.
public Projectile projectilePrefab;

void Shoot(Vector2 direction) {
    Projectile shot = Instantiate<Projectile>(projectilePrefab, shotPoint);
    shot.direction = direction;
    shotTime = Time.time + timeBetweenShots;
}

```

This lets us simplify the firing routine to something like...

```
void Update() {

    // This is called a guard clause. By flipping our condition and exiting early,
    // we don't have as many nested levels of if indenting, making it easier to read.
    if(Time.time < shotTime)
       return;

    if (Input.GetKeyDown("Up")) {
       Shoot(Vector2.up);
    }
    else if (Input.GetKeyDown("Right)) {
       Shoot(Vector2.right);
    }
    else if (Input.GetKeyDown("Down)) {
       Shoot(Vector2.down);
    }
    else if (Input.GetKeyDown("Left)) {
       Shoot(Vector2.left);
    }
}

```

The `else if` clauses here ensure we only fire one shot in cases when two keys were pressed in the same frame, giving priority clockwise from "up". Note how packaging up the shooting work into the `Shoot` method keeps this concise and avoids duplicating code.

---

Longer term, I'd advise not moving your projectile shot yourself in `Update` but instead using a `Rigidbody2D` component on your bullet and setting its speed & direction via the body's `velocity` property. This keeps the movement of the projectile under the control of the physics system, helping you get more consistent behaviour (and sometimes better performance).

# Answer
> 0 votes
It is really hard to understand what exactly you want.

If you want a local `Vector2` you can use to translate to north west east south:

```
Vector2 direction = Vector2.zero;

void Update()
{
    bool up = Input.GetKey(KeyCode.UpArrow);
    bool down = Input.GetKey(KeyCode.DownArrow);
    bool left = Input.GetKey(KeyCode.LeftArrow);
    bool right = Input.GetKey(KeyCode.RightArrow);

    if(up) direction = Vector2.up;
    else if(left) direction = Vector2.left;
    else if(right) direction = Vector2.right;
    else if(down) direction = Vector2.down;
    else direction = Vector2.zero;

    if(direction != Vector2.zero)
        transform.Translate(direction * speed * Time.deltaTime);
}

```

Keep in mind that multiple keys can be pressed at once and this doesn't account for that and although the displayed logic works, the behaviour is weird, so you need to build your input logic around what you need for game! It is meant only as a display.

---
Tags: unity, c#, 2d, vector
---


# Question
Title: How can I disable Unity's default cursor functionality?
Not too sure how to ask this, I'll try my best.

Currently, I'm working on a First-Person Controller. I'm adding functionality for a pause menu so that when you press escape, it will open the pause menu, unlock the cursor, and make it visible. If you press escape again, while the pause menu is open, it will do the opposite: hide the cursor and lock it again.

The problem I'm running into is that Unity already kind of does this. It doesn't matter if you're in the editor or if your game is built: whenever you press escape, it will unlock the cursor and show it, so you can exit the game (in a built application) or get out of play mode (in the editor).

I'm 99% sure this is Unity's default functionality. I have looked in Unity itself and haven't found a way to turn it off, and I have also looked online. Any help would be greatly appreciated.

# Answer
If you are using Unity's FPSController then this post might have the solution https://forum.unity.com/threads/how-to-disable-escape-key-to-unlock-the-cursor-fix.511674/

If the forum post does not solve your problem, the error probably lies in your own escape code triggering twice (or fails to set the correct value). Edit: in that case please provide your code.

According to the documentation https://docs.unity3d.com/ScriptReference/Cursor-lockState.html the unlock on escape should only happen in editor.
> 2 votes

# Answer
This seems to be a problem related to the code in Unity's standard assets: In order to lock the cursor, you would set the `CursorLockMode` to `Locked`;

Your `FPSController` script (or whatever script is attached to your player) is checking wheather the "escape" key is pressed and setting the cursor mode to `None` by doing:

```
if(Input.GetKey(KeyCode.Escape))
    Cursor.lockState = CursorLockMode.None; // free the cursor

```

Contrarily, when pressing the left mouse button (also known as "mouse button 0"), it's setting the cursor state to locked:

```
if(Input.GetMouseButtonDown(0))
    Cursor.lockState = CursorLockMode.Locked; // lock the cursor

```

If you don't want this code to be managed within the fps controller (which i assume you don't, given the situation), you just need to remove the bit of code where the cursor `lockState` gets changed from the `FPSController` script;

This obviously also applies if you are not using the standard assets.
This is not Unity's standard behavior, so i suggest you look for any eventual script that might be modifying the cursor `lockState`.
> 0 votes

---
Tags: unity
---


title: Bulk level when user gets bulk exp

text:
# Question
Title: Bulk level when user gets bulk exp
I've been working with this for the entire week now, this is about a leveling system of my application. When a user gets the enough exp needed, it gets leveled up, everything works fine. But, when a user gets a bulk exp, it won't get a bulk level as well. The default for exp needed for every user is 1000. For example:

The user gets 1000 exp, for level 1, it gets leveled up to level 2. It works fine that way, but if it gets more than the exp needed the flow won't work the same way. Because the exp needed for level 2, is 1400. So the algorithm for this if the user gets enough or more than the exp needed, the current exp\_needed for the next level is multiplied by 1.4.

```
if($user->level <= 19){
   while($user->curr_exp >= $user->exp_needed){
   $user->level += 1;
   $user->curr_exp -= $user->exp_needed;
   $user->prev_exp = $user->exp_needed;
   $user->exp_needed = $user->prev_exp * 1.4;
   $user->save();
  }
}
elseif($user->level >= 20){
 while($user->curr_exp >= $user->exp_needed){
 $user->level += 1;
 $user->curr_exp -= $user->exp_needed;
 $user->prev_exp = $user->exp_needed;
 $user->exp_needed = $user->prev_exp * 1.1;
 $user->save();
 }
}

```

Edit : The levels 1-20 and their exp\_needed is working fine now, but when I'm at Level 21, I'm having troubles with the exp, because the exp\_needed at level 21 should only be multiplied by 1.1,

For example,

Scenario 1: The User will earn a curr\_exp(current exp) of 2,100,000 the user will jump on to level 21 with an experience of 836,6825.55 which is wrong because the exp\_needed at level 21 should be the sum of the prev\_exp(level 20 = 597,630.40) multiplied by 1.1 which will be

(prev\_exp of level 20) 597,630.40 * 1.1 = 657,393.44

Scenario 2:

The user gets an exp of 2,000,000 it will be on the level 20 with an exp of 508,424.01 with an exp\_needed of 597,630.40 and when it gets another exp of 100,000 the user will be leveled up to 21 with an exp\_needed of 657,393.44 which is correct.

So to summarize each scenarios results:

Scenario 1:

```
Level 21
Exp:10,793.61
Previous Exp: 597,630.44
Exp Needed for the next level: 836,682.55

```

Scenario 2:

```
Level 21
Exp: 10,793.61
Previous Exp: 597,630.40
Exp needed for the next level: 657,393.44

```

Scenario 2 should be the results I am seeking for but it doesn't work that way on my while loop. Any ideas how to deal with this? Thank you.

# Answer
> 4 votes
It's usually as simple as

```
while (expReceived > expNeededForNextLevel) {
    expReceived -= expNeededForNextLevel
    levelup()
}

```

---
Tags: algorithm
---


# Question
Title: Pygame Error AttributeError: 'pygame.Surface' object has no attribute 'add_internal'
I'm making my first game of Pygame. I'm going to create groups for making collisions but when I add an object to the group, I get an error in sprite.py (Pygame's Files)

```
AttributeError: 'pygame.Surface' object has no attribute 'add_internal'

```

Why I get this error?
There is a simplest way to make collisions?

There is my code:

```
import pygame
from pygame.locals import *
import sys
import os
import time
width = 950
height = 500
Game = False
GameOver = False
keyboard = pygame.key.get_pressed()[K_UP]
def main():
    pygame.init()
    screen = pygame.display.set_mode((width, height))
    pygame.display.set_caption('Flappy Dog')
    background = pygame.image.load(os.path.join("Images", "Background_00.png")).convert()
    FlappyDog = pygame.image.load(os.path.join("Images", "Flappy.png")).convert_alpha()
    Play = pygame.image.load(os.path.join("Images", "Play.png")).convert_alpha()
    Dog0 = pygame.image.load(os.path.join("Images", "Dog0.png")).convert_alpha()
    Dog1 = pygame.image.load(os.path.join("Images", "Dog1.png")).convert_alpha()
    SpikeUp0 = pygame.image.load(os.path.join("Images", "SpikeUp0.png")).convert_alpha()
    SpikeUp1 = pygame.image.load(os.path.join("Images", "SpikeUp1.png")).convert_alpha()
    SpikeDown0 = pygame.image.load(os.path.join("Images", "SpikeDown0.png")).convert_alpha()
    SpikeDown1 = pygame.image.load(os.path.join("Images", "SpikeDown1.png")).convert_alpha()
    GameOver = pygame.image.load(os.path.join("Images", "Game-Over.png")).convert_alpha()
    Replay = pygame.image.load(os.path.join("Images", "Replay.png")).convert_alpha()
    Bone = pygame.image.load(os.path.join("Images", "Bone.png")).convert_alpha()

    Game = True
    Dog1_pos_x = 100
    Dog1_pos_y = 100
    screen.blit(background, (0, 0))
    screen.blit(FlappyDog, (0, 0))
    screen.blit(Bone, (550, 100))
    screen.blit(Play, (600, 350))
    screen.blit(Dog0, (5, 240))
    bones = pygame.sprite.Group()
    bones.add(Bone) # <-- Error here
    Dog = pygame.sprite.Group()
    Dog.add(Dog1)
    pygame.display.update()

    while True:
        if GameOver == true:
            screen.blit(background, (0, 0))
            screen.blit(GameOver, (20, 50))
        if pygame.sprite.gropucollide(Dog, Bones, True, True):
            Game = False
            GameOver = True
        while Game == True:
            pygame.event.pump()
            if pygame.key.get_pressed()[K_UP]:
                for i in range(10): # Up
                    Dog1_pos_y = Dog1_pos_y -1
                    screen.blit(background, (0, 0))
                    screen.blit(Dog1, (Dog1_pos_x, Dog1_pos_y))
                    screen.blit(SpikeDown0, (0, 436))
                    screen.blit(SpikeUp0, (0, 0))
                    pygame.display.update()
                    pygame.time.delay(1)
            else: # Down
                Dog1_pos_y = Dog1_pos_y +1
                screen.blit(background, (0, 0))
                screen.blit(Dog1, (Dog1_pos_x, Dog1_pos_y))
                screen.blit(SpikeDown0, (0, 436))
                screen.blit(SpikeUp0, (0, 0))
                pygame.display.update()
                pygame.time.delay(1)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                pygame.display.update()

if __name__ == "__main__":
    main()

```

# Answer
> 0 votes
Programming languages like Python have types, which determine what you can do with which piece of data. Using each variable in a way that's appropriate to its type is like putting a round peg in a round hole, or a square peg into a square hole.

When you try to do an operation that expects one type, but you give it a different, incompatible type, that's trying to shove a square peg into a round hole. The computer won't be able to make sense of the operation and it will throw an error.

That's what you have happening here. `bones = pygame.sprite.Group()` tells the computer "`bones` is a group that holds `Sprite` objects" (ie. it's a round hole to put round pegs into)

`Bone = pygame.image.load(os.path.join("Images", "Bone.png")).convert_alpha()` tells the computer "`Bone` is a `Surface` object loaded from an image like so..." (ie. it's a square peg to put into a square hole)

`bones.add(Bone)` says "take that square peg (`Surface`) and shove it into that round hole (group of `Sprite` objects)"

So the computer errors-out and tells you that the `Bone` variable's type, `pygame.Surface`, does not have the shape that the `bones` variable's type, `pygame.sprite.Group` needs for its `add` method. It wants a `Sprite` that has an `add_internal` attribute, but you gave it a `Surface` which doesn't have that attribute.

> AttributeError: 'pygame.Surface' object has no attribute 'add\_internal'

So, first you need to make `Sprite` objects from the `Surface` objects you loaded from your images - think of it like an adapter to turn the square peg into a round peg - like so:

```
boneSprite = pygame.sprite.Sprite()
boneSprite.image = Bone
boneSprite.rect = Bone.get_rect()

```

Now that you have a `Sprite` that uses the `Bone` image, you can add it to your group like so:

```
bones.add(boneSprite)

```

This will not generate errors, because we're putting a round peg into a round hole now.

As described in the comments, this is all explained in existing answers, so please take the time to search for existing documentation and read it thoroughly to solve your problems faster in future.

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


# Question
Title: Why the lockState of the doors is all the time false even if in the editor I set one of them to true?
In the DoorsLockManager in the class DoorClass I changed in the editor one of the lockState to true but when running the game they are all change to false including the one I tried to set to true. Not sure why if I set it to true it's changing back to false.

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

[ExecuteInEditMode]
public class DoorsLockManager : MonoBehaviour
{
    [System.Serializable]
    public class DoorClass
    {
        public bool lockState;
    }

    public DoorClass[] doorclass;

    private List<HoriDoorManager> Doors = new List<HoriDoorManager>();

    private void Start()
    {
        var doors = GameObject.FindGameObjectsWithTag("Door");
        doorclass = new DoorClass[doors.Length];

        for (int i = 0; i < doors.Length; i++)
        {
            Doors.Add(doors[i].GetComponent<HoriDoorManager>());
            doorclass[i] = new DoorClass();
            Doors[i].doorLockState = doorclass[i].lockState;        }
    }
}

```

And the HoriDoorManager script:

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

public class HoriDoorManager : MonoBehaviour
{
    public List<DoorHori> doors = new List<DoorHori>();
    public bool doorLockState;

    private void Awake()
    {
        if (transform.parent != null)
        {
            Transform parent = transform.parent;
            var children = parent.GetComponentsInChildren<Transform>();

            if (children != null)
            {
                foreach (Transform door in children)
                {
                    if (door.name == "Door_Left" || door.name == "Door_Right")
                        doors.Add(door.GetComponent<DoorHori>());
                }
            }
            ColorDoors(Color.red, Color.green, doorLockState);
        }
    }

    void OnTriggerEnter()
    {
        if (doorLockState == false)
        {
            if (doors != null)
            {
               for(int i =0; i < doors.Count; i++)
                {
                    doors[i].OpenDoor();
                }
            }
        }
    }

    private void ColorDoors(Color red, Color green, bool state)
    {
        List<Transform> children = new List<Transform>();

        for (int i = 0; i < doors.Count; i++)
        {
            foreach (Transform child in doors[i].GetComponentsInChildren<Transform>())
            {
                if (child == doors[i].transform)
                    continue;

                var renderer = child.GetComponent<Renderer>();
                renderer.material.shader = Shader.Find("Unlit/ShieldFX");

                if(state == true)
                {
                    renderer.material.SetColor("_MainColor", red);
                }
                else
                {
                    renderer.material.SetColor("_MainColor", green);
                }
            }
        }
    }

    public bool GetLockState
    {
        get { return doorLockState; }
        set { doorLockState = value; }
    }
}

```

# Answer
> 3 votes
```
doorclass = new DoorClass[doors.Length];

```

This line throws out any lock state information you might have previously had and creates a new array from scratch. So if your plan was to use data you'd authored in the inspector at edit time, you've just lost it.

```
doorclass[i] = new DoorClass();

```

This line creates a new instance of the `DoorClass` type, with default values. The default value of a `bool` is false. So the value of `lockState` on this instance is always false,

Your next line then applies this always-false value to the i-th door:

```
Doors[i].doorLockState = doorclass[i].lockState;

```

Booleans are a value type, which means when you do this, you're copying the false value from `doorclass[i].lockState` to `Doors[i].doorLockState`, not creating a reference from the door to the bool in your array.

Since you never check `doorclass[i].lockState` again, changing this value in the inspector later won't change the door's behaviour. It still has its own copy of the false value and knows nothing about the `DoorClass` instance you created for it.

I'm not sure what to tell you about how to fix this, because it's unclear how you expected this to work.

If you meant to author these lock values ahead of time in the Inspector, then you should remove the lines that create a new `DoorClass[]` array and default instances in `Start()`, as that throws away anything you wrote at edit time. However, this is a brittle method with no real control over order, and it would be easy for the collection of doors & lock bools to get out of sync and cause errors like an index out of range.

If you meant to populate these lock values procedurally as your level is generated at runtime, then that procedural logic to determine true or false lock states should run before you assign the lock values to the doors, rather than using the default false for all of them.

If you meant to use this collection of bools as a control panel to later change the states of the doors after `Start()` has run, then you need some code to fire when the i-th door's lock bool has changed and relay that state change to the i-th door. You'd do that differently if you need it to work for editor interaction via the Inspector (which seems to be suggested by the fact you made this array public), versus via code (which I'd assume you'd want to do for systemic gameplay, but I don't see evidence of it in your current sample), so again it's unclear from the current question what solution is appropriate for your needs here.

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


# Question
Title: Play a sound on button click before loading the load scene in Unity3D
I am trying to play the sound of the button click before loading the scene in unity. However, the sound is never played. Below is my code, help would be appreciated.

```
public void RestartGame()
{
    audioManager.PlaySound(forwardSound);
    StartCoroutine(DelaySceneLoad("Gameplay"));
}

IEnumerator DelaySceneLoad(string scene)
{
    yield return new WaitForSeconds(forwardSound.length);
    GameTracker.SetGameOver(false);
    SceneManager.LoadScene(scene);
}

```

# Answer
`SceneManager.LoadSceneAsync()` might be of interest to you, it lets you do lots of cool things such as loading screens and more before a scene completes loading and changes.

Instead of waiting for the length of your audio clip (which might not be loaded and played completely from memory in time), try checking to see if the `AudioSource` its attached to `isPlaying` and load the scene when it sets to `false`.
> 2 votes

---
Tags: unity, c#, sound, sound-effects
---