# Question
Title: How to limit framerate in Unity without causing screentears?
Is there any way to limit framerate in Unity without causing screentears in build? I cannot seem to do it, but Valheim has an fps-slider and they use Unity, so thinking there must be a way?

I am aware of v-sync, but I'm talking about using https://docs.unity3d.com/ScriptReference/Application-targetFrameRate.html

# Answer
> 1 votes
Note that the way you enable vSync in Unity is by setting the value `QualitySettings.vSyncCount`, which is an integer value, with 4 being the allowed maximum. The target framerate becomes the monitor refresh rate divided by that integer. Which can be obtained via `RefreshRate.value`. So if you want both vSync and a limited framerate that is lower than the refresh rate, then you can just set the vSyncCount to the correct factor.

The documentation says that the maximum allowed vSyncCount is 4, but the behavior you get when you set it to a higher value is undocumented. So I would recommend to `Mathf.Clamp` the value to the range of 1 to 4.

So if you want to have a limit of (as close as possible to) 60 Fps while also having vSync enabled, then you can do this:

```
float vSyncFactor = RefreshRate.value / 60.0f;
QualitySettings.vSyncCount = Mathf.Clamp(Mathf.RoundToInteger(vSyncFactor), 1, 4);

```

Due to vSyncCount being an integer, you can not rely on getting *exactly* 60 FPS. For example, a 144Hz monitor will result in a framerate of 72 FPS. So while you do reach your goal to keep the players GPU reasonably cool, you will still need to have those `* Time.deltaTime` multiplication in your Update-methods.

---
Tags: unity
---


# Question
Title: Texture base color not showing for Unreal Engine auto material?
So on the right there's the item that needs to be in the auto material (the base color for snow) but it isn't showing up in the material instance. The node is in the proper group (also shown)

Any ideas? tyvm

# Answer
Depending on what you're asking there's a few possible answers here, so in the spirit of the q/a format I'll try to cover a few:

1. Looks like you have a texture parameter named "Texture Snow Base Color" in the group "0\_snow", so its listed there in your circled image. If you want to change that texture you can tick the option box to the left of the parameter name in the child and override it to something else.
2. It looks like the texture isn't showing on your object, but without seeing more of the graph its hard to decern why. Based on how your object looks it seems like perhaps you have a z-up or red-channel mask currently plugged into the base color or emissive outputs. Considering your parent materials looks similar I'd say this is an issue with your graph and not the child instance, unless there are some switch or boolean parameters that you expect to change the path the graph takes to show this snow texture.

Hope those give you a hint to fix your problem.
> 0 votes

---
Tags: unreal, materials, unreal-5
---


# Question
Title: Imported IK Rigged FBX model into Unreal Engine makes the feet point in the wrong direction
Hi I have a model I rigged in Cinema 4d following the same structure as the UE5 mannequin that I've imported into UE. I am trying to setup retargeting however the animations have the feet pointing in the wrong directions.

I'm fairly new to rigging so I'm not sure what's the issue. I've tried setting up a pole and constraints but I'm still having issues in UE. Any ideas on how I can fix this?

# Answer
This looks like a joint orientation issue.

Simply put, the joints in your skeleton need to be orientated the same way (or as close as possible) to the mesh you intend to retarget from - there are ways around this; by only using IK-based retargeting and ignoring the rotation of the target bones, however, in your case I'd suggest not working around it by fixing the joint orientation at the source to avoid future complications.

As you can see in the above image, the X-axes of Manny's leg joints are "looking down the chain", where the X+ points at the child's bone or the parent bone depending on the orientation (in this case the orientation is flipped on the left limbs to more easily allow mirrored movement).

I'm unfamiliar with Cinema4D's rigging toolkit but I'd suggest looking for ways to set the orientation of your joins so that X+ points down the chain toward the children or leaf nodes, then flip the orientation from the Left Hip and Clavicle joints.

Note: some DCCs have different coordinate spaces, ie. Cinema may by default orient joints with Z+ points down the chain if this is the case it may be a matter of ensuring a correct unit conversion in the FBX exporter.

Hope it helps.
> 2 votes

---
Tags: animation, unreal, rigging, unreal-5, cinema-4d
---


# Question
Title: What is the point of Geometry2D.make_atlas()?
I'm completely bewildered by the `Geometry2D.make_atlas()` method. I believe it has to do with texture atlases based on its name and comment on its source code but am unable to parse exactly how it's supposed to work and what it's supposed to do.

For example, this:

```
func _ready():
    print(Geometry2D.make_atlas([
        Vector2(1.0, 1.0),
        Vector2(20.0, 1.0),
        Vector2(1.0, 20.0),
        Vector2(20.0, 20.0)
    ]))

```

Produces this:

```
{ "points": [(20, 0), (0, 0), (20, 1), (0, 1)], "size": (21, 21) }

```

And it's not clear to me how the points given in my initial array are translated into the ones in the resulting "points" portion of the atlas nor how this would be useful.

# Answer
It provides the layout for a texture atlas. You give it an ordered list of tiles sizes and the algorithm tries to rearrange those tiles into the smallest square that it can. It gives you the size of the atlas and the locations of the tiles (based on the original index order) within the atlas.

In your example, you're giving it four tiles. The resulting atlas that it finds to holds them all is of size 21 x 21.

* The first tile you provided (1x1) is packed such that its starting corner is at position (20,0) within that 21x21 atlas.
* The second tile you provided (20x1) is packed such that its starting corner is at position (0,0) within that 21x21 atlas.
* The third tile you provided (1x20) is packed such that its starting corner is at position (20,1) within that 21x21 atlas.
* The fourth tile you provided (20x20) is packed such that its starting corner is at position (0,1) within that 21x21 atlas.

If we assume a layout where 0,0 is the upper left hand corner, then the layout would look like this:

Note: if you prefer to assume a different coordinate plane layout, just flip the result as necessary to fit that mental model.

As mentioned in the implementation comments, the function attempts to pack the tiles into a square to increase the likelihood that the result will comply with video card memory constraints.

The use case for this function is that it saves you the trouble of determining your own texture atlas layout. You *could* do this on your own, either by hand or with your own algorithm, but the framework is giving you a prebuilt solution so that you don't have to. The one provided by Godot is brute force - there's probably a faster implementation. But it would be one more thing to code, test, debug, and maintain. And relative to the overall performance of your game, optimizing texture atlas construction might not be worth the tradeoff.
> 1 votes

---
Tags: geometry, godot-4
---


# Question
Title: Unity-UI not scaling correctly on android
My UI appears extremely small when i build and launch my game on my android device. Im working with unity 4.6. I've tried changing the UI scale mode of my canvas to all 3 types. Scale with screen size option and constant physical size option makes it too big. Constant pixel size makes it too small. With constant pixel size this is what it looks like on my mobile:

I could increase the scale factor but then it looks like this on PC. Also, I don't think it would look right on a tablet then.

# Answer
Make sure you set your anchor points to the corners of your graphics if you are using `Scale with Screen Size`. I have often run into problems when using the presets for middle, corner, etc when building to an actual device and setting the anchors directly on the corners usually fixes the problem.
> 2 votes

# Answer
You are 2 steps away from solution.

1- Select Canvas and change `UI Scale Mode` in `Canvas Scaler` to `Scale With Screen Size` in inspector.

2- Set screen size from Free Aspect to any other size in Game tab.

Now adjust your UI, it will remain same as in Unity Editor.
> 1 votes

# Answer
I know this thread is pretty old, but I have a solution. When it comes to scale by screen size, the trick is to use a reference resolution that will scale up and down in a way that will fit AND set the match so it knows how to scale. I have been using .5 for that. Here are a couple examples of common sizes that you can use to scale up and down in Unity. I like to use these sizes because they have a scale up and down that is in the common range. When using an image or sprite that only works in one aspect, you can check the preserve aspect box to make sure that image looks right every time. If you're just coloring the button, you don't need to use this option.

* 640 x 960 (SD)
* 1280 × 720 (HD)

Another thing to consider is how the objects will remain in the frame when changing from landscape to portrait, as well. By default, Unity sets the anchor points to the center of the canvas. If you set them to the closest corner instead you will notice that when changing the landscape it will also maintain the proximity to the anchor point that was set.

\[ Credit Unity Docs\]

Doing these things together should help with most resolutions.

Another side note, when objects are set to be children of objects that are already children of the Canvas, the anchor points are then set back to center of the object it's a child of. This can also cause undesired results.

Here are samples of a project I put together for this purpose:
> 0 votes

---
Tags: unity, android, ui-design
---


# Question
Title: How to make non-respawning collectables with a collection counter?
Using Godot 3.1, I've written this script for diamonds that the player collects:

```
extends Area2D

const save_location = "user://data.json"

var details = {
    "diamond": 0,
    "life": 0,
}
func _on_diamondfinal_body_entered(body):
    if body.name == "player":
        loading()
func loading():
    var file = File.new()
    if file.file_exists(save_location):
        file.open(save_location, File.READ)
        var data = parse_json(file.get_as_text())
        details = data

        details.diamond += 1
        saving()
        queue_free()

func saving():
    var file = File.new()
    file.open(save_location, File.WRITE)
    file.store_string(to_json(details))
    file.close()

```

And I have written this script for the "level one" scene:

```
extends Node2D

const save_location = "user://data.json"
var details = {
    "diamond": 0,
    "life": 0,

}

func _process(delta):
    loading()
    $CanvasLayer/Panel/diamond_label.text = str(details.diamond)
    $CanvasLayer/Panel/life_label.text = str(details.life)

func loading():
    var file = File.new()
    if file.file_exists(save_location):
        file.open(save_location, File.READ)
        var data = parse_json(file.get_as_text())
        details = data

```

I have two problems:

1. When I play the "level one" scene, I collect diamonds, but their number does not increase in the scene and it remains at 00.
2. In level one, there are 20 diamonds. How can I set it so that when I go back into the "level one" scene, the diamonds I have collected will not be displayed again?

That means, no matter how many times the player loses and returns to this scene, only the diamonds that they have *not* already collected will be displayed.

# Answer
You seem to be saving and loading a file in multiple locations on your game, instead of having it centralized (e.g. with an autoload). This leads to repetition. And any fix or update to how you handle, you need to make the changes in every location... Which makes it error prone since you might forget to update some.

My current advice is to use `ConfigFile` (although I see you have opted for JSON). I recently explained that solution in my answer to: Increment score when player touches a coin's Area2D.

Your code also has a time-to-check to time-to-use bug. While unusual, the save file could be removed after you checked if it exists and before you try to open it. The correct approach is to handle when Godot fails to open the file.

---

> When I play the "level one" scene, I collect diamonds, but their number does not increase in the scene and it remains at 00.

You don't close the file in the second script. The contents of the file might not have been flushed to storage for the other script to read them.

I expect that having all the code that accesses the file in a single location would also fix this. You can then keep a single representation of the data in memory, which is the only one you save or load. And since everybody would be acceding through the same script, there should not be discrepancies in the data they see (barring multi-threading).

---

> In level one, there are 20 diamonds. How can I set it so that when I go back into the "level one" scene, the diamonds I have collected will not be displayed again? That means, no matter how many times the player loses and returns to this scene, only the diamonds that he has not collected will be displayed.

How yo save *which* diamonds were collected? You save *which* diamonds were collected (not just how many). The same way you save anything else you save. *However you choose to save things.*

And then, every diamond on `_ready` can check if it has already been collected, and if so, erase itself with `queue_free`.
> 0 votes

---
Tags: savegame, serialization, godot-3
---


# Question
Title: How to clamp rotation on a specific axis?
I want to rotate an object based on mouse delta but I am unable to clamp it because I only want it to turn so far on a specific axis.

```
Vector2 inputAxis;
GameObject obj;
//
//
//
void Update()
{
    obj.transform.rotation *= Quaternion.AngleAxis(inputAxis.y,Vector3.Right);
    obj.rotation.eulerAngles = new Vector3(Mathf.Clamp(obj.rotation.eulerAngles.x,-45,45),obj.transform.rotation.y,obj.transform.rotation.z);
}

```

Just results in an error code "Cannot modify the return value of 'Transform.rotation' because it is not a variable." I've googled several pages on how to do this and pretty much every one of them have this almost exact type of clamping so I'm not sure what I'm missing.

I've also tried these...

```
Vector3 targetRotation = obj.transform.eulerAngles;
targetRotation.x = Mathf.Clamp(targetRotation.x, -45,45);
obj.transform.eulerAngles = targetRotation;

```

...as well as...

```
Vector3 targetRotation = obj.transform.eulerAngles;
targetRotation.x = Mathf.Clamp((targetRotation.x<=180)?targetRotation.x:(360-targetRotation.x), -45f, 45f);
obj.transform.eulerAngles = targetRotation;

```

BUT both, instead of going less than 0, will snap to back to 45 instead.

I've also tried something else...

```
// in order to put both units in the positive.
float targetAngle = 45;
Vector3 targetRotation = new Vector3(180f,0,0); //face the other direction
targetRotation.x *= inputAxis.y;//to rotate from player movement
target.x = Mathf.Clamp(target.x, 180-targetAngle, 180 + targetAngle ); //to get the clamp
target.x -= 180f; //to get it back in the right direction
obj.transform.eulerAngles = target; //and set

```

# Answer
> 1 votes
It's generally not safe to use Euler angles as the input to a computation. Many different Euler angle representations map to the same resulting orientation, and the values need to wrap around somewhere, so this very easily leads to problems like the ones you've discovered.

You can avoid this by tracking your current rotation angle internally, and not reading it out of the `eulerAngles` getter. Something like this:

```
public class LimitedRotation : MonoBehaviour {

    public Vector3 axis = new Vector3(1, 0, 0);

    public float currentAngle = 0f;
    public float maxAngle = 45f;
    public float minAngle = -45f;

    Quaternion _relativeTo;

    void Start() {
        _relativeTo = transform.localRotation;
    }

    public void Rotate(float delta) {
        currentAngle = Mathf.Clamp(currentAngle + delta, minAngle, maxAngle);

        var fromInitial = Quaternion.AngleAxis(currentAngle, axis);

        transform.localRotation = _relativeTo * fromInitial;
    }
}

```

---
Tags: unity, rotation, euler-angles
---


# Question
Title: How do I make AI avoiding obstacles on tile map?
I implemented 2 NPCs chasing the character using Dijkstra algorithm for pathfinding. Tile map is represented by graph, where a node is basically the tile, and the adjacency list consist of adjacent tiles.

Only walkable way points are added to the graph (tiles which are not empty on walkable layers). All obstacles and their backgrounds are on different layers, that are not used for path finding. However, you can see that entities do intersect obstacles or end up on non-walkable layers).

How would experienced game developer handle this? What strategy should I use? I have tried applying collider which I use for my character to avoid intersection of obstacles to the NPCs, however this results in chaotic velocity changes (AI applies velocity and collider drops it)

**UPD:**

I noticed that I was comparing entity's top left corner to tile center to check if entity has reached a certain tile.

Now i use tile's center and entity's center to check if the entity reaches certain tile while traversing the path. Diagonal movement to diagonally adjacent tiles is also possible. But it still does not solve the problem even though now movement is more natural.

```
private fun modifyVelocity(tileIndex: Int) {
    val nextPos = tileMap.getTilePosition(tileIndex)
    val x = nextPos.x + tileMap.getTileWidth() / 2
    val y = nextPos.y + tileMap.getTileHeight() / 2

    val centerPoint = params.getCenterPoint()

    params.velocityX = when {
        isHorizontalDiffInsignificant(x) -> 0f
        x > centerPoint.x -> VELOCITY
        x < centerPoint.x -> -VELOCITY
        else -> 0f
    }

    params.velocityY = when {
        isVerticalDiffInsignificant(y) -> 0f
        y > centerPoint.y -> VELOCITY
        y < centerPoint.y -> -VELOCITY
        else -> 0f
    }
}

```

I also can show the unwalkable layers of the map, which are not added to the path. One layer for obstacles and one layer for their background.

I personally have a feeling, that this is geometrical problem, probably I should use another point to represent entity position

# Answer
Since heights of tiles and entities may vary dramatically, the idea of comparing their centers is wrong way to solve this problem.

After some research I came up with a solution which supposes comparing bottom-center positions of the tiles and the entities.

```
    val nextPos = tileMap.getTilePosition(tileIndex)
    val x = nextPos.x + tileMap.getTileWidth() / 2
    val bottomY = nextPos.y + tileMap.getTileHeight()

    val centerPoint = params.getCenterPoint().x
    val bottomPoint = params.y + params.ySize

    params.velocityX = when {
        isHorizontalDiffInsignificant(x) -> 0f
        x > centerPoint -> VELOCITY
        x < centerPoint -> -VELOCITY
        else -> 0f
    }

    params.velocityY = when {
        isVerticalDiffInsignificant(bottomY) -> 0f
        bottomY > bottomPoint -> VELOCITY
        bottomY < bottomPoint -> -VELOCITY
        else -> 0f
    }

```
> 2 votes

---
Tags: collision-detection, tilemap
---


title: Collision between AABB and Circle

text:
# Question
Title: Collision between AABB and Circle
I'm programming collision systems for a 2D game engine. The idea is that different systems can interact with each other. So one of the cases would be check collisions between axis aligned bounding box against a radius based circle collision. They both are implemented to react with its same type of collision returning me a minimum translation vector. So my approach is to combine them was to interpret the box with its bounding circle if the circle was in one of the corner outer regions of the box, and check collisions between both circles but if the circle is located in a side outer region of the box I interpret the circle with its bounding box and apply AABB collision.

The question: Is that approach, a good one?

# Answer
( Edit : the method above works only for square AABB, i'll have to think on how to improve it, sorry )

Fastest way is to :
\- A) test circle against rect's outer bounding circle -\> reject if too far.
\- B) test circle against rect's inner bounding circle -\> accept if near enough.
\- C) test that the outer point of the circle (on the line joining both centers) is in the AABB.

To do that quickly , precompute inner, outer radius for your AABBs.

Some pseudo-code to illustrate :

```
var sqDistanceBetweenCenters = sqDistance ( AABB.center, Circle.center );
if (sqDistanceBetweenCenters > sq ( AABB.outerRadius + Circle.radius ) ) return false;
if (sqDistanceBetweenCenters < sq ( AABB.innerRadius + Circle.radius ) ) return true;
var c1c2Vect =  ( Circle.center - AABB.center ) . normalize();
var outerPoint = Circle.center + Circle.radius * c1c2Vect ;
return AABB.pointInRect(outerPoint);

```

In most cases they won't intersect so you have very few operations.
In quite some of the remaining cases they will intersect with the inner radius, so again few operations.
> 8 votes

# Answer
I've been thinking about this problem for a long time and looked at some of the answers here and on other forums. I came up with the following idea:

Suppose the circle has radius `R`. When looking at cases where the circle collides with the AABB , the **center** of the circle has to fall within a certain area around the AABB. The extreme cases are when the center is contained in the rectangle, then collision obviously occurs. Or if the distance between the center and the outer circle on the rectangle is greater than `R`, then collision obviously didn't occur. But what about the intermediate cases?

The idea is to find extreme points for the center of the circle to lie on. These are points where the circle is positioned in such a way that it's just touching the rectangle at one point. If we trace out all such extreme points, we get something like the following picture:

As we can see the set of extreme points trace out a rounded rectangle around the AABB, this rounded rectangle is precisely the set of points that are distance `R` from the AABB. In fact, collision occurs if and only if the center of the circle is inside that rounded rectangle. So now we've reduced the problem to checking if a point `(x, y)` is inside of a rounded rectangle.

To that end we can divide the rounded rectangle into 6 parts (4 circles with centers on the vertices of the AABB, and 2 rectangles):

The 4 green circles are identical in size (all with radius `R`) and so are the two rectangles. Moreover the intersection of the red rectangle and the blue rectangle is precisely the AABB. So if the center of the circle is inside any of these 6 shapes, then collision occurs. If the center of the circle is in none of these 6 shapes, then collision doesn't occur.

Note that this method does not require the center of the AABB (although you would already have that information anyway) and only depends on the center and the radius of the circle.
> 5 votes

# Answer
To detect collisions between a circle and an AABB, you should find the closest point from the AABB to the circle. You can run the below code snippet and try to move the purple point which represents the AABB center to watch the position of the closest point.

```
<iframe src="https://www.desmos.com/calculator/u32th8uhli?embed" width="500px" height="500px" style="border: 1px solid #ccc" frameborder=0></iframe>
```
The math behind it is to clamp the distance from AABB to circle on each axis separately. The value will be clamped on each axis if the distance is greater than the extent(half-width or height) or less than the negative extent. Like the below figure shows:  (Forgive my clumsy finger).
The pseudo-code is:
```
func CheckCollision() {
    vector3 distance = Circle.Center - AABB.Center;
    vector3 clampDst = Clamp(distance, -AABB.Bounds, AABB.Bounds);
    vector3 closestPoint = AABB.Center + clampDst;
    return Distance(closestPoint, Circle.Center) <= Circle.Radius;
}

```
> 5 votes

# Answer
Assuming case 1 means the *center* of the circle is in a lateral region, and case 2 means the *center* of the circle in a corner region, this approach has a problem.

Specifically, when the circle is just barely into a corner region, the square is treated as suddenly larger. If the circle was grazing the square, it will suddenly be intersecting. The behavior over time goes nonlinear...

**What you actually want for case 2 is to treat the AABB's vertices each as a circle of radius zero.** (You'd only have to check the vertex for current corner region.)

(Additionally, the method as you describe it becomes asymmetric on rectangular AABB's; the long sides will bulge more than the short sides, when approximated with a circle.)
> 1 votes

# Answer
Im not sure if I am missing some cases but if you use combine the AABB AABB test and then check if the distance between any of the 4 AABB vertices to the circle's center is less than circle's radius, doesnt that cover all cases? NVM, you need to check axis that is from the circle's center to the closest vertex of the AABB is less than circle's radius.

This should work:

```
//copy the circle center to a new point (this changes so there needs to be a copy)

Point pt = circle.center;

    //point on rectangle closest to circle
    //(snaps the point to the rectangle, pretty much,
    //if the circle center is inside the rectangle there isn't snapping,
    //but this is fine since it will detect a collision as a result)

if(pt.x > rectangle.right) pt.x = rectangle.right;
if(pt.x < rectangle.left) pt.x = rectangle.left;
if(pt.y > rectangle.bottom) pt.y = rectangle.bottom;
if(pt.y < rectangle.top) pt.y = rectangle.top;

    //distance check, just use distance^2 for actual implementation

return distance(pt, circle.center) < circle.radius;

```
> 0 votes

# Answer
There's almost certainly a cleaner way to write this, but I wasn't able to find a fully-formed solution that returns a proper collision manifold for contact resolution anywhere on the web. Just a bunch of half-baked stuff. So I wrote and tested this. I *think* it works correctly for all cases, but I was especially concerned with the case where the circle is fully inside of the AABB for my use-case.

Red = circle that is colliding
Green = new position of circle after contact resolution
Blue Dot = point-of-contact
Orange Line = contact resolution vector (normal * depth)

```
struct Rectangle { float x, y, width, height; };

bool dlb_CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec, Vector2 &contact, Vector2 &normal, float &depth)
{
    float xOverlap = 0;
    float yOverlap = 0;

    Vector2 pt = center;  // circle center point constrained to box
    if (pt.x < rec.x) {
        pt.x = rec.x;
    } else if (pt.x >= rec.x + rec.width) {
        pt.x = rec.x + rec.width;
    } else {
        float recCenterX = rec.x + rec.width / 2;
        xOverlap = pt.x < recCenterX ? rec.x - pt.x : (rec.x + rec.width) - pt.x;
    }

    if (pt.y < rec.y) {
        pt.y = rec.y;
    } else if (pt.y >= rec.y + rec.height) {
        pt.y = rec.y + rec.height;
    } else {
        float recCenterY = rec.y + rec.height / 2;
        yOverlap = pt.y < recCenterY ? rec.y - pt.y : (rec.y + rec.height) - pt.y;
    }

    if (Vector2DistanceSqr(pt, center) < radius*radius) {
        contact = pt;  // closest point to "pt" on the surface of the box
        if (fabsf(xOverlap) < fabsf(yOverlap)) {
            contact.x += xOverlap;
        } else if (fabsf(yOverlap) < fabsf(xOverlap)) {
            contact.y += yOverlap;
        }

        Vector2 pen = Vector2Subtract(center, contact);
        depth = radius - Vector2Length(pen);
        normal = Vector2Normalize(pen);

        if (xOverlap && yOverlap) {
            depth -= radius*2;
        }
        return true;
    }
    return false;
}

```

This is how I use it in the code. Note that the dot product check is optional, and is there to allow circles with outward velocities to escape the rectangle as opposed to getting stuck inside of it.

```
struct Vector2 { float x, y; };

float Vector2DotProduct(Vector2 v1, Vector2 v2) {
    return v1.x*v2.x + v1.y*v2.y;
}

Vector2 contact{};
Vector2 normal{};
float depth{};
if (dlb_CheckCollisionCircleRec(entity.position, entity.radius, tileRect, contact, normal, depth)) {
    entity.colliding = true;
    if (Vector2DotProduct(entity.velocity, normal) < 0) {
        entity.position.x += normal.x * depth;
        entity.position.y += normal.y * depth;
    }
}

```
> 0 votes

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


# Question
Title: How do I use SetTile() with a tile asset/ scriptable tile?
How do I use `Tilemap.SetTile()` with a tile asset? I want to use it for scriptable tiles in the 2d-extras package, such as rule tiles, weighted random tiles, and animated tiles.

How would I...

1. get inspector reference of this scriptable tile, and then
2. use `SetTile()` with it?

# Answer
> -1 votes
TileBase actualy works, so i recommend using it.

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


# Question
Title: Unity is reimporting everything! How do I stop that?
I have a relatively large project (about 8GB) and it is constantly reimporting itself over and over, to the point that I spend 80% of my time waiting for Unity to:

* Reimport everything
* Stop hanging.

Even for the smallest of changes (ie. removal of a comment on one line in a script), or changing import settings on an asset can cause these long hangs and reimports.

To make matters worse, this project is also synced over UnityCollabBETA, which throws manual/selective import (auto-refresh is forced on) out the window.

I've also read up that other programs locking asset files (to read them) can also cause Unity to reimport everything as opposed to simply doing a selective import (only reimporting things that has been changed).

I've tried creating blacklists for my auto-backup programs, anti-viruses and anything that would snoop around and/or mess with the Unity Project folders. However, despite those programs not accessing anything, Unity still reimports the whole project every time I alt-tab out.

The only workaround I've found so far is to just kill Unity every time it does it and relaunch it as for some reason it processes the actual changed files first, then hangs itself by going through everything else.

It is also worth noting that I/O is maxed up by Unity (due to the sheer size of the project) and CPU/GPU usage are relatively low (does not exceed 20-30%, assuming nothing else is running in the background).

**Note:** This has persisted through installs and computers.

---

# Question

How do I stop Unity from reimporting everything without constantly killing Unity?

# Answer
One option which can in some cases greatly decrease the waiting time after small script changes can be to disable domain reloading and to disable scene reloading in your project settings. You can find this under File -\> Project Settings -\> Editor. Enable "Enter Play Mode Options" and then leave "Reload Domain" and "Reload Scene" disabled.

However, be aware of the side-effects:

* Any `static` variables in your scripts will no longer get reset to the initial values when you restart the game. They will only reset when you restart the Unity editor. A possible workaround for that problem can be a `[RuntimeInitializeOnLoadMethod]` which resets all static variables.
* Any arrays which are exposed inspector properties but have no entries in the inspector, will be `null` instead of arrays with 0 entries.
* On switching from editor mode to play mode, `[ExecuteInEditMode]` scripts won't get disabled and re-enabled as usual and there won't be an obligatory `OnValidate()` call for all scripts either.

None of these behavior differences will affect the game builds, but might result in some unexpected behavior during development.
> 3 votes

# Answer
Another way to mitigate reimports is for example to enable Parallel Import in the `Project Settings/Editor/Asset Pipeline` section, or changing how many cores the Unity Editor can use for imports (`Preferences/Asset Pipeline`) etc. This isn't a real solution, but I've found some salvation in atleast doing this when I didn't want to do the more bug-risky methods described by the others.

Edit 1: As noted by the first comment below, this could potentially cause issues with some libraries that use importers relying singlethreaded global state.

Edit 2: You can also consider using Assembly Definitions for parts of code that are separable, like your main scripts and editor-scripts. I use a git submodule with assembly definitions for my projects for tools that do not need to be recompiled every time a gameplay script or editor script is changed.
> 2 votes

# Answer
I am guessing you have some scripts in your project that is causing this, as it is possible to override Unity's default behavior when it comes to importing assets. I would try to copy the project, remove all scripts and see what happens.

If this removes the problem, then looking for any scripts that imports UnityEditor should help narrow it down further
> 0 votes

---
Tags: unity
---


# Question
Title: Variable not updating while program is running
I am having issues where the variable action\_cooldown does not update. I could remove this but then both the player and enemy attack at the same time, which is something you do not want in a turn based game. The variable action\_cooldown counts up by adding one each pass and when action\_cooldown reaches 90 (action\_wait\_time) the player can then attack. However in my code the action\_cooldown does not count up, instead it adds 1 and stops counting. Im guessing this is something to do with pygame and or the fact that the code is running under a constant while loop. I've played around with while loops and adding in other files and it didn't work. I'm sure it's something simple however I just cannot seem to see it.

Relevant code is added below, however if you need more please let me know and I'll upload the whole project. Thanks!

```
        #control player actions
    #reset action variables
    attack = False
    potion = False
    #define other variables
    game_over = 0 # 0 = running 1 = player won -1 = player lost
    current_fighter = 1 # 1 = hero's turn 2 = enemy's turn
    total_fighters = 2
    action_cooldown = 0
    action_wait_time = 90
    enemy_list = []
    enemy_list.append(self.enemy)
    #create buttons
    restart_button = Button(self.screen, 330, 120, restart_img, 120, 30)
    #make sure mouse is visible
    pos = pygame.mouse.get_pos()
    for count, enemy in enumerate(enemy_list):
        if self.enemy.rect.collidepoint(pos):
            if clicked == True and self.enemy.alive == True:
                attack = True

    #Main Turn Based Logic
    if game_over == 0:
        #player action
        if self.hero.alive == True:
            if current_fighter == 1:
                action_cooldown += 1
                print(action_cooldown)
                if action_cooldown >= action_wait_time:
                    #look for player action
                    #attack
                    if attack == True:
                        self.hero.Attack()
                        current_fighter += 1
                        action_cooldown = 0

        else:
            game_over = -1

        #enemy action
        for count, enemy in enumerate(enemy_list):
            if current_fighter == 2 + count:
                if self.enemy.alive == True:
                        action_cooldown += 1
                        if action_cooldown >= action_wait_time:
                                #check if bandit needs to heal first
                                if (self.enemy.health / self.enemy.max_hp) < 0.5:
                                        #check if the potion would heal the bandit beyond max health
                                        if self.enemy.max_hp - self.enemy.health > potion_hp:
                                                heal_amount = potion_hp
                                        else:
                                                heal_amount = self.enemy.max_hp - self.enemy.health
                                        self.enemy.health += heal_amount
                                        self.enemy.potions -= 1
                                        current_fighter += 1
                                        action_cooldown = 0
                                #attack
                                else:
                                        self.enemy.Attack()
                                        current_fighter += 1
                                        action_cooldown = 0
                else:
                        current_fighter += 1

        #if all fighters have had a turn then reset
        if current_fighter > total_fighters:
            current_fighter = 1

    #check if all enemies are dead
    alive_enemies = 0
    if self.enemy.alive == True:
        alive_enemies += 1
    if alive_enemies == 0:
            game_over = 1

    #check if game is over
    if game_over != 0:
        if game_over == 1:
            self.screen.blit(victory_img, (250, 50))
        if game_over == -1:
            self.screen.blit(defeat_img, (290, 50))
        if restart_button.draw():
            self.hero.reset()
            for enemy in enemy_list:
                self.enemy.reset()
                current_fighter = 1
                action_cooldown = 0
                game_over = 0

    pygame.display.update()

```

# Answer
> 0 votes
Your comment `#Main Turn Based Logic` implies this is all in a loop that isn't shown.

If so, this line is also inside the loop:

```
action_cooldown = 0

```

Which means it will reset to `0` every time, then add 1...

It's also worth noting that if you move the `action_cooldown` outside the loop (but not in a class or other encapsulating structure) you may need to use the global keyword to write to it.

---
Tags: python, pygame
---


# Question
Title: The Unity 2021 URP 2D Renderer Sprite-Unlit-Default material transfers transparency of layered sprites to render texture
So, complicated title, but I am not sure how to properly describe this phenomenon.

I have switched recently from Unity version 2019 to 2021 to use the URP 2D-Renderer and make use of the \_CameraSortingLayer for blending in custom shaders.

Since then the Sprite-Unlit-Default shader produces weird results for unrelated GameObjects in the same scene.

as example this Characters mouth, the character itself consists of stacked sprites, which are captured by another camera and rendered onto a render texture. That render texture is then used in the scene. The mouth has a slight transparency in the lipstick to fade it onto the face:

Resulting face as it should be:

When I use the Sprite-Unlit-Default shader (which I assume is the proper choice, since I am not using lights), however the mouth transfers that transparency over to the render texture and the background color bleeds through. It looks then like this:

Literally any other shader (lit, builtin Sprites-Default) is fine.

I tried playing around with the camera settings an such. Disabling post processing on the character camera also fixes this, but then the whole render texture is filled with black background.

Whats happening here?

# Answer
> 1 votes
This occurs because of this line in the default unlit sprite shader:

```
Blend SrcAlpha OneMinusSrcAlpha

```

This says to use the standard "layer" transparency function:

```
resultColour = outputColour * outputAlpha + backgroundColour * (1 - outputAlpha)

```

The trouble is, it's using this formula for *both* the colour channels *and* the alpha channel.

So blending partially-transparent red over the background will both nudge the texture colour toward red *and* nudge the texture alpha toward partially-transparent.

You can fix this to only accumulate alpha into the background like so:

```
Blend SrcAlpha OneMinusSrcAlpha, One OneMinusSrcAlpha

```

This ensures the resulting alpha is never less than what was in the texture already.

Copy the default unlit sprite shader and change the `Blend` line to use this, then make your own sprite material that uses this shader.

Note though, when you're pre-composing images to a staging texture to later render over a different background, what you really want to use is pre-multiplied alpha rendering (see "super-power #2" in that answer). Otherwise you can get some subtle fringing in the blend against the background where multiple translucent layers mingle in the pre-composed texture.

---
Tags: unity, shaders, sprites, unity-urp
---


# Question
Title: how to rotate my character along the y axis when character is aligned with a slope
I have a capulse character Im moving around in my 3d Game, I usually rotate the character using this line of code:

```
void HandleRotation(){
        if(_move.magnitude > 0.1){
            _targetAngle = Mathf.Atan2(_move.x, _move.y) * Mathf.Rad2Deg + _camera.transform.eulerAngles.y;
            angle = Mathf.SmoothDampAngle(_playerTransform.eulerAngles.y, _targetAngle, ref _turnSmoothVelocity, 0.02f);
            Vector3 relativeForce = (Quaternion.Euler(0f, _targetAngle, 0f) * Vector3.forward).normalized;

                publisher.UpdateDirection(_move);
                _force.x = relativeForce.x * Speed * _move.magnitude;
                _force.z = relativeForce.z * Speed * _move.magnitude;

        }
        else {
            _force.x = 0;
            _force.z = 0;
            publisher.UpdateDirection(new Vector2());
        }
    }

 void ApplyRotation(){

      _rigidbody.MoveRotation(Quaternion.Euler(0, angle , 0));
 }

```

This works fine when on a flat plane, and on slopes, however id like to align my player to the slope they're on. I have code to check if a player is on a slope and to align them to the slope:

```
void SlopeCheck()
    {
        Quaternion newRot;
        RaycastHit downHit;
        if (Physics.Raycast(_groundCheck.position + Vector3.up, Vector3.down, out downHit, 5f, _groundLayer) && _isGrounded && !_jumpPressed)
        {
            _onSlope = true;
            slopeNormal = downHit.normal;
            _playerTransform.rotation = (Quaternion.FromToRotation(_playerTransform.rotation.eulerAngles.normalized, slopeNormal)) * _playerTransform.rotation;
        }
    }

```

However this ends up making my character jitter like crazy along the x axis:

I have tried combining these two rotations in various ways but each one gives me awkward results, is there a way for me to make sure I can still rotate my character along the Y axis when aligned along a slope? I'm guessing because my character isnt pointing directly upwards, the rotation would need to be some combination of an x,y,z rotation but I'm unsure how to derive this in code. Any help would be greatly appreciated!

# Answer
It seems like this order of rotation did the trick for me:

```
_playerTransform.rotation = (Quaternion.FromToRotation(Vector3.up, slopeNormal)) * (Quaternion.Euler(0, angle , 0));

```

It also works using `MoveRotation`!
> 0 votes

---
Tags: unity, rotation, rigidbody
---


# Question
Title: Bold black bar on right side of game in Unity (Android)
I am trying to create an endless runner. I have already created a system to generate infinite backgrounds from an array of some. However, on running the game, I get huge black bar on the right side of the screen, both on PC and on Android phone.

Here are the screenshots :

One more thing, on Android, it doesn't even display the left side of the game, i.e, where the character is. It looks like the things are displaced towards left.

Also, the game is a scrolling on and everything is scrolling but behind that bar. It just doesn't go.

I hope I can get some help. Ask me if you need any piece of code.

EDIT :

"CameraFollow" script

```
 using UnityEngine;
using System.Collections;

public class CameraFollow : MonoBehaviour {

    public GameObject targetObject;
    private float distanceToTarget;

    // Use this for initialization
    void Start () {
        distanceToTarget = transform.position.x - targetObject.transform.position.x;

    }

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

        float targetObjectX = targetObject.transform.position.x;

        Vector3 newCameraPosition = transform.position;
        newCameraPosition.x = targetObjectX + distanceToTarget;
        transform.position = newCameraPosition;
    }
}

```

My "GeneratorScript"

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

public class GeneratorScript : MonoBehaviour {

    public GameObject[] availableRooms;

    public List<GameObject> currentRooms;

    private float screenWidthInPoints;

    // Use this for initialization
    void Start () {
        float height = 0.0f * Camera.main.orthographicSize;
        screenWidthInPoints = height * (Camera.main.targetDisplay);
    }

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

    }

    void FixedUpdate()
    {
        GenerateRoomIfRequred ();
    }

    void AddRoom(float farhtestRoomEndX)
    {
        int randomRoomIndex = Random.Range (0, availableRooms.Length);

        GameObject room = (GameObject)Instantiate (availableRooms [randomRoomIndex]);

        float roomWidth = room.transform.FindChild ("floor").localScale.x;

        float roomCenter = farhtestRoomEndX + roomWidth * 3.0f;

        room.transform.position = new Vector3 (roomCenter, 0, 0);

        currentRooms.Add (room);
    }

    void GenerateRoomIfRequred()
    {
        //1
        List<GameObject> roomsToRemove = new List<GameObject>();

        //2
        bool addRooms = true;

        //3
        float playerX = transform.position.x;

        //4
        float removeRoomX = playerX - screenWidthInPoints;

        //5
        float addRoomX = playerX + screenWidthInPoints;

        //6
        float farhtestRoomEndX = 0;

        foreach(var room in currentRooms)
        {
            //7
            float roomWidth = room.transform.FindChild("floor").localScale.x;
            float roomStartX = room.transform.position.x - roomWidth * 6.0f;
            float roomEndX = roomStartX + (roomWidth * 13.0f);

            //8
            if (roomStartX > addRoomX)
                addRooms = false;

            //9
            if (roomEndX < removeRoomX)
                roomsToRemove.Add(room);

            //10
            farhtestRoomEndX = Mathf.Max(farhtestRoomEndX, roomEndX);
        }

        //11
        foreach(var room in roomsToRemove)
        {
            currentRooms.Remove(room);
            Destroy(room);
        }

        //12
        if (addRooms)
            AddRoom(farhtestRoomEndX);
    }

}

```

(I tried playing with the numbers on GeneratorScript, but nothing seemed to help.

# Answer
> 1 votes
I know this is 8 years later, but I found that for me this black bar was from adjusting the viewport rect settings to make the camera smaller. I reversed it by resetting viewport rect back to X-0 Y-0 W-1 H-1

The main reason I am reporting it here is because I could not find anything else online and could have benefited from this earlier.

---
Tags: unity, c#, 2d, android, software-engineering
---


# Question
Title: How to code shaders in C# without resorting to other programming languages?
I'm working on game and game engine and want a way to prototype shaders. I'm not skilled with C++ or GLSL or HLSL or something, but I can code in C#.

My question is: How can I code shaders in C#, without using the other mentioned languages?

# Answer
> 11 votes
This is not wholly impossible. There's a type of compiler called a transpiler that will take source code written in one language and compile it, not to bytecode or machine instructions, but to equivalent source code in another language.

Unity for instance uses this technique to transpile its hlsl-like Shaderlab code to glsl for platforms that don't use DirectX. (As well as a variant on the idea in IL2CPP to transform CIL bytecode to C++)

So, in theory, you could write a C# library with an API equivalent to an hlsl/glsl shader environment, write your shader in C#, and either run it on the CPU to emulate a GPU, or transpile it to equivalent hlsl/glsl to send to a real graphics card.

In the comments below, Theraot has provided a link to a project that does something like this.

But I don't think you gain anything by doing that.

C#, hlsl, and glsl syntax all descend from the same C-like conventions, so your code would look almost identical. You wouldn't really gain any particular ease of use this way.

Some idioms that are easy to express in shader languages, like annotating semantics, swizzling to swap the order of components of a vector, or constructing temporary vectors without `new`, can be more cumbersome to express in C# — so your code could even end up a bit *more* complicated in this form.

Worse, there are a lot of things that would be valid C# that are not valid in a shader, like side effects that mutate global state in the middle of a fragment shader. Shader languages are deliberately constructed to ensure you can't break the rules like this. Your C# version would need good error reporting from your transpiler to catch these errors, because the C# compiler thinks they're OK.

So really, the biggest hurdle in writing shaders is wrapping your head around the massively parallel paradigm they use. Just swapping the language won't make that easier.

So, I'd argue you're much better off just picking up hlsl or glsl — there's very little new syntax to learn, and you won't need a complicated emulation environment. Or, if you want to work your way up slowly, consider using a nodegraph based shader editor to get a feel for the operations in a shader, without writing code at all. Once you understand the data flows, replacing nodes with familiar C-like code should be no big obstacle.

# Answer
> 1 votes
As of 2023, you may look at the ComputeSharp library

It seems to be mostly targeted at computing stuff (as opposed to creating visual effects), i.e. using the GPU to calculate things really really fast and in parallel. But after seeing their demo it seems that you can just use it for anything.

A good point is that they claim to be production ready (i.e. it's not a small, short-lived, unfinished, unmaintained library).

# Answer
> -1 votes
I don't know if C# has an API that can compile and load up a shader, and communicate with it wrt sending it data. I bet it does with DirectX. OpenGL might be a different story in C#. Or, perhaps try to link to the opengl lib directly:

```
[DllImport("opengl32")] public static extern void glVertex3f(float x, float y, float z);

```

OpenGL example

You might want to code it all up in a C/C++ lib, and then make your C# code call into it. You need to be able to compile and link GLSL code, then be able to communicate with it, at least with uniform variables. I think C# has bindings for DirectX. But, I am not familiar with it.

---
Tags: c#, shaders
---


# Question
Title: Are there viable alternatives to polygons for creating 3D worlds?
Of course, I see the benefit in using polygons to create 3D worlds. But I sometimes wonder if other methods exist and have been used in published computer games; perhaps even hybrid methods of 3D animation that combine polygons with some other style of rendering, so that the limitations of polygonal rendering might be overcome or just mitigated. For example, a way of rendering human bodies without jagged limbs.

# Answer
A technique which comes around again and again for decades is raytracing. While usual 3d engines are based on taking a bunch of vertices in 3d space and see where they end up if transformed to 2d space through a projection matrix, raytracing engines simulate a ray of light from each screen-pixel into the scene and see where it hits a surface.

Raytracing engines usually like to show off by rendering perfect spheres reflecting their environment. While spheres and reflections are hard to do well in polygon-based engines, they are quite trivial to do with raytracing.

Unfortunately GPUs aren't optimized for raytracing, so very few games make use of this extensively, so no GPU vendors bothers to optimize for it. This chicken-egg problem prevents the method from becoming mainstream. There are a few experimental games which use raytracing-based engines, though.
> 5 votes

# Answer
To throw out one other possibility, we can define a scene in terms of a signed distance field and raymarch against that. Many demoscene creations use this technique to create highly detailed scenes on a minuscule data budget, letting the mathematical formulae do the heavy lifting.

This scene, from a demo called rgba slisesix was created by Íñigo Quilez, one of the most prolific creators using this technique. It's generated from a 4 kilobyte executable, with no models or texturemaps.

You'll see this technique used in many Shadertoy examples too, like these elephants, again by Íñigo Quilez (warning - this link is pretty taxing on the browser)

(Check out Íñigo Quilez's site for more examples and fascinating articles about the math & programming behind these and other effects)

The technique is darn near magical in its ability to represent smoothly curving surfaces and absurdly, even fractally fine detail as you zoom in. Thanks to some clever space-folding math, it's also great for representing repeating content, like regular structures in architechture. Once you render one motif/column/arch/etc, you can mirror and tile it infinitely at little additional cost.

There are many downsides though:

* The distance functions for a complex scene can be very expensive to evaluate. (See the elephants above. As a polygonal mesh scene, we could render a similar visual at a much higher framerate using current hardware & software) The usual performance fixes we might apply to polygonal scenes, like level of detail reduction, culling, and impostors, don't have a direct or easy-to-plug-in analogue in signed distance fields.
* Authoring a signed distance field scene requires a kind of mathematical sculpting skill that few game content creators have mastered. It's not as simple as creating your scene in a conventional 3D package and clicking "convert to signed distance field." While voxelized distance information from a mesh can be used for some effects like shadowing, any demo with complex signed distance visuals has almost certainly been built from the math up.
* Modifying a scene dynamically is even trickier. With a polygonal scene, we can potentially move, delete, or add each polygon independently. We can use skinned meshes to animate characters. With a signed distance field, everything is a product of the formula, and not every intuitive operation we might want to apply has a clear or side-effect-free expression in that domain.

So far, polygonal rasterization has proven to be a more flexible tool, practical for the majority of the games we build today. But I bet there could be some clever ways to design a game around the particular quirks of distance field raymarching and create something pretty cool!

One interesting development in that direction: as I understand it, MediaMolecule's Dreams uses signed distance fields for their creation tools, but they don't render them directly - they convert them to points or quads to render the resulting forms in a more conventional fashion.

Claybook takes this a step further by baking a signed distance field into a 1024 x 1024 x 512 pixel volume texture, to 1/32 voxel precision, and raymarching through that volume in the shader. This limits the detail that can be achieved and the size of the world you can create, but sidesteps the three downsides I listed above.

In this screenshot, the blobby shapes in the foreground are rendered as a raymarched SDF, while the character and room in the background are more conventional polygonal rendering.
> 6 votes

# Answer
It's possible to build a graphics engine using other geometric primitives. In 1994, Accolade released a 3D fighter called Ballz used spheres. It was impressive for the hardware at the time & notably different from other things available on console, but didn't do particularly well as a franchise. The underlying engine was later used for a number of virtual pet games.

Ecstatica & Ecstatica 2 (released by Psygnosis in 1994 & 1997 respectively) primarily used ellipsoids. I didn't play either of these, but again recall that they looked distinctive.

A more recent example is Toribash, which appears to use a combination of spheres, cylinders, cones & polygons.
> 2 votes

# Answer
The most common alternative to describing 3D world in terms of polygons are various voxel based techniques. Voxels are to 3D as pixels are to 2D. You can construct a 2D picture using vector graphics, or pixels. Similarly you can create 3D world using polygons or voxels.

One way of doing voxels is popularized by Minecraft. You divide 3d space into smaller portions using cubes and give each cube a color/transparency - similarly like you did in 2D picture dividing it in small squares. If the cubes are large, you can assign them a texture instead of one color.

A variant of this technique was already mentioned - signed distance fields. It works by dividing space with 3D planes. At cross-section of three planes there is a unique point. This can be visualized as a uniform mesh of points floating in the air. You assign a number to each point. If you want to determine the properties of a point in 3D space, you sum up values in close proximity and for example if it is above certain threshold, you treat the point as solid. Positive numbers "project" solidity around, negative project "opaque". What the world looks like is determined by computing cross-sections of many values.

Cube engines reverse that approach. You take a finite cube of 3D space which will be your world. You divide this cube into 8 smaller cubes, and mark each whether it is opaque, solid (which color/texture/slant/round) or is subdivided. If the cube is subdivided, you mark each one of 8 subdivisions, whether it is opaque, solid or is subdivided. Rinse, repeat. The world is described with a tree structure of such subdivisions. There is no (theoretical) limit to these subdivisions, so you can always make the smallest voxel even smaller and add more detail. You can check tesseract.gg for the latest engine in the line, to see what can be accomplished.
> 1 votes

---
Tags: 3d, skeletal-animation
---


# Question
Title: for event in pygame.event.get(): pygame.error: video system not initialized
I'm going through a tutorial and trying to build a game using Python and struggling to resolve below error. Not sure what I'm missing here can someone help with it

**Alien\_invasion.py**

```
import sys
import pygame
from settings import Settings
from ship import Ship

class AlienInvasion:
    """Overall Class to manage game assets and  behavior.."""

    def __int__(self):
        """Initialize the game and create game resources.."""
        pygame.init()

        self.settings = Settings()   #pygame.display.set_mode((1200,800))
        self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        self.ship = Ship(self)
        #pygame.display.set_caption("Alien Invasion")

        #Set the background color
        #self.bg_color = (230,230,230)

    def run_game(self):
        """ Start the main loop for the game..."""
        running = True
        while running:
            #Watch for Keyboard and mouse events.
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    #pygame.QUIT()
                    #running = False
                    sys.exit()

            #Redraw the screen during each pass through the loop
            self.screen.fill(self.settings.bg_color)
            self.ship.blitme()

            # Make the most recently drwan screen visible.
            pygame.display.flip()

if __name__ == '__main__':

    ## Make a game instance and run the game.
    ai= AlienInvasion()
    ai.run_game()

```

**settings.py**

```
class Settings:
    """A class to store all the settings related for Alien Invasion...! """
    def __int__(self):
        """Initialize game settings..! """
        #screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230,230,230)

```

**ship.py**

```
import pygame

class Ship:
    """ A class to Manage the ship...! """
    def __int__(self,ai_game):
        """ Initialize the ship and set its starting position...! """
        self.screen = ai_game.screen
        self.screen_rect = ai_game.screen.get_rect()

        # Load the ship image and get its rect.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()

        # Start each new ship at the bottom center of the screen.
        self.rect.midbottom = self.screen_rect.midbottom

    def blitme(self):
        """ Draw the ship at its current location...! """
        self.screen.blit(self.image,self.rect)

```

**Error**

```
C:\Users\user\PycharmProjects\pythonLearningProject\venv-dev\Scripts\python.exe C:\Users\user\PycharmProjects\pythonLearningProject\alien_invasion.py
pygame 2.1.2 (SDL 2.0.18, Python 3.9.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
  File "C:\Users\user\PycharmProjects\pythonLearningProject\alien_invasion.py", line 45, in <module>
    ai.run_game()
  File "C:\Users\user\PycharmProjects\pythonLearningProject\alien_invasion.py", line 26, in run_game
    for event in pygame.event.get():
pygame.error: video system not initialized

Process finished with exit code 1

```

# Answer
> 1 votes
You have a typo, `__int__` instead of `__init__` (you forgot the second `i`), which is the problem.

It doesn't run run `pygame.init()` so it can't initiate `video` and it can't display `window` (and later it would give a problem with `events` because events can't work when `window` doesn't exist..)

You could use `print()` to see which part of code is executed and possibly catch these kinds of issues.

---
Tags: python, pygame
---


# Question
Title: Collision detection between transformed meshes (not primitives)
I know questions related to collision detection have been asked multiple times, but I find all of them like this and this depend on the assumption that I have some sort of measurement of the object like the dimensions of the cube, or the radius of the sphere which is not true. I am working with vertex based geometry.

In my game, the vertex data is discarded after it is loaded into the Vertex Buffers.

So the question is that how can collide 2 objects of which i don't know details like the radius of the sphere? I am willing to implement the collision mesh, which again isn't necessarily going to be a cube but is regularly translated, rotated and scaled.

# Answer
> 0 votes
Ok I can write an answer.

You can either save the vertex data when you load the mesh and run the collision on those structures.

Or you can implement collision detection entirely on the GPU. Since there is no known solution by the community you will be looking at writing the collision engine in GPU code. Also, as you have found it is difficult to get vertex data back from the GPU so your collision results would mostly only exist in the OpenGL rendering.

The second option is dangerous territory, and if you are having problems with the first option I would say that it's probably easier to make some changes to allow copying the data than it is to write collision code for the GPU.

# Answer
> 0 votes
Several meshes are usually used for an object:

* The rendering meshes, for rendering on screen. There can be several rendering meshes, for example to manage Level of Detail (LOD) or to display several states of the same object.
* The collision mesh, used by the physics engine for collision detection and resolution. This mesh is usually very simple compared to the rendering meshes to avoid very costly operations while being good enough for its purpose.

A mesh is a mesh, whether you intend to use it in OpenGL to render that magnificent ball or in your favorite physics engine to make that bouncy ball bounce.
Moreover, the physics engine will probably expect data not in the same format as OpenGL.

It is usual to have both the rendering mesh and collision mesh to be manually created, with the collision mesh being a crude approximation of the rendering mesh. I'm not aware of tools to automate this process, but they certainly exist, although it might be simpler to create the collision mesh manually.

If you still insist on using a single mesh to generate collision data, you still have a few options:

### 1. Use a single mesh to generate both OpenGL vertex data and to use in your collision system (NOT ADVISED)

This will be a performance nightmare. Really.

### 2. Simplify the rendering mesh to use in your collision system

You can do the transformation from a complex rendering mesh to a simplified collision mesh at runtime if you find an algorithm/tool that suits your need for it, although I would advise that you do it during the development process and that you embed the result along with the initial mesh in your game.
For this, you will need **not to discard the data after loading it to OpenGL.** You already have access to the data you need, use it!

# Answer
> 0 votes
Expanding on my comment to try to give this old question some closure: common non-primitive polygon mesh collision detection functions include...

Both of these techniques work only for convex hulls: meshes that have no holes, caves, or divots, but they're way faster than the alternatives.

For that reason, many game engines will make (or allow the designer to author separately) a CPU-side physics-only version of the mesh that's reduced to its convex hull for collision purposes. Meshes that have important concavities can often be broken down into parts that are each convex, so you can run these fast algorithms on each part - see approximate convex decomposition for details on those techniques.

If your mesh is concave but well represented by a heightfield (eg. a terrain without caves or overhangs), then you can reduce collision detection to a 2D sweep over the heightfield checking if the highers height in the colliding object's footprint is above the lowest part of the object there.

If you need to find collisions with more general concave meshes that aren't heightfields and don't break down neatly into convex parts (meaning they have so many concavities that you'd end up with something close to one convex hull per triangle anyway), or worse, non-manifold geometry (meshes that don't have a clearly identified interior vs exterior), then unfortunately the only solution is to test for intersection against each polygon in the mesh. If you have to collide two such meshes, then you need to test for an intersection of each *pair* of triangles (yuck!). About the best you can do here is break up the triangles into some kind of acceleration structure like a spatial hash, BSP, or octree that lets you quickly find relevant triangles without visiting every single one.

If you can afford to approximate to some fixed resolution, and your mesh doesn't cover "too huge" an area, you can also create a signed distance function (SDF) from the mesh, and store it in a 3D array where the value at each lattice point is the distance from there to the closest point on the mesh (with negative values for points "inside". These are expensive to create, but fast to query, especially for small colliders. When you transform the mesh, you transform your query by the inverse of that transform, so you don't have to recalculate the SDF every time you move the mesh.

All of these approaches get much more expensive the more polygons are in your mesh, so it's common for the CPU-side physics mesh to be significantly lower-poly than the display mesh, whether it's crafted by hand or automatically decimated by some mesh simplification algorithm on import.

---
Tags: c++, collision-detection, 3d-meshes
---


# Question
Title: Detect mouse click on object with no script attached
I'm creating a 2D project which does not have a character. So I created an empty game object and attached a script to it. In the script, I have declared other objects which are in the scene like this:

```
public GameObject obj1,obj2,obj3;

```

How can I know if obj1 or obj2 or obj3 was clicked? Is raycasting the only solution?

# Answer
> 12 votes
Yes, you can use raycasting to detect the objects in your scene. You don't need to attach a custom script to the game objects you want to detect, but you do need to attach colliders to them.

In the update method of your script, attached to the otherwise empty object, you can check for when the mouse button is pressed. Then, cast a ray into the scene from the camera, through the mouse. Something like the following:

```
void Update() {
    if (Input.GetMouseButtonDown(0)) {
        Debug.Log("Pressed left click, casting ray.");
        CastRay();
    }
}

void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit hit;
    if (Physics.Raycast(ray, out hit, 100)) {
        Debug.DrawLine(ray.origin, hit.point);
        Debug.Log("Hit object: " + hit.collider.gameobject.name);
    }
}

```

# Answer
> 5 votes
I modified the script and now it works. First, I remove:

```
public GameObject obj1, obj2, obj3; // Although this shouldn't affect the script.

```

The updated script is as follows:

```
using UnityEngine;
using System.Collections;

public class ClickTest : MonoBehaviour {
    // public GameObject red, red2, yellow, yellow2, MainCamera;
    // Use this for initialization

    void Start () {
    }

    // Update is called once per frame
    void Update () {
            if (Input.GetMouseButtonDown(0)) {
            Debug.Log("Pressed left click, casting ray.");
            CastRay();
        }
    }

    void CastRay() {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
        if (hit) {
            Debug.Log (hit.collider.gameObject.name);
        }
    }
}

```

# Answer
> 0 votes
I Still Believe that part of this question was not answered. The part

> Is raycasting the only solution?

Well its not the only solution there is also:

```
void OnMouseDown(){
    Destroy(gameObject);
}

```

Attach that script to the target object i.e. the one that wants to register the mouse clicks.

# Answer
> 0 votes
If you set up an edge collider on the objects you can use:

```
void Update()
{
    //this detects the mouse position
    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    //this check to see if the mouse is over the collider documentation below
    if (this.GetComponent<EdgeCollider2D>().ClosestPoint(mousePos) == mousePos)
    {
         print("mouse is hovering over object");
         if(Input.GetKeyDown(KeyCode.Mouse0))
         {
             print("mouse clicked on object");
         }
    }
 }

```

For more information, refer to the documentation for `Collider.ClosestPoint`.

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


title: Rotating on Z axis with easing

text:
# Question
Title: Rotating on Z axis with easing
I am stuck with rotating a GameObject on the Z axis with easing.

I want to achieve an effect like in this game:

Here, the ring of targets starts rotating periodically. It starts slower, than rotation speed increases and again towards the end it decreases.

My speed of rotation is constant and I tried few approaches but with no luck. In my current code, I lerp new angle and then I substract previous angle from it to get actual angle needed for a turn.

```
private float degreesToTurn = 45;

private float t = 0;
private float previosDegrees = 0;
private float actualDegrees = 0;

void Update() {
    float degrees = GetDegreesToTurn();

    transform.Rotate(Vector3.forward * degrees);
}

private float GetDegreesToTurn() {
    t += 0.05f * Time.deltaTime * 10;

    actualDegrees = Mathf.Lerp(0, degreesToTurn, t);
    float rotateDegree = actualDegrees - previosDegrees;

    previosDegrees = actualDegrees;

    return rotateDegree;
}

```

I tried to increase `t` variable till I reached degreesToTurn / 2 but and then decrease it but that resulted not in easing but in rotating back.

Also I tried to use Quaternions but the problem is that I want to be able to rotate targets over 360 degrees which must result in N amount of spins. Quaternions don't allow me to do that.

# Answer
Here's a strategy you can use. Instead of using `transform.Rotate` that applies a rotational increment relative to your current rotation, set the whole rotation to some absolute orientation.

You can Lerp that absolute orientation between your start and destination orientations according to a `progress` parameter that goes from zero to one over the duration of the movement. Then you can apply any easing function you want to that `progress` value to change the movement.

```
// Easing function that gradually accelerates from rest
// and then gradually decelerates to a stop at the end.
float SmoothStep(float t) {
    t = Mathf.Clamp01(t); // Technically unused in this example.
    return t * t * (3 - 2 * t);
}

IEnumerator RotateWithEase(float relativeAngle, float duration) {
    // Remember where we started from.
    Quaternion startOrientation = transform.rotation;

    // Vary a "progress" parameter linearly from 0 to 1
    // over the duration of the movement.
    float speed = 1f/duration;
    for (float progress = 0f; progress < 1f; progress += Time.deltaTime * speed) {
        // Use the easing function to turn that linear motion
        // into an eased curve.
        float eased = SmoothStep(progress);

        // Apply your easing.
        float currentAngle = relativeAngle * eased;

        // Rotate that far from wherever we started (in local coords).
        transform.rotation = startRotation * Quaternion.Euler(0, 0, currentAngle);

        // Wait a frame, then resume the loop.
        yield return null;
    }

    // Snap exactly to the destination rotation at the end of the loop.
    transform.rotation = startRotation * Quaternion.Euler(0, 0, relativeAngle);
}

```
> 1 votes

---
Tags: unity, c#, 2d, rotation, easing
---


# Question
Title: How to randomize all the colors to different colors every time the snake eats and grows?
I'm new to python and am making snake for a project/ I'm not sure how to randomize all the colors to different colors every time the snake eats and grows. I've looked up multiple things and nothing has worked.

# Answer
Keep colors in variables like

```
snake_head_color = 'red'
snake_tail_color = 'green'

```

In main loop use these variables to draw objects like

```
    # draw head
    pygame.draw.rect(screen, snake_head_color, (100, 100, 48, 48))

    # draw tail
    for x in range(150, 700, 50):
        pygame.draw.rect(screen, snake_tail_color, (x, 100, 48, 48))

```

And later you can use `random.choice(list)` to assign new colors when it grows.

```
snake_head_color = random.choice(['red', 'yellow', 'gray50'])
snake_tail_color = random.choice(['green', 'blue', 'gray25'])

```

This way it will draw snake using new colors.

---

Minimal working code. It changes colors when you use mouse button (or wheel)

```
import pygame
import random

# === constants ===  # PEP8: UPPER_CASE_NAMES

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

FPS = 60
FPS = 120

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# === classes ===  # PEP8: CamelCaseNames

# empty

# === functions ===  # PEP8: lower_case_names

# empty

# === main ===

pygame.init()

screen = pygame.display.set_mode( (SCREEN_WIDTH, SCREEN_HEIGHT) )

# set some color at start
snake_head_color = 'red'
snake_tail_color = 'green'

change_colors = False

# --- mainloop ---

clock = pygame.time.Clock()

running = True

while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_ESCAPE:
                running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            change_colors = True

    # --- changes/moves/updates ---

    if change_colors:
        # select random color
        snake_head_color = random.choice(['red', 'yellow', 'gray50'])  # select new color
        snake_tail_color = random.choice(['green', 'blue', 'gray25'])  # select new color

        change_colors = False

    # --- draws ---

    screen.fill(BLACK)

    # draw head
    pygame.draw.rect(screen, snake_head_color, (100, 100, 48, 48))

    # draw tail
    for x in range(150, 700, 50):
        pygame.draw.rect(screen, snake_tail_color, (x, 100, 48, 48))

    pygame.display.flip()

    # --- FPS ---

    dt = clock.tick(FPS)
    #pygame.display.set_caption(f'{dt:.2f} ms')

# --- end ---

pygame.quit()

```

---

Because it always select new color from the same list so sometimes it may select exactly the same color as current color - and it may seen like it doesn't select color. But you can remove current color from list before select new color.

```
    # --- changes/moves/updates ---

    if change_colors:
        color = ['red', 'yellow', 'gray50']       # create list with all colors
        color.remove(snake_head_color)            # remove current color
        snake_head_color = random.choice(color)   # select new color

        color = ['green', 'blue', 'gray25']       # create list with all colors
        color.remove(snake_tail_color)            # remove current color
        snake_tail_color = random.choice(color)   # select new color

        change_colors = False

```

**BTW:**

Previous version needs to create new local list with all colors in every loop.
If you want to keep lists in global variables then it may need to create local copy (using `list.copy()`).

```
# --- constants --- (UPPER_CASE_NAMES)

SNAKE_HEAD_ALLOWED_COLORS = ['red', 'yellow', 'gray50']
SNAKE_TAIL_ALLOWED_COLORS = ['green', 'blue', 'gray25']

    # ... later ...

    # --- changes/moves/updates ---

    if change_colors:
        color = SNAKE_HEAD_ALLOWED_COLORS.copy()  # create list with all colors (it needs `copy()`)
        color.remove(snake_head_color)            # remove current color
        snake_head_color = random.choice(color)   # select new color

        color = SNAKE_TAIL_ALLOWED_COLORS.copy()  # create list with all colors (it needs `copy()`)
        color.remove(snake_tail_color)            # remove current color
        snake_tail_color = random.choice(color)   # select new color

        change_colors = False

```

Eventually you could use `list comprehension` to select all colors except current color

```
# --- constants --- (UPPER_CASE_NAMES)

SNAKE_HEAD_ALLOWED_COLORS = ['red', 'yellow', 'gray50']
SNAKE_TAIL_ALLOWED_COLORS = ['green', 'blue', 'gray25']

    # ... later ...

    # --- changes/moves/updates ---

    if change_colors:

        color = [x for x in SNAKE_HEAD_ALLOWED_COLORS if x != snake_head_color]
        snake_head_color = random.choice(color)   # select new color

        color = [x for x in SNAKE_TAIL_ALLOWED_COLORS if x != snake_tail_color]
        snake_tail_color = random.choice(color)   # select new color

        change_colors = False

```
> 1 votes

---
Tags: python, snake
---


title: Can I use DirectX with C#?

text:
# Question
Title: Can I use DirectX with C#?
I thought that if you wanted to make games using DirectX, you had to know C++. But I recently found out that that is not actually true. It looks like some parts of Direct3D can be used from C#. This MSDN document, for example, which has C# examples.

Am I understanding this incorrectly? Have I waited all these years for nothing?

# Answer
Yes, there are DirectX bindings for C#. This has been available for almost 10 years or more.

XNA (announced 2004), MonoGame (announced 2009), SharpDX and more all provide you the ability to access DirectX using C#. You actually only need to Google "C# DirectX" and you'll find plenty resources on this. The MSDN documents you are link to in your question, however, are referencing Microsoft's own "Managed DirectX," which is now deprecated and not a viable choice for new development.

Additionally, you only need to look a little further into link you provided to find sample projects you can use with the Direct3D API.
> 8 votes

# Answer
In 2023, this question is still one of the most prominent search engine results when typing "DirectX C#". Therefore, **here is a renovated answer:**

Since 2013, the answers to that question have been coming and going.

Here is a little guided tour:

**1. Wrapper libraries**

DirectX is designed to be programmed in C++, so for a decade some people have attempted to write interop libraries and wrappers to use it in C#.

You can find several of those libraries with search engines, the most recent being mostly targeted at Visual Studio 2017 and DirectX11.

Some examples :

The problem is that those were mostly projects working "around" DirectX's official development effort, the support can be limited. SharpDX was very promising but the support stopped in 2019.

**2. Mono**

For some time, Microsoft has pushed Mono to make games. That's not exactly directX (I didn't research it but I bet it does rely on it, though) however it's definitely made for cross-platform, high-performance (accelerated) graphical applications. In a way, you could say that it is "better" than DirectX.

the problem is that Mono has stalled and in 2023 is no longer bleeding edge.

**3. Unity**

Unity lets you work directly in C#. And lets you make fully-fledged high-performance, interactive graphical applications. Just like Mono, it's an advanced engine on top of DirectX. And an IDE on top of the engine.

I guess that Unity's very existence it's telling you that the industry is moving away from accessing DirectX "directly" (unless you can program in C++, obviously) and instead use a "real" environment. Game development has become so complex that there's no in-between offer anymore.

**3bis. Unreal Engine?**

I don't know if there are C# wrappers around Unreal Engine but I wouldn't be surprised. Just like Unity it's much, much more than "just" DirectX so it's up to you to decide if it's "too much" depending on your needs.

**4. ComputeSharp**

But do not despair! ComputeSharp is a production-ready C# library meant to use the GPU mostly for computing. It's modern, well-maintained, well documented.

It's designed for computing BUT their Sample applications show you how to interop with WinUI, UWP and others (so that you can draw pixels onto the screen). Plus, it lets you access any underlying DirectX resource that you might need thanks to special binders -- those require a tiny bit of effort because you need to switch your brain to "C++ mode" even if you're still in C#. Just go along with it. Read the documentation, you should be fine.

So in some places it resembles C++ very much (again: even in your C# code) but you can still fully benefit from C# -- especially in the shaders, which is awesome.

**CONCLUSION**

I don't know exactly what was the intent of the original poster's question.

Butin 2023 if YOUR goal is to use the GPU, draw pixels onto the screen and write a "regular" graphical application on Windows (with sound, input/output, etc.) without relying on the absolute monster that is Unity, then I'd go for ComputeSharp.
> 2 votes

---
Tags: c#, directx
---


title: rotating a sprite with mouse cursor

text:
# Question
Title: rotating a sprite with mouse cursor
i am learning how to make a 2d game using sdl and c++ and am currently trying to rotate the sprite so that is always facing the cursor, my game is set up with an entity component system, i have a keyboardcontroller component where the game will use atan2 to work out the angle of the mouse to the sprite and rotate it to match when whenever the mouse is moved. i managed to get it to work but only on the sprites starting coordinates for some reason. all the things to do with drawing the sprite and animating it are stored in the spritecomponent, inside there is a draw() override function that is called for every sprite of every entity for every frame of the game, inside that there is member function of my texturemanager class, when it is called it uses sdl\_rendercopyex to draw a sprite onto the renderer in the window. i then try to pass the angle to sdl\_rendercopyex so that it changes every time the mouse is moved.

as stated it only seems to work around the starting position of the sprite, after moving away the rotation no longer works, just rotates very slightly but only in the sameish direction. to try and troubleshoot i made it print to the console the player sprite coords, the mouse cursor coords and the angle calculated from this, this all seemed correct, this is the code i wrote for the rotation angle, anglerot is the angle parameter of the texturemanager::draw() function passed to the sprite:

```
if(Game::event.type == SDL_MOUSEMOTION){
    Vector2D playerPos = entity->getComponent<TransformComponent>().position;
    int x1;
    int y1;
    int x = playerPos.x;
    int y = playerPos.y;
    SDL_GetMouseState(&x1 , &y1);
    int DeltaX;
    int DeltaY;
    double* result;
    DeltaX = playerPos.x -  x1 ;
    DeltaY = playerPos.y - y1;
    result = ((atan2(-DeltaX, DeltaY) * 180.00000) / 3.141592);
    sprite->anglerot = static_cast<int> (result);

    std::cout << "mouse cursor: " << x1 << " , " << y1 << '\n' << "player position: "         << playerPos.x << " " << playerPos.y << '\n' << "angle of rotation: " << result << std::endl;

```

As requested, inside my sprite component class i had a camera set up following the player like so:

destRect.x = static\_cast(transform-\>position.x)- Game::camera.x;
destRect.y = static\_cast(transform-\>position.y)- Game::camera.y;

where destRect is the rectangle in which my sprite is drawn.

# Answer
It turns out the issue came from what I thought was my player position used in the calculation. I had forgotten I had a camera that followed the player as it moved, so player position was relative to that in-game. Taking into account the camera position fully fixed the issue. Here is my updated code:

```
if(Game::event.type == SDL_MOUSEMOTION && Game::dead() == false){
Vector2D playerPos = entity->getComponent<TransformComponent>().position;
    int x1;
    int y1;
    SDL_GetMouseState(&x1 , &y1);
    int DeltaX;
    int DeltaY;
    double result;
    DeltaX =   x1 - (playerPos.x - Game::camera.x);
    DeltaY =  y1  - (playerPos.y - Game::camera.y) ;
    result = ((atan2(DeltaY, DeltaX) * 180.00000) / 3.141592) + 90;

    sprite-> anglerot = static_cast<int> (result);

```
> 2 votes

---
Tags: c++, sprites, sdl2, mouse, trigonometry
---


title: How do I implement data persistence?

text:
# Question
Title: How do I implement data persistence?
I wonder how do I implement data persistence in 2d game. I am not using any engine, just pure Kotlin and OpenGL for rendering, so it is more of a software architecture question. The case:

Character travels on the tile map and after crossing the edge of it proceeds to the next level (or next map). Let's assume I want to store the character and its attributes, update actions (which are being performed in "update" method of the game), .

1. Of course I can store the character entity in some kind of an object, that will be passed from one "scene" to another. Possible cons: unnecessary additional code to store and pass object.
2. Using a file. Cons: This leads to parsing the file, opening streams to read data and etc.
3. Declaring entities as static objects. Cons: I am afraid this can cause memory leaks, I am not sure how I am going to dispose static objects.
4. Declare static object, which will hold the collection of data objects. Share it between all scenes. This seems like an optimal solution so far, even though I still will be referencing the object, I will have the ability to dispose certain entities.

I am not sure if some of the cons I mentioned are really making difference and will be significant. I want to know how this kind of logic is usually implemented.

# Answer
> 2 votes
It largely depends on a game, but generally, it seems like you have a classic RPG/FPS/Arcade composition, where you have:

* a Game instance (roughly speaking, this is your launched executable),
* Game creates Sessions instances, one at a time (e.g. starting a new playthrough, loading a save, restarting, etc),
* Session has a single Character instance and several instances of different Maps(Levels) he walks through. Maps(Levels) being instantiated on demand, existing one at a time.

Now you can see, that Characters lifetime spans over several Maps(Levels) and is equeal or just a bit shorter than the Session.

This is just the general direction, it can change to your game specifics. For example, in simulation-heavy games, it may be simpler to create new Character object for each Map(Level) from scratch, using just a small stored data (3-4 vars) and store it back on completion. Some games might deny Character progress unless Map(Level) is won, in that case you create a Character and only write back the results to the Character on completing. Other games could have very complex Characters (think RPGs), or ones that can even persist over Session in meta-gameplay.

How exactly do you store the Character instance in Session on serialization to savegame it up to you (heck, some games don't even do saves, they use level-codes), but generally you would store just the "persistent" bits (Level, Inventory, Skill-tree, etc).

---
Tags: architecture, kotlin
---


# Question
Title: Unity + Steamworks.NET: GetLaunchCommandLine() does not include "+connect_lobby" when launching through an invite
The title describes the problem. I am trying to launch the game through an invite from a friend. When I accept the invite, it launches the game just fine. But when I try to then read the Command line through `SteamApps.GetLaunchCommandLine()` it does not contain the "+connect\_lobby" that the documentation describes. There is very little I can find on this online.

What situations could cause the game to not start up with that line when it should? Is there an alternative?

I read the command line as intended, like this:

```
string steamCommandLine = "";
Steamworks.SteamApps.GetLaunchCommandLine(out steamCommandLine, 260);

```

Note that the `OnGameRichPresenceJoinRequested` callback works perfectly as intended.

We have a custom parameter that *does* go through. Would it be possible that this parameter overwrites the rest of the command line?

After I did a bit more research, and in the steam console (with spew level 4 4) I found that steam executes a url: `ExecuteSteamURL: "steam://rungame/<appID>/<steamID64>/GuideHouse"`. That steamID is exactly what I want, but I am not able to retrieve it in code...

# Answer
This forum post mentions a valid alternative that just retrieves the command line argument using Base Class Libraries:

https://forum.unity.com/threads/steam-invites-getlaunchcommandline-not-working.1152140/

Incase the link rots here is the solution it documents:

```
        // get your command line arguments
    var args = System.Environment.GetCommandLineArgs();

    // we really only care if we have 2 or more if we just want the lobbyid.
    if (args.Length >= 2)
    {
        // loop to the 2nd last one, because we are gonna do a + 1
        // the lobbyID is straight after +connect_lobby
        for (int i = 0; i < args.Length - 1; i++)
        {
            if (args[i].ToLower() == "+connect_lobby")
            {
                if (ulong.TryParse(args[i + 1], out ulong lobbyID))
                {
                    if (lobbyID > 0)
                    {
                        // do something with your lobby id
                    }
                }
                break;
            }
        }
    }

```

I've just tested this myself and it works fine. No idea why Steamworks.NETs/ SteamAPIs implementation doesn't correctly manage to get normal commandline arguments.
> 1 votes

---
Tags: unity, multiplayer, steam, steamworks
---