# Question
Title: How to keep sprites sharp and crisp, even while rotating
# How can I maintain crisp, sharp edges on sprites, while avoiding the aliasing caused by rotation?

None of the things I've tried produce a pixel-perfect *non-rotated* block, while allowing rotation without aliasing

### Click here for the sample project, which also has some extra images in it.

### Click here for my Unity Forums Thread

---

## Ideally, this is what it would look like

From Photoshop, not Unity.

* Flawless edges, smooth corners, and very faint aliasing when rotated.

Screenshot from Github project:

##

## Row 1

***Non-rotated*:** Perfect edges, pixelated corners

***Rotated*:** Pixelated everywhere

---

## Row 2

***Non-rotated*:** Perfect edges, smooth corners.

***Rotated*:** Pixelated edges, smooth corners

---

## Row 3

***Non-rotated*:** Blurry everywhere.

***Rotated*:** Blurry everywhere

---

## Row 4

***Non-rotated*:** Not quite perfect edges, pixelated corners

***Rotated*:** Blurry everywhere

---

## Row 5 (MY BEST SOLUTION SO FAR)

***Non-rotated*:** Semi-blurry everywhere.

***Rotated*:** Semi-blurry everywhere

---

Texture for "no border padding" texture:

Texture for "with padding" texture:

---

# Shader Method

(Note: I'm a total shader newbie)

I created a fragment shader to draw the block.

It has AA (via smoothstep) built in, and throttles it on as block is rotated (so that there is no AA when it's not rotated)

## This has some problems:

1. **A (geometry) shader doesn't seem like the correct solution for this problem at all**, since I'd have to make a shader for all the geometry that has this problem.

* ***But maybe there is a shader that can apply AA to a texture***, that doesn't do anything for vertical or horizontal (non-rotated) edges?
2. Corners of block with AA turned off are pixelated

* This doesn't seem too difficult to fix
    * I'd probably want it to work identically to row 2 (non-rotated)
3. Not sure how much AA to apply (when rotated) so that it's as sharp as possible for a given screen DPI.

* **I thought this is what mip maps were good for, since the highest possible res texture should be chosen.** (Another reason why a texture-based solution seems best)

---

# Other things I've tried:

### Vector graphics (per Unity's vector package)

* Unity's vector package required 4x MSAA to look right, which was too intensive for mobile devices

### MSAA

* Creates blurry graphics (is there a way around this?)

# Answer
I'd be tempted to solve this with a Signed Distance Field.

Here we swap our original texture with one where the brightness value represents how far we are inside/outside the shape.

I set one up quickly to test with using the stroke layer effect in Photoshop:

I saved this as a single-channel greyscale image, imported uncompressed to avoid errors.

Now in our shader, we can use the value read from this texture, along with the partial derivatives from adjacent fragments, to estimate how many screen pixels we are from the true boundary, and shade the pixel accordingly. Here's the SDF shader I used for this test, which plays nicely with Unity's built-in sprite rendering:

```
Shader "Sprites/SDF Sprite"
{
    Properties
    {
        _MainTex ("Texture", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)
        _Sharpness("Sharpness", Range(0.01, 1)) = 1.0
    }
    SubShader
    {
        // Duplicate normal sprite shader behaviours.
        // (I skipped implementing split alpha though)
        Tags
        {
            "Queue" = "Transparent"
            "IgnoreProjector" = "True"
            "RenderType" = "Transparent"
            "PreviewType" = "Plane"
            "CanUseSpriteAtlas" = "True"
        }

        Cull Off
        Lighting Off
        ZWrite Off
        Blend One OneMinusSrcAlpha

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"

            struct appdata
            {
                float4 vertex : POSITION;
                float4 color : COLOR;
                float2 uv : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex : SV_POSITION;
                fixed4 color : COLOR;
                float2 uv : TEXCOORD0;
            };

            sampler2D _MainTex;
            fixed4 _Color;
            float _Sharpness;

            v2f vert (appdata v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.uv = v.uv;
                o.color = v.color * _Color;
                o.color.rgb *= 2.0f;

                return o;
            }

            fixed4 frag (v2f i) : SV_Target
            {
                float sdf = tex2D(_MainTex, i.uv).r - 0.5f;

                float2 gradient = float2(ddx(sdf), ddy(sdf));
                float speed = length(gradient);
                float distance = sdf / speed;
                float coverage = saturate(distance * _Sharpness + 0.5f);

                fixed4 color = i.color;

                color.a *= coverage * coverage * (3.0 - 2.0f * coverage);

                color.rgb *= color.a;

                return color;
            }
            ENDCG
        }
    }
}

```

Comparing this against a standard sprite at the same resolution, with the SDF shader's Sharpness parameter tuned to 0.7:

And with SDF, we get the bonus win that we can scale the object larger / zoom in closer before we start to see ugly interpolation artifacts:

One thing I noted during this test was that if I ensured both sprites were displayed at a 1:1 screen pixel to sprite texel scale ratio, both looked identically well anti-aliased. I had to muck with my camera/window a bit to force a non-integer ratio before the sharp stairstep aliasing artifacts started to creep in with the regular sprite. So, that suggests another possible fix: if you can ensure the regular sprites are drawn at 1:1 scale in screen pixels, then you might not need to do anything fancy in the rendering at all.
> 3 votes

---
Tags: unity, textures, sprites
---


# Question
Title: How does real-time raytracing draw reflections of off-screen geometry?
I know what raytracing is, but I'm a bit curious how games are able to reflect off-screen geometry using raytracing in real-time.

I tried looking up the technical details but most of the articles are "what it is"

# Answer
The basic algorithm for raycasting is actually surprisingly simple. In pseudocode it is:

```
for each pixel on the screen
  calculate an angle which begins at the camera and crosses through that pixel on the near-plane of the camera
  trace a ray from the camera position with that angle through the 3d geometry of your scene until you hit an object
     if the object is not reflective
         color the pixel in the color of the object
     else
         calculate the reflection angle at the impact point
         continue tracing the ray from the impact point with the new angle

```

The reflected ray might move out of the view frustum and still report back a color value which then gets applied to the screen pixel it originally originated from.

Decades ago I followed a tutorial about how to implement a basic CPU-based raytracing renderer and did it myself. I found that really illuminating. A real, modern raytracing engine would of course use the GPU for performance reasons, but doing it on the CPU as an academic exercise usually makes it easier to understand the basic principles if you are not familiar with GPU programming. All you need is some basic trigonomety and collision detection, which are both things most game developers should already be familiar with. I don't think it was more than 100 lines of code. It shouldn't be hard to find a similar tutorial in your favorite programming language.

The complicated stuff about raytracing starts when you want to implement light sources. Especially when you want to simulate them in real-time and not just have a pre-calculated lightmap. But that's outside of the scope of the question.
> 1 votes

# Answer
You can calculate the intersection of a ray with a triangle (you could use a lot of shapes, but since ray tracing usually needs a helping hand from rasterization, it's best to use those), that gives you a point on it. Then you can get the normal by taking the cross product of two vectors made out of any two sides of this triangle (and by additionally querying a normal map if needed). From there it's just a simple formula (this is a built-in in glsl, but I don't know about the shading language used for ray tracing)

This by itself is really fast, most modern computers can deal even with 5-6 bounces per ray. The part that's slow is shading the object correctly.

It's not possible to render a full, shaded scene with acceptable graphics in real time with consumer graphics cards using only ray tracing. Even stuff like that Quake 2 RTX port needs to do a lot of tricks to get a good framerate (it only does the ray tracing to part of the pixels every frame and guesses the others based on the surroundings. This can lead to some strange effects, but it works).
> 0 votes

# Answer
One neat detail to add here is that we can use hybrid strategies to get some of what raytracers are good at (reflection accuracy) and some of what rasterization is good at (raw speed / coverage in one pass)

We can first draw our scene with regular rasterization to determine which visible pixels have reflective materials, and the detailed surface normal at those points from the normal maps via the G-buffer.

Then we can fire reflection rays from those point reflectors, and intersect them against a set of proxy geometry we've used to approximate our scene content (eg. a bunch of oriented boxes or ellipsoids)

This is a depth-only raycast: we don't try to compute the exact surface colour or illumination at the struck point, all we need to know is how far down the ray did we hit something. This and the fact that we're checking only against very simple bounding shapes helps this part go very fast.

Now with an estimated hit point in hand, we can look up into a conventional rasterized reflection probe. But now since we know not just the direction of the reflected ray but also its depth, we can use this to perspective-correct our lookup, and get reflections that parallax more correctly as the viewpoint moves.

It's not a perfect mirror reflection because of the approximations we took, but it can handle semi-shiny/bumpy surfaces or shallow puddles very convincingly, without the "infinitely distant background" artifacts we normally get from reflection probes.

So this is the kind of flavour of thing you'll often see with realtime raytracing at present: using raycasts tactically, in tandem with rasterization techniques, to add the kinds of detail rays are great at capturing, but without the full complexity of rendering all shading through recursive ray bounces as we might do in offline renders.
> 0 votes

---
Tags: raytracing, realtime, reflection-rendering
---


title: Sharing Physics in Unity

text:
# Question
Title: Sharing Physics in Unity
I'm making a game with an endless mode where you have to dodge asteroids until you eventually die. Since the game could be endless, I wanted to avoid the coordinates issue mentioned here.

My player ship remains at 0,0,0. The asteroids spawn at the top of the screen and "fall" to simulate the player flying past them. The player can also accelerate and decelerate. I have tried scripting asteroid movement, but now I would like to try using Unity's physics to simplify code.

When accelerating/decelerating I could add force to all existing asteroids, but then asteroids which haven't spawned yet will not reflect the player's current speed. I basically want all asteroids to have the same speed.

I was thinking maybe I could create a dummy physics object that I can apply forces to, that also keeps track of its speed. It would be great if all objects could just reference this dummy object's speed and forces. Is something like this possible with Unity's physics? Or is there a better way to do what I'm attempting?

# Answer
> 1 votes
I ended up changing my implementation based on DMGregory's comment. I apply forces on the player, spawn objects ahead of them, and just recenter all the objects if they get too far in coordinate space. It seems to be the route with the least moving parts.

To answer my own question about sharing physics, I used something similar to Philipp's answer.

I couldn't just assign an asteroid's RigidBody to the dummy RigidBody to get the effect I wanted. However, forces added to the dummy object's RigidBody change its velocity. The asteroids can simply copy that velocity in FixedUpdate, so they will always be updated with the result of forces on the dummy object.

# Answer
> 0 votes
I assume you have the current "virtual" speed of the player in some variable? If that is the case, you can simply add its current value to the `rigidbody.velocity` of every asteroid the moment you spawn it. Those asteroids which already exist could be updated with `rigidbody.AddForce` whenever the player accelerates or decelerates. But keep in mind that the acceleration is independent of the mass of the asteroid, so you might also want to modify the velocity here instead.

Yes, the documentation tells you to not rely on changing the velocity property too much because it might result in unrealistic physics, but your physics model is unrealistic to begin with.

# Answer
> 0 votes
If instead of adding forces you play with the gravity in the physics maybe you could make it easier.

You can change gravity of the engine via script by:

```
Physics.gravity = Vector3(0, -1.0, 0);

```

But the visual effect is not the same as adding forces.

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


title: Finding islands from array

text:
# Question
Title: Finding islands from array
Say I have an two dimensional array with values 0 or 1. How would I construct an algorithm (preferably in C#) to work out which ones are separated or islands. The algorithm would transform the left 2d array to look something more like the right array?

# Answer
> 7 votes
This is a standard computer science problem called connected component search.

You can solve it in time linear in the number of cells using iterated depth-first / breadth-first search or a flood fill algorithm.

1. Walk over the cells of your grid systematically.
2. If the cell is 0, skip ahead to the next cell.
3. Otherwise, check if you've already visited this cell and assigned it to an island. If so, skip ahead to the next cell.
4. Lastly, if it's a 1 not yet visited and assigned to an island, then it's the first cell of a new island. Start a depth-first (or breadth-first, or flood fill) search from this location, looking for adjacent 1 cells, then 1 cells adjacent to them, etc...
5. For each cell you visit in this depth-first search, mark it visited, and add it to the island.
6. Once the search bottoms-out, you've found & marked all cells in this island. Resume your systematic walk of the grid.
7. Once you finish your systematic walk, all grid cells have been categorized into islands.

---
Tags: c#, algorithm, matrix
---


# Question
Title: How do I prevent flickering when drawing to a JPanel?
So I have a JFrame holding a JPanel, to which I'm drawing at about 60 FPS. I've been told that "Swing is double buffered by default", but, nevertheless I'm getting massive flickering. At first, I tried modifying the Graphics object from `JPanel.getGraphics()`, but was not surprised when it flickered (to black, the background colour of the game so far), as I assumed that it was redrawing when I blanked the screen. However, then I overrode `paintComponent()`, passing the Graphics to all objects to draw with, and made it call the super version, which I assumed would solve it, but no difference.

I'm still getting the Graphics object from the same place, i.e. `JPanel.getGraphics()`, because `paintComponent()` needs a Graphics argument. Should I be getting it from some other place? If not, what else could be causing the problem?

# Answer
> 3 votes
Whoops. Looks like I should have been calling `repaint()`, not calling `paintComponent(Graphics)` directly. `repaint()` calls that as part of the double buffering process, so it shouldn't be called by hand if you want to avoid flickering.

# Answer
> 4 votes
tried to activate double buffering manually (just to make sure)? setDoubleBuffered

On the other hand I always used a self writen double buffering at the (overwritten) update method. Something like that

# Answer
> 0 votes
I'm not sure what you're trying to draw onto the JPanel, but the code below worked for me to animate a sinusoidal wave. Using `repaint()` in the program run loop seems to hold back the flickering.

```
public class YourClass extends JPanel implements Runnable{
     private boolean running = true;
     // your code here
     public void run(){
         repaint(); // called repeatedly as along as program is running
         while (running){
             update(); // called preferably 60 times a second
             render(); // no limits set, depends on computer performance
         }
     }
     // your code here
}

```

---
Tags: java, graphics
---


# Question
Title: To move an object forward an exact distance and then stop
I am using this script below to move an animated object in unity with no root-motion. it simply walks across the terrain and has a timer so it waits 60 seconds until starting.

```
void Update ()
{
    if (Time.timeSinceLevelLoad > 60)
    {
        transform.Translate(0, 0, Time.deltaTime);
    }
}

```

I want the object to travel a certain distance or certain amount of steps and then stop at an exact point and stay there, is there a simple way to add to the above code to do this? does it entail xyz position reached maybe?

# Answer
We can do this more simply:

```
public class WaitThenMoveToTarget : MonoBehaviour {

    // Set your parameters in the Inspector.
    public float waitSeconds = 60f;
    public Vector3 targetOffset = Vector3.forward * 10f;
    public float speed = 1f;

    // Make Start a coroutine that begins
    // as soon as our object is enabled.
    IEnumerator Start() {

         // First, wait our defined duration.
         yield return new WaitForSeconds(waitSeconds);

         // Then, pick our destination point offset from our current location.
         Vector3 targetPosition = transform.position + targetOffset;

         // Loop until we're within Unity's vector tolerance of our target.
         while(transform.position != targetPosition) {

              // Move one step toward the target at our given speed.
              transform.position = Vector3.MoveTowards(
                    transform.position,
                    targetPosition,
                    speed * Time.deltaTime
               );

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

         // We have arrived. Ensure we hit it exactly.
         transform.position = targetPosition;
    }
}

```
> 4 votes

# Answer
First you will want to define a start and end position in your scene. Create `GameObjects` in the editor to place at the start and end positions of your movement path, and drag and drop them into the `startObject` and `endObject` fields in the script below.

Then you can interpolate between the two positions using the `Vector3.Lerp()` function (more details here).

The code below linearly moves your object from `startPos` to `endPos` over `moveDuration` seconds.

```
public Transform startObject;
public Transform endObject;

[Tooltip("How long the movement will take in seconds.")]
public float moveDuration = 1;

[Tooltip("The delay in seconds before movement starts.")]
public float startDelay = 60;

bool isMoving = false;
bool hasMoved = false;

void Update() {
    // if it is time to move, and this object is not moving, and hasn't moved yet
    if (Time.timeSinceLevelLoad > startDelay && !isMoving && !hasMoved) {
        // start moving (this moves the current object from startObject.position to endObject.position over moveDuration seconds)
        StartCoroutine(Move(startObject.position, endObject.position, moveDuration));
    }
}

IEnumerator Move(Vector3 startPos, Vector3 endPos, float duration){
    // Record that we are about to start moving
    isMoving = true;
    // timeElapsed will incresase from 0 to duration over the course of the while loop
    var timeElapsed = 0f;
    while(timeElapsed < duration){
        // lerp (linearly interpolate) the position of this object between startPos and endPos
        // Use (timeElapsed / duration) to control how close it is to the startPos vs the endPos
        transform.position = Vector3.Lerp(startPos, endPos, timeElapsed/duration);
        // Wait a frame and record that time has elapsed
        yield return new WaitForEndOfFrame();
        timeElapsed += Time.deltaTime;
    }
    // Make sure that the object ends at the correct endPos
    transform.position = Vector3.Lerp(startPos, endPos, timeElapsed/duration);
    // Record that we are not moving anymore and that this object has moved
    isMoving = false;
    hasMoved = true;
}

```
> 0 votes

---
Tags: unity, animation
---


# Question
Title: should my static class be derived from UnityEngine.MonoBehaviour instead?
I am working on creating an object to maintain state of the game, player data, etc. It is static (singleton lifecyle) through the life of my game.

I started down the path of a static class, with a static instance, like this:

```
public class PlayerState
{
    private static PlayerState DATA_INSTANCE = new PlayerState();
    public static PlayerState Instance
    {
        get { return DATA_INSTANCE;  }
    }
}

```

Then I started looking around and I see implementations that derive from `UnityEngine.MonoBehaviour` and implement the instance handling differently, adding the script to a game object and using `DontDestroyOnLoad()` to ensure it stays in memory.

So I am wondering: what is the correct idiomatic pattern in unity for a singleton type?

Do I really need all of the unity functionality of a `UnityEngine.MonoBehaviour` derived type (eg: `Update()`) for my static type?

I admit I am uneasy about static classes, in general. In this case, I am equally uneasy adding another type that potentially gets in the frame cycle when its not needed (I mean that unity will call the methods like `Update()` for every cycle).

Thnx Matt

# Answer
Not every class in a Unity project must necessarily inherit from `MonoBehaviour`. If there is no good reason to attach an instance of your class to a specific GameObject and you don't have a reason why you would need it to implement any Unity event, then there is no reason why you need to make it one.

In fact putting the whole game state into a `static` class (implementing the singleton pattern or not) is my favorite way to share data between scenes.
> 2 votes

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


# Question
Title: Is there a way of making the Unity editor paint decals on surfaces?
I see other engines can do this, here's a video of what I would like to achieve :

I think the one on the image uses something that blends the surface and the image, but I just want to be able to paint a image on a surface.

How can I do this within the unity editor ? :)

---

Edit : Here's another video that kinda shows what I want to do. (Click me)

(I want to code it myself, I don't want some kind of downloadable asset :P )

# Answer
The footage you have provided uses a vertex color blend method.
it's the same method used by most terrain systems.
you have to first have a custom shader that blends textures based on vertex colors
(u may find a couple of them via the internet or easily make one with node based shader editors like:
**Amplify shader editor**(paid), **Unity's builtin Shader graph**(Free, get it through package manager -still in beta phase-), or **shader forge**(Free, open source -works on older unity versions like 2017-)).

Then you have to paint on vertex color values via a script or just use some assets from the asset store.

Unity has a built-in tool called Polybrush, it's a multifunctional tool capable of both painting vertex colors and offsetting their position for sculpting meshes.
Get Polybrush
as it may be complex for the sake of reverse engineering there is a simpler tool you can take a look at:
Get TOZ vertex painter
and it's free too.

have a nice day!
> 2 votes

---
Tags: graphics, unity
---


# Question
Title: If I own the rights to a third party game on a defunct console, can I republish it without the permissions of the console manufacturer?
Suppose I owned the rights to a third party game published on the NES. Could I make a ROM of it and sell the emulated version?

# Answer
It depends on the terms of the contract(s) that define the rights that you supposedly own, any contracts involved with having released the game on that and possibly other platforms and possibly laws of local jurisdiction.

For instance, the contracts involved with releasing it on the NES may include exclusivity clauses, which would likely prohibit selling an emulated version.

Ultimately, if you want a sound legal answer on a specific legal matter, your best bet is to consult with a legal expert.
> 1 votes

---
Tags: emulation
---


# Question
Title: Design of a turn-based game where actions have side-effects
I am writing a computer version of the game Dominion. It is a turn-based card game where action cards, treasure cards, and victory point cards are accumulated into a player's personal deck. I have the class structure pretty well developed, and I am starting to design the game logic. I'm using python, and I may add a simple GUI with pygame later.

The turn sequence of the players is governed by a very simple state machine. Turns pass clockwise, and a player can't exit the game before it is over. The play of a single turn is also a state machine; in general, players pass through an "action phase", a "buy phase", and a "clean-up phase" (in that order). Based on the answer to the question How to implement turn-based game engine?, the state machine is a standard technique for this situation.

My problem is that during a player's action phase, she can use an action card that has side effects, either on herself, or on one or more of the other players. For example, one action card allows a player to take a second turn immediately following the conclusion of the current turn. Another action card causes all other players to discard two cards from their hands. Yet another action card does nothing for the current turn, but allows a player to draw extra cards on her next turn. To make things even more complicated, there are frequently new expansions to the game that add new cards. It seems to me that hard-coding the results of every action card into the game's state machine would be both ugly and unadaptable. The answer to Turn-based Strategy Loop does not go into a level of detail that addresses designs to solve this problem.

What kind of programming model should I use to encompass the fact that the general pattern for taking turns can be modified by actions that take place within the turn? Should the game object keep track of the effects of every action card? Or, if the cards should implement their own effects (e.g. by implementing an interface), what setup is required to give them enough power? I have thought up a few solutions to this problem, but I am wondering if there is a standard way to solve it. Specifically, I'd like to know what object/class/whatever is responsible for keeping track of the actions that every player must do as a consequence of an action card being played, and also how that relates to temporary changes in the normal sequence of the turn state machine.

# Answer
> 11 votes
I agree with Jari Komppa that defining card effects with a powerful scripting language is the way to go. But I believe that the key to maximum flexibility is scriptable event-handling.

In order to allow cards to interact with later game events, you could add a scripting API to add "script hooks" to certain events, like the beginnings and endings of game phases, or certain actions the players can perform. That means that the script which is executed when a card is played is able to register a function which is called the next time a specific phase is reached. The number of functions which can be registred for each event should be unlimited. When there is more than one, they are then called in their order of registration (unless of course there is a core game rule which says something different).

It should be possible to register these hooks for all players or for certain players only. I would also suggest to add the posibility for hooks to decide for themselves if they should keep being called or not. In these examples the return value of the hook function (true or false) is used to express this.

Your double-turn card would then do something like this:

```
add_event_hook('cleanup_phase_end', current_player, function {
     setNextPlayer(current_player); // make the player take another turn
     return false; // unregister this hook afterwards
});

```

(I have no idea if Dominion even has something like a "cleanup phase" - in this example it's the hypothetical last phase of the players turn)

A card which allows every player to draw an additional card at the beginning of their draw phase would look like this:

```
add_event_hook('draw_phase_begin', NULL, function {
    drawCard(current_player); // draw a card
    return true; // keep doing this until the hook is removed explicitely
});

```

A card which makes the target player lose a hit point whenever they play a card would look like this:

```
add_event_hook('play_card', target_player, function {
    changeHitPoints(target_player, -1); // remove a hit point
    return true;
});

```

You won't get around hard-coding some game actions like drawing cards or losing hit points, because their complete definition - what exactly it means to "draw a card" - is part of the core game mechanics. For example, I know some TCGs where when your have to draw a card for whatever reason and your deck is empty, you lose the game. This rule isn't printed on every card which makes you draw cards, because it's in the rule book. So you shouldn't have to check for that lose condition in every card's script either. Checking things like that should be part of the hard-coded `drawCard()` function (which, by the way, would also be a good candidate for a hookable event).

By the way: It's unlikely that you will be able to plan ahead for every obscure mechanic future editions could come up with, so no matter what you do, you still will have to add new functionality for future editions once in a while (in this case, a confetti throwing minigame).

# Answer
> 10 votes
I gave this problem - flexible computerized card game engine - some thought some time ago.

First off, a complex card game like Chez Geek or Fluxx (and, I believe, Dominion) would require cards to be scriptable. Basically each card would come with its own bunch of scripts that may change the state of the game in various ways. This would let you give the system some future-proofing, as the scripts might be able to do things you can't think of right now, but might come in a future expansion.

Second, the rigid "turn" may be causing problems.

You need some kind of "turn stack" which contains the "special turns", such as "discard 2 cards". When the stack is empty, the default normal turn continues.

In Fluxx, it's entirely possible that one turn goes something like:

* Pick N cards (as stated by current rules, changeable via cards)
* Play N cards (as stated by current rules, changeable via cards)
    + One of the cards may be "take 3, play 2 of them"
        - One of those cards may well be "take another turn"
    + One of the cards may be "discard and draw"
* If you change rules to pick more cards than you did when your turn started, pick more cards
* If you change rules for fewer cards in hand, everybody else must discard cards immediately
* When your turn ends, discard cards until you have N cards (changeable via cards, again), then take another turn (if you played "take another turn" card sometime in the above mess).

..and so on, and so forth. So designing a turn structure that can handle the above abuse can be rather tricky. Add to that the numerous games with "whenever" cards (like in "chez geek") where the "whenever" cards can disrupt the normal flow by, for instance, cancelling whatever card was last played..

So basically I would start from designing a very flexible turn structure, design it so that it can be described as a script (as each game would need its own "master script" handling the basic game structure). Then, any card should be scriptable; most cards probably don't do anything strange, but others do. Cards can also have various attributes - whether they can be kept in hand, played "whenever", whether they can be stored as assets (like fluxx 'keepers', or various things in 'chez geek' like food)...

I never actually started implementing any of this, so in practice you may find plenty of other challenges. The easiest way to start would be to start with whatever you know of the system you want to implement, and implement them in scriptable ways, setting as little in stone as possible, so when an expansion comes along, you won't need to revise the base system - much. =)

# Answer
> 0 votes
Hearthstone seems to do things relatable and honestly i think the best way to achieve flexibility is through an ECS engine with a data oriented design. Been trying to make a hearthstone clone and it's proven impossible otherwise. All the edge cases. If your facing a lot of these weird edge cases then that's probably the best way to go about it. I'm pretty biased though from recent experience trying out this technique.

Edit: ECS might not even be needed depending on the kind of flexibility and optimization your wanting. It's just one way of accomplishing this. DOD I've mistakenly thought of as procedural programming though they relate a lot. What I mean is. That you should consider doing away with OOP entirely or mostly at least and instead focus your attention on the data and how it's organized. Avoid inheritance and methods. Instead focus on public functions(systems) to manipulate your card data. Each action isn't a templated thing or logic of any kind but is instead raw data. Where your systems then use it to perform logic. Integer switch case or using an integer to access an array of function pointers help figure out the desired logic from the input data efficiently.

Basic rules to follow are that you should avoid tying logic directly together with data, you should avoid making data depend on one another as much as possible(exceptions may apply), and that when your wanting flexible logic that feels out of reach... Consider converting it into data.

There's benefits to be had doing this. Each card may have an enum(s) value or string(s) to represent their action(s). This intern allows you to design cards through text or json files and allow the program to automatically import them. If you make player actions a list of data this gives even more flexibility especially if a card depends on past logic like hearthstone does, or if you'd like to save the game or a replay of a game at any point. There's potential to create A.I. more easily. Especially when using a "utility systems" instead of a "behavior tree". Networking also becomes easier because instead of needing to figure out how to get entire possibly polymorphic objects to transfer over the wire and how serialization would be setup after the fact, your already having your game objects be nothing more than simple data which ends up being really easy to move around. And last but definitely not least this allows you to optimize easier because instead of wasting time worrying about code your able to better organize your data so the processor will have an easier time dealing with it. Python may have issues here but look up "cache line" and how it relates to game dev. Not important for prototyping stuff perhaps but down the road it'll come in handy big time.

Some useful links.

Note: ECS allows one to dynamically add/remove variables(called components) at runtime. An example c program of how ECS "might" look(there's a ton fo ways of doing it).

```
unsigned int textureID = ECSRegisterComponent("texture", sizeof(struct Texture));
unsigned int positionID = ECSRegisterComponent("position", sizeof(struct Point2DI));
for (unsigned int i = 0; i < 10; i++) {
    void *newEnt = ECSGetNewEntity();
    struct Point2DI pos = { 0 + i * 64, 0 };
    struct Texture tex;
    getTexture("test.png", &tex);
    ECSAddComponentToEntity(newEnt, &pos, positionID);
    ECSAddComponentToEntity(newEnt, &tex, textureID);
}
void *ent = ECSGetParentEntity(textureID, 3);
ECSDestroyEntity(ent);

```

Creates a bunch of entities with texture and position data and at the end destroys an entity who has a texture component which happens to be at the third index of the texture component array. Looks quirky but is one way of doing things. Here's an example of how you'd render everything which has a texture component.

```
unsigned int textureCount;
unsigned int positionID = ECSGetComponentTypeFromName("position");
unsigned int textureID = ECSGetComponentTypeFromName("texture");
struct Texture *textures = ECSGetAllComponentsOfType(textureID, &textureCount);
for (unsigned int i = 0; i < textureCount; i++) {
    void *parentEntity = ECSGetParentEntity(textureID, i);
    struct Point2DI *drawPos = ECSGetComponentFromEntity(positionID, parentEntity);
    if (drawPos) {
        struct Texture *t = &textures[i];
        drawTexture(t, drawPos->x, drawPos->y);
    }
}

```

---
Tags: software-engineering, design-patterns, turn-based, card-game, effect-modifier
---


# Question
Title: Octahedral impostors, Octahedral mapping
I'm facing some issues understanding this article about octahedral impostors.

More specifically I quite don't understand how one can map the hemi-octahedron (subdivided) vertices to texture coordinates.

Quote from the article :

> "For those not familiar with octahedra, they are a convenient way to convert between 2D and 3D space, or vice versa."

This two images help visualize the transformation:

Here we can see an animated transition from a tesselated quad mesh to a hemisphere or a full sphere.

Here we see a view of the model to be imitated associated with each vertex of the mesh, giving coverage of viewpoints around the hemisphere: side views around the perimeter of the square, and top-down views near the center.

I don't understand the math used to perform this mapping from the square domain of the quad to the hemisphere or sphere of directions around the model.

This article also says that we can easily map 3D to 2D uvs, without explaining how or why. I found a few research papers about octahedron and normals compression but it is quite a different problem and honestly I didn't really get the grasp of them.

**Could someone explain to me how to map a vertex expressed in 3D (ie impostor camera position) from the octahedron to a plain 2D texture?**

The goal is to be able to cast a ray to the octahedron and map the hit point coordinates to 2D uvs, or find the nearest vertex and render the texture associated with it.

# Answer
Let's start by going from the \[0,1\]x\[0,1\] UV domain to a complete unit octahedron, running from -1 to 1 on each axis:

```
float3 UVtoOctahedron(float2 uv) {
    // Unpack the 0...1 range to the -1...1 unit square.
    float3 position = float3(2.0f * (uv - 0.5f), 0);

    // "Lift" the middle of the square to +1 z, and let it fall off linearly
    // to z = 0 along the Manhattan metric diamond (absolute.x + absolute.y == 1),
    // and to z = -1 at the corners where position.x and .y are both = +-1.
    float2 absolute = abs(position.xy);
    position.z = 1.0f - absolute.x - absolute.y;

    // "Tuck in" the corners by reflecting the xy position along the line y = 1 - x
    // (in quadrant 1), and its mirrored image in the other quadrants.
    if(position.z < 0) {
        position.xy = sign(position.xy)
                    * float2(1.0f - absolute.y, 1.0f - absolute.x);
    }

    return position;
}

```

We can of course normalize the position to "puff it out" to a unit sphere.

Now that we have the full unit octahedron, it's simple to get just the top pyramid: we just map our UV quad to just the inner diamond \\$|x| + |y| \leq 1\\$, then do the same lift as before:

Here the origin of our UV space sits at the bottom of the unit diamond (0, -1). Moving a distance of 1 along the U direction brings us up & right (+1, +1) to arrive at the right corner. And moving a distance of 1 along the V direction takes us up & left (-1, +1). I fold the addition of the origin, U, and V components into the calculation of `position` below:

```
float3 UVtoPyramid(float2 uv) {
    float3 position = float3(
                         0.0f + (uv.x - uv.y),
                        -1.0f + (uv.x + uv.y),
                         0.0f
                    );

    float2 absolute = abs(position.xy);
    position.z = 1.0f - absolute.x - absolute.y;
    // No need for the final "tuck in" fold since we're skipping the bottom half.

    return position;
}

```

And again, this can be normalized to "puff out" to a rounded hemisphere.

Now, mapping from a 3D direction to 2D is just a matter of inverting the operation. Let's say we have a (unit) vector pointing out from our imposter position toward the viewer. To place that in UV space we can...

```
float2 OctahedronUV(float3 direction) {
    float3 octant = sign(direction);

    // Scale the vector so |x| + |y| + |z| = 1 (surface of octahedron).
    float sum = dot(direction, octant);
    float3 octahedron = direction / sum;

    // "Untuck" the corners using the same reflection across the diagonal as before.
    // (A reflection is its own inverse transformation).
    if(octahedron.z < 0) {
        float3 absolute = abs(octahedron);
        octahedron.xy = octant.xy
                      * float2(1.0f - absolute.y, 1.0f - absolute.x);
    }

    return octahedron.xy * 0.5f + 0.5f;
}

```

And again, chopping down to just the top pyramid if we have only a hemisphere to work with...

```
float2 PyramidUV(float3 direction) {
    float3 octant = sign(direction);

    float sum = dot(direction, octant);
    float3 octahedron = direction / sum;

    return 0.5f * float2(
              1.0f + octahedron.x + octahedron.y,
              1.0f + octahedron.y - octahedron.x
           );
}

```

Here our last step is to transform our xy space so its inner unit diamond maps to the \[0,1\]x\[0,1\] UV square, and the unused triangles hang off the edges, like so:

Here the xy origin maps to the center of the UV space (0.5, 0.5), and moving a distance of 1 along either the x or y moves us 0.5 along each of U & V.

Now that you have your point in UV space, you can round it to your desired increments to snap to the closest grid intersection.
> 6 votes

---
Tags: opengl, mathematics, rendering, billboarding
---


# Question
Title: Finding the on-screen height of straight walls in raycasting rendering
I have an issue to find the correct height of walls to make them straight in raycasting rendering.

This is how I calculate the height of the wall which is `h_seen`:

```
dist_w = sqrt(pow((w->cam->position.x - w->cam->rays[i].endPoint.x), 2) + pow((w->cam->position.y - w->cam->rays[i].endPoint.y), 2));
distortion = dist_w * tCos(w->cam->fov / 2 - (i * w->cam->fov / WIN_W));
if (distortion)
    h_seen = dist_c * wall_h / distortion;
//printf("h_seen = %f\n", h_seen);
y = cam_h - (h_seen / 2) - 1;

```

This is a screenshot of the problem  I have fisheye effect, if i use depth directly

```
    if (l == 0)
    {
        raytravel.y = w->cam->rays[i].endPoint.y - w->cam->position.y;
        raytravel.x = w->cam->rays[i].endPoint.x - w->cam->position.x;
        depth = raytravel.x * dir.x + raytravel.y * dir.y;
        h_seen = dist_c * wall_h / depth;
        y = cam_h - (h_seen / 2) - 1;
        if (hit == 1)
            while (++y < (cam_h + (h_seen / 2)))
                put_pixel_img(w, WIN_W - i + WIDTH_MM, y + 150, 0xff0000);
    }

```

// Direction of each ray inside the while loop

```
if ((hit = intersection(w, l, &dir)))
        w->cam->rays[i].endpoint = w->cam->intersection;
else
    {
        w->cam->rays[i].endpoint.x = w->cam->position.x + w->cam->raylength * tcos((w->cam->angle + w->cam->fov / 2) - (i * (w->cam->fov / limit)));
        w->cam->rays[i].endpoint.y = w->cam->position.y + w->cam->raylength * tsin((w->cam->angle + w->cam->fov / 2) - (i * (w->cam->fov / limit))); // limit is just the screen width
    }

```

# Answer
> 0 votes
You can simplify your calculation of "distortion," and get rid of some extra trigonometry & divisions, by recognizing that it's actually the depth of the hit point along your camera's forward direction. So, if you keep a unit vector in the direction the camera is facing...

```
// Vector from the camera to the ray hit using vector subtraction.
rayTravel = w->cam->rays[i].endPoint - w->cam->position;

// Dot product of ray onto camera's unit forward vector.
depth = rayTravel.x * w->cam->forward.x + rayTravel.y * w->cam->forward.y;

// Visible wall height is proportional to true height divided by depth.
h_seen = dist_c * wall_h / depth;

```

I don't have enough of your raycaster to verify whether this distortion calculation was the source of the problem, but this simplification should at least reduce the surface area for bugs and help narrow down the cause further. ;)

---
Tags: raycasting
---


# Question
Title: Uninitialized Variables with Deactivation of Objects in Game Maker Studio 2
I am currently working on some map generation for my GMS2 game, and I have run into an issue that I absolutely cannot figure out. (I am very new to GMS2, so bear with me).

I am working on map generation, in which there are 9 rooms, and a piece of land for each room. Each piece of land has the exact same code, along with 2 to 4 paths connecting each room to the next. This is all handled by a persistent object `pathManager` that I have created. I want to make it so that certain paths connect to certain rooms in a grid-like format, but I have run into an issue.

Here is the code for creation of each room:

```
//Create pathManager
instance_create_layer(960, 540, "Character", pathManager);

//Create paths
/*
We must create the paths before the land, because upon creation, the
land does some things with the paths. So we will move the paths to their
proper spots later on down the code.
*/
instance_create_layer(960, 540, "Path", oPathTL);
instance_create_layer(960, 540, "Path", oPathTR);
instance_create_layer(960, 540, "Path", oPathBL);
instance_create_layer(960, 540, "Path", oPathBR);

//Create land
var land = oLand1;
instance_create_layer(960, 540, "Land", land);

//Create character
instance_create_layer(960, 540, "Character", oCharacter);

//Move paths
var top = land.y - land.sprite_height/4;
var bottom = land.y + land.sprite_height/4;
var left = land.x - land.sprite_width/4;
var right = land.x + land.sprite_width/4;

if(instance_exists(oPathTL)){
    oPathTL.x = left;
    oPathTL.y = top;
}
if(instance_exists(oPathTR)){
    oPathTR.x = right;
    oPathTR.y = top;
}
if(instance_exists(oPathBL)){
    oPathBL.x = left;
    oPathBL.y = bottom;
}
if(instance_exists(oPathBR)){
oPathBR.x = right;
oPathBR.y = bottom;
}

```

Here is the code for the `pathManager`:

```
TL_active = true;
TR_active = true;
BL_active = true;
BR_active = true;

//This finds what index our room is on the map
roomIndex = 0;
numRooms = pathManager.numRooms;

for(i = 0; i < numRooms; i++){
    if(pathManager.roomLibrary[i] == room){
        roomIndex = i;
        break;
    }
}

//This sets up the path connections of the room
    if(roomIndex == 0){//If room is top left corner
        instance_deactivate_object(oPathTL);
        TL_active = false;
        instance_deactivate_object(oPathBL);
        BL_active = false;
    }
    else if(roomIndex == (sqrt(numRooms) - 1)){//If room is top right corner
        instance_deactivate_object(oPathTL);
        TL_active = false;
        instance_deactivate_object(oPathTR);
        TR_active = false;
    }
    else if(roomIndex == (numRooms - sqrt(numRooms))){//If room is bottom left corner
        instance_deactivate_object(oPathBL);
        BL_active = false;
        instance_deactivate_object(oPathBR);
        BR_active = false;
    }
    else if(roomIndex == (numRooms - 1)){//If room is bottom right corner
        instance_deactivate_object(oPathTR);
        TR_active = false;
        instance_deactivate_object(oPathBR);
        BR_active = false;
    }
    else if(roomIndex > 0 && roomIndex < sqrt(numRooms)){//If room is top middle
        instance_deactivate_object(oPathTL);
        TL_active = false;
    }
    else if(roomIndex % sqrt(numRooms) == 0){//If room is left middle
        instance_deactivate_object(oPathBL);
        BL_active = false;
    }
    else if((roomIndex + 1) % sqrt(numRooms) == 0){//If room is right middle
        instance_deactivate_object(oPathTR);
        TR_active = false;
    }
    else if(roomIndex > (numRooms - sqrt(numRooms)) && roomIndex < numRooms){//If room is bottom middle
        instance_deactivate_object(oPathBR);
        BR_active = false;
    }

//We see here that we must create the paths in the room FIRST,
//this way we can manipulate where the paths connect, directly from here.
if(TL_active == true){
    with(oPathTL){
        roomConnection = pathManager.roomLibrary[roomIndex - sqrt(numRooms)];
    }
}
if(TR_active == true){
    with(oPathTR){
        roomConnection = pathManager.roomLibrary[roomIndex + 1];
    }
}
if(BL_active == true){
    with(oPathBL){
        roomConnection = pathManager.roomLibrary[roomIndex - 1];
    }
}
if(BR_active == true){
    with(oPathBR){
        roomConnection = pathManager.roomLibrary[roomIndex + sqrt(numRooms)];
    }
}

```

Finally, the paths are named `oPathTL`, `oPathTR`, `oPathBL` and `oPathBR`. Their code has nothing to do with the issue, because they are currently empty objects.

Now, my issue seems to have something to do with uninitialized variables in the land coding, but I absolutely cannot figure it out. When I run the game, I get the following error:

---

\#

FATAL ERROR in action number 1 of Create Event for object oLand1:

Variable oPathTR.roomIndex(100018, -2147483648) not set before reading it. at gml\_Object\_oLand1\_Create\_0 (line 70) - roomConnection = pathManager.roomLibrary\[roomIndex + 1\];

## ############################################################################################

stack frame is gml\_Object\_oLand1\_Create\_0 (line 70) called from - gml\_Room\_room0\_Create (line 17) - instance\_create\_layer(960, 540, "Land", land);

---

I've looked at these lines many times, but I cannot see what I'm doing wrong. Can someone tell me? Thank you for your help!

# Answer
I haven't located the axact issue in *my* code; however, I believe I have found the overarching issue of what's going on. I found it here: https://www.reddit.com/r/gamemaker/comments/4jj8vn/referencing\_the\_object\_that\_called\_instance\_create/. I created a solution in which, instead, I create the land objects, and then have the *land* spawn in the paths. This looks as follows (for the land object coding):

```
TL_active = true;
TR_active = true;
BL_active = true;
BR_active = true;

//This finds what index our room is on the map
roomIndex = 0;
numRooms = pathManager.numRooms;

for(i = 0; i < numRooms; i++){
    if(pathManager.roomLibrary[i] == room){
        roomIndex = i;
        break;
    }
}

//This sets up the path connections of the room
    if(roomIndex == 0){//If room is top left corner
        TL_active = false;
        BL_active = false;
    }
    else if(roomIndex == (sqrt(numRooms) - 1)){//If room is top right corner
        TL_active = false;
        TR_active = false;
    }
    else if(roomIndex == (numRooms - sqrt(numRooms))){//If room is bottom left corner
        BL_active = false;
        BR_active = false;
    }
    else if(roomIndex == (numRooms - 1)){//If room is bottom right corner
        TR_active = false;
        BR_active = false;
    }
    else if(roomIndex > 0 && roomIndex < sqrt(numRooms)){//If room is top middle
        TL_active = false;
    }
    else if(roomIndex % sqrt(numRooms) == 0){//If room is left middle
        BL_active = false;
    }
    else if((roomIndex + 1) % sqrt(numRooms) == 0){//If room is right middle
        TR_active = false;
    }
    else if(roomIndex > (numRooms - sqrt(numRooms)) && roomIndex < numRooms){//If room is bottom middle
        BR_active = false;
    }

//Create paths
var top = y - sprite_height/4;
var bottom = y + sprite_height/4;
var left = x - sprite_width/4;
var right = x + sprite_width/4;

if(TL_active == true){
    instance_create_layer(left, top, "Path", oPathTL);
    oPathTL.roomConnection = pathManager.roomLibrary[roomIndex - sqrt(numRooms)];
}
if(TR_active == true){
    instance_create_layer(right, top, "Path", oPathTR);
    oPathTR.roomConnection = pathManager.roomLibrary[roomIndex + 1];
}
if(BL_active == true){
    instance_create_layer(left, bottom, "Path", oPathBL);
    oPathBL.roomConnection = pathManager.roomLibrary[roomIndex - 1];
}
if(BR_active == true){
    instance_create_layer(right, bottom, "Path", oPathBR);
    oPathBR.roomConnection = pathManager.roomLibrary[roomIndex + sqrt(numRooms)];
}

```
> 0 votes

---
Tags: c++, architecture, game-maker
---


# Question
Title: How can I edit collisions in Unreal Engine?
I made a concave house model. When I import it to Unreal Engine it generates a simple box collision that covers the full mesh. I need a collision that only covers the walls. How can I generate one or edit the collision? (I'm using Maya.)

# Answer
> 0 votes
There's a couple things you can do. What's considered the best practice is to make your own collision bodies to import with the asset. I forget the exact file format but your basically just using boxes or other basic shapes to create your physics bodies. The other method is letting ue4 generate more thorough physics bodies for your mesh though probably not the most optimized way of doing it. I believe it's called "Convert boxes to Convex"(or "Auto convex collision"). Here's an image.

# Answer
> 0 votes
There's three main ways you can do it - you can either open the house as a blueprint and add a bunch of "box collision" componenents, and edit them by hand. Another thing you can do is open the house's mesh and (as the previous commenter said) add box collisions. The result will be more or less the same.

The last way you can do it, is to also open the house's mesh. Then, you can use the window in bottom right. It should have a button "create convex collision". You can choose how many colliders you want and how complex they should be with the sliders. It can take few seconds, and the results might not be satisfying - but it will be fully automated. If that's not enough, you can check the option "use complex shapes as simple" - that should totally cover the house, however it will be the most costly.

---
Tags: 3d, unreal-4, 3d-meshes, unreal, maya
---


title: Wrong FPS calculations in GLFW game

text:
# Question
Title: Wrong FPS calculations in GLFW game
In my game loop,

```
m_currentFrameTimestamp = glfwGetTime(); // Get the current timestamp
if ((m_currentFrameTimestamp - m_lastFPSDisplayTimestamp) >= 0.25) { // If 1/4 of a second
                                                         // passed, update the FPS counter
    double renderTime = m_currentFrameTimestamp - m_lastFrameTimestamp; // Frame time
    m_fps = (unsigned int)round(1 / renderTime); // FPS
    std::string title = "MyGame ["s;
    title += std::to_string(m_fps);
    title += " FPS]"s;
    glfwSetWindowTitle(m_window, title.c_str()); // The title
    m_lastFPSDisplayTime = m_currentFrameTime; // Reset the FPS update timer
}
m_lastFrameTime = m_currentFrameTime; // Reset the frame time timer

```

calculates the FPS from the frame time and displays it in the window title. However, with just this and `glClear()` above, the FPS displayed in the title is very unstable (with each FPS update, it changes from 46 FPS to 87 FPS and back), even though back in the initialization step, I enabled VSync, and my display's frequency is 60 Hz. Furthermore, using Fraps, I found out that the program actually runs at a stable 60 FPS. So, what's the problem with my FPS calculation code (more specifically, why is `glfwGetTime()` producing inaccurate results - my code, being way too simple, just can't be wrong, it's a very simple calculation that cannot give errors of any kind)?

# Answer
The issue is that you calculate the FPS according to a single measurement, which means that any slight variation will cause a significant shift in results. Since the actual loop time varies due to system considerations, you'll get stabler results by averaging more calculations.

```
fpsCount = 0;
m_lastFPSDisplayTimestamp = glfwGetTime();
while(shouldRender()) {
    m_currentFrameTimestamp = glfwGetTime(); // Get the current timestamp
    if ((m_currentFrameTimestamp - m_lastFPSDisplayTimestamp) >= 0.25) {
        std::string title = "MyGame ["s;
        title += std::to_string(fpsCount);
        title += " FPS]"s;
        glfwSetWindowTitle(m_window, title.c_str()); // The title
        fpsCount = 0;
        m_lastFPSDisplayTime = m_currentFrameTime;
    } else {
        fpsCount++;
    }
    m_lastFrameTime = m_currentFrameTime;
}

```
> 3 votes

# Answer
Could be missing something but am pretty sure a 4th of a second is way bigger than a 60th of a second. Might be weird quirks about that not sure. I'd personally just do something like.

```
void foo(){
    sleep(1.0f/1000);
    //if last frame is 60th of a second(or some other num)
    //draw window then display fps
}
//or
void foo(){
    //if last frame is 60th of a second(or some other num)
    //draw window then display fps
}

```

Depending on if your trying to benchmark it or not. Also the sleep function will need tweaking to get the right balance between preserving cpu usage and having stable fps. And there's a whole art to doing this right if your really wanting to.
> -2 votes

---
Tags: opengl, c++, glfw
---


# Question
Title: How to add to a MonoBehavior array from an Editor script in Unity
I've made an editor which makes a list of tags and splits them into two rows of true or false values (selectable by the user). I then compile this list into a dictionary, and each entry is like so:

```
{"tag", bool, bool}

```

On my MonoBehavior script, I have two arrays:

```
string[] depth_tags;
string[] angle_tags;

```

My goal is to essentially save the dictionary data and be able to recall it/also have it affect the script. To do this, I've been trying to add to these arrays according to the values found in the Editor script's dictionary.

I've done quite a bit of searching and this was the only potential solution I could come up with, but sadly it did not work.

**EDIT: Ok, I can now edit the list (added and subtracted from arraySize when doing operations on them), but I have a new problem:**

The array reports as being twice as large as it should be. The first half of the arrays are correct and as they should be, but the latter half is made up of empty values. When I try to access beyond the first half, Unity throws an error saying that I exceeded the array's max range.

**EDIT 2: FIXED**

Answers telling you to increase and decrease arraySize are WRONG/OUTDATED. Clearing, inserting, and deleting from the table does that for you! Quick Tip: Inserting at index 0 in a serialized table takes care of the element bumping for you! No need to cycle through the table and move each array.

```
void update_tags()
{

    SerializedProperty depth_tags = serializedObject.FindProperty("depth_tags");
    SerializedProperty angle_tags = serializedObject.FindProperty("angle_tags");

    depth_tags.ClearArray();
    angle_tags.ClearArray();

    foreach (string tag in tag_list_values.Keys)
    {

        if (tag_list_values[tag][0] == true)
        {
            depth_tags.InsertArrayElementAtIndex(0);
            depth_tags.GetArrayElementAtIndex(0).stringValue = tag;
        }

        if (tag_list_values[tag][1] == true)
        {
            angle_tags.InsertArrayElementAtIndex(0);
            angle_tags.GetArrayElementAtIndex(0).stringValue = tag;
        }

    }

    serializedObject.ApplyModifiedProperties();

}

```

}

# Answer
> 1 votes
> The property's array size needs to be edited every time (or appropriately before) an operation is made.

WRONG. Not sure what I changed to make it work, but I laid out my code in the original question.

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


# Question
Title: Flatten transform hierarchy at build time
Nested hierarchies cause a performance overhead when they include moving objects.

> Every time a GameObject moves, altering its transform, we need to let every game system that might care about this know. Rendering, physics, and every parent and child of the GameObject needs to be informed of this movement in order to match. As the scope of a game increases, and the number of game objects skyrockets, just the overhead of sending out all these messages can become a performance problem.

However, nested hierarchies are useful in organising a scene and keeping logical groups of gameobjects separate.

What options exist to save performance whilst keeping the hierarchy? Is there any pre-existing solution to flatten a hierarchy when building only?

# Answer
First of all, hierarchies structured for organizational purposes should have minimal impact. I believe *dirtyness* (nescessity to recalculate position, rotation or scale) messages travel *up* the hierarchy for every child that is *dirtied* (changed) in a normal or fixed frame/tick, but dirtyness only travels back *down* to *other* siblings if a/the *parents* get dirty, which shouldn't be the case for organizational objects acting like folders.

This means that you should not worry about this until 1) your game actually needs optimization, and 2) other more relevant bottlenecks have already been optimized. Otherwise you're engaging in *premature optimization*.

---

As for flattenning the hierarchy, one easy solution is to simply have a script that unparents every child of the object on `Awake()` and then destroyes the object itself. And then plug that script in every organizational object. This will probably incur a small performance hit on the first frame after a scene is loaded, but it's negligible, can be considered part of loading that scene, and still elimitanes the continuous performance hit that the hierarchy would cause (even though that in itself should be negligible, as I explained).
> 2 votes

---
Tags: unity
---


# Question
Title: Godot 3.1: Moving sprites together after raycast2d Collision
I'm fairly new to Godot, but I've been programming games for a bit. I understand GDScript, but using it fully still escapes me. So i'm still learning/struggling.

Anyway, I'm working on a sokoban style puzzle game (grid based movement) and I want blocks that have moved next each other to 'combine' and move together. Kinda like legos. I'm currently using raycast2D to detect collision between sprites, and it has been successful, but I receive an error when the sprite being moved collides with a wall (object in tilemap).

This is the error: Invalid get index 'position' (on base: 'Node').

To track the position i'm essentially grabbing colliding sprite and saving it once in a variable. Then I match the collided sprites position to that of the one that is in 'control' or allowed to move, but again I receive the error when the control sprite reaches a collision.

The idea behind control is that ill have multiple instances of a sprite and have the ability to shuffle control between the various sprites in a scene.

Here is the sprite script:

```
extends Sprite

# if the sprite is currently in control, can be rotated with space
export var Control = false

# make the raycast available to use in the player script
onready var ray = $Area2D/RayCast2D
onready var rayUP = $Area2D/rayUP
onready var rayDOWN = $Area2D/rayDOWN
onready var rayLEFT = $Area2D/rayLEFT
onready var rayRIGHT = $Area2D/rayRIGHT

# detect collision only once with these flags
var colUP = false
var colDOWN = false
var colLEFT = false
var colRIGHT = false

var UColSprite
var DColSprite
var LColSprite
var RColSprite

var speed = 600 # large speed value to determine how fast the sprite will move
var tile_size = 64 # size in pixels of the tiles on the grid

var last_position = position # last idle position to keep track of
var target_position = position # new position to be moved to
var movedir = Vector2(0, 0) # the move direction

# init function
func _ready():
    # snap the player to a grid position if misplaced
    # and update its position trackers to the snapped vector2
    position = position.snapped(Vector2(tile_size, tile_size))
    last_position = position
    target_position = position

# set move direction based on player input
func get_movedir():
    # collect the input and store it
    var LEFT = Input.is_action_pressed("ui_left")
    var RIGHT = Input.is_action_pressed("ui_right")
    var UP = Input.is_action_pressed("ui_up")
    var DOWN = Input.is_action_pressed("ui_down")

    # process the movement based on each vector
    movedir.x = -int(LEFT) + int(RIGHT) # is negative one if moving left and vice versa, if both then zero
    movedir.y = -int(UP) + int(DOWN) # same up with y

    # prevent diagonal movement
    if movedir.x !=0 && movedir.y != 0:
        movedir = Vector2.ZERO # no value

    # set the end of the ray cast to the edge of the player sprite
    if movedir != Vector2.ZERO:
        ray.cast_to = movedir * tile_size / 2

# process movement every frame
func _process(delta):

    if Control == true:
        # idle
        if position == target_position:
            get_movedir()
            last_position = position # save the players current position
            target_position += movedir * tile_size # if movement, then calculate new target position

        # moving
        else:

            # make sure not to move the player if they will collide with a wall
            if ray.is_colliding():
                target_position = last_position # set the player back to there original location
            else:
                # update the position
                position += speed * movedir * delta

                # prevent the player from moving past the target
                var distance = (position - last_position).abs().length() # how far they moved frem the idle position

                # track the distance
                if distance > tile_size - speed * delta:
                    # subtract speed * delta so there's no break/pause in movement
                    position = target_position
    else:
        # if the sprite is not being controlled, collect a collision if the controlled sprite moved next to it6

        if rayUP.is_colliding():
            if colUP == false:
                colUP = true
                UColSprite = rayUP.get_collider().get_parent()
            position = UColSprite.position - Vector2(0, 64)

        if rayDOWN.is_colliding():
            if colDOWN == false:
                colDOWN = true
                DColSprite = rayDOWN.get_collider().get_parent()
            position = DColSprite.position + Vector2(0, 64)

        if rayLEFT.is_colliding():
            if colLEFT == false:
                colLEFT = true
                LColSprite = rayLEFT.get_collider().get_parent()
            position = LColSprite.position + Vector2(64, 0)

        if rayRIGHT.is_colliding():
            if colRIGHT == false:
                colRIGHT = true
                RColSprite = rayRIGHT.get_collider().get_parent()
            position = RColSprite.position - Vector2(64, 0)

```

# Answer
> 0 votes
**Tilemap Collision**

> Invalid get index 'position' (on base: 'Node')

**The Error**

The above means that the collider's(The Tilemap) get\_parent() is likely the root Node in your scene.

This error message indicates that the method(position) cannot be found in the node(Node) that you are trying to detect.

**Raycaster**

When your Raycast detects the Tilemap, it tries to get\_parent() and finds the root Node, which has no position method.

A solution I may have is to alter the collision mask of your Sprite's Raycaster so that it will only collide with objects on a certain layer.Then placing the Tilemap on a separate layer should solve it if I'm right.

Good Luck!

---
Tags: godot
---


# Question
Title: Spawning large numbers of navmeshagents causes them to jump position
Cross posted on StackOverflow

I'm making a tower defense style game in 3D using Unity. I'm experiencing a frustrating issue with spawning large numbers of characters in an area of navmesh where if I spawn too many near the same location many of them will 'teleport' immediately after instantiation to near the navmesh destination.

Here's a doodle of one of the levels:

The black spot is the player base the NPCs have to get to. The green scenery has no navmesh and uses mesh colliders. Scenery is mostly steep hills forming a valley the NPCs should path through. It is composed of multiple meshes marked Unwalkable in navigation. The large blue spot is the first spawn location I tried, I later tried a larger area indicated in the right side of the image (see 'things I've tried' below).

When instantiating at the original spawn location if I spawn more than about 20 NPCs at once many of them will jump to the the area indicated by the red spots. The NPCs have a radius of about 1.5m, as do their colliders and navmeshagents avoidance property.

Things I've tried:

* Spawning to a random position inside a circle with a radius of 50m.
* Adding a large new hidden area of navmesh as in the image above, defining an array of vector positions spread well apart and spawning at each position in turn so no two navmeshagents spawn near each other.
* Adding a delay to `navmeshAgent.SetDestination(playerBase)` after instantiation hoping this would prevent the immediate jump to near the destination.
* Reducing navmeshagents avoidance radius. This sometimes reduces the problem a little but still, even with a radius of 0.1 any more than around 50 NPCs triggers the problem.
* Turning avoidance off althogether (setting to none in navmeshagent), again, can spawn more but problem still happens
* Turning off auto traverse links and auto repath in navmeshagent
* Increasing the time between instantiations, a large gap of several seconds works but makes the game too easy
* Not setting a destination - oddly they still teleport to near the player base, so I guess destination is not a factor

How can I spawn large numbers of navmeshagents in a short timeframe, avoiding this 'teleporting' behaviour?

# Answer
Have you tried spawning them with disabled navmesh agents, and enabling the agent on each unit only when you want it to appear?

Also, it seem peculiar that they teleport to a specific area. Is there something specific there, which doesn't appear in the rest of the scene?

In order to fully understand the issue, I recommend trying to recreate the minimal conditions needed in order to repeat this behavior - that way you could better understand the source of the issue, or send a bug report to Unity with the minimal project.
> 1 votes

---
Tags: unity, navmesh
---


# Question
Title: Unity3D Raycasting in Start behaves uncorrectly, but works correctly in Update?
I have this method, which just raycasts at a position downwards, and checks what tile is there, if there is one:

```
    public static Tile RaycastTile(Vector3 position)
    {
        Debug.Log("raycastTile at pos: " + position);
        var layerMask = 1 << LayerMask.NameToLayer("Floor");
        RaycastHit hit;
        Debug.DrawRay(position, new Vector3(0, -10, 0), Color.red, 50);
        if (Physics.Raycast(position, new Vector3(0, -1, 0), out hit, 10, layerMask))
        {
            var tile = hit.collider.gameObject.transform;
            Debug.LogWarning(tile.name + " - " + tile.parent.name + " - at pos: " + tile.position);
            var coordinates = new Vector2Int(Mathf.RoundToInt(tile.position.x) / 2, Mathf.RoundToInt(tile.position.z) / 2);
            return map.GetTile(coordinates);
        }
        else
        {
            Debug.LogError("Tile not found under position: " + position);
            Debug.Break();
            return null;
        }
    }

```

Currently it is called for the player

* at **Start()** *("starting at: \< player's absolute position \>")*
* and at **Update()** *("update at pos: \< player's absolute position \>")*
* And the **map is being generated** (tiles created, destroyed, etc) in **Awake()**.

and for some reason this is the **output**:

**And the map generation works like this:**

* Creates a room at (0, 0) with tiles and all, then it searches for a connection point on the existing map, whom the new room could be connected to. (with some rotation, if it's needed)
* (Every tile is 2x2 meters, and they are on a strict grid)

So for some reason calling this method at **Start()** (with the same position) hits a totally different tile. While in **Update()** it works correctly.

At first I thought that it's because of **Destroy()**, because the objects are only destroyed at the end of the frame. But I tried **DestroyImmediate()** and it didn't help. (And after thinking, I realised that destroying objects at the end of the frame wouldn't cause issues. Or is it?)

Then I had the idea, t**hat maybe Start doesn't wait for Awake because it compute heavy**. And the raycast in the Start hits a (yet) non translated newly generated room. So I edited the code so every room is initially created at very far away, which is relatively "infinite far away" from the player: at (9999, 9999). But the issue remained.

**EDIT:** With (9999, 9999) Sometimes (maybe half of the time?) now it is correctly raycasted even at start, while before it was never correct in start.

**EDIT2:** With (0, 0) it hits correctly at start as well, but very very rarely.

**Do you have any idea what could cause this issue?**

Sorry if there isn't enough info, feel free to ask. :)

# Answer
> 2 votes
The game world of Awake/Start/Update, and the physics world of PhysX, are actually two separate sets of data. It takes some extra work from the engine to apply changes from one world to the other.

Normally this is done once in the physics step for each FixedUpdate, but depending on frame timings, we might not get a physics step / FixedUpdate in the frame that Start runs.

My best guess here is that Start is sometimes asking the physics engine to raycast before the physics engine has been told about all of the tiles, so it gets stale data.

According to the docs, you can force a sync manually with Physics.SyncTransforms, which might help flush any pending transform updates through the pipe before you start your raycast.

Or, if your game can tolerate taking a moment to settle when the objects are first spawned, you can let Start wait for a FixedUpdate or two for the physics to be up to date before it tries to raycast against it, something like this:

```
IEnumerator Start() {
    // Wait until the first physics step runs...
    yield return new WaitForFixedUpdate();
    // Wait until later in that frame,
    // after physics is stepped
    yield return null;

    // Now do physics tests.

}

```

---
Tags: unity, tilemap, raycasting
---


# Question
Title: Bullet Physics Integration - direct movement of rigid bodies
I'm adding bullet physics to my engine. The physics simulation bits are all working nicely, but one bit I'm struggling with is being able to move objects using their co-ordinates, and then have them affect other bullet objects. I currently have this code just before I step the simulation, and this moves all of the objects to the co-ordinates that the game engine thinks the object should be, due to outside movement.

```
btTransform trans;
trans.setFromOpenGLMatrix(glm::value_ptr(host->getTransMat() * host->getRotMat()));

motionState->setWorldTransform(trans);
body->setWorldTransform(trans);

```

Then I step the simulation, and move every object to where bullet thinks it should be. I am aware there are nicer ways to do this part (custom written motionstate classes I think) but I want to get the logic down first. This works, but moving a cube directly into another causes the second cube to just shake a bit.

I've read in few places I should be applying forces to objects, but:

1. I don't really want to expose the btRigidBody and physics stuff to the core gameobject, and
2. I have a lot of code that does it's own movements using co-ordinates, and I don't really want to rewrite it, although I will if it's the only way.

Could I replace the code below with something that compares the position of the gameobject to the rigidbody's position, and applies the correct force to make that happen? How would I implement this code? It can't be as simple as F = MA can it, given that this would happen any frame?

Edit 1:

I have implemented the formula provided by DMGregory and I've not had any success. I've tried swapping this out for applyCentralImpulse too. The objects just stay stationary and anything falling just goes into hyper speed. This runs for every physics object just before step sim, and then the simulations positions are applied to back to their hosts.

```
    if (host == nullptr)return;

btVector3 newPos = convert(host->getPos());

btVector3 oldPos = body->getWorldTransform().getOrigin();

btVector3 dist = newPos -oldPos;

btVector3 acc = 2 * ((newPos - oldPos -( body->getLinearVelocity() * timeStep)) / (pow(timeStep, 2)));

if (dist.length() > btScalar(0.1f))
{
    std::cout << acc.length() << "large acc \n";
}

body->applyCentralForce(mass * acc);

```

# Answer
My usual approach here — and one I've seen work well in VR and motion controlled games too — is to compute a velocity that will bring the previous position of the object's physics body to the desired target position in one physics step.

$$\vec v\_{desired} = \frac {\vec p\_{desired} - \vec p\_{previous}} {\Delta t}$$

Here \\$ \Delta t\\$ is the duration of your physics timestep, not necessarily your frame time if those are decoupled in your case.

Some APIs will let you set the velocity directly, overriding other physics effects on it. If you can only apply forces though, then we need to apply an acceleration to achieve this. Working from the equation for movement in constant acceleration...

$$\vec p (t) = \vec p (0) + \vec v \cdot t + \vec a \cdot \frac {t^2} 2\\ \vec a\_{net} = 2 \cdot \frac {\vec p\_{desired} - \vec p\_{previous} - \vec v\_{previous} \cdot \Delta t} {\Delta t^2}$$

This is the net acceleration required to land at the desired point. If you have other continuous forces acting on this body (like gravity), subtract them to get the intervention acceleration that you need to apply.

Then to convert this acceleration to a force to apply, it really is just \\$\vec F = m \cdot \vec a\\$ ;)

You can use a similar strategy to set the angular velocity or apply an angular acceleration in order to bring an orientation into sync. First you compute the difference in orientation between the two:

$$R\_{difference} = R\_{desired} \cdot {R\_{previous}}^{-1}$$

Then convert this to an angle-axis representation, and scale the axis vector by the angle in radians over delta time. That gives you your angular velocity to set.
> 3 votes

---
Tags: opengl, c++, physics, bullet-physics, kinematic
---


title: Libgdx black rectangles problem

text:
# Question
Title: Libgdx black rectangles problem
I'm working on a game for Android using Android Studio with LibGDX in Java. I recently found a weird problem when closing and reopening the game. When I first open the game, it works fine. If I click the QUIT button and close the app, the asset manager disposes. When I reopen the game, some of the atlas regions are shown as black rectangles in the same size of the region. I noticed that it happens only when I call assets manager's dispose method. If I remove it, the problem doesn't appear. It's funny, but the game seems to work fine when not calling that method but I read that it is recommended to dispose it. This is my AssetsManager class:

```
public final class AssetManagerWrapper extends AssetManager {
    ArrayMap<String, FileHandle> configs = new ArrayMap<String, FileHandle>();
    public Texture lightTexture;
    public Texture alarmTexture;
    public TextureAtlas particlesAtlas;

    public final void loadGFX() {
        FileHandle dirHandle;
        dirHandle = Gdx.files.internal(Rules.System.GFX.GFX_FOLDER_NAME);
        FileHandle subDirHandle;

        for (FileHandle dir : dirHandle.list()) {
            subDirHandle = Gdx.files.internal(dir.path());
            if (dir.name().equalsIgnoreCase(AssetsPaths.Gfx.Sheets.SHEETS_FOLDER_NAME)) {
                for (FileHandle file : subDirHandle.list()) {
                    if (file.extension().equalsIgnoreCase(Rules.System.GFX.SHEETS_DATA_EXTENSION)) {
                        load(file.path(), TextureAtlas.class);
                    }
                }
            } else {
                for (FileHandle file : subDirHandle.list()) {
                    load(file.path(), Texture.class);
                }
            }
        }
    }

    public final void loadSounds() {
        FileHandle dirHandle;
        dirHandle = Gdx.files.internal(Rules.System.SFX.SFX_FOLDER_NAME);
        FileHandle subDirHandle;

        for (FileHandle dir : dirHandle.list()) {
            subDirHandle = Gdx.files.internal(dir.path());
            if (dir.name().equalsIgnoreCase(Rules.System.SFX.SOUNDS_FOLDER_NAME)) {
                for (FileHandle file : subDirHandle.list()) {
                    if (file.extension().equalsIgnoreCase(Rules.System.SFX.SOUNDS_DATA_EXTENSION)) {
                        load(file.path(), Sound.class);
                    }
                }
            }
        }

    }

    public void loadParticlesConfigs() {
        FileHandle dirHandle;
        dirHandle = Gdx.files.internal(AssetsPaths.Configs.CONFIGS_FOLDER_NAME + '/' + AssetsPaths.Configs.PARTICLE_CONFIGS_FOLDER_NAME);

        for (FileHandle file : dirHandle.list()) {
            if (file.extension().equalsIgnoreCase(Rules.System.GFX.PARTICLE_CONFIGS_DATA_EXTENSION)) {
                configs.put(file.nameWithoutExtension(), file);
            }
        }
    }

    public final void loadMusic() {
        FileHandle dirHandle;
        dirHandle = Gdx.files.internal(Rules.System.SFX.SFX_FOLDER_NAME);
        FileHandle subDirHandle;

        for (FileHandle dir : dirHandle.list()) {
            subDirHandle = Gdx.files.internal(dir.path());
            if (dir.name().equalsIgnoreCase(Rules.System.SFX.MUSIC_FOLDER_NAME)) {
                for (FileHandle file : subDirHandle.list()) {
                    if (file.extension().equalsIgnoreCase(Rules.System.SFX.MUSIC_DATA_EXTENSION)) {
                        load(file.path(), Music.class);
                    }
                }
            }
        }

    }

    public void loadData() {
        loadGFX();
        loadSounds();
        loadMusic();
        loadParticlesConfigs();
        finishLoading();
    }

    @Override
    public void finishLoading() {
        super.finishLoading();
        lightTexture = get(AssetsPaths.Gfx.Other.LIGHT);
        alarmTexture = get(AssetsPaths.Gfx.Menu.ALARM);
        particlesAtlas = get(AssetsPaths.Gfx.Sheets.Misc.PARTICLES_DATA_FILE);
    }

    public ArrayMap<String, FileHandle> getConfigs() {
        return configs;
    }
}

```

The life-cycle (Main class which implements Application Listener):

```
   @Override
        public void create() {
            assetsManager = new AssetManagerWrapper();
            assetsManager.loadData();
            soundPlayer = new SoundPlayer(this);
            Gdx.input.setCatchBackKey(true);
            goToMenu();
        }

     @Override
    public void resume() {
        assetsManager.finishLoading();
    }
 @Override
    public void dispose() {
        assetsManager.dispose(); //For some reason this creates the black rectangles bug.
        soundPlayer.dispose();
        if (warScreen != null) {
            warScreen.dispose();
        }
        menuScreen.dispose();
    }

```

Does anybody have any idea what could cause it? Is that ok that I just remove the call to that method? Thanks in advance.

# Answer
According to this section in the AssetManager page. When Android pauses, then the managed libgdx elements, like Textures, get cleaned up an have to be reloaded when the app resumes. To do this, you call `Texture.setAssetManager(manager);` and then call update on the asset manager like you did when you first loaded.

Secondly, Android apps have no guarantee that they will really stop executing when you quit them. Android is the one that chooses when it cleans up an app that is in the background. Perhaps even though you selected quit, your app was still running and needed the textures loaded again.
> 1 votes

# Answer
Just had the same issue. Problem was that I had some texture regions as static fields. And to avoid finding texture region over and over for each object I added some extra static variable "intitialized" so I was finding regions only for first generated object, setting that variable for trued and all other were skipping region finding. That works fine when I run the game for the first time. But when I exit and run app again and it stayed in phone memory that static "initialized" variable also keeps it's value, meaning find regions were not called again. And old regions existed but their memory was flushed so when drawn I was getting only black rectangles for them.

Solved by calling findRegion() again.
> 1 votes

---
Tags: java, android, libgdx, asset-management, android-studio
---


# Question
Title: What are some alternative options for saving level data for a game like Hurtworld?
For a multiplayer building/crafting game like Hurtworld (where the player can build structures on the map), what are some alternative options or example data structures for saving the world data on the server?

Level data including:

* Grid of squares that foundations can be built on, with a flag to indicate whether the square is empty or already has a foundation
* Walls etc which have been built on the foundations, and multiple floors above
* Windows/doors which can be built on window frames/door frames
* Furniture/machines which can be placed on foundations/floors
* Other dynamic world data such as trees, animals, chests with items, etc

I feel like it's too much data to store in a database. Am I wrong?

If it can be stored in a database, how can I get my head around the data structure I would need to set up? Is there some simplified example?

Can each square in the world grid be represented by 1 row in the database? And should there be a new row for each structure built on a square, with that row referencing the square/structure that it was built on?

# Answer
> 1 votes
When trying to choose databases, or any method of saving information, the way the data should be saved should be dependant on its usage patterns, not on how the world is modeled.

Out of all of the information that describes your world, what information needs to be persistent and what doesn't? What information will be queried more often, what less? What information should be returned ASAP, and what could take a while without harming user experience? Are there some bits of data that are dependant on each other, and should be saved together, or is all of your data completely independent?

For example, if you have a round planet, the player will not be able to see all of its parts. Make sure that you model your data in a way that allows the player to query only the visible parts of the planet at each moment. If you have a LOD system that will show the building and only later minute details such as windows, make sure that getting the building data isn't blocked by getting windows data. If the player will not get closer, that data is irrelevant.

These questions and similar ones should determine your data structures and the way they are persistently saved. From the phrasing of the question it seems like you want to model your data the way you would model your world, and in general that tends to be less efficient. I advise you to learn about data-oriented design, and try to properly understand the constraints you should put on your data, in order to understand how your data should be structured and saved. Once you'll have that, you'll have the constraints that your data places on your DBs.

---
Tags: mmo, data-structure, level-design
---


# Question
Title: Understanding the rendering of the raycasting on flat screen
I have a misunderstanding of the raycasting formulas on flat screen because my rendering is not what I expected, this is some parts of the code to show my projection formulas that I wrote by myself

This is the code for the function intersection

```
int         intersection(t_wolf3d *w, int i, t_vec2f *dir, int iter){
int             mapx;
int             mapy;
unsigned int    length;

length = -1;
while (++length < w->cam->raylength)
{
    mapx = (int)(w->cam->position.x + (length * dir->x));
    mapy = (int)(w->cam->position.y + (length * dir->y));
    if ((mapy / BLOC_SIZE < w->map->h && w->map->board[mapy / BLOC_SIZE]
                    [mapx / BLOC_SIZE]) || (i == 1 && mapy >= HEIGHT_MM))
    {
        w->cam->intersection.x = mapx;
        w->cam->intersection.y = mapy;
        return (1);
    }
}
return (0);

```

}

Code used for the raycasting algorithm:

```
void                    raycasting(t_wolf3d *w, int limit){
int         i;
int         hit;
t_vec2f     dir;
t_vec2f     forward;
t_vec2f     right;
double      halfwidth;
double      offset;

i = -1;
forward.x = tcos(w->cam->angle);
forward.y = tsin(w->cam->angle);
right.x = forward.y;
right.y = -forward.x;
halfwidth = ttan(w->cam->fov / 2.0);
while (++i < limit && !(hit = 0))
{
    w->cam->rays[i].startpoint = w->cam->position;
    w->cam->rays[i].startpoint.color = 0xff0000;
    offset = ((i * 2.0 / (limit - 1.0)) - 1.0) * halfwidth;
    dir.x = forward.x + offset * right.x;
    dir.y = forward.y + offset * right.y;
    if ((hit = intersection(w, limit, &dir)))
        w->cam->rays[i].endpoint = w->cam->intersection;
    else
    {
        w->cam->rays[i].endpoint.x = w->cam->position.x + w->cam->raylength
            * dir.x;
        w->cam->rays[i].endpoint.y = w->cam->position.y + w->cam->raylength
            * dir.y;
    }
    limit == w->width ? render(w, i, hit) : 0;
}

```

}

For non-straight walls, I thought it was my variable types, it seems like not, I changed them from integers to double and i still got the same result, this is a look of my structures :

```
typedef struct      s_point{
int             x;
int             y;
int             color;}                 t_point;

typedef struct      s_vec2f{
double          x;
double          y;}                 t_vec2f;
typedef struct      s_camera{
double          radius;
double          angle;
double          fov;
double          raylength;
double          speedmove;
double          speedangle;
t_point         position;
t_point         intersection;
t_point         rays[WIDTH];}                   t_camera;
typedef struct      s_map{
int             **board;
int             w;
int             h;}                 t_map;
typedef struct      s_wolf3d{
t_map           *map;
t_camera        *cam;
int             hit;
t_image         *img;
void            *mlx_ptr;
void            *win_ptr;
char            texture;
t_image         *textures[3];
int             colors[3];
int             mini_h;
int             mini_w;
int             width;
int             height;}                    t_wolf3d;

```

# Answer
The trick here is to think of your image plane as though it was actually a flat object sitting in front of the camera, perpendicular to its view direction. This parallels the way the player's screen is a flat object in front of their eyes, perpendicular to their gaze - and this similarity is what makes the optical illusion of linear perspective work.

Following this line of thinking, each column of pixels on your screen corresponds to a specific point on this image plane in your game space.

Because the pixels on our screen are spaced out evenly, we need to space out these samples evenly in space along the image plane - I've visualized that with the line of little squares in the diagram above. So we need to find a direction to shoot each ray so it first "through" one of these evenly-spaced pixel points.

If we sweep our rays using equal angular increments like you do in this code:

```
angle = (w->cam->angle + (w->cam->fov / 2) - (i * w->cam->fov / WIDTH_MM));

```

then we don't get evenly-spaced points on our image plane - they'll bunch up in the middle and spread out at the sides, breaking our illusion. It makes straight edges of walls start looking bent.

In reality, the angular gap between adjacent pixels changes as we sweep our ray across the screen - with smaller angular spread at the sides and bigger strides in the middle:

So, working in angles can be a bit of a trap, and it helps to get out of angular space and into cartesian coordinates & vectors early. As a bonus, this will also save us most of our trig calculations! :)

First we'll need a unit vector in the direction the camera is facing, our `forward` vector. We'll use this a lot, so it's worth saving rather than looking up the trig values every time:

```
 forward.x = tcos(w->cam->angle);
 forward.y = tsin(w->cam->angle);

```

Next we need a vector pointing parallel to the image plane, to the camera's right. We can use a little trick to compute this from forward with no more trig:

```
right.x = forward.y;
right.y = -forward.x;

```

And we'll need to now how wide to sweep from the center of our view to one edge.

```
halfWidth = ttan(w->cam->fov / 2)

```

Now the ray through the leftmost pixel in our image plane points along `forward - halfWidth * right`, and the ray through the rightpmost pixel points along `forward + halfWidth * right`.

We can calculate the direction the `i`th ray should travel like so:

```
offset = ((i * 2.0 / (WIDTH_MM - 1.0)) - 1.0) * halfWidth;

rayDirection.x = forward.x + offset * right.x;
rayDirection.y = forward.y + offset * right.y;

```

You can optionally normalize or scale this direction vector as needed to suit your ray intersection routines.

---

To demonstrate that this works, I built a test scene in Unity that would render a series of cubes with the standard rasterization pipeline, then also fire rays and overlay a greyscale version calculated raycasting-style. You can see from this cross-fade between the two, the raycasting approach accurately reproduces the same linear perspective, with no erroneous curving of the walls:

Here's the code I use to fire my rays, and save the depths into a buffer to use in drawing the raycast version:

```
void Update()
{
    // Compute worldspace width of the projection plane (at a depth of 1)
    // using the camera's field of view (which in Unity is a vertical FoV).
    float halfHeight = Mathf.Tan(_camera.fieldOfView * Mathf.Deg2Rad / 2.0f);
    float halfWidth = _camera.aspect * halfHeight;

    // For each pixel column in our raycasting buffer...
    for(int i = 0; i < _depths.Length; i++) {
        // Compute a ray firing through that point on the image plane.
        float offset = (2.0f * i) / (_depths.Length - 1.0f) - 1.0f;
        var ray = new Ray(
            transform.position,
            transform.forward + transform.right * halfWidth * offset
        );

        // If it hits something, get its depth along the camera forward vector.
        RaycastHit hit;
        float depth = float.PositiveInfinity;
        if(Physics.Raycast(ray, out hit)) {
            depth = Vector3.Dot(hit.point - transform.position, transform.forward);
        }
        _depths[i] = new Color(depth, depth, depth, depth);
    }

    _depthRibbon.SetPixels(_depths);
    _depthRibbon.Apply(false, false);
}

```

And inside the shader:

```
fixed4 frag (v2f i) : SV_Target
{
    // Sample depth from the buffer populated by our rays.
    float depth = tex2D(_MainTex, i.uv).r;

    // Wall height is our master height divided by depth.
    float height = _WallScale / depth;

    // Default floor / ceiling to black.
    fixed4 col = fixed4(0, 0, 0, _Alpha);

    // If the pixel we're shading is closer to the middle of the screen
    // than the edge of the wall, shade it as a wall.
    if (abs(i.uv.y - 0.5f) < height) {
        col = lerp(fixed4(0, 0, 0, _Alpha), fixed4(1, 1, 1, _Alpha), exp(-depth * 0.3f + 0.3f));
    }

    return col;
}

```
> 3 votes

---
Tags: raycasting
---


# Question
Title: Raycasting center of camera is not working: why?
In my game i'm using Unity First Person controller. I check every second what I am looking with the following code:

```
 cam = Camera.main;
 RaycastHit hit;
 Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane));
 if (Physics.Raycast(CameraCenter, transform.forward, out hit, 5))
 {
      WhatIamLookinTag = hit.transform.tag;
 }

```

The problem is that isn't working if move Up and down player "view" (so i move up and down mouse..)

I need the object that is in screen center (based on what am i looking).

Why ?

# Answer
This solved my problem: cam.transform.forward instead transform.forward

```
cam = Camera.main;
 RaycastHit hit;
 Vector3 CameraCenter = cam.ScreenToWorldPoint(new Vector3(Screen.width / 2, Screen.height / 2, cam.nearClipPlane));
 if (Physics.Raycast(CameraCenter, cam.transform.forward, out hit, 5))
 {
      WhatIamLookinTag = hit.transform.tag;
 }

```

Thanks to DMGregory.
> 0 votes

---
Tags: unity, raycasting
---