title: Characters ai code organization

text:
# Question
Title: Characters ai code organization
I want to create a an ai with finely customizable character. The ai should be able to handle generic behaviors, like scheduled activity, shared across all character, but have specific override for group of character called persona (for example artist for art club activity), and override for unique character behavior (named characters). There is hundreds of characters simulated at the same time.

I'm using an "if tree" with behavior tree pattern, (grew organically from prototype). I originally wanted to refactor into a bunch of "cards", as an abstraction. Cards have a check, then a body of actions when the check is passed, cards can be nested as actions of other card, break() is a specific action that terminate the execution of the whole tree. But I'm stumbling on some issue refactoring...

Override for specific characters, could happen at any branch of the "if tree", and it makes it harder to write code that separate specific and unique code, because a top level card can have specifics to a character, but lower behavior be a mix of generic and specific, making it hard to untangle the two. It also makes it hard to propagate change during dev, because number of behavior card can reach up to tens of thousands. That makes it that a lot of card would be identical variants save for a few actions, and updating them all would be a nightmare (for example, gameplay adjustement). On top of that, breaking the ai code into multiple files makes it harder to track the logic and debug specific vs generic behavior, especially when part the tree becomes deep (for example, there is an investigation routine, broken into persona and specific character).

I haven't even started to touch on how to do character interactions, from specific to generic and vice versa, and specific to other specific.

Right now I have just a single file with a big pile of if, where I intercept the logic with hardcoded exception (if characterID or personaID is ... then execute body), and also manage group interactions ad hoc.

What architecture or programming design pattern you would recommend to cope with these difficulties? Specifically how to manage the explosion of card variants? So far anything I tried collapsed.

# Answer
First of all, game AI with lots of actors with partially shared and partially unique behaviors is never a simple problem to solve. Especially considering that it's probably an area of your game you want to do a lot of experimentation and iteration on, which means it needs to be very flexible and easy to maintain.

There is no one architectural pattern that is going to solve all your problems. Most projects mix several patterns. Some patterns you might want to look into are:

## Object-oriented programming with inheritance.

When you have an AI actor that should behave mostly like the default actor, but behaves differently in certain situations, then it can make sense to handle that using polymorphy.

First, create a class "AIBehaviorBase" that implements a "default" AI actor. Design its public interface so that it properly encapsulates the whole AI decision making process.

When you want to create another AI actor that acts differently, then:

1. Create it as a new class inheriting from "AIBehaviorBase".
2. Identify the code in "AIBehaviorBase" which you need to act differently in the new class.
3. Refactor "AIBehaviorBase" to move that code into methods (in some cases, those methods might not actually do anything at all - they basically act as "injection points" for additional logic).
4. Override those methods in the new class. Make sure you properly follow the Liskov Substitution Principle while you do that. Any code that uses your base class must still work when it uses your inheriting class instead.
5. Use an instance of that new class as the behavior for that actor.

## State-machines

After the "humongous-if-else-tree" pattern, state machines are the next basic architecture for game AI. The basic idea is that each actor can be in one of several states, like for example "moving somewhere", "in combat", "making conversation" etc. While the actor is in a certain state, only the code for that state gets executed. Several events can lead to the actor changing into a different state. Those state transitions might also have logic.

Sometimes states might have state machines on their own. For example, in a hack&slash combat system, the "in combat" state might be implemented by a sub state-machine with states like "dodging", "parrying", "swinging" etc.. This architectural pattern is called "hierarchical state machines".

or some actors, standard states might be replaced by custom states. For example, different actors might have different combat strategies, which could be represented by different "in combat" states, which do however recycle some of the sub-states from the default AI for their internal implementation. So when you organize your AI as a tree of hierarchical state-machines, then AI customization could be implemented by overriding certain states or sub-states with alternative implementations.

## Behavior Trees

These are one of my favorite patterns in game AI, because they allow you to define AI decision logic using very concise code (or even a UI) while you hide the nasty details of the implementation in abstract nodes. This is also really useful for iterative approaches.

As an introduction to this topic I recommend this article by Chris Simpson on GameDeveloper.com which helped me a lot to understand the pattern and build my own behavior tree framework which I have recycled for multiple projects. You might notice some similarities with the data-driven concept of your "modular implementation of an if tree", but behavior trees are far more powerful.

When you have lots of actors with different behaviors, then you would usually **not** try to represent all this in one super behavior tree with selectors or sequences that check for actor type and make decisions accordingly. That would soon turn into madness. No, what you usually do is create a separate behavior tree for each actor.

The reusability of behavior trees comes from the neat ability that they can be nested. So you can easily put a generic behavior tree as a sub-tree into multiple other trees. You can also replace individual branches or leaves of trees by creating a copy of a tree, modifying it, and then inserting it into a larger tree. But that usually gets a lot uglier and results in far less readable code.

The conclusion: Behavior Trees are great for customizing high-level behavior, but not so much for customizing low-level behavior.

## Utility AI

I am not sure how well this fits into your particular design, but I would still like to mention it nevertheless as an alternative to the binary do-or-not-do principle of the aforementioned architectures.

The idea of a utility AI is:

* You have several variables that feed into the decision making process. These can be variables about the state of the actor itself or about the world around them.
* Each AI actor has a set of actions the actor can perform. "Do nothing" is usually such an action as well.
* When an actor is about to make a decision which action to perform, then it uses a rating function for each action. That rating function uses those variables and returns a score representing the "utility" of that action, or in other words how useful it would consider this action right now.
* Then it performs the action that got the highest "utility" score.

The "personality" of an AI actor is determined by the rating functions it uses. As an example, let's take a rating function for the "attack" action. Should or shouldn't the AI actor engage a certain enemy? A very bold AI actor looking for a real challenge might want to prove itself by picking only the strongest fights while it doesn't concern itself with "small fish". So it would use a rating function where the enemy strength is a positive factor resulting in a higher utility for attacking. A more careful actor might choose its battles more carefully and only engage when it knows it can win, so enemy strength would be a negative factor in its attack utility rating function.
> 2 votes

---
Tags: architecture, ai, software-engineering, character, behavior-tree
---


# Question
Title: What was the rationale behind the updating of 'changed' tiles in John Carmack's Adapatie Tile Refresh?
I was recently reading up on Carmack's Adaptive Tile Refresh, of which was written extensively in this thread, to implement in a hobby gamedev project of mine: https://retrocomputing.stackexchange.com/questions/22175/what-is-adaptive-tile-refresh-in-the-context-of-commander-keen

I must admit that I know little of the exact ways the PC was limited at the time (as in limited fill rate, restrictive display modes and what not) so I don't entirely understand as to why some of the steps mentioned in the answer to the above thread were used. I also understand modern PCs can more than blaze past with naive techniques such as storing the level data entirely in memory, but I'd wanted to implement this since I found the idea exceedingly interesting

Here's what I understand of ATR so far:

1. Assume the world map is stored in memory (not video memory)
2. Carmack would use a special drawing mode that allowed to extend the video buffer by an extra few pixels (say, by 16 pixels) (enough to fit an extra tile) horizontally (in this case)
3. Assume that the initial screen has been drawn (along with the extra tiles in the offscreen buffer) by loading them from the world map in main memory, to the buffer
4. Pan the 'camera' pixel by pixel horizontally to smoothly scroll through the screen
5. Once you've scrolled the entire length of the buffer along with the extra length of the offscreen buffer, this would mean i) The tile we initially had on the left side of the screen (assuming we were scrolling to the right) is now wiped out, stuck in another offscreen buffer to the left of the screen ii) The tile we initially had on the right-hand side off-screen buffer has now been fully 'drawn' into view
6. 'Jolt' the screen back by 16 pixels, load in the next tile from the world map from the main memory to the offscreen buffer, repeat the process again (As for what happens to the tile that was in the left-hand side offscreen buffer after the jolt, I am not sure myself. Where would it go?)

What I don't get is the step wherein existing tiles on screen are compared before being drawn (I've left out the step here since I do not quite fully understand them)

Why are we checking if a tile's changed if we are panning through the buffer anyway? Assume we are drawing pixel by pixel, this would be the equivalent of simply changing the 'range' of values which we loop over and display right? It has to be drawn pixel by pixel if we want to smoothly scroll over tiles

I did think of one scenario where the tile checking would be useful:

If the display card renders **tile by tile** and is 'state-based', where the state are the **values/data** held by each tile (values/data as in the exact tile you want to display) ,where the process of checking if the previous and current frame's tile index match, and leaving them as is if so, or updating the tile state to match the new tile if not is **cheaper** than blindly updating and redrawing the state each time, tile checking would be more efficient

This would of course mean that smooth scrolling by going pixel-by pixel would be nigh impossible since all you ever have are tilemaps on hand, so you can't 'partially' scroll through a tile

I know I've gotten the concept horrifically wrong somewhere but I can't quite figure out where despite wracking my head it at it. Where exactly did I go wrong?

# Answer
> 1 votes
I haven't heard of this algorithm before, but I *think* I understand what you're missing.

> 'Jolt' the screen back by 16 pixels, load in the next tile from the world map from the main memory to the offscreen buffer, repeat the process again (As for what happens to the tile that was in the left-hand side offscreen buffer after the jolt, I am not sure myself. Where would it go?)

You're imagining that tiles are *added* at the right edge in some way, leaving the area of the video memory corresponding to the part of the level that stayed on screen untouched. That's not the case for the situation which this algorithm was used. Instead, the *same* region of video memory is always filled with currently visible or almost-visible tiles, exactly as if there was no smooth scrolling (every step is a whole tile).

Therefore, **each scrolling step has to redraw tiles that are in the interior region of the screen,** not just the edge.

The value of the comparison, then, is that the program can skip redrawing any tiles which *haven't changed due to scrolling* (because the old tile and its neighbor in the scrolling direction are identical), and it can do this purely by comparing the (small) tile map data, in order to decide whether it has to spend time writing every pixel of the tile into video memory.

And, entirely separately from this process, the sub-tile scrolling (0 to 15 pixels of distance) is handled not by writing anything to the video memory, but by writing to video card registers that tell it where to start *reading* from when generating the output video signal.

---
Tags: tilemap, optimization, side-scroller, scrolling
---


# Question
Title: Why do modern games take so long to reset the current level after failing?
While recently playing a game I kept failing at, I realized that I don't fully understand why I need to wait for the level to reset at all. Taking time to load a new level makes sense to me - assets need to be loaded, maybe some computation needs to be performed. But if the game was already mostly in the state I wanted it to be in, the level is likely already in the memory, what does the machine spend its time on? At first I thought it's because it's more convenient to just load everything from scratch as opposed to implementing better reset routines, but it doesn't make sense because pretty much every game does it this way. Which brings me to the question: why do modern games take so long to reset the current level after failing?

# Answer
As I mentioned in a comment above, we can't really say much specific about "all modern games" as a group, since each game is made in potentially very different and idiosyncratic ways, and the details of each one are usually known only to the folks who worked on that specific title.

So the best general answer, as unsatisfying as it is, is probably what you already said in your question:

> it's more convenient to just load everything from scratch as opposed to implementing better reset routines

This isn't to say "devs are lazy", but a combination of two things:

* Implementing a minimal state reset, while potentially possible in many game frameworks, can be much more complex in practice than it may seem conceptually, potentially adding many person-weeks of development investment and bug-fixing.
* Time spent on such a feature is time not spent on other areas of the game, like polishing core gameplay. So at some point, teams need to prioritize: what will give more bang for our buck in terms of making the game more enjoyable? Shaving 2 seconds off the load screen, or adding a new player ability or cool boss battle or maybe even a whole new chapter of gameplay?

I know it may seem unreasonable that such a feature could be so expensive that the trade-offs could be so steep, but the complexity can creep in sneakily, similar to what I describe in the latter half of this answer about implementing checkpoint saving.

A system that resets the state of all game entities and systems in the level can end up needing knowledge of every one of those entities and systems so it can reach into them and wind them back — or all those entities and systems need to be set up in a way that's aware of the reset system, so they can handle resetting themselves. That adds friction whenever you want to add or change content and rules in the game.

If a game entity was destroyed, we need to know to re-create it, and we also need to know which other entities *had* been referencing that entity, so we can re-wire their references to point to the newly instantiated successor. That's non-trivial to do automatically, and usually needs special mark-up or manual scripts to support.

And if any of that goes wrong — say a junior programmer adds a new variable on an enemy class and forgets to correctly set it up to be rewound, or a level designer sets up a puzzle script and makes an error hooking up the reset event — now you have a subtle bug that *only* shows up if the player dies and restarts the level in a very specific place. This massively multiplies the surface area for potential bugs and the number of testing permutations you need to go through after any change to be sure you've covered every contingency.

That's all cost. Development time spent that doesn't necessarily make the gameplay any more fun, or the graphics any more beautiful, or the story any more compelling. Only the small subset of players who die in exactly that spot get to see any benefit at all from those extra hours.

Now much like my earlier save answer, one could reasonably object that it's possible to sensibly plan and build a well-desined level loading and state management system in a way that makes this kind of state reset "easy", but I'll let you in on a dirty secret of game development:

A lot of our tech is neither sensibly planned nor well designed for the tasks we're putting it to.

It's not that folks making games are lazy or unskilled, it's just that games are a moving target — so the requirements by the time we ship can be wildly different than the requirements we knew at the start — and we're often subject to outside pressures that are antagonistic to software engineering best practices.

I've worked on sequels that, by fiat of upper management, were forced to be built on the same underlying engine as the previous 5 games in the franchise, a mountain of technical debt that had been accreting for over a decade. A level reloading system that was plenty fast two console generations ago when our asset budgets were a fraction of what they are today might now be straining under HD textures and high res meshes that weren't even an imaginable possibility when it was first designed. But now years of critical code all depend on it, and ripping it all out and replacing it might be a months-long task with unknown ripple effects on everything else in the engine — too risky for most game development timelines.

So sometimes you have to make tough prioritization calls, and say "we estimate players are only going to die and reset once every ~20 minutes on average, so instead of spending time saving 2 seconds every 20 minutes, we're going to spend that same effort making the 20 minutes of play in between more awesome, so it's worth 2 extra seconds to wait for"

That's not the right call for every game. In some games resets are much more common, and that can shift the priority scales toward favouring fast reload and spending the time and money to make that happen, even if it means sacrifices elsewhere. Limbo is one such game built around repeated, instructive failure, and I recall the devs giving a GDC talk specifically mentioning the need to optimize reload times in the game for that reason.

So I hope that gives some context about why it's not always as simple as "just reset the state" and why sometimes games have to focus on other priorities.
> 3 votes

---
Tags: architecture, performance
---


# Question
Title: How to layer multiple terrain tile types using Marching Squares
I've done a lot of research on marching squares, including:

But I just can't seem to get my head around it for some reason.

A few questions I have just while going into the algorithm:

* Are the "blending"/"marching square" tiles the same size as the original tile?
* Do the "blending" tiles overlay the tiles POST the original render/draw? (I assume there would need to be a transparent portion of the "blending" tile for this to work)
* The second displaced grid is just completely confusing to me, is that the location where the "blending" tiles would be placed? I thought the "blend" would just be placed at the intersection (so that 1 tile "invades" the other).

Additionally, I was confused about how this would work if there were multiple terrain types.

For example, If I were to have 3 terrain types and they were laid out like this:

```
0 2

1 2

```

Where the overlap is 2 -\> 1 -\> 0. I believe the way I would code this is so that the 1 overlaps the 0, and then the 2 overlaps the 1 & 0. So, if I had 128 x 128 pixel tiles, I would need 32x32 blending tiles for this to work.

The "2" overlap would also end up overlapping 2 of the 32x32 "1" tiles, but I suppose I could just not draw those if they look weird..

The other option I thought of was to simply ignore either the "0" or "1" tile, and have them be converted so that only 2 different tiles could ever sit next to each other..

# Answer
I made a simple live demo in JavaScript, where you can draw with 3 different materials using layered marching squares: water, soil and grass

https://stuepfnick.macbay.net/js/tiles/latest/

Feel free to make a copy of the code and use your own tiles or whatever. If you need to export/import raw data of the map, there is a test version that can handle this:

https://stuepfnick.macbay.net/js/tiles/test/

The source can also be found here: Map tile terrain transitions with 3-4 different types (don't get, how to link the files together here with code snippets … ;)
> 2 votes

---
Tags: 2d, tiles
---


# Question
Title: How can i make a sprite appear middle of your cursor? Pygame
I made a sprite (hitmarker) to appear middle of your mouse when you click on a sprite (egg), but the hitmarker sprite appears at the right bottom of your mouse like this:

however, I wanna make it appear like this:

I tried `screen.blit(hitmarker, (pygame.mouse.get_pos()))` but it appears at the right bottom of your mouse.

Source Code:

```
import pygame, sys, time
from pygame.locals import *
from millify import millify,prettify

pygame.mixer.init()
pygame.init()
music = open("music.txt", "r+")
pygame.mixer.music.load("soundtrack.wav")
x = int(music.read())
WHITE = 255,255,255
font = pygame.font.SysFont(None, 44)
cpsecond = open("clickpersecond.txt", "r+")
cps = int(cpsecond.read())
baltotal = open("totalbal.txt", "r+")
totalbal = int(baltotal.read())
totalbalM = prettify(totalbal, '.')
clock = pygame.time.Clock()
w = 800
h = 600
screen = pygame.display.set_mode((w,h))
pygame.display.set_caption('Tap Simulator')
Loop = True
background = pygame.image.load("Background.jpg")
egg = pygame.image.load("egg.png")
resized_egg = pygame.transform.scale(egg, (282, 352))
text = font.render(f'Your total clicks are {totalbalM}', True, WHITE)
pygame.mixer.music.play(-1,0.0)
volume = pygame.image.load("volume.png")
mute = pygame.image.load("mute.png")
resized_volume = pygame.transform.scale(volume, (100, 100))
resized_mute = pygame.transform.scale(mute, (100,100))
icon = pygame.image.load("ico.ico")
hitmarker = pygame.image.load("hitmarker.png")
resized_hitmarker = pygame.transform.scale(hitmarker, (50, 50))

pygame.display.set_icon(icon)

while Loop:
    for event in pygame.event.get():
        if event.type == QUIT:
            Loop = False
        if event.type == MOUSEBUTTONDOWN:
            if event.button == 1: # 1 == left click
                egg_rect = resized_egg.get_rect(topleft = (260,150))
                vol_rect = volume.get_rect(topleft = (700,500))
                if vol_rect.collidepoint(event.pos):
                    x += 1
                    if x > 2:
                        x = 1
                if egg_rect.collidepoint(event.pos):
                    totalbal += cps
                    totalbalM = prettify(totalbal, '.')
                    screen.blit(background, (0,0))
                    if x == 1:
                        screen.blit(resized_volume, (700,500))
                    if x == 2:
                        screen.blit(resized_mute,(700,500))
                    screen.blit(text, (235,557))
                    screen.blit(resized_egg, (260,150))
                    screen.blit(resized_hitmarker, (pygame.mouse.get_pos()))
                    pygame.display.flip()
                    text = font.render(f'Your total clicks are {totalbalM}', True, WHITE)
                    print("Your total clicks are", totalbalM, end="\r")
                    time.sleep(0.07)

    #print(pygame.mouse.get_pos()) #to get mouse pos
    screen.blit(background, (0,0))
    screen.blit(resized_volume, (700,500))
    if x == 0:
        screen.blit(background, (0,0))# [...] draw something different
    elif x == 1:
        pygame.mixer.music.unpause()
        screen.blit(resized_volume, (700,500))
    elif x == 2:
        pygame.mixer.music.pause()
        screen.blit(background, (0,0))
        screen.blit(resized_mute,(700,500))
    screen.blit(text, (235,557))
    screen.blit(resized_egg, (260,150))
    pygame.display.flip()
    pygame.display.update()
    clock.tick(30)

with open("totalbal.txt", "w") as baltotal:
    baltotal.write(str(totalbal))
baltotal.close

with open("music.txt", "w") as music:
    music.write(str(x))
music.close
pygame.quit()
sys.exit()

```

# Answer
`pygame.Surface.blit` takes the destination position as the top-left corner of the surface you want to blit. To move the center of the surface to the position, you simply need to offset the position by half of the surface's width. This way the center of the image aligns with the original position.

So in pseudo-code you want to do `screen.blit(cursor, pygame.mouse.get_pos() - cursor.get_size() / 2)`.
> 3 votes

# Answer
this is the way that worked for me.

First you need to find de center of the image, i did it like this:

```
self.mid_height = (self.image.get_width()/2)
self.mid_width = (self.image.get_height()/2)

```

this way i store the middle value of the height and width of the sprite or image, then, i separete the two values that returns te get\_pos() function in two variables:

```
self.cursor_x, self.cursor_y = pygame.mouse.get_pos()

```

and substract each value of middle height and middle width to the position values of the cursor:

```
self.cursor_center_x = (self.cursor_x - self.mid_height)
self.cursor_center_y = (self.cursor_y - self.mid_width)

```

then i stored again the new values in the final variable:

```
self.cursor_pos = self.cursor_center_x, self.cursor_center_y

```

and last i used that final tuple in the blit function:

```
self.screen.blit(self.image, self.cursor_pos)

```
> 0 votes

---
Tags: python, pygame
---


# Question
Title: Mapping world objects and camera to a sonar/radar/minimap
I have a Doom-like FPS game in Unity, with 3D objects laid out across the map in essentially 2D coordinates. The game scene is 3D with the usual setup where the camera is showing what the player sees.

I'd like to add a "sonar" gadget (like in Alien(s) movies and games), which would show where the surrounding objects on the game map are, relative to the player, and which would rotate so that the "up" direction in the sonar always points to where the camera looks at (i.e. the camera's Y position in this case).

I'm having trouble mapping the camera movements and rotation to the sonar. The sonar has a canvas on which "dots" (sonar "pings") prefabs are instantiated, so the widget contains an accurate representation of in-game objects.

I have an `Update()` method on the controller component which does this:

```
    void Update()
    {
        // This moves the canvas with sonar pings according to camera movements
        swivelRectTransform.anchoredPosition = new Vector2(-Camera.main.transform.position.x * RadarScaleFactor, -Camera.main.transform.position.z * RadarScaleFactor);
        // This rotates the sonar background and the canvas of sonar pings according to the camera direction
        var rotation = new Vector3(0, 180, Camera.main.transform.eulerAngles.y);
        swivelRectTransform.localEulerAngles = rotation;
        radarBackgroundTransform.localEulerAngles = rotation;
    }

```

This works for rotation as long as the player is at the origin position (0,0) and falls apart otherwise: the canvas always rotates around its pivot, not around the camera's position, and altering the pivot apparently messes up positioning in a way which I don't understand.

Here's a video showing what I have so far: https://www.youtube.com/watch?v=MR15zOnObNk

This seems like it should be a common feature - is there a canonical algorithm which does it correctly?

# Answer
> 1 votes
In case anyone else comes across this, here's what to do (intiuited from @Strom's rather cryptic comment):

1. Reset the rotation of the canvas containing "pings"
2. Translate the sonar canvas where it needs to be
3. Apply a new rotation according to the camera bearing and remember it so it can be reset later

---
Tags: unity, movement, minimap
---


# Question
Title: Should purchasing the game immediately unlock all levels?
I am planning to release my first game as an in-app purchase.

When the user buys the game, they own the entire game. If they can't skip a stage because of its difficulty, they can't unlock the next stages, but they should be able to use the entire game they own.

On the other hand, if all stages are open or if there are infinite coins, the game has no dignity and it loses its sense of effort and competition.

How can I address this problem to not block paying customers from enjoying their purchase, while also not trivializing the effort for those players?

# Answer
There is a reason why the most common design choice for progression in games is a more or less linear series of unskippable challenges: Earlier stages often teach the player important skills which they are going to need to properly enjoy later stages. This is called a "difficulty curve".

A common method used in "invisible tutorials" is to present the player with a challenge that is impossible to overcome without using a certain strategy, but becomes trivial if that strategy is employed. This can be a challenge as trivial as "press E to open door", but it can also be a complicated but powerful combination of moves they learned before.

Such an invisible tutorial stage is usually followed by a series of stages where the skill that was just taught gets practiced. This reinforces the knowledge and turns it into muscle memory. For example, when you just taught the player how to open doors, then the next stage should include a whole lot of doors to open, so pressing E as soon as there is a door ahead will become an automatic reflex.

This means that when you design later levels, you can assume that the player is familiar with the mechanics they had to use to complete earlier levels. This allows you to use those mechanics in more challenging and less obvious ways or to introduce mechanics that build upon them.

Now imagine the player skipped those stages that teach and reinforce the knowledge of how to open doors. Now they are in a stage that has a pretty complex puzzle and one element they need to proceed is hidden behind a very inconspicuous door. They aren't aware that doors even can be opened, so they won't be able to reach that element. So they will get frustrated by the seemingly impossible challenge ahead of them.

So by forcing the player to complete the content in your game in a specific order, you can ensure that the player always has all the knowledge they need to properly enjoy the game and have a good game experience. If players gets stuck on certain challenges nevertheless, then that's a sign that you as a designer made a mistake: You didn't properly teach them the skills they need to proceed. Allowing the player to skip that stage would make the problem **worse**: They don't learn the more advanced skills *this* stage was supposed to teach them, so the next stage will be an even more frustrating experience for them. The proper solution is usually to insert some obligatory stages in between which provide teaching and practice in the skills the players need to overcome this difficulty spike.

**Conclusion:** Only let the player skip stages if those stages don't teach them anything they are going to need later. For example, especially difficult "bonus challenges" that require a level of mastery of a certain skill that is beyond what is required to finish any other stages.

---

However, there is also another reason why players might want to skip stages besides those stages being too difficult: The stage being **too easy**. The player might have already mastered the skill the stage is supposed to teach and reinforce, so completing it becomes a chore. In that case it might be useful to offer a way to complete such a stage quickly by demonstrating mastery of that skill. For example, a stage that is intended to practice some simple jumping through repetition might be completable instantly by performing a complicated double-walljump-airdash-interrupt technique that actually gets taught a couple stage later.

Adding intentional "skips" like that can also make the game interesting to speedrunners. However, you need to be careful to ensure that the skip only becomes possible if the player *definitely* mastered *everything* the stage is supposed to teach them. If the player skips the stage by accident, they might find themselves in a situation where they lack a required skill and get stuck.
> 5 votes

# Answer
I've seen some games add an "Unlock all levels" option in the settings menu.

So by default, levels are locked, and unlock in some staged order, using game mechanics like the ones Zibelas describes. This means that most players, just playing what's in front of them in the default state, get a satisfying feeling of progression as their effort unlocks more and more of the game, and a gradual escalation in challenge from early to late game (so they can't accidentally jump into a late game level with an exacting test of a skill they haven't practiced in an earlier teaching level, and have a frustrating time).

But for players who get stuck, or who previously unlocked levels on another account/device and don't want to play through every one again, they have a way to skip this gradual unlock if they go looking for it (or check on the game's help page)

You can distinguish two distinct visual states for a level that's been unlocked vs one that's been completed (or completed to a given level of perfection as Zibelas describes), so even a player who hits "unlock all" can still get an enjoyable feeling of progression from turning all their unlocked levels into completed/perfect levels, filling in the gaps on their checklist.
> 2 votes

# Answer
Congratulation for your soon first game release. There are a number of ways this can be done that depend on what kind of game you are having and how it is played.

* The next level could unlock by X failed attempts in the previous level.
* Automatically after X amount of time (each day one more stage unlocks) or playing time spent in the previous level.
* Watching an ad. If your game is paid, ads might feel wrong to the player since they paid for it.
* By paying an ingame collectable currency (this could be spent on upgrading the character or used to skipping a level)
* By having a certain level of perfection/ stars. If a level can be cleared and you can evaluate how good (barely, good, perfect) and award a currency that is just used for unlocking next levels. The player would get initially 3-X levels unlocked and needs to have Y stars to get the next ones. This has the benefit that not every level needs to be done perfectly
> 1 votes

---
Tags: game-design, level-design, in-app-purchase, progression
---


# Question
Title: How can I right-align elements in Unity's UI Toolkit scroll view?
I've tried a basic google search and am still having trouble with this one.

Unity encourages the use of UI Toolkit at this point, as opposed to their old system, so that's what I'm going with; I have a status bar planned filled with image icons. Like so:

However, I'm trying to get its elements to right-align, like this image edit:

So far, the most I've come up with is style/align/align-items, but none of its options seem to have any affect on the actual item alignment. What am I missing here?

Thank you!

# Answer
> 1 votes
Have you tried putting the image you want to align within a visual element? And then using that as a container to set the alignment on. I'm still new to UIToolKit but I think this should work.

# Answer
> 0 votes
Evidently, after some investigation on the Unity Forums, this is pretty much impossible right now. I would have to use the old Unity UI system to have that much control.

There may be a way to do it, but it requires digging through the UI Debugger—which it really shouldn't—and most of the properties seem to be entirely undocumented right now.

Better to keep it simple.

---
Tags: unity, css, user-interface, ui-toolkit
---


# Question
Title: How to make a Unity navmesh agent keep distance from the target
I want my enemies to follow the player, stop at a certain distance and when enemy is within that distance he will walk away.

```
[SerializeField] Transform target;
[SerializeField] float followRange = 5f;
[SerializeField] float fleeRange = 2f;

NavMeshAgent navMeshAgent;
float distToTarget = Mathf.Infinity;

public Animator anim;
[SerializeField] bool hasTarget = false;
[SerializeField] bool hasDanger = false;

void Start()
{
    navMeshAgent = GetComponent<NavMeshAgent>();
}

void Update()
{
    distToTarget = Vector3.Distance(target.position, transform.position);

    if(distToTarget <= followRange && distToTarget >= (fleeRange - 1f))
    {
        hasTarget = true;
    }
    else
    {
        hasTarget = false;
    }

    if(distToTarget <= fleeRange)
    {
        hasDanger = true;
    }
    else
    {
        hasDanger = false;
    }

    if(hasTarget && hasDanger)
    {
        navMeshAgent.SetDestination(transform.position);
    }

    HasTarget();
    HasDanger();
}

void HasTarget()
{
if(hasTarget)
    {
        navMeshAgent.SetDestination(new Vector3 (target.position.x, transform.position.y, target.position.z));
        anim.SetInteger("Status_walk", 1);
    }
    else
    {
        navMeshAgent.SetDestination(transform.position);
        anim.SetInteger("Status_walk", 0);
    }
if(hasDanger){return;}
}

void HasDanger()
{
if(hasDanger)
    {
    Vector3 toTarget = target.position - transform.position;
    if(Vector3.Distance(target.position, transform.position) < fleeRange)
    {
        Vector3 targetPosition = toTarget.normalized * -fleeRange;
        navMeshAgent.SetDestination(targetPosition);
    }
    }
if(hasTarget){return;}
}

```

This code kinda works, but they just walk up to the target, walk away, walk back and so on.

# Answer
> 1 votes
The NavMeshAgent actually has a property `stoppingDistance` that allows you to control the radius around the destination which will cause the agent to consider the target "reached". Unfortunately there is no good way to detect when a NavMeshAgent reached its destination and then react to this event. You can only check if its moving at all, but it could also have stopped because it can't find a valid path.

One simple pattern for implementing AI behaviors in games is the state-machine. A simple way to implement one is to have:

1. An `enum` with constants representing each state the AI actor can be in.
2. A variable of that type that holds the current state.
3. a `switch`/`case` tree in the Update method which causes the object to behaves differently depending on the current state.

Here is a (abridged and simplified) example from my current project:

```
public class HunterAI : MonoBehaviour {

    private enum State {
        IDLE,
        CHASING_PREY,
        RETURNING_TO_START
    }
    private State currentState = State.IDLE;

    private NavMeshAgent myNavMeshAgent;
    private Vector3 startLocation;

    private Prey chasedPrey;
    [SerializeField] private float preyDetectRadius = 5f;
    [SerializeField] private float preyInteractionRadius = 1f;

    private void Start() {
        myNavMeshAgent = GetComponent<NavMeshAgent>();
        startLocation = transform.position;
    }

    private void Update() {

        switch (currentState) {
            case State.IDLE:
                myNavMeshAgent.destination = startLocation;
                // look for the prey
                var objectsAround = Physics.OverlapSphere(transform.position, preyDetectRadius);
                foreach (var o in objectsAround) {
                    if (o.TryGetComponent<Prey>(out chasedPrey)) {
                        currentState = State.CHASING_PREY;
                        break;
                    }
                }
                break;
            case State.CHASING_PREY:
                // navigate to prey
                myNavMeshAgent.destination = chasedPrey.transform.position;
                // check if caught

                if (myNavMeshAgent.remainingDistance <= preyInteractionRadius) {
                    currentState = State.RETURNING_TO_START;
                }
                break;
            case State.RETURNING_TO_START:
                myNavMeshAgent.destination = startLocation;
                if(myNavMeshAgent.remainingDistance <= 0f) {
                    currentState = State.IDLE;
                }
                break;
        }
    }

```

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


# Question
Title: Help understanding the math to position sphere vertices by latitude and longitude
For a project of mine, I need to render spheres without loading a pre-made model or using built-in functions.

I found this bit of code on the internet that seems to work but I really want to understand what is going on for future reference or in case I want to use this again but modify a few things.

This is the code snippet that's specific to this question:

```
int i, j;
std::vector<GLfloat> vertices;
std::vector<GLuint> indices;
int indicator = 0;
for(i = 0; i <= lats; i++) {
   double lat0 = glm::pi<double>() * (-0.5 + (double) (i - 1) / lats);
   double z0  = sin(lat0);
   double zr0 =  cos(lat0);

   double lat1 = glm::pi<double>() * (-0.5 + (double) i / lats);
   double z1 = sin(lat1);
   double zr1 = cos(lat1);

   for(j = 0; j <= longs; j++) {
       double lng = 2 * glm::pi<double>() * (double) (j - 1) / longs;
       double x = cos(lng);
       double y = sin(lng);

       vertices.push_back(x * zr0);
       vertices.push_back(y * zr0);
       vertices.push_back(z0);
       indices.push_back(indicator);
       indicator++;

       vertices.push_back(x * zr1);
       vertices.push_back(y * zr1);
       vertices.push_back(z1);
       indices.push_back(indicator);
       indicator++;
   }
   indices.push_back(GL_PRIMITIVE_RESTART_FIXED_INDEX);
}

```

The main part that is confusing me is the math with the `lng` `lat` and `x` `y` and `z` variables. Any help would be greatly appreciated.

# Answer
> 0 votes
The code produces quads that approximate the surface of a sphere.

`longs` and `lats` are the number of subdivisions of the circles on their respective axes.

For a globe with 10 degree longitudinal lines the value of longs would be:

```
longs = 360 / 10; // == 36

```

The actual number does not matter to the calculations, just an easy value to demonstrate. Higher values better approximate a sphere at the cost of performance.

With vertex normals, and the shader to support normals, 8 to 20 would be the usual range. Without normals, much higher values(\< 100) are needed, depending on number, scale, distance and target platform performance constraints.

## Longitude and Lng

Let us start in the second loop and work backwards:

The following line calculates each angle 360 / (-1 to 35) (-10,0,10,...,340,350) in radians(a fraction of 2\*PI instead of 360.) Note that -10 == 350 in angles, thus closing the circle.

```
double lng = 2 * glm::pi<double>() * (double) (j - 1) / longs;

```

## X and Y initial values

These values are based on the equatorial axis.

```
double x = cos(lng);
double y = sin(lng);

```

`x` and `y` are the coordinates of the point on the circle at the equator of the sphere.

For uniform scaling purposes by radius `r`, these are part of the lines to change to:

```
double x = r * cos(lng);
double y = r * sin(lng);
// The Z still needs to be scaled.

```

## Lats and Z

The circles described in this section are polar aligned.

The analysis given above for `longs` applies to `lats` with a few differences:

The circle is broken up into 2 parts, one following the other(i and i-1), to allow for the surface to be created across the span.

The following code calculates the radius of the Z (polar) aligned circular component. The XY axis scaling adjustment from the Equator for the Z component of the sphere.

```
double zr0 =  cos(lat0);

```

`zr1` is the same, only for the next slice.

So:

```
vertices.push_back(x * zr0); //Apply the Z circular scale from the Equator to the x axis.
vertices.push_back(y * zr0);//Apply the Z circular scale from the Equator to the y axis.

```

## To complete the uniform scaling example

```
vertices.push_back(z0 * r);
///...
vertices.push_back(z1 * r);

```

For non-uniform scaling(ellipsoid), the value of r(xyz) is based on the axis it is multiplied against, with 2 multiplies of the same value for Z(`z0` and `z1`).

---
Tags: opengl, c++, geometry, mesh, sphere
---


# Question
Title: StaticMeshActors not Multiplayer Replicated in Unreal 5
I'm attempting to add multiplayer support to a new first person game we're working on in Unreal 5.

Starting with the FPS template, it seems like the player and the gun both behave as expected across instances (after some tweaks), but the dynamic cubes in the environment don't match when moved around.

The cubes are StaticMeshActors, and they all have replication enabled (the checkbox for "net load on client"). Is there something else we're missing?

# Answer
> 1 votes
Non-decoration physical object interactions need to only exist on the server.

Uncheck the `Simulate Physics` box in the editor.

To make the change replicate, you need to create a blueprint applied to the the base object that has the condition of `HasAuthority`, and then call the `Enable Physics` node. Be sure to enable replication on the object.

Yes, it is possible to replicate the position to peers without "Authority", but this could lead to discrepancies in gameplay. since each clients physics resolver adds forces based upon position, the results would not be consistent.(since physics is enabled on all clients/servers)

---
Tags: multiplayer, unreal, unreal-5
---


# Question
Title: Rotation is happening in reverse when the cube is upside down
I am writing this functionality in DirectX to rotate cube using the mouse. Now the functionality is working perfectly fine when the cube is sitting straight, but mouse functionality is reversed when the cube is upside down, i.e. the rotation flips completely when rotated about X-axis by 180 degrees. Here is the code implementing the same.

```
XMMATRIX mProjection =
    DirectX::XMMatrixTranspose(
        DirectX::XMMatrixPerspectiveFovLH(DirectX::XM_PIDIV4, 2.2f, .1f, 10000.f));

XMStoreFloat4x4(&viewProj, XMMatrixMultiply(mProjection, mView));

DirectX::XMMATRIX scalingMatrix = DirectX::XMMatrixScaling(m_zoom, m_zoom, m_zoom);
//DirectX::XMMATRIX m_rotationMatrix = DirectX::XMMatrixRotationQuaternion(DirectX::XMLoadFloat4(&m_Rot));
DirectX::XMMATRIX m_rotationMatrixX = XMMatrixRotationX(m_radiansX);
m_rotationMatrix = m_rotationMatrixX * XMMatrixRotationY(m_radiansY);

DirectX::XMMATRIX translationMatrix = DirectX::XMMatrixTranslation(0, 0, 0);

//m_newWorld = scalingMatrix * m_rotationMatrix * translationMatrix;
m_newWorld = scalingMatrix * m_rotationMatrix * translationMatrix;

DirectX::XMMATRIX m_worldMatrix = m_newWorld;

//MatrixBuffer constWordMatrix;
constWordMatrix.mWVP = XMMatrixMultiply(XMLoadFloat4x4(&viewProj), m_worldMatrix);

```

I found this solution in one of the old posts, but not sure how will that translate to my current code. directX rotation of a 3d cube inconsistent

# Answer
> 0 votes
This is perfectly normal behavior.

Imagine being in a inverted airplane. Left is right and up is down.

If you feel this is the incorrect behavior, multiply your inputs by the sign of the dot product of your orientation to ground.

---
Tags: c++, rotation, directx11
---


# Question
Title: Making Unity shadows work at a small scale
I'm trying to cast shadows from a small (3cm) sphere onto a table surface.

If I place a large object, I get shadows as expected, but below a certain size, I get nothing.

I appreciate that under normal circumstances, shadow map resolution wouldn't allow this level of detail, however, my entire scene is 2x2x3 metres.

I could scale up everything to work around the issue, but that would cause a lot of knock-on issues when it comes to physics, VR and a whole slew of other things.

How can I take the shadowmap area Unity would usually assign to a whole scene and apply it to a single tabletop?

I've tried tweaking the `Lightmapping` properties for the table, but haven't seen any visible difference.

Edit: Changing clipping planes didn't have any obvious impact (different angle as from the camera, not editor view)

# Answer
@DMGregory's suggestion was enough to point me in the right direction...

Changing the camera clipping plane didn't help, however, changing the max shadow distance worked.
> 3 votes

---
Tags: unity, shadows, shadow-mapping
---


# Question
Title: How to stream a game world to & from disc while supporting dynamically added objects?
Let's just say you have a massive world that isn't loaded into RAM all the time, and is streamed from the hard drive storage.

How would that world be stored on the hard drive? Is it serialised?

Let's say you have a serialised buffer which holds the data on the world, and you add an object or a component to something in the middle.

How would you do that in a way that doesn't require the entire buffer to be resized after that insertion? Or deletion?

# Answer
> 1 votes
I know of at least one (proprietary) open world game engine that effectively stores its world contents as a database in the development version. These systems are made to support efficient insertions/updates/removals, without moving large swaths of the data around for each operation.

Loading a chunk of the world is then just a database query vaguely like:

```
SELECT * FROM worldObjects WHERE x >= xMin, x < xMax, y >= yMin, y < yMax

```

The trouble is, this is quite slow to load from when scaled up to millions of objects, so this was only done in dev mode (and all our dev machines had big fast SSDs to hide the inefficiency).

For players, we had a part of the build process that would do these slow database queries and bake their results out to an optimized flat file for each chunk of the world at a given level of detail. That way, as you approach a sector of the map in the released game, the engine can quickly find the file for that sector and load it in one linear pass.

So that shows two strategies you can use:

* If this is just for development, or if the set of dynamic changes is small / short lived, consider a database system that supports random insertions and deletions out of the box.
* For linearly-loaded data, don't store it all in one single file buffer, but divide it into separate files at regular spatial intervals. That way you can still randomly seek to a given zone by its file name, and if any chunk file needs to change in size, you have to modify only that one file, not the entirely of the world's map buffer "after" that point.

Elaborating on this, you can use the same strategies we use to support dynamically growing collections in RAM too:

* The location of something in the data's byte order does not need to strictly map to its location in the world. To find stuff by location, you can construct a spatial lookup acceleration structure, like a quadtree, during load. That way, adding something near the "start" position of the map doesn't mean you have to move everything else's bytes down: you can add it at the end, and update your lookup structure to point to it.
* Store the volatile parts separately from the long-lived parts. If you have a core terrain that doesn't change (often), put that part of the file first. Then adding/removing dynamic stuff only affects stuff close to the end of the file, not the whole layout.
* Keep a little wiggle room: when you need to expand the container to hold a new item, don't expand it by just one slot, round up to a multiple. When you remove an item, you can leave a gap to fill later, rather than immediately vacuum-sealing the container to its minimal size. That way the next several adds are free, and you amortize the cost of resizing the container over many operations.

This does waste some disc space, but your file system is likely allocating it in blocks of ~4kiB at a time anyway. You can fit a lot of game entities in 4kiB if you take that extra space all at once.

---
Tags: serialization, streaming, open-world, streaming-assets
---


# Question
Title: Unity stuck on "Installing APK" when "OVR build APK and run" is run
I was trying to make a game for the Oculus Quest 1 with Unity and Oculus plugin.

Until yesterday, everything was working fine but now, when I click on "OVR build APK and run" (as I always did), after the build is finished, Unity is stuck on "Installing APK".

I tried:

* restarting Unity, the Oculus and the Computer;
* run everything as administrator;
* soft-resetting the oculus;
* using "Build and Run" instead of "OVR build APK and run"
* using only "Build" and installing the app with Sidequest (but got stuck on "Checking APK against blacklist");
* using two other computer (Windows 10);
* using `adb install -r app.apk` (but got stuck on `Performing streamed install...`")
* removing the app from the oculus before reinstalling.
* trying to compile an older version of the project.
* using another Oculus (Quest 2)

The logcat wasn't helpful.

Unity version: 2020.3.12f1 personal

Sidequest version: 0.10.21

Oculus XR plugin version: 1.9.1

OpenXR plugin version: 1.2.3

The oculus was last updated a few days ago, but it was working even after the update.

EDIT: tried with another computer (Windows 10, every software/plugin version matches mine) and unity gives another error: `OVRADBTool Error type 3 Error: Activity class {com.Scuola.VR_Scuola/com.unity3d.player.UnityPlayerActivity} does not exist.`. Nothing changes with Sidequest.

Tried also wit a macbook, every software/plugin version matches mine but it works perfectly with both Unity and Sidequest.

# Answer
Solved by reinstalling all the XR related plugin and creating a new project.
> 0 votes

# Answer
This is the only answer that worked for me:

https://answers.unity.com/questions/1248123/build-run-apk-freezes-on-pushing-content-only-one.html

In short, Player settings -\> Publishing settings -\> Split application binary
> 0 votes

---
Tags: unity, android, oculus
---


# Question
Title: Distributing objects on an infinite map with density decreasing with distance from the center
I'm working on a game that has a procedurally generated world akin to Minecraft, but in 2D. I'm generating my terrain by using Perlin noise to determine heights and type of terrain. The advantage of this is that I can input any coordinate and get a result from it. I'd like to be able to do this for objects generated on top of this terrain as well. These objects should be more frequent towards the center of the world and less frequent as the distance from the center increases.

I'm simply not sure how to achieve this, I've found a few potential solutions but they all have their caveats. The one that might work the best would be to use Poisson Sampling with variable radii as this algorithm would also allow for proper spacing between the objects, the problem here is that it has to be generated beforehand and is not useable when going towards infinity. Another idea is to utilise a Gaussian probability density function and to increase the standard deviation with the increasing distance, what I dislike here is that the generation of objects would still be up to chance, making it hard to tweak. Lastly trying to create a circular noise could be an option as well, it would not go towards infinity, but a cutoff at some large value is also alright.

How can I tackle this kind of problem?

# Answer
You can get some of the benefits of Poisson disc sampling with variable radii and still extend out to infinite distance by using tiling blue noise textures. (That link has both source code to generate them, and free textures you can use directly)

The examples above are set up so that each colour channel (RGBA) is an independent square of blue noise that tiles with itself. Within each channel, the pixels between 0-x% brightness form a point set with an approximately Poisson disc distribution covering the area to a density of x%.

This lets you generate placements in a way similar to using Perlin-style noise: put in a pair of x, y coordinates, multiply them by some scale factor and use a modulo to wrap the result to within the bounds of the texture, then sample the pixel they land on. If the brightness of that pixel is lower than your density value at this radius, place an item there, otherwise skip it.

You can add a pseudo-random jitter at each point (eg. generated by Perlin/simplex noise) so that the regular grid of pixels doesn't induce a regular grid in the placements.

The downside is that the texture itself is tiling, and can introduce repetition as a result. But your changing density fall-off should help with that: any two repeats of the same tile will have a different density gradient running across them, and so should still produce distinct results - at least until you get so far from the origin that the density differences between adjacent tiles are only about 1/256 or less. You can add a layer of Perlin/simplex noise to your density function so it always has some non-repeating local variation, even far from the steep part of the radial gradient.

Using larger textures can help too, and will probably be enough to drown out any noticeable repetition of patterns that fit within a screen.

But if you really need to get aperiodic placements - say you can zoom so far out that you can see the tiles no matter how large a texture you choose - then there's another trick you try: upgrade from a single repeating tile to a collection of Wang tiles. These tile the plane aperiodically, so even though a single tile may repeat multiple times, it will do so in the context of different neighbouring tiles, so the pattern as a whole is non-repeating up to the largest scales.

Check out some Shadertoy examples to get a sense of this in action. The way these shaders work is, for each point in the image plane, they find which cell of the repeating tile grid that point falls within, and pseudorandomly choose one of the Wang tiles for that cell, in a way that's guaranteed to match the edges of the tiles selected at adjacent cells without actually generating all the neighbours first (so every pixel can make this decision independently in parallel, and still agree where it matters).

Here's a paper that discusses this technique in more detail, and its accompanying presentation.
> 4 votes

# Answer
As you're working on a discrete grid, I thought I'd offer a simpler implementation. It's potentially quite inefficient for large radius values.

The idea is we imagine ordering the infinite plane of points by a random shuffle, and looping over each point. We only add an object at a point if there isn't already an added object sufficiently nearby. This is quite similar to rejection sampling.

We don't need literally order all infinity points, we only need check the points in the immediate vicinity would have been sorted earlier given some priority function.

```
def variable_radius(x, y):
  # Whatever function you like
  return log(x*x+y*y+1)

def get_priority(x, y):
  # Returns a deterministic pseudo-random unique sort key
  import hashlib
  b = repr((x, y)).encode()
  return hashlib.sha1(b).digest() + b

def is_object_at_point(x, y):
  r = variable_radius(x, y):
  priority = get_priority(x, y)
  for (x2, y2) in cells_in_circle(x, y, r):
    if deterministic_rand(x2, y2) < priority:
      return False
  return True

```

As this is so inefficient, you may have to resort to evaluating large blocks at a time, or using a more advanced algorithm described in other answers.
> 2 votes

---
Tags: unity, c#, procedural-generation
---


title: Can I use DirectXTK12 commercially?

text:
# Question
Title: Can I use DirectXTK12 commercially?
This question is about the licensing of DirectXTK.

Is DirectXTK12 free for commercial use? I ask because I use it in my project, and I may want to go commercial in the future. If it is not, I'll create all the tools for my project.

Similarly for DirectXTex - is it also free for commercial use?

# Answer
> 4 votes
From the license posted in the DirectXTK12 repo:

> microsoft/DirectXTK12 is licensed under the MIT License:
>
> A short and simple permissive license with conditions only requiring preservation of copyright and license notices. Licensed works, modifications, and larger works may be distributed under different terms and without source code.
>
> Permissions
>
> * Commercial use
> * Modification
> * Distribution
> * Private use
>
> Limitations
>
> * Liability
> * Warranty
>
> Conditions
>
> * License and copyright notice

Under that license you are entitled to the permissions (which includes commercial use) provided that you accept the limitations and conditions. It is 'free' in the sense that you don't have to pay for the license as listed, but using that license represents an agreement regarding the use and distribution of the software.

# Answer
> 1 votes
I am not a lawyer, as such, none of the following should be construed as legal advise. Please consult a lawyer.

Yes, you can use any MIT licensed in a commercial product without fees, royalties...

However the license and copyright lines must be distributed with the use of the code. Windows has a long file of these notices.

This is accomplished by including a text file packaged with the end product containing the following text:

```
DirectXTK12 used in this software is licensed as follows:
MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

```

I would include the fitness indemnity clause as well, but not specifically required:

> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

This clause means that if there is an exploitable bug in the the implementation and you get sued, that is on you, and not the original author of the code.

The same goes for DirectXTex.

Some projects choose to include one text file per project:

DirectXTK12.LICENSE

containing the above required text. Either way is acceptable.

Some licenses require(not MIT), compiled, in program attribution. This is accomplished with a credits tab on the main menu for games or in the `Help->About` for Windows Forms.

---
Tags: c++, directx, legal, licensing
---


# Question
Title: Which is better to use C# and Shader to move textures?
We could use C# code `Material.SetTextureOffset` to move a texture, and ShaderGraph can do the same by `Time` and `Tiling and Offset` nodes. So Which way is better for performance purpose?

# Answer
> 0 votes
The primary concern is functionality.

If collisions are needed, the CPU is (mostly) the required method.

I could go into the the specifics of my ancient computer to ask you to identify the hardware first. That would require to much duplication of code to achieve optimal results.

Select a midrange audience and develop and optimize the code for that group.

For the Intel integrated GPUs, the GPU speed gain is in the low values or negatives.

For today's common computer, the GPU option is only viable for larger games, where a discrete GPU is expected.

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


title: Snake Game body rotation

text:
# Question
Title: Snake Game body rotation
I am currently trying to make a snake game with Unity. I'm a beginner at C# so I decided to make a game that seemed easy. With the help of this tutorial How to make Snake in Unity (Complete Tutorial) I made a basic snake game. The problems came when I tried to change the sprites.I somehow managed to figure out how to turn the head in the direction that the snake is moving, but I cant figure out how to move the body in the right direction. I've been stuck on this for days.

Here is an example so you can understand better what I mean:  As you can see, everything works besides the body rotation. I tried to follow this tutorials Making a Snake with Snake Like Movement in Unity (Part 1/2): Follow the Leader / Synchronized Motion, Making Snake in Unity: Snake Body Corners (Unity Tutorial for Beginners) but i couldn't make the body rotate.

Here is my code so far:

```
private List<Transform> segments = new List<Transform>();
public Transform segmentPrefab;
public Vector2 _direction = Vector2.right;
private Vector2 input;
public int initialSize = 4;
public float rotationSpeed;

private void Start()
{
    ResetState();

}

//controls
private void Update()
{
    if (_direction.x != 0f)
    {
        if (Input.GetKeyDown(KeyCode.W) || Input.GetKeyDown(KeyCode.UpArrow))
        {
            input = Vector2.up;
        }
        else if (Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow))
        {
            input = Vector2.down;
        }
    }

    if (_direction.y != 0f)
    {
        if (Input.GetKeyDown(KeyCode.D) || Input.GetKeyDown(KeyCode.RightArrow))
        {
            input = Vector2.right;
        }
        else if (Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.LeftArrow))
        {
            input = Vector2.left;
        }
    }
}

private void FixedUpdate()
{
    //Body Movement
    for (int i = segments.Count - 1; i > 0; i--)
    {
        segments[i].position = segments[i - 1].position;
    }

    //Snake Movement
    if (input != Vector2.zero)
    {
        _direction = input;
    }

    float x = Mathf.Round(transform.position.x) + _direction.x;
    float y = Mathf.Round(transform.position.y) + _direction.y;

    transform.position = new Vector3(x, y);

    //Head Rotation
    if (_direction != Vector2.zero)
    {
        Quaternion toRotation = Quaternion.LookRotation(Vector3.forward, _direction);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation, rotationSpeed * Time.deltaTime);
    }
}

//Add body part
public void Grow()
{
    Transform segment = Instantiate(segmentPrefab);
    segment.position = segments[segments.Count - 1].position;
    segments.Add(segment);
}

//reset game
public void ResetState()
{
    _direction = Vector2.right;
    transform.position = Vector3.zero;

    for (int i = 1; i < segments.Count; i++)
    {
        Destroy(segments[i].gameObject);
    }

    segments.Clear();
    segments.Add(transform);

    for (int i = 0; i < initialSize - 1; i++)
    {
        Grow();
    }
}

//grow or Reset
private void OnTriggerEnter2D(Collider2D other)
{
    if (other.gameObject.CompareTag("Food"))
    {
        Grow();
    }
    else if (other.gameObject.CompareTag("Obstacle"))
    {
        ResetState();
    }
}

//body rotation

}

```

Due to the fact that I'm a beginner, some code would be useful. Thank you!

# Answer
> 0 votes
Each segment needs to inherit the rotation along with the position:

```
segments[i].position = segments[i - 1].position; //existing line
segments[i].rotation = segments[i - 1].rotation; // added line

```

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


# Question
Title: Load in all NPC asset dependencies at once, or Just In Time during their construction?
I have an `NPC` class with a `DialogueTree` object as a field. `DialogueTree` objects are automatically constructed recursively by loading in the contents of `.xml` files where they're stored.

In building my `XMLDialogueLoader` class, I see two main approaches:

1. Load in every dialogues for every NPC on game start, available as a sort of pool from which any components that depend on it can access. Sort of like a global dictionary, when NPCs are constructed they index their ID in that Dialogue pool to retrieve their dialogues.

```
dialogue_pool: dict[str, DialogueTree] = dialogue_loader.load('dialogues/')
npc = NPC('John', dialogue_pool['John']
npc = NPC('Tom', dialogue_pool['Tom']

```
2. Load in every dialogue for NPCs only when they are being constructed. I would likely do this by creating an `NPCFactory` object that takes in a `DialogueLoader` with a method to load in a specific NPC's dialogue at a time, like `self.dialogue_loader.load('npc_name')`

```
class NPCFactory:
  dialogue_loader: DialogueLoader

  build(self, name: str):
    dialogue_tree = dialogue_loader.load(name)
    return NPC(name, dialogue_tree)

```

I suppose another set of variations would be loading in specific dialogues just in time rather than all at once, but that seems maybe excessive.

What advantages and disadvantages exist in these approaches? What is typical in industry? Are there better ways of doing this or alternative approaches?

# Answer
There is little difference in the given approaches unless load speed is an issue(multi-megabyte trees).

The final memory utilization will be the same no matter what once they are loaded.

The industry "standard," if such a thing exists, would be to load all dialog for the current "level" or streamed partition, and dispose of it on level change(or partition exit).

Memory disposal is relatively easy in C++ (`free`). In Python, removal works but the effects can be delayed.

For most smaller games, the load times nor memory is an issue, always keep an eye on memory, just in case(excessive swapping will kill performance, so always test on minimum RAM):

So load away, and unload when no longer needed.
> 1 votes

---
Tags: python, loading, asset-management
---


# Question
Title: Why is Physics.CapsuleCast returning a mix of true and false when it should return only true?
I'm making a simple character controller. Each frame the player moves by `moveDistance` units in the `moveDir` direction.

I'm casting a capsule to detect any collision:

```
private void Update()
{
    Vector2 input = _gameInput.GetGameInputNormalized();

    Vector3 moveDir = new Vector3(input.x, 0, input.y);

    float moveDistance = moveSpeed * Time.deltaTime;
    bool canMove = !Physics.CapsuleCast(transform.position, transform.position + Vector3.up * 2f, .7f, moveDir, moveDistance);

    Debug.Log(canMove);

    if (canMove)
    {
        transform.position += moveDir * moveDistance;
        IsWalking = true;
    }
    else
    {
        IsWalking = false;
    }

    transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotationSpeed);
}

```

It's working as expected but with one problem. Printing `canMove` when the user is colliding with a wall and still trying to move towards it prints a mix of `True` and `False` as shown here:

Note that the player is still moving towards the wall when the console is printing both True and False.

I've tried removing the rotation logic, increasing the capsule cast distance but nothing worked.

One thing I suspected was the need to use Unity's `FixedUpdate` method, but it also didn't work.

# Answer
It was actually a small bug where the class was mistakenly attached to 2 game objects. And that is because there is a class responsible for animations that is attached on the graphics game object of the player. That class had the attribute: `[RequireComponent(typeof(Player))]` where `Player` is the class that is printing to the console.
> 0 votes

---
Tags: unity, collision-detection, raycasting, character-controller
---


title: Unity UI button not working

text:
# Question
Title: Unity UI button not working
I'm creating a game in unity and I can't get the UI buttons to work. Here is what I tried:

* Added a graphics raycaster to the canvas
* Added an events system with an Input System UI Input Manager
* Checked that nothing is blocking the buttons

This is in a pause menu, when the time scale is 0.

Here is the hierarchy:

# Answer
> 0 votes
I just fixed the problem, I was using the new Input System UI Input Manager instead of Standalone Input Module

# Answer
> 0 votes
Check if Raycast Target is on in order to click, and off for being unclickable. More advice: just enable inside the button background and disables it inside the text, optimizing your game.

---
Tags: unity, 3d, gui, unity-ui
---


# Question
Title: BeginPlay and Tick do not work for blueprint class inherited from C++ class
The problem is that the begin play and tick functions do not work in a blueprint inherited from a C++ class.

If the blueprint does not inherit from a C++ class, then the functions work perfectly.

Functions declaration in C++ parent class:

```
protected:
    virtual void BeginPlay() override;

public:
    //Called every frame
    virtual void Tick(float DeltaTime) override;

```

Child BP:

Nothing appears on startup.

# Answer
The problem was that the base C++ class, from which the APocketDrill class is inherited, did not contain a call to the Super method in BeginPlay.
> 1 votes

# Answer
Blueprint events are not the C++ defined functions. You need to call a public C++ function with an event.

I copied exactly what you showed and hit play. My screen was filled with text.
> 0 votes

---
Tags: c++, unreal, blueprints, unreal-5
---


# Question
Title: Make ready player me Avatar replicate animation from Mixamo by pressing an oculus quest2 controller button
I have a ready playerme avatar that I rigged with Final IK.

I downloaded an animation from mixamo to play with this avatar. My goal is to animate the avatar with the downloaded animation once a button is pressed on my oculus quest 2 controller. I am also using XR Interaction toolkit. However, I have not been able to completely do it. Below are the things I did

1. Avatar is rigged with final IK
2. Animation is downloaded from Mixamo with (FBX for unity) format
3. downloaded animation is placed under Assets \> Plugins \> ReadyPlayer Me \> Resources \> Animations
4. Animation is extracted from the fbx file
5. I dragged the extracted animation (Clapping) into the Animator window. Made a transition from the **'Entry'** state to it and then from it to the **'VRIK Animated Locomotion state'**
6. I created a boolean parameter, **'isClap'**
7. The transition from **"Entry"** to the animation, **"Clapping"** is given the condition. **'isclap'** and set to **true**.
8. The transition from "Clapping" to **"VRIK Animated Locomotion"** is also given same condition but set to **false**.
9. I created a new action map with a new action and then binded it to the primary button on the oculus quest2 left controller
10. I created the following script and added it to my avatar object. In the script, I intend to activate the animation by setting **'is clap'** to **true** when the button is pressed and make it **false** when the button is released. This way, I can achieve my goal

```
using System.Collections;

    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.InputSystem;

    public class AnimatorScript : MonoBehaviour
    {
        Animator animator;

        public InputActionReference clap = null;

        // Start is called before the first frame update
        void Start()
        {
            animator = GetComponent<Animator>();
        }

        private void update()
        {
            clap.action.started += clapping;
        }

        private void OnDestroy()
        {
            clap.action.started -= clapping;
        }

        private void clapping(InputAction.CallbackContext context)
        {
            animator.SetBool("isclap", true);
            //Debug.Log("now executing....: " + clap.action.GetHashCode());
        }

    }

```

Unfortunately, it's not working. I believe I'm missing a few things or something is not done right.

**Update:**

I started all over again. Without rigging, I wanted to see if my newly imported avatar can perform those animations by pressing the oculus controller button. It works, but the animation keeps going without stop.

This is simpler with OVR because it has mappings for button up, down and so on. I'm using XR for input mapping and I have no idea on how to change my boolean parameter, **isclap** to **false** when the button is released. I also used the **Invoke()** method to set a delay time to make it **false** after it has been **true** for a while. Still didn't work for me. updated code.

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

public class AnimatorScript : MonoBehaviour
{
    private Animator animator = null;

    public InputActionReference clap = null;

    private void Start()
    {
        animator = GetComponent<Animator>();
        clap.action.started += ClappingEnabled;
        Invoke("ClappingDisabled", 3f);
    }

    private void ClappingEnabled(InputAction.CallbackContext context)
    {

        animator.SetBool("isclap", true);

        //Debug.Log("now executing....: " + clap.action.GetHashCode());
    }

    private void ClappingDisabled(InputAction.CallbackContext context)
    {
        animator.SetBool("isclap", false);
        //Debug.Log("now executing....: " + clap.action.GetHashCode());
    }

}

```

I have played around with **isclap** in play mode and the animation works pretty fine when alternating between **true** and **false**. Nothing much has changed from my previous trys, the only difference is that I have not done any rigging. I just attached the Mixamo animation and edited the avatar's default state machine below with my animation and added the **isclap** condition for transition.

# Answer
I figured it out. Step 1 to 5 in my original question remains the same. Instead of creating a boolean parameter, I created a trigger (**checkclap**) instead.

I am making a transition from **Any state** to the **clap** state which has the clap animation. The transition from **Any state** has the condition **checkclap** and no condition for the transition from **clap** to **VRIK\_Locomotion**. Step 9 remained the same and I added the below script to my avatar.

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

public class AnimatorScript : MonoBehaviour
{
    private Animator animator = null;

    public InputActionReference clap = null;

    //private Coroutine coroutine;

    //Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();

    }

    private void OnEnable()
    {
        clap.action.started += ClappingEnabled;
    }

    private void OnDisable()
    {
        clap.action.started -= ClappingEnabled;
    }

    private void ClappingEnabled(InputAction.CallbackContext context)
    {
        animator.SetTrigger("checkclap");
    }
}

```
> 1 votes

---
Tags: unity, c#, animation, skeletal-animation, animation-states
---


# Question
Title: How to draw/calculate a parabolic arch to hit stationary target in Javascript
First off I must admit I'm really not good at math and am trying to learn but have had a hard time finding examples someone like myself can follow. I'm trying to figure out how to draw and calculate the parabolic arch from one point to hit a target.

I really appreciate any help on this, I have been struggling to figure out a this for the past 2 days and still am unable to come up with anything that works.

The best visual depiction I found was something like this but I am looking for a 2D solution.

```
<html>
  <body>
    <canvas id="myCanvas"></canvas>
    <script>
      function ranInt(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

     var canvas = document.getElementById("myCanvas");
      canvas.width = 500;
      canvas.height = 500;
      let w = canvas.width;
      let h = canvas.height;
      document.body.appendChild(canvas);
      var ctx = canvas.getContext("2d");
      var ox = 20;
      var oy = h - 20;
      var cannon = { x: ox - 12, y: oy - 12, width: 50, height: 24 };
      var target = { x: w - 150, y: h - 350, width: 42, height: 42 };
      var ball = { x: ox, y: oy, r: 10, cx: ox, cy: oy };

      function draw() {
        ctx.fillStyle = "yellow";
        ctx.fillRect(cannon.x, cannon.y, cannon.width, cannon.height);
        ctx.fillRect(target.x, target.y, target.width, target.height);
        ctx.fillStyle = "red";
        ctx.fillRect(ball.cx, ball.cy, 4, 4);
      }

      var state = "ready";

      function update() {
        if (state === "flying") {
          var x = ball.cx;
          var y = ball.cy;
          x += vx;
          y += vy;
          vy += 0.1;
          ball.cx = x;
          ball.cy = y;
          ctx.fillStyle = "black";
          ctx.fillRect(ball.cx, ball.cy, 4, 4);

          if (ball.cy > h || ball.cx > w) {
            state = "ready";
            ball = { x: ox, y: oy, r: 10, cx: ox, cy: oy };
          }
        }

        draw();
      }

      setInterval(update, 10);
      var vx = 0;
      var vy = 0;
      document.addEventListener("click", function (e) {
        ball = { x: ox, y: oy, r: 10, cx: ox, cy: oy };
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        vy = -9.22;
        vx =  (e.pageX - ox) / 50;

        state = "flying";
      });
    </script>
  </body>
</html>

```

# Answer
> 1 votes
One way is to predetermine the point shooting to, and also pre plot each point used to get from point a to z. I've used an open source library to simplify this example;

```
(function() {

    var canvasObject = new tabageos.CanvasObject(null,250,250);

    document.getElementById("theBody").appendChild(canvasObject.canvas);

    var cannon = new tabageos.MoverPoint(20,100);

    var ball = new tabageos.MoverPoint(20,100);

    var ballTarget = new tabageos.MoverPoint(230,100);

    var ballPath = tabageos.GeometricMath.getRawArcCurvePath(cannon.x,cannon.y, 150,4, ballTarget.x,ballTarget.y,100);

    canvasObject.drawCircle(cannon.x,cannon.y,16,"#c8c8c8");

    canvasObject.drawCircle(ballTarget.x, ballTarget.y, 16,"#c80000");

    canvasObject.drawCircle(ball.x, ball.y,8,"#000000");

    var currentBallPathIndex = 0;

    var loop = function() {
       canvasObject.clear();
       canvasObject.drawCircle(cannon.x,cannon.y,16,"#c8c8c8");
       canvasObject.drawCircle(ballTarget.x, ballTarget.y, 16,"#c80000");

       ball.x = ballPath[currentBallPathIndex];
       ball.y = ballPath[currentBallPathIndex+1];
       canvasObject.drawCircle(ball.x,ball.y,8,"#000000");

       if(currentBallPathIndex < ballPath.length-1) {
           currentBallPathIndex += 2;
       } else { currentBallPathIndex = 0; }

       requestAnimationFrame(loop);
    };
    loop();

})();
```

```
<script src="https://cdn.jsdelivr.net/gh/tabageos/tabageos/tbgs_min.js"></script>

<div id="theBody"> </div>
```

This is what getRawArcCurvePath would look like;

```
getRawArcCurvePath = function(p0x, p0y, p1x, p1y, p2x, p2y, amountOfPoints) {
    var i = 0;
    var added = (100 / amountOfPoints) / 100;
    var path = [];
    while(i < 1) {
       var a = (1 - i) * (1 - i);
       var t = i * i;
       path[path.length] = a * p0x + 2 * (1-i) * i * p1x + t * p2x;
       path[path.length] = a * p0y + 2 * (1-i) * i * p1y + t * p2y;
       i += added;
    }
    return path;
}

```

---
Tags: physics, javascript, projectile
---


title: Collision detected early between images

text:
# Question
Title: Collision detected early between images
Im making a "catcher" style game in python, where the player has to collect "Gems", and avoid the "Spikes". However the games collision detection is off by quite a lot. When I run the game, everything is going well. The player is moving, the objects are falling from the correct positions. But when the collision is detected it is detected early. How can I improve the collision detection so it can detect more accurate collisions with either of the objects? Here is part of the code including the Player, Gem, and Spike class. The full code, with graphics is in the github link below. Any help is appriciated!

```
class Player(pygame.sprite.Sprite):

    def __init__(self):
        global game_state

        # super().__init__()

        self.player_surf = pygame.image.load('game graphics/player_stand.png').convert_alpha()
        #scaled player image
        self.player_surf = pygame.transform.scale(self.player_surf,(500,500))
        self.rect = self.player_surf.get_rect(midbottom = (x,y))
        self.x_speed = 5
        self.health = 5
        self.score = 0

class Gem(pygame.sprite.Sprite):

    def __init__(self):
        self.x = random.randrange(0, screen_w)
        self.y = -20
        self.vel = 4
        self.gem_image = [pygame.image.load('gems & spikes/greenGem.png'),
                          pygame.image.load('gems & spikes/redGem.png'),
                          pygame.image.load('gems & spikes/blueGem.png'),
                          pygame.image.load('gems & spikes/yellowGem.png')]
        self.gem_image = [pygame.transform.scale(img, (90, 90)) for img in self.gem_image]
        self.counter = 0
        self.rect = self.gem_image[counter].get_rect(midbottom=(self.x, self.y))
        self.update_y()

    def update_y(self):
        self.y += self.vel
        self.rect = self.gem_image[self.counter].get_rect(midbottom=(self.x, self.y))
        self.collide = self.rect.colliderect(player.rect)
        if self.y > screen_h:
            self.y = -20
            self.x = random.randrange(0, screen_w)
            self.counter = (self.counter + 3) % len(self.gem_image)
        if self.collide:
            self.y = 0
            self.x = random.randrange(0, screen_w)
            player.score += 1

class Spike(pygame.sprite.Sprite):

    def __init__(self):
        self.x = random.randrange(0,screen_w)
        self.y = -20
        self.vel = 2
        self.spike_image = pygame.image.load('gems & spikes/spike.png')
        self.spike_image = pygame.transform.scale(self.spike_image,(120,120))
        self.rect = self.spike_image.get_rect(midbottom = (x,y))
        self.update_y()

    def update_y(self):
        self.y += self.vel
        self.rect = self.spike_image.get_rect(midbottom=(self.x, self.y))
        self.collide = self.rect.colliderect(player.rect)
        if self.y > screen_h:
            self.y = -20
            self.x = random.randrange(0, screen_w)
        if self.collide:
            player.health -= 1
            self.y = -20
            self.x = random.randrange(0, screen_w)

```

Github Repository: Cave-Of-Doom-

Here is a video of the problem on youtube: https://youtu.be/J5sGUwhVh4s

# Answer
Solution was found through asking the question on reddit. Here is the thread,

https://www.reddit.com/r/pygame/comments/10wis5l/how\_to\_change\_the\_size\_of\_a\_rect\_for\_a\_collision/
> -1 votes

# Answer
Separate the collision rectangles from the drawn sprites rectangles.

This is a common practise in games.

Reduce the size of the Spike collision by 2 or 3 pixels.

The following code would be an example for the reduced spike collision:

```
   self.collide = self.spike_image.get_rect(midbottom=(self.x + 1, self.y), width =  self.spike_image.width - 2, height = self.spike_image.height - 2)

```

Since the rectangle is defined from `midbottom`, the x needs to be adjusted by (+1) to center the new width, and the bottom stays the same with reduced height (-2).
> 0 votes

---
Tags: collision-detection, pygame
---


# Question
Title: How can I create a mask for 2d lights in Unity?
I'm working on a top-down 2d game in Unity. assume my world/map looks like this through the player's eyes:

(The art isn't mine, this is just an example) Now by making art directly like this, I can control the "lighting" as in drawing lighter and darker areas in the grass to create the illusion of sunlight and shadow.

I like this since it's very convenient and lets me have a lot of control, however, How would I make the player sprite "react" to this "light"? for example, if the player sprite were to walk into the sunny/bright parts of the map then it should be lit up/ bright and if it walks into the shadow regions then it darkens up.

I'm okay with creating multiple sprites for this if necessary, however, how do I detect whether the player is in light or not? Is there a way to create some sort of mask or texture map that lets me change the sprite or add lighting somehow?

I'm sorry if this isn't a good question, I'm still new to unity.

# Answer
The Light2D component might help you. But note that it is only available in projects that use the Universal Render Pipeline (URP), not for the standard render pipeline or the high-definition render pipeline. (See the manual article on render pipelines for more information on which render pipeline to use for your project).

Note that with this package, you don't define *shadows* you define *lights*. The default state is in shadow, and you say what areas are lit and how they are lit.

When you install this package, you have the Light 2D component which has various options. Those that seem most relevant for your particular use-case are:

* "Freeform light" which allow you to define a lit area using a polygonal shape
* "Sprite light" which allows you to define a lit area by providing an image
> 0 votes

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


# Question
Title: Loading game state before first save has occurred (chicken/egg problem)
I've learned that storing and loading game saves is commonly done by serializing runtime data into binary files and then loading in those binary files de-serialized to reconstruct the runtime state respectively

A Python library pickle allows for serializing and de-serializing entire objects. It makes intuitive sense and ease of use then to compose all relevant world state variables into a single object `WorldState`, which will be serialized on saves and reconstructed on loads.

```
class WorldState(metaclass=Singleton):
    relationships: dict[Entity, dict[Entity, Literal['friendly','neutral','hostile']]
    questlines: list[QuestLine]
    locations: list[Location]
    items: list[Item]
    entities: list[Entity]
    player: Entity
    time: float

```

This works, but I'm not sure how to handle the *initial* game state, before any saves have occurred. I'm left with a chicken/egg scenario, where in order to **load** game state there must already be serialized binary files to reconstruct, which happens on **save**, but in order to **save** game state into serialized binary files there must already be a `WorldState` instance constructed to save.

If I were using XML/JSON to store game state I would simply write the initial content manually which would be overwritten on saves to be loaded again later, but since I am serializing them into binary I obviously cannot do that.

The only solution seems to be adding an `if` to check whether any game saves already exist, and to manually construct all the initial objects if not, either in the source-code (using dependency injection containers) or loaded from xml/json files that would exist only to represent the initial game state since every other load after the first will be based on serialized binary files, not json.

Am I missing something? Is there a better approach? Should I just represent game state in human-readable formats like json? What techniques are common in industry?

# Answer
The file system can fail beyond your control.

If you have a default file, it might be removed due to fortuitous reasons.

That might suggest to you that to check if the file exists is the way to go. But don't do that. That would be race condition… Because your game execution can be preempted by the operating system after you checked the file is there, but before you load it. *That is a Time-of-check to time-of-use bug.*

Thus, what you should do is to try to load the file (no check done before hand), and if that fails you instance your objects from code by more conventional means. *Another option is to have your default file bundled in the game executable as a resource.*

*Note that I'm talking about saving game state, not the asset pipeline.*

*The fact that the file system can fail beyond your control also suggest that it is a good idea to make an automatic backup of the save file. Which means that when the load fails, you should try to load the backup before falling back to conventional instanciation.*

---

If we are talking about a single player game, then tampering with the save files mainly affects the same player who did it. Let them. Perhaps worry about making the game entertaining enough that they don't want to go into the trouble. I'm saying that using a binary format as a deterrent against tampering with save files is not worth it.

However, sometimes players share save files, and if you are using a generic serialization solution that might be a security risk. You want a solution that either allows you to whitelist the classes it will handle, or allows setting a callback to resolve classes, which is allowed to fail.

If you opt for the human readable format, be mindful of loss of precision due to the representation of values in human readable format. You want to make sure that whatever you serialize can be deserialized losslessly, or it is only lossy where it does not matter.

---

If this is a multiplayer game, where each player has a save file (it is a multiplayer game with document-oriented database for the player data※)… You want a binary format because of performance.

※: Some games benefit from from having a document-oriented database for player data that is only acceded by the player (e.g. inventory), in combination with a more traditional relational database for other things that might be acceded by other players (e.g. name and public stats) or for which the game need complex queries. This also allows the game server to send a copy to the client who can browse the data without doing many requests to the server (operations on it still need to go through the server, and logged on the server, but usually the client can do the same operation locally - when the server approved it - instead of downloading and deserializing the document again).

*Note that security would not be a concern of the serialization solution in this case, as only the copy of these files in the server is trusted, and it cannot be written directly from client machines.*

Be aware that GMs might need to work with player data (or even run custom scripts over them) to solve problems (e.g. issue a mass refund). And there should be tooling for such operations.

Oh, and the file system can fail beyond your control, and if it is your server you want to know when that happens.
> 2 votes

# Answer
I made very good experiences with keeping savegames in JSON format. The reason is that you can easily view savegames for troubleshooting and manually create and edit savegames in a text editor to quickly test certain scenarios.

This also makes it possible to represent the initial state of a new game as yet another hand-written savegame.

When you are worried about JSON taking too much space, then just compress them using a stock compression algorithm like DEFLATE. That should greatly reduce the filesize. Usually not as much as a native binary format, though. But hard drive space is cheap, and it's not your space anyway.

If you insist on a binary file format, then you might want to consider to create your own savegame editor application for that purpose. Either that, or get comfortable with a hex editor.
> 2 votes

---
Tags: assets, data-structure, savegame, loading, serialization
---


# Question
Title: Can't access core/assets in a Desktop-Only Libgdx Project
I'm trying to use libgdx to set up a little quiz application for Desktop.

So I used the setup.jar to create a project and everything went fine (using Eclipse).

The problem is following:

Whenever I try to access the assets in core/assets, as you should do: `Gdx.files.internal(filePath)`

I always get a NullPointerException:

```
java.io.FileNotFoundException: PATH\QuizApplication\desktop\questions.xml (The system cannot find the file specified)

```

My assets Folder in the desktop project is linked to the core project, and inside Eclipse, I can see the right contents. As you can see from the Exception, the application tries to read the desktop project instead of the core project.

In build.gradle in the desktop project, the link to the core assets folder is there too:

```
project.ext.assetsDir = new File("../core/assets");

```

Does anyone know how I might fix this problem, so that I can access the core/assets folder?

# Answer
I could fix the problem by using these two questions:

https://stackoverflow.com/questions/26195511/libgdx-project-cant-find-assets-folder

https://stackoverflow.com/questions/22822767/file-not-found-when-running-new-libgdx-project?noredirect=1&lq=1

I guess the gdx-setup.jar does everything for you except directing the Workspace the right way.

My second problem in the comments could be fixxed by using a lower Java JDK (1.8.0\_151).
> 1 votes

# Answer
I was also able to resolve this by changing the active directory to the subproject. For example instead of running gradle in your base project, you can change the current directory to the subproject.

**For example**

Task that fails due to OP issue

`./gradlew task`

So instead...

```
cd subproject
../gradlew task

```

worked for me.

(note I'm using gradle wrapper thus I had to point it back to it's local in the main project with ../, if you're just using gradle you won't need this.
> 0 votes

---
Tags: java, libgdx, assets
---