# Question
Title: How do I calculate the angle of the slope at a point on a 2D bitmap terrain?
I have an arbitrary destructible bitmap terrain like the one in "Worms". It's easy to work out if a character or missile intersects the terrain, but how do I work out the angle of the slope at the contact point, so I can make grenades roll down hills, bounce off at the right angle, etc. I know it can be down by somehow taking a sample of points around the impact point and seeing which ones intersect, but I'm not sure exactly how to go about it, and in an efficient way.

# Answer
If you're happy sampling then run a coarse sample at a defined radius around your hit point. 16 samples in a circle will provide you with quite accurate curvature. If you add up all the vectors that "missed", you'll have a vector that can be normalised to a surface normal.

If you hit the flat floor, all the vectors will miss if they're pointing up at all, so they add up to an up vector. If you hit a 45 degree slope, the vectors that point away from the slope will miss and add up to a 45 degree vector away from the slope. Even a rough surface will provide a reasonable surface normal as you're checking for "misses" not a surface.

This works fine until you get into really tight spaces, at which point, curvature is all shot to crap anyway, and you would probably not get a sensible result in any technique other than precomputed surface normals (which can be found by blurring a "vector to closest feature" map where feature is non colliding / non matter).

so:

```
Vec collisionPoint # point of collision
Vec acc(0,0)
for f = 0 to 2pi:
 vec check = vec( sin( f ), cos( f ) )
 if ( check + collisionPoint ).collides():
  acc += check
normal = acc.normalise() # yes, there is a chance of a divide by zero.

```
> 7 votes

# Answer
You need two points to calculate it. The slope is then the coefficient of the line passing for the two points, i.e.:

```
m = ( y2 - y1 ) / ( x2 - x1 )

```

To get it in form of an angle use the `arctan(m)` function.
> 2 votes

# Answer
If you want to go crazy, you could take a grid of samples around your test-point, do an edge-detection algorithm to identify the surface (i.e. any point part of the terrain with a neighbour which isn't, or vice-versa, is a surface point), and then find the best-fit line through those points to use as an approximation to the surface.

Might be overkill though :)
> 1 votes

# Answer
The original Worms probably didn't do anything more complex than bitmap/bitmap intersections - i.e. does the bitmap of the grenade intersect with the collision map of the world. Moving the grenade (or whatever) would follow these steps:

1. Can the object move down one pixel without a collision? If so, move object down one pixel and end test.
2. Can the object move left and down without a collision? If so, move object down and left one pixel and end test.
3. Can the object move right and down without a collision? If so, move object down and right one pixel and end test.
4. If object moved left and down (2) last time, can object move left one pixel? If so, move object left one pixel and end test.
5. If object moved right and down (3) last time, can object move left one pixel? If so, move object right one pixel and end test.

You probably only want to do (4) and (5) for a few frame to simulate friction, e.g. repeat (4) for each preceding (2).
> 1 votes

# Answer
Late reply but I was looking for something similar and found an algorithm that works pretty well :

Take a bunch of samples around your test point (in my case I get all points that are below a given radius). Calculate the average position of all points that are inside collider (black) in this case and the average position of all points that are outside collider (white).

At the end, you got two points. From there you can calculate a vector, normalize it and your get your surface normal.

Some pseudo-code:

```
vec collisionpoint, pa(0, 0), pb(0, 0)
counta = 0, countb = 0

for y = 0 to r:
for x = 0 to r:
    vec offset(x, y)
    if offset.sqrMagnitude < (r * r):
        if (collisionpoint + offset).collides():
            pa += offset
            counta++
        else:
            pb += offset
            countb++

if counta > 0: pa /= counta
if countb > 0: pb /= countb
normal = (pb - pa).normalized

```
> 0 votes

---
Tags: 2d, collision-detection
---


# Question
Title: How do I step into my code when automatic Pause mode in Unity occurs?
In my scripts, I have several "Debug.Break();".

I use them to halt the execution of the script when unexpected situations occur, for example like here:

```
 if (condition == 1)
 {
    DoThis();
 }
 else if (condition == 2)
 {
    DoThat();
 }
 else
 {
     //this should not happen! Check what goes on here
     Debug.Break();
 }

```

When my game hits such a "Debug.Break()", the gameplay is automatically paused.

It looks like this:

Ideally, I would have the Debugger attached, and I would have a breakpoint set, then Visual Studio would show me exactely where it stopped.

It would look like this:

However, I don't have breakpoints at all Debug.Break(); and sometimes I do not even have the Debugger attached to Unity.

It would look like that:

How could I anyways still step into the line where Unity halted? I would like to see where exactely Unity halted, but I don't see how.

Do I always have to have breakpoints set and the Debugger attached? Or could I still attach the debugger later and still step into where the script halted?

The reason why I don't have the Debugger attached at all time is that I frequently change the scripts, then I need to save it and detach and re-attach the Debugger. This is too time-taking.

I am using Visual Studio Community Edition.

# Answer
> 1 votes
> How could I anyways still step into the line where Unity halted? I would like to see where exactely Unity halted, but I don't see how.
>
> Do I always have to have breakpoints set and the Debugger attached?

Yes.

> The reason why I don't have the Debugger attached at all time is that I frequently change the scripts, then I need to save it and detach and re-attach the Debugger.

You should not need to detach and re-attach the debugger each time you make a change to a script. If the debugger is detaching itself, then you should try updating to the latest versions of Unity and Visual Studio. If you're manually detaching the debugger, just stop doing that.

# Answer
> 1 votes
*This answer is for the original question; the asker completely rewrote the question into a new question.*

`Debug.Break()` is useful if you need to look at what's going on in a scene at a specific point in time. Some example use cases:

* An character occasionally walks through a wall. When this happens, you want to pause the editor to check the character's speed, waypoints, and current animation.
* You have a coroutine which checks every 30 seconds for characters that are stuck and moves them until they're un-stuck. You want to see the before-and-after, so you set a `Debug.Break()` to pause the engine when 30 seconds have gone by and the coroutine is about to un-stick the characters.
* `OnCollisionEnter()` is occasionally getting called when you don't expect it, so you use `Debug.Break()` to pause the engine when a collision occurs so you can see what's causing the collision.

Any time that you need to pause the engine to examine the scene, but it's difficult or impossible to manually hit the pause button at exactly the right time, use `Debug.Break()`.

# Answer
> 0 votes
If you look at `Debug.log()` in the official docs, it takes `context` as its second parameter, you can pass your `Gameobject` in that to know which object is calling the debug statement then call your `Debug.break()` to pause the scene.

> ```
> Debug.log("myMessage",myGameObject);
>
> Debug.break();
>
> ```

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


# Question
Title: How to detect when a shot hits the opponent from behind?
I'm making a game where the enemy can turn on its own axis in 360 degrees (top view game).

The player-controlled character has a bow. With this bow he shoots and deals damage when he hits the enemy.

I would like that when the arrow shot from the bow hits the enemy's back he would take double the damage.

I tried to make a system using arrow and enemy angles, but that system doesn't cover all cases.

**Code:**

```
if((image_angle-other.image_angle>280 && image_angle-other.image_angle<360) || (image_angle-other.image_angle<80 && image_angle-other.image_angle>0)){
    other.life-=damage*2;
}else{
    other.life-=damage;
}

```

**Image of one of the inconsistencies that happen:**

If the game's view was from the side, you could even use something using the angle the way I did, but as it's from above and the shot can come out at any angle and the enemy can be at any angle I couldn't think of anything.

In fact I even thought. Create an object that sticks to the enemy's back and is not visible to the player. Each detector object would have an enemy as its owner. If the arrow collides with that object, it would make the owning enemy suffer double damage.

However in the game there are arrows that go through enemies, so the arrows would end up hitting the detector object as well. I would have to make a way for the arrow to leave a mark on the enemy so that it doesn't take normal damage and then double damage (by colliding with the enemy and then with the detector object respectively).

Not to mention that from my knowledge I already knew that this alternative by itself is no longer ideal because it is not optimized, even if there was no double collision problem.

# Answer
> 0 votes
**FrostyCat's answer (member of the GameMaker community):**

---

**First consider the important angles involved (given that this is the arrow's collision event with a player):**

* The back-facing direction for the player: `other.image_angle+180`
* Direction of hit from the player's perspective: `point_direction(other.x, other.y, x, y)`

**Then use angle\_difference instead of simple subtraction:**

```
if (abs(angle_difference(point_direction(other.x, other.y, x, y), other.image_angle+180)) <= 40) {
    other.life -= damage*2;
} else {
    other.life -= damage;
}

```

**Link:**

https://forum.yoyogames.com/index.php?threads/how-to-detect-when-a-shot-hits-the-opponent-from-behind.87965/#post-526778

---
Tags: collision-detection, game-maker
---


title: How to clip cut-off text in a textbox?

text:
# Question
Title: How to clip cut-off text in a textbox?
I'm writing a textbox class for my XNA game and I'm using SpriteFont to draw the text. It's only a single line textbox so when the text width exceeds the size of the rectangle box, it currently just keeps going.

In Windows textboxes extra text is cut off so that you may only see half a letter. I'd like to emulate this with my custom control. However, I see no overload with `SpriteBatch.DrawString` that would allow for anything that could cut off text that didn't fit within certain bounds.

Does anyone know of a method that would allow for this? I'm still quite new to the XNA API so I'm not sure what out there exists for this sort of thing.. Thanks

# Answer
The way I handled this in my simple textbox UI element was to use a scissor rectangle (as Nicol Bolas said while I was writing this :P).

Here's the basic idea:

1. First off, create a `RasterizerState` field in whatever class does the drawing of the text like so:

```
 RasterizerState _rasterizerState = new RasterizerState() { ScissorTestEnable = true };

```

You'll pass this to the spritebatch to tell it to use the `GraphicsDevice.ScissorRectangle`.

2. Then, your Draw method would go something like this:

```
 public void Draw(GameTime gameTime) {
     spriteBatch.Begin();
     //Draw other stuff
     spriteBatch.End();

     //Set up the spritebatch to draw using scissoring (for text cropping)
     spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend,
                       null, null, _rasterizerState);

     //Optional: Draw the border using a 1x1 white square texture that is
     //          stretched to fill a slightly larger rectangle behind the
     //          background (below).
     spriteBatch.Draw(_boxTexture, _borderRectangle, _borderColor);

     //Optional: Draw the background
     spriteBatch.Draw(_boxTexture, _textboxRectangle, _backColor);

     //Copy the current scissor rect so we can restore it after
     Rectangle currentRect = spriteBatch.GraphicsDevice.ScissorRectangle;

     //Set the current scissor rectangle
     spriteBatch.GraphicsDevice.ScissorRectangle = _textboxRectangle;

     //Draw the text at the top left of the scissor rectangle
     spriteBatch.DrawString(_font, _text, Vector2.Zero, _fontColor);

     //Reset scissor rectangle to the saved value
     spriteBatch.GraphicsDevice.ScissorRectangle = currentRect;

     //Draw more textboxes or whatever else using the scissor rectangles here

     //End the spritebatch
     spriteBatch.End();
 }

```

You can probably get away with not resetting the scissor rectangle for this basic situation, but you need to reset it if you want to draw other things (like those backgrounds). This example also assumed a lot of variables which you can infer (I hope :-) ) from their names.

A few other notes on the variables:

1. `_textboxRectangle` is the clipping rectangle to use. I pulled this from my textbox UI class which is where that and basically all other variables comes from.
2. `_borderRectangle` is just a rectangle that is a few pixels larger than `_textboxRectangle` so that when the background is drawn over top of it, it will appear as the border for the box. Pretty simple.

Hope this helps!
> 10 votes

# Answer
If you want to clip things to a certain region, you use the scissor box. It's a property of the `GraphicsDevice`: GraphicsDevice.ScissorTestEnable and either RenderState.ScissorRectangle pre-XNA 4.0 or RasterizerState.ScissorTestEnable in XNA 4.0.

You don't need to measure text for it; just set the scissor box to the area you want to clip to. You can draw all the text you want after that. Indeed, scissoring is useful in all kinds of places for GUIs.

Just don't forget to turn *off* scissoring when you're done.
> 4 votes

# Answer
What you need to do is use SpriteFont.MeasureString()

Loop through your string and check MeasureString(substring) to see when it exceeds your maximum width. Then use that substring to render.

Edit: Sorry didn't realize you wanted that precision.

What you want to use is a ScissorRectangle.

* Set GraphicsDevice.ScissorRectangle to the rect of your textbox.
* Set ScissorTestEnable to true in the RasterizerState
* Pass that RasterizerState to your SpriteBatch.Begin()
> 0 votes

# Answer
You need to use multiple render targets. You need to create an off-screen texture where you will draw the text-box area, then draw that to the main render target. Here's a post on the MSDN forum about this: http://social.msdn.microsoft.com/forums/en-US/xnaframework/thread/71263016-b26a-44bd-80f3-8cd620b119ff
> 0 votes

# Answer
You have to create a new `RasterizerState` to change its state:

```
RasterizerState rState = new RasterizerState()
{
    ScissorTestEnable = false,
};

GraphicsDevice.RasterizerState = rState;

```
> 0 votes

---
Tags: xna, c#, spritebatch, culling, text
---


# Question
Title: Stride 3d how to make move around the sphere? translating unity 3d code
I'm trying to move code from unity 3d to stride 3d but I have huge issues as IDE doesn't help me find words when I type as unity 3d does

the unity 3d code that works:

```
public Transform Planet; // to rotate to
void Update(){
    PlanetDirection = Planet.position - transform.position;
    planetDistance = MathFunctions.V3Distance(transform.position, Planet.position);
    Ray ray = new Ray(transform.position, PlanetDirection);
    RaycastHit hit;
    if (Planet.GetComponent<Collider>().Raycast(ray, out hit, planetDistance)  ){
        transform.rotation = Quaternion.LookRotation( Vector3.Cross(transform.right, hit.normal) , hit.normal);
    }
}

```

this is updated stride code:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Stride.Core.Mathematics;
using Stride.Input;
using Stride.Engine;
using Stride.Physics;

namespace example1{
    public class PlanetaryMovement : SyncScript{
        public Colliders PlanetCollider;
        public Entity Planet; // to rotate to
        //maybe I don't need so much only Simulation
        Stride.Physics.Simulation sim;
        Vector3 near = this.Entity.TransformComponent.position;
        Vector3 to = Planet.TransformComponent.position;
        //var result = sim.Raycast(vectorNear.XYZ(), vectorFar.XYZ());
        IList<HitResult> hit = new IList<HitResult>();
        CollisionFilterGroups filterGroup = CollisionFilterGroups.DefaultFilter;

        public override void Start(){
        }

        public override void Update(){
            sim.RaycastPenetrating(near, to, hit, filterGroup);

            PhysicsComponent col;
            for(int i=0; i< hit.Count; i++){
                if (PlanetCollider == hit[i].Collider){
                    this.Entity.Quaternion.Rotate(hit[i].Normal);
                }
            }
        }
    }
}

```

and the reference with witch I was trying to figure out how to translate my code

EDIT: -Updated the code errors that still exists:

```
[C:\programming\Stride 3D\example1\example1\Movement.cs(14,12)]: Error: The type or namespace name 'Colliders' could not be found (are you missing a using directive or an assembly reference?)

```

what I need is to link the HitResult with Planet somehow I don't know what to use to compare them.

Raycasting Simulation Simulation HitResult Physics quaternion

# Answer
> 0 votes
I think you just forgot to `using Stride.Physics;` and where `vector3 near` first letter must be upper like this `Vector3 near`. In the end you should using Visual Studio because it helps fix errors like these.

---
Tags: c#, stride
---


# Question
Title: How to create and assign tiles via script?
I am trying to make some kind of tileset texture replacer using an editor window.

First, I try to save all tile and texture names in let say "scenename.ctss" (ctss stand for "custom tilemap save system"), and then load but with different textures. ut

The problem is that I can't find anywhere on the internet on how we can create a `TileBase` instance, and then apply texture to it.

I was expecting creating `TileBase` would be as simple as this line of code:

```
TileBase tileBase = new TileBase();

```

but i get this error message:

> CS0144: Cannot create an instance of the abstract type or interface 'TileBase'

Is there a way so that we can create our own custom `TileBase` in Unity?

# Answer
> 0 votes
What this error message is telling you is that `TileBase` is an `abstract` class. It's just the foundation ("Base") to use when building custom tile classes that you might want to instantiate. But you can't instantiate the base itself — it's incomplete on its own.

A concrete implementation of the `TileBase` is given by the `Tile` class, which you can create as:

```
Tile myTile = Tile.CreateInstance<Tile>();

```

The `Tile` class inherits from `TileBase`, so it can be used as an argument anywhere a function parameter asks for a `TileBase`. `Tile` is just a specialized flavour of `TileBase` (and a fairly general-purpose one that's fit for the most common use cases).

So for example, assigning this tile to a specific spot on your tilemap could be accomplished by:

```
tilemap.SetTile(position, myTile);

```

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


# Question
Title: In a multi-player game where one player becomes invisible, is the data about the invisible player sent to the enemy game clients?
In my 3d FPS game, there is a feature where a player could have it's character become invisible for some time. The character is only invisible, they're still *there* and can move around: the other players can try predict where they are and shoot them, and if they succeed the invisible character becomes visible again.

I'm worried about cheaters using aim bots and I'm wondering how I should handle the invisible characters in this context.

# Answer
> 1 votes
As much as you can, you should not send the data that a player does not need to play the game, for two reasons: bandwidth reduction and cheat prevention.

This means that if a character in the game world becomes invisible, the server should send the information to the clients that the character is no longer part of the game world. When the character becomes visible again, the server should send information about what character to create and where to place in the game world.

This *could* be a bit hard to implement depending on the architecture of the game client and the server (e.g. if games are created with all the characters at the start of the game session, and it's difficult for the client to create a new character after the start), then sure, a flag could be sent to the clients telling them that the character is now invisible and should not show it. The server should probably also send "fake" coordinates along this flag to help prevent cheat.

---

Is not sending information about where the invisible characters are enough to completely prevent cheating using aim bots? I don't think it is. Not sending the data could *help* preventing aim bots tracking invisible characters, but if there is enough money to be made, someone could develop a "more advanced" bot that "thinks like a human" and predicts the coordinates of the invisible characters. If you can figure out that Character A is traveling at X m/s in direction Y, and you can figure out that in 3 seconds they'll be at about spot Z in the game world, then one could program their aim bot like this. (To be honest, I'm pretty sure this already exists.)

---
Tags: networking, multiplayer, anti-cheat
---


# Question
Title: Calculating view matrix from rotation, elevation and location
I have the rotation(`A`), elevation(`B`) and location(`C`) of a camera in a left handed 3d space. +x is right, +y is down and +z is inwards. Initially the camera is pointing in +z direction with up direction being -y. This camera is rotated by angle `B` along x axis, rotated by angle `A` along y axis and then translated by vector `C`.

How do I calculate the view matrix for such a camera?

# Answer
> 1 votes
You can compute your new right vector using the unit circle (assuming your angle `A` is measured in radians):

```
right.x = - cos(A)
right.y = 0
right.z = sin(A)

```

Here I've used a negative on the x component, because you said the camera is initially pointed in the +z direction. That would mean its "right" vector points in the world's "left" direction when angle `A` is zero.

We can use a similar trick for the forward and up vectors, using spherical coordinate formulas and a cross product:

```
forward.x = cos(B) * sin(A)
forward.y = sin(B)
forward.z = cos(B) * cos(A)

up = cross(forward, right)

```

Now a 3x3 matrix with (`right`, `up`, `forward`) as its columns will rotate an object by angles `A` and `B`.

Expand it to a 4x4 matrix and make the last column `(C.x, C.y, C.z, 1)` and now you have a complete local to world matrix, with both rotation and translation.

Invert this matrix to get a world to local matrix, to transform the worldspace positions of objects into the camera's view space.

---
Tags: mathematics, matrix, transformation, viewport
---


# Question
Title: Pygame having trouble with surface.blits method
I got used to blit every image into the screen on a seperate line in Pygame but now I want to start using the `pygame.Surface.blits()` method.

According to the documentation, it draws many images into another and it accepts a blit\_sequence parameter.

So here is what I've tried:

```
MyScreen.blits([img1, img2, img3], [(230, 598), (350, 598),(470, 598)])

```

This led to an error : TypeError: an integer is required (got type list)

I also tried this :

```
MyScreen.blits([img1, (230, 598)], [img2, (350, 598)], [img3, (470, 598)])

```

This made the terminal throw another TypeError: function takes at most 2 arguments (3 given)

I tried the same last example but with tuples but it didn't work.

## NOTE :

I've taken a look at this post in which a very similar problem was discussed and I realized that there's an issue with that method but that post is 2 years old until now, so aren't there any solutions ?

# Answer
> 1 votes
The documentation for `blits` says that the syntax is

> blits(blit\_sequence=(source, dest), ...), doreturn=1)

I am not sure if there is intentionally an opening parenthesis missing there, but it's easy to deduce that the required syntax is `blits(sequenceOfPairsOfSurfaceDestination)`, meaning that your second attempt is close, but missing the outer sequence, as you are simply trying to pass each of the elements of the sequence as parameter to the function.

So what you want is

```
surface.blits(((surface1, dest1), (surface2, dest2)))

```

Notice that we are only passing in one argument, which here is a tuple of tuples. If the amount of parentheses is confusing, feel free to break it up into separate variables until you can understand the individual elements.

---
Tags: pygame, screen, bit-blit
---


title: How To Separate Tilemaps (Unity)

text:
# Question
Title: How To Separate Tilemaps (Unity)
I am trying to separate unconnected contiguous areas in one tilemap into their own separate tilemaps.

# Answer
> 0 votes
thanks to @dmgregory for helping me help my idiot self.

```
public List<List<Vector3Int>> FindConnectedGroups(Tilemap world)
{
    var visited = new List<Vector3Int>();
    var dirs = new List<Vector3Int>{Vector3Int.up, Vector3Int.down, Vector3Int.left, Vector3Int.right};
    var groups = new List<List<Vector3Int>>();
    for (int x = world.cellBounds.xMin; x < world.cellBounds.xMax; x++)
    {
        for (int y = world.cellBounds.yMin; y < world.cellBounds.yMax; y++)
        {
            var group = new List<Vector3Int>();
            var visit = new List<Vector3Int>();
            var tile = new Vector3Int(x, y, 0);
            if (!visited.Contains(tile))
            {
                visit.Add(tile);
                for (int z = 0; z < visit.Count;z++)
                {
                    var t = visit[z];
                    if (!visited.Contains(t) && world.GetTile(t))
                    {
                        visited.Add(t);
                        group.Add(t);
                        foreach (var d in dirs)
                        {
                            if (!visited.Contains(t + d))
                            {
                                visit.Add(t + d);
                            }
                        }
                    }
                    else if(!world.GetTile(t))
                    {
                        visit.Remove(t);
                    }
                }
            }
            if (group.Count > 0)
            {
                groups.Add(group);
            }
        }
    }
    visited.Clear();
    return groups;

}

```

It's less elegant than it could be, but more functional then what I was trying before.

---
Tags: unity, tilemap
---


# Question
Title: How can I switch cameras by key press in late update?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchCameras : MonoBehaviour
{
    public List<Camera> cameras = new List<Camera>();

    private Vector3 originalPos;

    // Start is called before the first frame update
    void Start()
    {
        originalPos = transform.position;
    }

    // Update is called once per frame
    void Update()
    {

    }

    private void LateUpdate()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (cameras[0].enabled)
            {
                transform.position = new Vector3(transform.position.x,
                    transform.position.y - 0.7f, transform.position.z);

                cameras[1].enabled = false;
            }
            else
            {
                cameras[1].enabled = false;
            }
        }
    }
}

```

Because transform have animator component the positions and switching is working in the late update.

My problem is the cameras switching and the positions change of the transform logic in the late update when pressing the space key.

I want that each press on the space key will switch between the cameras. First in the awake or start I need somehow to find what camera is first enabled true and make the changes than in the late update with the space key.

# Answer
```
private void LateUpdate()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        if (cameras[0].enabled)
        {
            transform.position = new Vector3(transform.position.x,
                transform.position.y - 0.7f, transform.position.z);

            cameras[0].enabled = false;
            cameras[1].enabled = true; //<-----
        }
        else
        {
            cameras[0].enabled = true;  //<-----
            cameras[1].enabled = false;  //<-----
        }
    }
}

```

I have indicated the places where I made changes with `//<-----`. Usually I try to write an accompanying explanation but this is so straightforward I can't think of any explanation to add.
> 1 votes

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


# Question
Title: How does a game like slither.io handle collision?
This question can be generalized to "how does one efficiently determine if a collision has taken place between curvy lines"

On https://slither.io there are snakes that players play as that can grow in length and width as the player collects food.

Similar to the "snake" game, if you collide with any other snakes, you die, but how are these collisions determined?

My intuition was that each snake is just a long list of circles, and you just use an Octree or Spatial Hash of circle collisions, but even this seems like it could be too slow, considering some snakes can get *extremely* long, and I doubt that the solution is just to have a snake be 1,000 circles long.

So, how is this sort of collision detection done then? Do they go with the naïve circle approach, or is there a more efficient way of calculating collisions between arbitrarily shaped and sized curves?

# Answer
You are correct that circle collision is a good first approximation. I suggest you compare the square of the distance between the centers instead of the distance, so you can save a lot of square root computations.

The naive approach would have you check check each circle against each circle, for a total of  comparisons (where `n` is the number of circles). *And you can bring that number down by not checking against circles you have already checked, for a total of `n * (n + 1)/2` comparisons.*

However, you only care about the heads (and each snake only has one head). So you would have `n * s` comparisons (where `s` is the number of snakes). Which is better than `n * (n + 1)/2` given that `s ≪ n` (read: `s` is much less than `n`).

Yet, you are correct again in that you should use some space partitioning structure.

I'll suggest to use a hierarchical space partitioning structure - such a quad-tree - because a large snake could be bundled up in a small space. And with that you would have `s * log(n)` comparisons.

---

Alternatively, you could add snakes to the hierarchical space partitioning structure, instead of their individual circles.

You can register the snakes by their middle position. *Which is the center of one of the circles, if the number of circles is odd… Or it would be half way between two circles if the number of circles is even.*

That way you can query for nearby snakes, and you might be able to prune some snake-snake collision by checking if the distance from center to center of the snakes is greater than the sum of the halves of their lengths. If it is, there is no position those snakes can be that they would be able to touch each other.

So you would only have to worry about collisions between snakes that are close enough. *It is worth noting that in the game a snake does not collide with itself.*

You would have `s * log(s)` possible snake-snake collisions. *Which is potentially better than `s * log(n)` considering that `s ≪ n`. But that depends on how efficient we can make a snake-snake collision check.*

---

For each snake-snake collision check, starting back at the naive approach, you would need `p * q` comparisons (where `p` is the number of circles of a snake, and `q` is the number of circles of the other). For a total of `s * log(s) * p * q`.

However, again, we only care when the head of a snake runs into the other other snake. I'll refer to these as snake-head collisions. If you need both snake-head collisions checks, that brings us down to `p + q` comparisons. For a total of `s * log(s) * (p + q)`.

---

But we don't need both snake-head collisions checks! If the head of a small snake is nearby the body of a large one, it does not mean the head of the large one is nearby the body of the small one.

So, wait, rewind. Do not prune snake-snake collision. Prune snake-head collisions. For these prunes follow the same idea as before: check if the distance from the center of the head to the center of the other snake is greater than half the sum of the size of the head and the length of the snake.

And each snake-head collision check requires `l` comparisons (where `l` is the length of the snake). And of these we need at most double as before: `2 * s * log(s)`. For a total of `2 * s * log(s) * l` comparisons. *Which is good given that `l ≪ n`.*

---

I had the idea that a large snake is like two shorter snakes connected head to tail. So you could check if the head could be close enough to collide to each half. And so on, like a binary tree. However, note that the sides of the tree are not mutually exclusive. The head of the snake could be close enough to collide with both halves of the other snake.

Yet, it is a good idea to put the circles of a snake in a convenient structure. For example, if you divide the circles in quadrants, and you find in which quadrant the head is…

Yep, make a quad-tree - or similar hierarchical space partitioning structure - per snake. And use it to find circles of the snake that are nearby the head of the other snake. So you don't have to compare the head with all of them. That should bring the number of comparisons down to `log(l)` per snake-head collision check. For a total of `2 * s * log(s) * log(l)` comparisons.

---

This total of `2 * s * log(s) * log(l)` is better than `s * log(n)` as long as `s ≪ l`. That is, if you have few large snakes, this is better. If you have a ton of small snakes, then storing all the circles in a single hierarchical space partitioning structure is better.

I believe the boundary condition is very low. *I mean that the snakes will grow soon enough.* However, if in doubt, profile to find the boundary conditions. Once you know those conditions, you can even write code that decides which approach to use according to those conditions. *You might even decide per snake if it is short enough to store all its circles directly in the hierarchical space partitioning structure.*
> 1 votes

---
Tags: collision-detection, algorithm, performance
---


# Question
Title: Tangent Space Light Direction Incorrect?
I have normal mapping with a directional light in place. I noticed the lighting looks off but am unsure why it is happening. I believe it is related to the TBN matrix and possibly the handedness fix that is in place. Lighting is being converted into tangent space. The two images below compare the lighting with and without the handedness impacting the TBN matrix:

You can see the issues with the spartan, especially when looking at the abdomen/chest area.

Outputting the light direction also looks funky with and without handedness fix in place.

It appears that disabling the handedness fix for calculating the TBN matrix seems to almost fix the issue. However, you can see that I still get some funky lighting issues (looking at the underside of the visor).

* Vertex Shader

```
#version 330 core
// Vertex Shader
// Normal Mapping
// OGL4 Shader Language Cookbook Pg. 159

layout (location = 0) in vec3 vertex_position;
layout (location = 1) in vec3 vertex_normal;
layout (location = 2) in vec2 tex_coords;
layout (location = 3) in vec3 vertex_tangent;
layout (location = 4) in vec3 vertex_bittangent;

// ======== Structure Definitions =========
struct LightInfo {
    vec4 light_in_world;
};

// ============ Global Uniforms ============
layout (std140) uniform uniform_matrices {
    mat4 projection_matrix;
    mat4 view_matrix;
};

// ============ Shader Uniforms ============
uniform mat4 model_matrix;
uniform mat3 normal_matrix;
uniform LightInfo light_info;

// =============== Output ==================
out vec3 vector_towards_viewer_tangent;
out vec3 light_direction_from_surface_to_lightsource_tangent;
out vec2 frag_tex_coords;

// ========= Function Prototypes ==========
mat3 get_tbn_matrix(vec3 vertex_tangent, vec3 vertex_bittangent, vec3 vertex_normal);
vec3 get_light_direction_eye(vec3 vertex_position_eye_space);

// ================== Main =================
void main(){

    vec3 vertex_position_eye = (view_matrix * model_matrix * vec4(vertex_position, 1.0)).xyz;
    vec3 light_direction_eye = get_light_direction_eye(vertex_position_eye);

    // TBN Matrix (View/eye space to tangent space)
    mat3 TBN = get_tbn_matrix(vertex_tangent, vertex_bittangent, vertex_normal);

    // Output
    light_direction_from_surface_to_lightsource_tangent = TBN * light_direction_eye;
    vector_towards_viewer_tangent = TBN * normalize(-vertex_position_eye);
    frag_tex_coords = tex_coords;

    // Convert vertex position to clip space for fragment shader
    gl_Position = projection_matrix * view_matrix * model_matrix * vec4(vertex_position, 1.0);
}

// ========= Function Definitions ===========

mat3 get_tbn_matrix(vec3 vertex_tangent, vec3 vertex_bittangent, vec3 vertex_normal){

    // Convert vertex normal and vertex tangent to eye space
    vec3 vertex_tangent_eye_T = normalize(normal_matrix * vertex_tangent);
    vec3 vertex_normal_eye_N = normalize(normal_matrix * vertex_normal);
    vec3 vertex_bitangent_eye_B = normalize(normal_matrix * vertex_bittangent);

    // Matrix for converting from tangent space to view space
    mat3 TBN = mat3(vertex_tangent_eye_T, vertex_bitangent_eye_B, vertex_normal_eye_N);

    // Matrix for converting from view space to tangent space (inverse); In this case the transpose works
    // because the TBN matrix is orthogonal (so its the same as doing the inverse but faster)
    TBN =  transpose(TBN);
    return TBN;
}

vec3 get_light_direction_eye(vec3 vertex_position_eye_space){

    // Convert light to eye space
    vec3 light_in_world_eye = vec3(view_matrix * light_info.light_in_world);

    // Determine if light_position_in_world is a positional light or directional light
    vec3 light_direction_from_surface_to_lightsource = vec3(0.0f);
    if(light_info.light_in_world.w == 0.0f){
        // Directional light from object to lightsource
        light_direction_from_surface_to_lightsource = normalize(light_in_world_eye);
    } else {
        // Positional light
        // Convert light position to eye space & get direction
        light_direction_from_surface_to_lightsource = normalize(light_in_world_eye - vertex_position_eye_space);
    }

    return light_direction_from_surface_to_lightsource;

}

```
* Fragment Shader

```
#version 330 core
// Fragment Shader
// Normal Mapping
// OGL4 Shader Language Cookbook Pg. 159

struct SceneLight {
    vec3 scale_light_intensity;
    vec3 ambient_intensity;
    vec3 diffuse_intensity;
    vec3 specular_intensity;
};

struct DiffuseMaterial {
    sampler2D m_sampler;
};

struct NormalMaterial {
    sampler2D m_sampler;
};

// ======= Input from Vertex Shader ========
in vec3 vector_towards_viewer_tangent;
in vec3 light_direction_from_surface_to_lightsource_tangent;
in vec2 frag_tex_coords;

// ============ Shader Uniforms ============
// Lights
uniform SceneLight scenelight;

// Texture
uniform DiffuseMaterial diffuse_material;
uniform NormalMaterial normal_material;

// =============== Output ==================
out vec4 fragment_color;

// ========= Function Prototypes ==========
vec3 phong_lighting(vec3 light_direction_surface_to_source_tangent);

// ================== Main =================
void main() {
    fragment_color = vec4(phong_lighting(light_direction_from_surface_to_lightsource_tangent), 1.0f);

    // Testing =============================
    // fragment_color = vec4(light_direction_from_surface_to_lightsource_tangent, 1.0f);
    // =================================
}

vec3 get_ambient_light(){
    return scenelight.ambient_intensity * vec3(texture(diffuse_material.m_sampler, frag_tex_coords));
}

vec3 get_diffuse_light(float light_dir_to_normals_dot){
    return scenelight.diffuse_intensity * light_dir_to_normals_dot * vec3(texture(diffuse_material.m_sampler, frag_tex_coords));
}

vec3 phong_lighting(vec3 light_direction_surface_to_source_tangent){

    vec3 mapped_normals_tangent = texture(normal_material.m_sampler, frag_tex_coords).xyz;

    // Textures store values from 0 to 1.  Normal vectors have values from -1 to 1.
    // This rescales the value to be between -1 and 1;
    mapped_normals_tangent = normalize(2.0 * mapped_normals_tangent - 1.0);

    // Lighting Calculations
    // The value here gives us a scalar for how strong our light is (if light_dir and vertex_normals were at 90 degrees, the result would be zero): pg 80
    float light_dir_to_normals_dot = max(dot(light_direction_surface_to_source_tangent, mapped_normals_tangent), 0.0f);

    // Ambient
    vec3 ambient_light = get_ambient_light();

    // Diffuse
    vec3 diffuse_light = get_diffuse_light(light_dir_to_normals_dot);

    // Combine lights (Note that diffuse and specular are multiplied by the intensity)
    return ambient_light + diffuse_light * scenelight.scale_light_intensity;

}

```
* Handedness Fix (Performed as the model is loaded)

```
    void update_handedness(){
        // Handedness fix for symmetric UV's
        if (glm::dot(glm::cross(m_normals, m_tangent), m_bitangent) < 0.0f) {
            m_tangent = m_tangent * -1.0f;
        }
    }

```

In both image examples, light is being supplied as a directional (vec4) light directly above the model: glm::vec4(0.0f, 1.0f, 0.0f, 0.0f)

It seems to me that when the TBN matrix has the handedness fix in place, the lighting looks incorrect. Disabling the fix corrects the lighting, but not fully (as shown by the visor in the 2nd image).

How I can make this lighting look correct? I would prefer to keep the handedness fix in place, and it's not clear to me why this is impacting the lighting so much. Additionally, even when it's disabled, the lighting looks mostly correct, but the visor in the 2nd image gives me some doubt.

# Answer
Update: I have a handedness fix that looks to be correct when it's applied. I still get the weird visor issue, but I'm thinking perhaps it's something funky with the model itself.

The solution I am using is from OpenGL 4 Shading Language Cookbook:

1. Tangent is now a vec4. The w component is used to track handedness in the shader
2. w is calculated using the following:

```
// Vec4 Version
glm::vec3 tangent_temp = glm::vec3(m_tangent.x, m_tangent.y, m_tangent.z);

// Re-orthogonalize T with respect to N
tangent_temp = glm::normalize(tangent_temp - (glm::dot(m_normals, tangent_temp) * m_normals));

// Handedness fix for symmetric UV's
const float w = glm::dot(glm::cross(m_normals, tangent_temp), m_bitangent) < 0.0f ? -1.0f : 1.0f;

// Update tangent
m_tangent = glm::vec4(tangent_temp.x, tangent_temp.y, tangent_temp.z, w);

```
3. In the vertex shader, tangent is now a vec4. The TBN matrix is calculated as follows:

```
mat3 get_tbn_matrix(vec4 vertex_tangent, vec3 vertex_bittangent, vec3 vertex_normal){

  // Convert vertex normal and vertex tangent to eye space
  vec3 vertex_tangent_eye_T = normalize(normal_matrix * vertex_tangent.xyz);
  vec3 vertex_normal_eye_N = normalize(normal_matrix * vertex_normal);

  // Compute bittangent and update handedness
  vec3 vertex_bitangent_eye_B = normalize(cross(vertex_normal_eye_N, vertex_tangent_eye_T)) * vertex_tangent.w;

  // Matrix for converting from view space to tangent space
  mat3 TBN = mat3(
      vertex_tangent_eye_T.x, vertex_bitangent_eye_B.x, vertex_normal_eye_N.x,
      vertex_tangent_eye_T.y, vertex_bitangent_eye_B.y, vertex_normal_eye_N.y,
      vertex_tangent_eye_T.z, vertex_bitangent_eye_B.z, vertex_normal_eye_N.z
      );

  return TBN;
}

```
4. Lastly, the following variables are updated and sent to the fragment shader:

```
    // Output
  light_direction_from_surface_to_lightsource_tangent = TBN * light_direction_eye;
  vector_towards_viewer_tangent = TBN * normalize(-vertex_position_eye);
  frag_tex_coords = tex_coords;

```

I am happy with this solution, as it allows me to keep the handedness fix in place and have lighting that *looks* to be correct. I will leave this question open for a few more days in case anyone has something to add (in particular, the underside visor weirdness that still occurs).
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: One global game loop vs multiple local game loops
What are the advantages of using multiple game loops instead of one?

Assume Level1, Level2, Level3. These levels may bring totally different problems and needs and they may also be completely separate, perhaps like a classic Mario game. One level needs multiple frame counters yet the others need none. Would it make sense to structure a game like that, with many loops?

I've written an implementation of this, which was actually my first loop design for my game, and memory management looks like few necessary global with many local variables, at the cost of less automated code (meaning more writing).

Is this done at all and if so, is this common?

# Answer
> 3 votes
The cost of rewriting your loop is not worth any perceived benefits of having "more efficient" loops that leave out unneeded bits.

This is "premature optimization". I would not consider multiple loops unless

1. A profiler tells you the code in the loop is causing bottlenecks (*very* unlikey)
2. Your levels are *so different* from one another that shared code is minimal

---
Tags: game-loop, c
---


title: Locking the frame rate in pygame?

text:
# Question
Title: Locking the frame rate in pygame?
I am having trouble setting up the frame rate in my first game. I know that I can set it up with:

```
clock = pygame.time.Clock()
clock.tick(60)

```

but this is not producing very desirable results. If I move a character 1 pixel per frame, it will move smoothly but jitter about once a second. If I `print(clock.get_fps())` it tells me that my frame rate is about 59.8. Since it never hits 60, it never syncs up with my monitor's refresh rate and the annoying jittering continues.

That I know of, this is not a problem with the game's performance, since it is in a very early stage of development. If I cap the FPS at 1000 then I can get a maximum FPS of about 270.7. Is there any way I can give my game a continuous frame rate of 60?

P.S. I don't mind that my movement code is tied to FPS. I tried making it FPS-independent using this code, but this introduced some floating-point inaccuracies to my movement. It wouldn't let me set the FPS to exactly 60, either.

# Answer
> 12 votes
If you read the `pygame.time.Clock.tick()` and `pygame.time.Clock.get_fps()` documents, you'll find that:

* `tick()` works with milliseconds - it returns the number of milliseconds since the last call
* `get_fps()` returns an average of the last 10 calls to `tick()`. If you do the math, that's pretty damn good that you're getting 59.8 most of the time, since with 60 FPS you'll be ticking 16 or 17ms per frame, and 59.88 is the closest number you can get ((16\*3 + 17\*7) / 10 = 59.88)

That explains why you're not seeing 60FPS from `get_fps()`. The jitter is a different matter though; it has to do with how `tick()` is implemented.

It uses `SDL_Delay`, which in turn uses various platform-specific sleep functions, which depending on the OS can be quite inaccurate at the millisecond level. What's probably going on is, a popular OS's sleep function has a granularity of 15ms, whereas your target FPS of 60 requires 16.66...ms sleeps. One of your frames is going to stick around for 30ms, maybe every second or so.

Basically if you want smooth frames, you'll need to avoid methods that exclusively use `SDL_Delay`. You'll want to read Fix Your Timestep, but here are your options:

* Use `tick_busy_loop()`, which doesn't sleep but makes your CPU spin until enough time has passed. The downside is increased power usage, a big no-no for battery-powered devices.
* Track the number of milliseconds you need to delay yourself, and use a combination of `pygame.time.wait()` and `pygame.time.delay()` to precisely control timing, without doing a busy-wait all the time.
* Divorce game time from draw time, and draw interpolated states based on delta time. What that means is, instead of drawing things at say `x + speed`, you draw them at `x + speed * delta`, where `delta` is the amount of time actually taken to draw that frame. This masks a lot of jittering problems.
* This option is probably out for you, but there are more precise sleeps available that are platform-specific. Sadly they are not available to SDL/pygame.

# Answer
> 3 votes
`clock.tick()` only sets the loops at intervals of milliseconds, so at 60 fps, it will make each game loop at 16 milliseconds, not 16.6666 (which is what you need) that causes the jittering.

The below code will ensure that your game runs at the frame cap exactly since `time.perf_counter()` gives very precise timing. How it works is that if the time passed from the last frame (unprocessed) is over or equal to the the frame cap, then the frame will render. Also note that if the frame renders, the frame cap is subtracted from the unprocessed time, making the frames more stable since the errors don't accumulate.

```
import pygame
import time

frame_cap = 1.0/60
time_1 = time.perf_counter()
unprocessed = 0

while True:
    can_render = False
    time_2 = time.perf_counter()
    passed = time_2 - time_1
    unprocessed += passed
    time_1 = time_2

    while(unprocessed >= frame_cap):
        unprocessed -= frame_cap
        can_render = True

    if can_render:
        # put everything inside here

        pygame.display.update()

```

---
Tags: python, pygame, frame-rate
---


title: How to keeping my AICar on track?

text:
# Question
Title: How to keeping my AICar on track?
so today I made an arcade race game but stuck on make AICar that keep on track when play, what I've made is the AICar sometimes cutting the track or like making a shortcut to the next checkpoint and I won't that happen

**What I've done**

* Make more checkpoints so the car going more smoothly

this my whole AICar script:

```
private void Start()
    {
        theRB.transform.parent = null;

        dragOnGround = theRB.drag;

        if (isAI)
        {
            targetPoint = RaceManager.Instance.allCheckpoints[this.currentTarget].transform.position;
            //RandomiseAITarget();
            aiSpeedMod = Random.Range(.8f, 1.1f);
        }

        UIManager.Instance.LapCounterText.text = currentLap + "/" + RaceManager.Instance.TotalLap.ToString();
    }

 private void Update()
    {
        lapTime += Time.deltaTime;

            targetPoint.y = transform.position.y;

            if (Vector3.Distance(transform.position, targetPoint) <= aiReachPointRange)
            {
                SetNextTarget();
            }

            Vector3 targetDir = (targetPoint - transform.position);
            float angle = Vector3.Angle(targetDir, transform.forward);

            Vector3 localPos = transform.InverseTransformPoint(targetPoint);
            if (localPos.x < 0)
            {
                angle = -angle;
            }

            //AI turning
            turnInput = Mathf.Clamp(angle / aiMaxTurn, -1f, 1f);

            if (Mathf.Abs(angle) < aiMaxTurn)
            {
                aiSpeedInput = Mathf.MoveTowards(aiSpeedInput, 1f, aiAccelerateSpeed);
            }
            else
            {
                aiSpeedInput = Mathf.MoveTowards(aiSpeedInput, aiTurnSpeed, aiAccelerateSpeed);
            }

            speedInput = aiSpeedInput * fowardAcceleration * aiSpeedMod;
    }

 public void SetNextTarget()
    {
        this.currentTarget++;

        if (this.currentTarget >= RaceManager.Instance.allCheckpoints.Length)
        {
            this.currentTarget = 0;
        }

        targetPoint = RaceManager.Instance.allCheckpoints[this.currentTarget].transform.position;
        //RandomiseAITarget();
    }

```

# Answer
> 1 votes
One way would be to add more waypoints around the turns. Think of it this way; every time a driver would need to turn the wheel, there should be a waypoint. However, collisions might still push the cars of the track slightly.

Another way would be to use a NavMesh.

You can set the grass to not have the Navigation Static flag, so the NavMesh would not include it. Then adding a NavMeshAgent component on your cars and using the navMeshAgent.SetDestination(point) would make sure the cars stay in the track.

Look here: Building a NavMesh

The AICar script would look something like this:

```
NavMeshAgent myAgent;

void Update()
{
    if (!myAgent.hasPath)
    {
        SetNextTarget();
    }
}

void SetNextTarget()
{
    this.currentTarget++;

        if (this.currentTarget >= RaceManager.Instance.allCheckpoints.Length)
        {
            this.currentTarget = 0;
        }

        myAgent.SetDestination(RaceManager.Instance.allCheckpoints[this.currentTarget].transform.position);
}

```

One thing to note, is that NavMeshAgents have collision avoidance which means they won't collide with each other. You CAN have the player object collide with them, and handle forces manually in `OnCollisionEnter()` (Look Here), but it might be a lot easier adding the `NavMeshObstacle` component on the player object. This would make the Agents avoid colliding with the player object as well.

---
Tags: unity, ai
---


# Question
Title: How can I make a list of factions, each of which has a "reputation" according to every other faction?
In my game, I'd like each and every NPC to belong to a faction, such as Bandits, Townsfolk, Elves, etc.. Each faction would then have an opinion of each other faction, stored as an integer rating, and if an NPC of one faction meets a member of an enemy faction, they'll attack.

How can I keep track of these factions and the relationships between them? I've tried creating a list of factions in a `FactionManager`, but then I don't know how to manage relationships.

Here is a similar query but for Python: How should I efficiently store faction relationships?

# Answer
Create a 2D array (matrix), and store accordingly. The left column here is the primary column, i.e. townsfolk's opinion of elves (elves' rep with townsfolk) is 0.5. Whereas elves opinion of townsfolk is less flattering (0.3).

|  | townsfolk | bandits | elves |
| --- | --- | --- | --- |
| townsfolk | 1.0 | 0.1 | 0.5 |
| bandits | 0.8 | 1.0 | 0.6 |
| elves | 0.4 | 0.2 | 1.0 |

Why have I used a floating point value between 0.0 and 1.0, instead of an integer? `float` is flexible:

* Any maximum number we pick, such as 100 or 5000, would anyway be a contrived figure, which we could arrive at just by mutiplying by some constant `k`. (e.g. 0.3 * 5000 = 1500). So `0.0-1.0` is "solution agnostic" if we change `k`.
* Floating point isn't restricted to "stepped" values such as all integers between 1 and 100. It is an *analog* range.

In C#:

```
enum Factions
{
    Townsfolk,
    Bandits,
    Elves
}

int numFactions = Enum.GetValues(typeof(Factions)).GetUpperBound(0);
float[,] repTable = new float[numFactions, numFactions];

//set a value

repTable[Townsfolk, Townsfolk] = 1.0f;
repTable[Townsfolk, Bandits] = 0.1f;
//etc.

//get a value

float rep = repTable[Townsfolk, Bandits];

```

Or if you want more information than just a single value, you can also make a 2D array of struct:

```
struct FactionStatus
{
    public float rep;
    public float affinity;
    public int debtsOwed;
}

FactionStatus[,] factionStatusTable = new FactionStatus[numFactions, numFactions];

//set a value

factionStatusTable[Bandits, Elves].affinity = 0.65f;

```
> 1 votes

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


title: Unity Animator Ignoring "Higher" Layers

text:
# Question
Title: Unity Animator Ignoring "Higher" Layers
I have a rather rudimentary layer set up:

* Lower Body: no mask, full weight, override.
* Upper Body: upper body mask, full weight, override. This works as intended.
* Standing Up: full body mask, full weight, override. This doesn't visibly work at all despite inspector showing animation playing. Character is fully upright, doing his walking/aiming thing as if Stand Up From Stomach isn't playing.

It appears it is only "partially" following the rule that "higher layers take priority." The lower and upper body work fine, as intended, where upper body overwrites. But the Standing Up layer should be overwriting both Lower Body and Upper Body, but it isn't. It's being ignored altogether.

Any ideas why this basic set up is having such difficulties? I haven't even gotten to the part of playing with the weights in script yet to make the Standing Up layer not override Lower Body and Upper Body once the character is upright...

# Answer
Turns out it was a stupid mistake!

Don't forget to set the animation rig type to humanoid!
> 0 votes

---
Tags: unity, animation, skeletal-animation, mecanim, animator
---


# Question
Title: How to count Score based on position of player?
So, I am making this game where you keep moving forward and there are obstacles in the path. If you collide with an obstacle 100 points are deducted and for every frame a point is deducted i.e. `score -= (int) (timeDecrement*Time.deltaTime)` You gain points the farther you go down the axis. However, this is presenting a bug I didn't expect. As of now, I am adding the `(int) player.position.z` to the score. But since the collisions slow you down you actually gain more points than lose. Sometimes you get completely stuck and continuously gain points. Any ideas to how I can solve this?

Edit: Also, the points added per frame gets higher. I was think of solving both of these by finding out how much we moved since last frame. But I can't figure out how to do this. I was thinking of adding a variable that got updated every frame and then we compared the difference and if it were say 10 or 25 we could add the same amount of points. However, with better frames the score is going down to negative instead because the position change is too little. But if the frame rate is low then adding 0.25 points for a 0.25 difference in the coordinates (which I also considered) the points again go down to negative.

# Answer
> 0 votes
You could create a variable `pointsLost` where you add up all the points you lose. Then your score would be `score = player.position.z - pointsLost`.

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


# Question
Title: How do I make a rainbow hue shift over time on text?
What I'm trying to do is make a Text object have an animation that allows for the hue of the color to go all the way up and loop back around, so it creates a cool rainbow thing.

I've looked on google for a solution but the solution I found only worked in older versions of Unity, which were used back in 2015. What I found

Any help would be appreciated!

# Answer
When you use TextMeshPro (which I would recommend for many more reasons - it is just superior to the old Text and TextMesh components), then you can assign a Material to the text. That material can have a shader which allows you to create any kinds of visual effects.

But even when shader programming is not your area of expertise: The standard shader might already be able to do what you want. You can assign a tiling rainbow as a texture and then use the UV Speed property to make it scroll.
> 2 votes

# Answer
Use Rich Text:

```
string message = "<color="red">R<color="orange">a<color="yellow">i<color="green">n<color="blue">b<color="purple">o<color="red">w";

```

You can use hex code colors for finer control:

```
string message = "<color=#FF000088>Semitransparent red";

```
> 0 votes

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


# Question
Title: How can I add a exit to the random maze generator?
This is the maze at runtime. There are some enterences/exists I didn't define yet what is enterence and what is exit. This is one problem to decide but for that I need some how to make at least one path I prefer that it will be a random path each time as part of the maze. Single path with enterence and exit.

The maze as it is not don't have one path that the player/object can move in and exit in another exit.

Once the maze has generated it's choosing one enterence randomly and put the player/object with a camera facing that enterence/exit

Now the player by controller or by automation should move in and try to find the path to the other side. Before the path finding how I create a path ? I mean I want to keep the random path's without exist but also to make one random path each time that will have also exit.

Than later the path finding ai but first how to generate a path with the maze ?

This is the maze generator script :

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

public class MazeGenerator : MonoBehaviour
{
    public Maze maze;
    public Transform objectToTravel;
    public int mazeWidth;
    public int mazeHeight;
    public string mazeSeed;
    public GameObject wallPrefab;
    public GameObject waypointPrefab;

    private System.Random mazeRG;
    public List<Vector3> positions = new List<Vector3>();

    // Use this for initialization
    void Awake()
    {
        mazeRG = new System.Random();

        if (mazeWidth % 2 == 0)
            mazeWidth++;

            if (mazeHeight % 2 == 0)
            {
                mazeHeight++;
            }

        maze = new Maze(mazeWidth, mazeHeight, mazeRG);
        GenerateMaze();
    }

    public void GenerateMaze()
    {
        var bricks = GameObject.FindGameObjectsWithTag("MazeBrick");
        var waypoints = GameObject.FindGameObjectsWithTag("Waypoint");

        if (bricks.Length > 0)
        {
            foreach(GameObject brick in bricks)
            {
                Destroy(brick);
            }
        }

        if(waypoints.Length > 0)
        {
            foreach(GameObject waypoint in waypoints)
            {
                Destroy(waypoint);
            }
        }

        positions = new List<Vector3>();

        maze.Generate();
        DrawMaze();
    }

    void DrawMaze()
    {
        for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == true)
                {
                    CreateMaze(position, transform, 0, mazeRG.Next(0, 3) * 90);
                }
            }
        }

        for (int x = 0; x < mazeWidth; x++)
        {
            for (int y = 0; y < mazeHeight; y++)
            {
                Vector3 position = new Vector3(x, 0.5f, y);

                if (maze.Grid[x, y] == false)
                {
                    var waypoint = Instantiate(waypointPrefab, new Vector3(x , 0, y), Quaternion.identity);
                    waypoint.tag = "Waypoint";

                    if (x == 0 || x == mazeWidth - 1 || y == 0 || y == mazeHeight - 1)
                    {
                        positions.Add(position);
                    }
                }
            }
        }

        var randpos = positions[Random.Range(0, positions.Count - 1)];
        objectToTravel.position = randpos;

        if (randpos.z == 0)
        {
            objectToTravel.position = new Vector3(objectToTravel.position.x, objectToTravel.position.y, objectToTravel.position.z - 2);
            objectToTravel.rotation = Quaternion.identity;
            objectToTravel.Rotate(0, 0, 0);
        }

        if(randpos.x == 0)
        {
            objectToTravel.position = new Vector3(objectToTravel.position.x - 2, objectToTravel.position.y, objectToTravel.position.z);
            objectToTravel.rotation = Quaternion.identity;
            objectToTravel.Rotate(0, 90, 0);
        }

        if(randpos.z == mazeHeight - 1)
        {
            objectToTravel.position = new Vector3(objectToTravel.position.x, objectToTravel.position.y, objectToTravel.position.z + 2);
            objectToTravel.rotation = Quaternion.identity;
            objectToTravel.Rotate(0, 180, 0);
        }

        if(randpos.x == mazeWidth - 1)
        {
            objectToTravel.position = new Vector3(objectToTravel.position.x + 2, objectToTravel.position.y, objectToTravel.position.z);
            objectToTravel.rotation = Quaternion.identity;
            objectToTravel.Rotate(0, -90, 0);
        }
    }

    void CreateMaze(Vector3 position, Transform parent, int sortingOrder, float rotation)
    {
        GameObject mazePrefab = Instantiate(wallPrefab, position, Quaternion.identity);
        mazePrefab.transform.SetParent(parent);
        mazePrefab.transform.Rotate(0, 0, rotation);
        mazePrefab.tag = "MazeBrick";
    }

    // Update is called once per frame
    void Update () {

    }
}

```

The maze class :

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

public class Maze
{
    //Grid size
    public int width;
    public int height;

    //Store grid
    private bool[,] grid;
    //Generate random directions to move
    private System.Random rg;

    //Start position
    public int startX;
    public int startY;

    //Public getter
    public bool[,] Grid
    {
        get { return grid; }
    }

    //Constructor of the grid for setting values
    public Maze(int width, int height, System.Random rg)
    {
        this.width = width;
        this.height = height;

        this.rg = rg;
    }

    //Generate the grid
    public void Generate()
    {
        grid = new bool[width, height];

        startX = 0;
        startY = 0;

        grid[startX, startY] = true;

        MazeDigger(startX, startY);
    }

    void MazeDigger(int x, int y)
    {
        int[] directions = new int[] { 1, 2, 3, 4 };

        //We create random array of directions
        HelpingTools.Shuffle(directions, rg);

        //We are looping over all the directions
        for (int i = 0; i < directions.Length; i++)
        {
            if (directions[i] == 1)
            {
                if (y - 2 < 0)
                continue;

                if (grid[x, y - 2] == false)
                {
                    grid[x, y - 2] = true;
                    grid[x, y - 1] = true;

                    MazeDigger(x, y - 2);
                }
            }

            if (directions[i] == 2)
            {
                if (x - 2 < 0)
                    continue;

                if (grid[x - 2, y] == false)
                {
                    grid[x - 2, y] = true;
                    grid[x - 1, y] = true;

                    MazeDigger(x - 2, y);
                }
            }

            if (directions[i] == 3)
            {
                if (x + 2 > width - 1)
                    continue;

                if (grid[x + 2, y] == false)
                {
                    grid[x + 2, y] = true;
                    grid[x + 1, y] = true;

                    MazeDigger(x + 2, y);
                }
            }

            if (directions[i] == 4)
            {
                if (y + 2 > height - 1)
                    continue;

                if (grid[x, y + 2] == false)
                {
                    grid[x, y + 2] = true;
                    grid[x, y + 1] = true;

                    MazeDigger(x, y + 2);
                }
            }
        }
    }
}

```

And last the Helping Tools class :

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

public class HelpingTools : MonoBehaviour
{
    public static T[] Shuffle<T>(T[] array, System.Random rg)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            int randomIndex = rg.Next(i, array.Length);

            T tempItem = array[randomIndex];

            array[randomIndex] = array[i];
            array[i] = tempItem;
        }

        return array;
    }
}

```

# Answer
My approach would be to find a different maze generation algorithm which guarantees that you get a maze where every point on the grid is part of a single connected graph. Or in other words: One where every point is guaranteed to be reachable from every other point. That way it does not matter where you place entrance and exit - there will always be a solution. Wikipedia has a good overview of a couple standard algorithms which fulfill that property.

But if you want to stay with your current algorithm, then a good way to handle it could be to create a list of potential entrance and exit locations in your `MazeDigger` method while you carve a randomized path through the maze. Whenever you land at a point which is on the outer wall of the maze, you put it in a list of potential entrance/exit locations. Then, when the generation is finished, you pick two random points from that list (preferable two points far away from each other, but definitely not the same point twice). Then carve a path from that point to the outside of the maze. These are your entrance and exit.
> 3 votes

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


# Question
Title: Is there a good way ECS for creating variants of a behaviour like in Java interfaces?
In Java, there are interfaces - I'm not clear on the details (I don't use Java) but from what I've learned, they seem to be "classes for classes": a way to effectively make individual classes "instances" of one overarching class. For example, a "Cup" interface could be implemented by a "Mug" class, a "Glass" class, a "Goblet" class etc. As long as they have the same I/O methods such as `fill()`, `empty()` or `drink()`, they can be used interchangeably.

In languages with duck typing, interfaces are not needed - the language allows for classes to be used interchangeably as long as no invalid properties of methods are referenced. This is another valid was of going about things in OOP. This is how I usually go about things.

**My question: how can I create varied behaviour in an ECS if components are data-only? I like to think in terms of first-class functions, but that seems to be taboo since components are not supposed to hold behaviour.**

1. Have a massive `switch` or `if`/`else` chain in my System:

For example, if I have an AI component with several different behaviours, I could use an integer to define which type of AI to use for that particular entity. It seems a bit convoluted and inelegant.
2. Have a separate Component and matching System for each behaviour:

This would be neater in each *individual* System but as a whole, the program would be a mess. This wouldn't work because of the large amounts of variation such as hundreds of different guns in a shooter game.
3. Use a flyweight-like data structure independent of the Component:

This would mean storing all of the different behaviours elsewhere, and storing a key that a System can use to access the behaviour. This is basically a fancy version of the `switch` option above, but it seems neater as there wouldn't be a massive dump of code in the System.
4. Creating a complex way of encoding a description of the desired behaviour which the System can interpret:

This seems to be the most overkill of the lot. Unless I have to, or there are significant advantages, I'm trying to stay away from this.

If there's no other way, I'll just adopt the methodology of first-class functions as I usually do and just ignore any guidelines about ECS I've heard, just for this one case. The problem is, it probably won't just be one case in the future.

Have I missed any other good options? Is there an industry standard or recommendation? If not, what considerations should I make about which option to choose?

# Answer
> 2 votes
ECS is effectively a database, and an interface is effectively a parent class, so a good portion of the answer may be borrowed from current DB design practices. ECS-specific and non-ECS solutions also exist.

### Component per hierarchy.

Every possible sub-type is merged into a single component. That's right, all the fields of all the would-be sub-types are present in a single component.

Discriminator field used to identify an underlying sub-type. Good to best cache performance except in degenerate cases (e.g. too many sub-types). Need to know all the sub-types in advance, thus making run-time extensibility problematic. Entity is still limited to one component per (concrete) component type, by design.

Discriminator is a field used to distinguish concrete sub-types. Systems may switch on it or use a dictionary that maps discriminator to a component's "driver" (the strategy pattern).

### Component per concrete sub-type

Each sub-type is implemented as a distinct component, with all inherited fields repeated.

Allows using language's built-in inheritance (including interfaces). Discriminator field is still needed to distinguish the components when accessing via a polymorphic reference. Discriminator field must also be included into a reference to a component, so you can know where to look when following a reference. Cache performance is not ideal, but has a theoretically possible opportunity for better parallelization. Limiting entity to one component per component type requires extra care.

### Extension component per sub-type.

Each sub-type is a component that includes only it's own fields but requires a base component to be present in the entity. That is, the entire component is assembled from multiple pieces, one piece per level in the hierarchy.

Discriminator in the base class is sufficient. Cache performance is even worse, but has a theoretically possible opportunity for even better parallelization. Instantiation and destruction involves multiple components. Working with entire instance of a concrete type is inconvenient.

### Varying-size components.

Using the normal inheritance, but custom allocator is employed to pack differently-sized components into a contiguous chunk of memory.

Discriminator in the base class is sufficient. In the other respects it retains all the features of mundane ECS.

### Pure behavior.

If all the different behaviors work with the same data (or require no data at all), using just a strategy must be enough. Multiple strategies per component are possible.

No overhead besides the aforementioned limitations.

### Feature flags.

Another option in absence of inheritance is to use feature flags. It is sometimes achieved emergently by having the special cases for the properties (e.g. zero effect radius means no effect at all).

### Event-driven.

Behaviors may be associated with a component type. In other words, a reference to a behavior implementation is stored per type rather than per instance.

Invocation of a behavior on an entity is not directed towards a concrete type or interface, but rather to any component that supports given behavior. Which means that an entity can have any number of behavior handlers (zero, one, few), depending on the components attached.

In many aspects, this is similar to raising an event on an entity.

### Message-driven.

Similar to an event-driven approach, but the events (messages) are stored to a queue to be read later by a system.

Due to delayed handling, message sending must be async, which makes it unfit for certain tasks (e.g. asking for answer immediately). On the other hand, the messages may be processed in bulk and in parallel, which is good for the performance.

### Out-of-ECS polymorphism.

Component may include a reference to a mundane object that supports polymorphism by the means of the language.

Depending on the usage, this may seriously disrupt the cache performance, so it may be a good idea to update the "outsourced" element outside of ECS as well.

It's normal for ECS-oriented system to have non-ECS modules. Examples may include AI (behavior trees, pathfinding), GPU physics, scene composition, input methods, scripts, etc.

# Answer
> 1 votes
This question comes from approaching DOD (data-oriented design) from an OOP perspective. In DOD there are no interfaces, as data *is* the interface.

I think this generic answer about interfaces and DOD is satisfactory. ECS itself is the solution :).

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


# Question
Title: How to get the RGB color values of a clicked pixel on a rendered image in SDL2?
In the same vein as this question and this question, I recently ran into a problem in my C++/SDL2 game architecture where I needed to get the R,G,B values from a clicked pixel in an image on the screen. That is, if the user clicked on a given image **surface** (SDL\_Surface) or **texture** (SDL\_Texture), it would give you back the R,G,B values of the specific pixel in the image that you clicked. The specific use case was for a color picker, to allow users to customize UI elements with a clickable color palette.

This resulted in many hours of keyboard-bashing, because it turns out that SDL2 really, really is not built to have simple solutions to such problems when it comes to shaders and graphics architecture (and that's completely fine - it comes with the efficiency of the library).

Therefore, to save future game developers using C++/SDL2 the massive headache I had to endure, I'm posting the method I discovered below as a self-answer to this question. Hopefully it's helpful to someone with a similar problem in the future!

# Answer
> 5 votes
After much scouring the Internet, I discovered this forum post, containing the following code that completely solved my problem. I've abridged it slightly for easy copy-paste into your project.

```
SDL_Color GetPixelColor(const SDL_Surface* pSurface, const int X, const int Y)
{
  // Bytes per pixel
  const Uint8 Bpp = pSurface->format->BytesPerPixel;

  /*
  Retrieve the address to a specific pixel
  pSurface->pixels  = an array containing the SDL_Surface' pixels
  pSurface->pitch       = the length of a row of pixels (in bytes)
  X and Y               = the offset on where on the image to retrieve the pixel; (0, 0) is the upper left corner
  */
  Uint8* pPixel = (Uint8*)pSurface->pixels + Y * pSurface->pitch + X * Bpp;

  Uint32 PixelData = *(Uint32*)pPixel;

  SDL_Color Color = {0x00, 0x00, 0x00, SDL_ALPHA_OPAQUE};

  // Retrieve the RGB values of the specific pixel
  SDL_GetRGB(PixelData, pSurface->format, &Color.r, &Color.g, &Color.b);

  return Color;
}

```

All you need to do is provide:

* the **SDL\_Surface** that was clicked into the function.
* the **X** and **Y** coordinates of the mouse click.

It will return the **SDL\_Color** object of the pixel clicked - which can subsequently be broken up into R,G,B values if needed using the **.r** (red), **.g** (green), and **.b** (blue) properties.

---
Tags: c++, sdl2, pixel
---


# Question
Title: Unity 2020.3.15f2: Choose between VR and Desktop at launch
Lots of games have options for launching in VR or Desktop modes, either through steam launch options ("Play game", or "Play game in VR") or command line flags (`-vrmode none`, `--no-vr`) at least from a user perspective. Phasmophobia, which was developed with Unity (engine version unknown) uses the `-vrmode none` option to force the desktop version of the game. I'm guessing this was in the 2019 version of unity, as that still supported the dev SKD options under `Project Settings -> Player -> XR`. However with the newer 2020 LTS version of unity, using the OpenXR Package, I don't see an equivalent.

I'd like to give a command line option to my game to launch in either VR mode or Desktop mode, then stay in that mode for the game session. Is there a way to do this with the OpenXR package?

```
Engine: Unity 2020.3.15f2
Template: Universal Render Pipeline
XR Interaction Toolkit Package: 1.0.0-pre.5 [Preview]
XR Plugin Management: 4.0.7

```

Only OpenXR is selected in XR Plug-In Management. This is a bare-bones project with an XR rig and a single intractable for testing.

# Answer
After more work and communicating with people, I managed to figure this out myself.

For other people who find this post, here is the solution for VR and non-VR in a single build.

Note that this will start your game in 2D, NOT VR. After it loads past the unity splash screen, it will switch to VR.

You need to create an empty game object in your scene (you do not have to switch scenes for this to work) and attach the below script to it. After this, build your game and launch the game with the "--enable-vr" flag after the game.exe. In a Windows Shortcut, this looks like "C:\Path\To\Game.exe" --enable-vr

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

public class VRSwitcher : MonoBehaviour
{
    public void Awake()
    {
        StartCoroutine(StartXRCoroutine());
    }

    // This function checks out startup arguments to see if we want VR
    // To do this, create a desktop shortcut and add the arg at the end.
    // Example: "C:\Path\To\Game.exe" --enable-vr
    private static bool GetArg(string name)
    {
        var args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            Debug.Log($"Arg {i}: {args[i]}");
            if (args[i] == name)
            {
                return true;
            }
        }
        return false;
    }
    // From unity docs
    // https://docs.unity3d.com/Packages/com.unity.xr.management@4.0/manual/EndUser.html
    public IEnumerator StartXRCoroutine()
    {
        var enableVRArg = "--enable-vr";

        // Only run the code block when we want VR
        Debug.Log("Looking if VR should enable");
        if (GetArg(enableVRArg))
        {
            Debug.Log("Initializing XR...");
            yield return XRGeneralSettings.Instance.Manager.InitializeLoader();

            if (XRGeneralSettings.Instance.Manager.activeLoader == null)
            {
                Debug.LogError("Initializing XR Failed. Check Editor or Player log for details.");
            }
            else
            {
                Debug.Log("Starting XR...");
                XRGeneralSettings.Instance.Manager.StartSubsystems();
            }
        }
        else
        {
            Debug.Log("Did not find VR arg, starting in 2D");
        }
    }
}

```

I hope this helps someone
> 0 votes

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


# Question
Title: Orthographic projection not showing a triangle
I just want to draw a simple triangle using **GL\_LINES** primitive with orthographic projection matrix.

This is my vertices...

```
float_t vertices[]{
    -0.5f, -0.5f, 0.0f,     0.0f, 0.0f, 1.0f,
     0.5f, -0.5f, 0.0f,     0.0f, 0.0f, 1.0f,
     0.5f, -0.5f, 0.0f,     0.0f, 0.0f, 1.0f,
     0.0f,  0.5f, 0.0f,     0.0f, 0.0f, 1.0f,
     0.0f,  0.5f, 0.0f,     0.0f, 0.0f, 1.0f,
    -0.5f, -0.5f, 0.0f,     0.0f, 0.0f, 1.0f
};

```

And this is my matrices(model, view, projection)...

```
glm::mat4 model = glm::mat4(1.0f);
prog.setMat4fv1("model", model);

glm::mat4 view = glm::mat4(1.0f);
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
prog.setMat4fv1("view", view);

glm::mat4 projection = glm::mat4(1.0f);
projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f, 0.1f, 100.0f);
prog.setMat4fv1("projection", projection);

```

And this is the code in the while loop (game loop) that draws a triangle...

```
prog.useProgram();
glBindVertexArray(vao);
glDrawArrays(GL_LINES, 0, 6);

```

I see nothing. But when I change the code for projection matrix from `glm::ortho()` to `glm::perspective()`, it draws a triangle which is obviously smaller than the original one because of the code `view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));` which moves all the objects a little bit away from the camera.(I am not coding for the camera class at this time.)

So this is the code for projection matrix which works fine...

```
projection = glm::perspective(glm::radians(45.0f), (float_t)win_width / (float_t)win_height, 0.1f, 100.0f);

```

Am I doing something wrong with glm::ortho()? I can only create a model matrix and it's just fine. But this the first time I am using glm::ortho() and I don't see any examples on the internet. How can I solve the issuse with glm::ortho()?

# Answer
The triangle appears very small because the ortho projection is quite big. Try this

```
projection = glm::ortho(0.0f, 4.0f, 0.0f, 3.0f, 0.1f, 100.0f)

```

And if you want the triangle to be centered:

```
projection = glm::ortho(-2.0f, +2.0f, -1.5f, +1.5f, 0.1f, 100.0f);

```

---

The OP also wanted to know whether it's better to use a projection such as `projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f, 0.1f, 100.0f);` and make objects bigger. Or use a smaller projection, and keep the objects small.

The `800x600`projection sounds like a window resolution. It might be okay to use pixels as the unit of measure (i.e. this chacter is 36x40 pixels). However, take into account that, if you always match the the proection with the window resolution, the bigger the window, the more content you will be able to see. I don't know if that is desirable for your game, but it could work handy if your game was fixed resolution.

I'm going to give some examples of how I like to approach it depending on the game (just my opinion :) ).

**If you wanted to make a game such as tetris**

I would assume one square is 1x1 units. So the visible region will be, in this example, 12x25 (if I counted the squares correctly). Also I will take the bottom left square as (0,0) coordinate because I find it convenient in this case. So the ortho matrix will be `glm::ortho(0.0f, 12.0f, 0.0f, 25.0f)`

**For a 2d adventure game**

I would take something remarkable as the unit of measurement of the game, for example, the main character, or the size of the tiles. For example, I could say the main chacter is going to be 4x4 units.

Then the ortho matrix, will define how much of the game you can see in the whole screen. If the ortho matrix is 4x4, I will only be able to see the main chacter, so you should adjust the dimensions to whatever you like (60x48 could be a good number in this example).

Also, for this kind of game, I would make the ortho matrix centered. i.e the (0,0) corrdinate is the center of the screen, instead of the bottom-left corner.

So the ortho matrix will be `glm::ortho(-30.0f, +30.0f, -24.0f, +24.0f)`.
> 4 votes

---
Tags: opengl, c++, glm
---


# Question
Title: Very small line when two sprites are exactly next from eachother
Recently, I have been thinking about a hangout game, not really need to go into detail, because I am focusing on creating the engine itself. Basically just to make my brain not hurt while making the core game altogether.

I found a little problem, though.

Whenever I have two sprites EXACTLY next to each other, there's a weird small gap between them.

Here's a picture:

Here's another picture with the background white instead of black (eye strain warning for those dark mode users lol):

As you can see, there's a tiny little gap between the sprites.

I know a very simple and easy solution would just be to subtract the position by like one pixel, but it kind of ticks me off that it's not evenly spaced.

Here's my code containing the sprites and the rendering:

```

    public static void render() {

        test.setSpriteX(test2.getSpriteX() + 125f);
        test.setSpriteY(test2.getSpriteY());
        test.draw();
        test2.draw();

    }

    public static void update() {

        test2 = new Sprite(-50, 0, new SpriteTexture[] {new SpriteTexture("res/Tileset/wood.png")}, 0.1f, 125, 125, 100, false, true, "center");
        test = new Sprite(-50, 0, new SpriteTexture[] {new SpriteTexture("res/Tileset/wood.png")}, 0.35f, 125, 125, 100, true, true, "center");
        button = new Sprite(0, 0, new SpriteTexture[] {new SpriteTexture("res/buttonplacehold/button_trig_1.png")}, 0.0f, 125, 125, 100, false, true, "center");
        Logo = new Sprite(0, 0, new SpriteTexture[] {}, 0.35f, 250, 250, 100, true, false, "center");
        T = new Sprite(0, 0, new SpriteTexture[] {}, 0.35f, 50, 50, 100, true, false, "center");

        while (!Display.isCloseRequested()) {

            GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

            render();

            Display.update();

        }

        Display.destroy();
        System.exit(0);

    }

```

You don't need to worry about the button sprite.

```

public Sprite(float sx, float sy, SpriteTexture[] t, float speed, int w, int h, int dms, boolean isStatic, boolean isDevMode, String o)

```

where sx is sprite x, sy is sprite y, t is the list of textures for it, speed is just player speed if it's a player, w is width, h is height, dms is delay in milliseconds, isStatic just makes it a player or not, isDevMode just turns on some debugging and fun things, and o is the origin, which isn't even implemented yet or won't be at all.

Hope somebody can help,

Thanks.

Also here are the parameter definitions for the Sprite class, so you don't get mixed up:

# Answer
Sorry for the late answer. Perhaps OpenGL, your matrix maths library, or your code is exclusive for positions rather than inclusive? As for a fix, as you said, you could just subtract one from the position.
> -1 votes

---
Tags: opengl, java, lwjgl
---


# Question
Title: Why when making a sphere child of a cube the sphere is losing his shape?
When I drag to the scene a new sphere it looks like a ball a rounded ball. When I drag the sphere to be a child in this case of a cube the sphere looks like ellipse.

Is there any way to fix it ?

# Answer
> 0 votes
Make sure the cube, or any parent of the cube, is scaled to (1,1,1). Otherwise, any children -- in your case the sphere -- will get scaled along with the parent and warped.

---
Tags: unity
---


# Question
Title: How Do I add turn based combat on these scripts in unity 2d?
I am working on a game and I am totally stuck on what to do here. My problem is that I want a turn based combat for my game like a pool game or tic tac toe or anything. I am working on local multiplayer where screen needs to be divided in two parts. Upper part for player1 and lower part for player2, So far I am also not able to do that. Each player will get 5 turns. Player will take turn one by one until all 5 are taken.

The controller script on my both object is :

```
Vector2 startPos, endPos, direction;
Rigidbody2D myRigidbody2D;
public float Power = 10f;
public float maxDrag = 5f;

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

void OnMouseDown() {
     if (Input.GetMouseButtonDown (0)) {
         startPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
     }
 }

void OnMouseUp () {
     if (Input.GetMouseButtonUp (0)) {
         endPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
         direction = startPos - endPos;
         myRigidbody2D.isKinematic = false;
         Vector2 force = startPos - endPos;
         Vector2 clampedForce = Vector2.ClampMagnitude(force, maxDrag) * Power;
         myRigidbody2D.AddForce (clampedForce, ForceMode2D.Impulse);
     }
 }

```

There is an empty gameobject named `battlehandler` that should handle the turns but I am stuck; the script is:

```
public enum gameState { Start,p1Turn,p2Turn,Won,Lost}
public class battleSsystem : MonoBehaviour {

public gameState state;
int randomTurn = 0;

int p1TurnCount = 5;
int p2TurnCount = 5;
bool flag = true;

// Start is called before the first frame update
void Start()
{
    state = gameState.Start;
    StartCoroutine(setupBattle());
    randomTurn = Random.Range(1, 1);
    if (randomTurn == 1) {
        state = gameState.p1Turn;
        Debug.Log("P1 Turn");
        p1TurnCount--;
    } else if (randomTurn == 2)
    {
        state = gameState.p2Turn;
        p2TurnCount++;
        Debug.Log("P2 Turn");
    }
}

private void Update() {
    if (state == gameState.p1Turn) {
        p1Enable();
        p2Disable();
        if (flag) {
            p1TurnCount--;
            flag = false;
        }
        Debug.Log("p1 has left: " + p1TurnCount);
    } else if (state == gameState.p2Turn) {
        p1Disable();
        p2Enable();
        Debug.Log("p2 has left: " + p2TurnCount);
    }
    if (p1TurnCount < p2TurnCount) {
        state = gameState.p2Turn;
    } else {
        state = gameState.p1Turn;
    }
}

IEnumerator setupBattle() {
    yield return new WaitForSeconds(0f);
}

IEnumerator p1Turn() {
    p1Enable();
    p2Disable();
    yield return new WaitForSeconds(10);
}

void p2Disable() {
    GameObject[] objs;
    objs = GameObject.FindGameObjectsWithTag("p2");
    foreach (GameObject p2 in objs) {
        p2.GetComponent<ballController>().enabled = false;
    }
}

void p2Enable() {
    GameObject[] objs;
    objs = GameObject.FindGameObjectsWithTag("p2");
    foreach (GameObject p2 in objs) {
        p2.GetComponent<ballController>().enabled = true;
    }
}

void p1Disable() {
    GameObject[] objs;
    objs = GameObject.FindGameObjectsWithTag("p1");
    foreach (GameObject p1 in objs) {
        p1.GetComponent<ballController>().enabled = false;
    }
}

void p1Enable() {
    GameObject[] objs;
    objs = GameObject.FindGameObjectsWithTag("p1");
    foreach (GameObject p1 in objs) {
        p1.GetComponent<ballController>().enabled = true;
    }
}

```

I want to select a random turn at first then change the turn after the selected player has made their turn.

How should I tackle this problem?

I am making a turn based game and I want to switch turns after a user is done back and forth. I cant use update as it will restart the turn every frame.

```
public enum gameState { Start,p1Turn,p2Turn,Won,Lost}
public class battleSsystem : MonoBehaviour { public gameState
state; int randomTurn = 0;

int p1TurnCount = 5;
int p2TurnCount = 5;
bool flag = true;

// Start is called before the first frame update
void Start() {
    state = gameState.Start;
    StartCoroutine(setupBattle());
    randomTurn = Random.Range(1, 3);
    if (randomTurn == 1) {
        state = gameState.p1Turn;
    } else if (randomTurn == 2) {
        state = gameState.p2Turn;
    }
    if (state == gameState.p1Turn) {
        Debug.Log("P1 Turn start");
        p1Turn();
    }
    if (state == gameState.p2Turn) {
        Debug.Log("P2 Turn start");
        p2Turn();
    }
}

IEnumerator setupBattle() {
    yield return new WaitForSeconds(0f);
}

void p1Turn() {
    Debug.Log("inside p1 turn");
    p1Enable();//enables the player 1 controller
    p2Disable();//disables player 2 controller
}

void p2Turn() {
    Debug.Log("inside p2 turn");
    p2Enable();//enables the player 2 controller
    p1Disable();//disables player 1 controller
}

```

# Answer
One pattern I have used very successfully in multiple turn-based projects is to implement each state as a separate GameObject which includes all the scripts and sub-objects which are supposed to be active during that state.

At game start, deactivate all those state GameObjects except the initial state. To transition to a different state, just deactivate the current one and activate the object for the new state. You might want to do this via a central StateManager game object, so the states don't need to know too much about each other.

Any logic which needs to be performed when exiting a state can be put into `OnDisable` methods of its scripts. Any logic which needs to be performed when entering a state can be put into `OnEnable`.
> 0 votes

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


# Question
Title: Root Motion: Where is left / right rotation coming from?
I am using a generic animation on a generic character (coming from Mixamo).

The original animation does include root motion. However, the animation contains of a "straight forward" walk without any rotation.

When I use the animation on my character, the character makes weird right / left rotation, and I don't see where they are coming from.

This is a video of the original animation as seen in Microsoft 3-D Viewer: https://youtu.be/HWA53XhlGC8

And here is a video of how it looks in Unity: https://www.youtube.com/watch?v=odQBVkYnKw4&ab\_channel=TW

Where is this rotation coming from? I don't see it in the original animation.

What could I check?

These are my import settings:

Thank you!

# Answer
> 1 votes
The reason why unexpected rotations with Apply Root Motion enabled happen on the character is that currently, it has no Root node defined. You can think of the Root node as the main driver of your character's Root Motion.

To set up the Root Motion properly, you will first need to select the character's FBX file in the Project window. You should see the character's Model Import Settings in the Inspector window. Select the Rig tab, and under Avatar Definition choose "Create From This Model". Next, select the Root node. Usually, the first one works, but depending on the way the model was set up, you might need to select a different bone to be the Root node. Click "Apply" and we are almost done.

Now, if you expand the character's FBX file in the Project window, you will see that an Avatar was created for this model. Select the character GameObject in the Scene Hierarchy, and drag the newly created Avatar onto the GameObject's Animator component's Avatar property. If you enter Play Mode in the scene now, you should see the character is walking without unexpected rotations.

I've attached some screenshots to help illustrate the instructions more clearly.

---
Tags: unity, animation
---