text:
How can I generate roads such as those in the game Twisty Road?
Here is a link to see the gameplay: https://www.youtube.com/watch?v=03PzsgO-uAM
How could I procedurally generate the path upon which the ball rolls in Unity/C#?
I know I could model distinct pieces of the road in Blender and import them into Unity as prefabs. My problem is, I genuinely have no idea where to start when it comes to programmatically generating the whole road out of those prefab sections in a cohesive manner, such that the road is built seamlessly and randomly with twists and turns in three-dimensional space.
I would appreciate any insight you could provide. Thank you.

I can't really offer you a full answer as it's not something I've done myself yet but what you want is Spline--based procedural geometry https://www.youtube.com/watch?v=o9RK6O2kOKo also https://github.com/JPBotelho/Unity-Road-Generator

@Pheonix2105 Thank you very much. The Spline-Based Procedural Geometry video is immensely helpful.

Glad I could help, good luck!

So, there are a few ways to do this theoretically, but I'll detail the one that you've been presented with. Firstly, you'd come up with a system for separating the roads into pieces. In Twisty Road, it looked like there were some straight strips that didn't bend much. Those are ideal locations to join the "seams" of your road gameobjects. What you would need to do is create bendy road prefabs of reasonable length that begin and end with straight portions.
Programmatically, you store these prefabs in an array. If I were you, I would give these prefabs two child gameobjects. These children will be start and end hinges. Move them to the ends of your roads, and then you'll be able to link your roads together on the fly. In your map generator code, you Instantiate a random road. Then, you Instantiate a second one and set its START hinge transform.position to the same as the previous road's END hinge transform.position. Recursively do this however many times as you'd like and voila. You have your procedurally generated bendy road map.
You could even rework this to start building more roads as the player progresses to its like a never-ending road if you wanted.

Thank you. So what you are saying is that the only pieces of road that are joined together should be straight ones and that any bendy piece would be best straightened out before joining a new one? And that will be accomplished by putting a gameobject on the start and end of each piece to reference the transform of on the fly? Do you think that method, Spline-Based, is the easiest/most efficient/best way to do it, or do you have any other methods you might recommend? Thanks again.

I do believe Spline-based to be the most logical solution to the problem. Its also easier than trying to generate a 3 dimensional curve and mapping a road to it, although that could also be done. I wouldn't know exactly how to go about it in Unity, though.

I know this question is old but there is a Unity package called the Path Creator Tool that solves this same exact problem. You can check out how to use it here: https://www.youtube.com/watch?v=saAQNRSYU9k
Consider becoming a Patreon to the guy that made this because this is a pretty complex tool and he was generous to make free for us all to use. Here's the creators Patreon page.

This is currently considered a "link only" Answer. Could you explain how to use the linked package here?


text:
Getting the bounding box of a sphere
I have a sphere with values center,radius and I need to convert the sphere to a bounding box with values min,max.
How do I convert a sphere into a bounding box?

Calculating the bounding box of a sphere is pretty trivial given the simplicity of sphere geometry.
Let's assume we have the radius of the sphere defined as a scalar (float or integer) value \$r\$, and the centre of the sphere defined as a vector \$\overrightarrow c\$ like this:
$$
\overrightarrow c = \begin{pmatrix}x \\ y \\ z\end{pmatrix}
$$
We can calculate the outer bound coordinate vectors \$\overrightarrow{min}\$ and \$\overrightarrow{max}\$ by doing the following:
$$
\begin{align}
\overrightarrow{min} &=
\begin{pmatrix}
c_x - r \\
c_y - r \\
c_z - r
\end{pmatrix}
\\
\\
\overrightarrow{max} &=
\begin{pmatrix}
c_x + r \\
c_y + r \\
c_z + r
\end{pmatrix}
\end{align}
$$
In code, that means:
// given
Vector3 center = new Vector3(10, 20, 30);
int radius = 5;

// then
Vector3 boundingBoxMin = new Vector3(
    center.x - radius,
    center.y - radius,
    center.z - radius
);
Vector3 boundingBoxMax = new Vector3(
    center.x + radius,
    center.y + radius,
    center.z + radius
);

If we'd prefer, another way to calculate this same thing is to define a vector \$\overrightarrow {r_{\text{offset}}}\$ for doing that addition, which simply represents the offset from the center to a corner of the bounding box:
$$
\text{given} \;
\overrightarrow c = \begin{pmatrix}x \\ y \\ z\end{pmatrix}
\; \text{and} \;
\overrightarrow {r_{\text{offset}}} =
\begin{pmatrix}
r \\
r \\
r
\end{pmatrix},
\\
\begin{align}
\overrightarrow {min} &= \overrightarrow c - \overrightarrow {r_{\text{offset}}} \\
\overrightarrow {max} &= \overrightarrow c + \overrightarrow {r_{\text{offset}}}
\end{align}
$$
// given
Vector3 center = new Vector3(10, 20, 30);
int radius = 5;
Vector3 radiusOffset = new Vector3(radius, radius, radius);

// then
Vector3 boundingBoxMin = center - radiusOffset;
Vector3 boundingBoxMax = center + radiusOffset;

Handling the 2D case
For the 2D case, calculating the rectangular bounding box of a circle, we omit the Z values like normal: \$\overrightarrow c\$, \$\overrightarrow{r_{\text{offset}}}\$ (if you're using that), \$\overrightarrow{max}\$, and \$\overrightarrow{min}\$ will just be 2D vectors and we'll just do only the x and y calculations.
Diagram!
The following diagram of the 2D scenario might help visualise what's going on here:

One's first instinct might be to calculate a hypotenuse using the Pythagorean theorem (\$\sqrt{x^2 + y^2}\$) and use that as the magnitude of a vector \$\vec h\$, but that's more computationally expensive than necessary: \$\overrightarrow{r_{\text{offset}}}\$ will give us the same result.

Here is something that helped me.
min = (center.x - radius, center.y - radius, center.z - radius);
max = (center.x + radius, center.y + radius, center.z + radius);

Hope it helps someone else.

What does vector - scalar mean?

@Tyyppi_77  Sorry for the confusion. I edited the post

You box is contained within the sphere. If you want the bounding box that contains the sphere you need to multiply your radius by 1 / .707 or basically use Pythagoras theorem to get the correct sized bounding box. Hope that helps. Sin of 45 degrees basically.

@ErnieDingo so I create a variable which contains 1 / .7071 and then multiply it by the radius before performing the code above

@ErnieDingo This does give a box that contains the sphere.

@Tyyppi_77 than just out of interest, how do you get a box that is inside the sphere

first point: center - (radius, radius, radius) * sqrt(1/3), last point: center + (radius, radius, radius) * sqrt(1/3).

That produces a box contained in the sphere

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How can you allow a sphere to rotate 360 degrees inside a hollow cylinder in Unity?
I have a hollow cylinder, within which is a sphere. The forward vector is predefined, so the user can not change their forward speed. What they do have control of, however, is the rotation of the sphere around the cylinder by swiping the screen.

Again, I want this rotational movement to occur while the ball is traveling on a forward vector.
Here is the code I have thus far in C#:
public float speed;

private Rigidbody rb;

void Start()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate()
{
    float moveHorizontal = Input.GetAxis("Horizontal");
    float moveVertical = 1;

    print(moveVertical);

    Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);

    rb.AddForce(movement * speed);
}

The current controls are for the left and right arrow keys, but I will implement swiping later.
I would appreciate any help you could provide. Thank you.

Create a parent object centered in the cylinder. Make the sphere a child of that parent. Rotate the parent and the sphere will "orbit" the parent origin.

https://gamedev.stackexchange.com/questions/61981/unity3d-orbit-around-orbiting-object-transform-rotatearound

If you want to do it purely from a mathematical point of view (so it works outside Unity too) you can use this:
x = sin(rot) *rad;
y = cos(rot) *rad;

This assumes that rot is the rotation of the sphere inside the pipe. This should be in radians, so to convert from 90 degrees do something like rot = 90 *Math.PI /180.
It also assumes that the sphere's z axis is the one moving "forward", which is unaffected.
This lets you have complete control over the sphere, you can for example reduce rad if you pan to make the sphere "jump" (approach the center) or increase/decrease it in case you plan to make the pipe bigger/smaller while the sphere is still inside.

Thank you. So would the rot value come from the user's finger swiping on the screen?

@JamieCorkhill This depends on how you want your game to function. You can configure it like "every 10 pixels the finger moves to the right, rot increases by 1 degree", same with the left side, this will cause the sphere to move to either direction as you are swiping.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How to find the degree of interpolation?
I have two quaternions: A and B. I want to lerp between them.
Given another quaternion C, I want to find the variable unknown, as seen in the equation below:
Quaternion.Lerp(A, B, unknown) == C

(Unfortunately, the equation above is misleading. In the scenario that C is "out of range" -- i.e. not along the shortest path to get from A to B -- unknown should simply be 0 or 1.)
How can I do so?

Math.se might be a better site for this

@MY_G I want to check my understanding of your question with you: You have two quaternions (A and B), you're lerping between them, and you want to find out at what % through the lerp the result will be equal to quaternion C. Is that correct? (And presumably you want to know how to do this in C# with Unity's quaternion utilities?)

@doppelgreener Sorry for my late reply. Yes, you are correct :-)

This is trickier than it looks on the surface for a couple of reasons:

Lerping Quaternions isn't the same as Lerping scalars, Euclidean vectors, or Colours.
You can think of an orientation Quaternion as a point on the surface of a 4-dimensional sphere with radius 1.
To perform a Lerp between two Quaternions, we draw a straight line between their respective points on the sphere (so this chord cuts inside the sphere, rather than wrapping around its surface). Then we Lerp along this straight line, as though we were working with Euclidean 4-vectors.
Since the result will generally not sit on the surface of the sphere, we finish up by normalizing it, to snap it back to unit length. This is effectively a Gnomonic projection, so it distorts our nice uniform Lerp along the straight line chord into a non-uniform blend along the geodesic arc on the surface of the sphere. Changes in the parameter t make smaller changes in the output Quaternion when t is close to zero or close to 1 (where the chord is closest to the sphere surface), and larger changes when t is close to 0.5 (where the chord is furthest from the sphere's surface, and the gnomonic projection magnifies it out)
For this reason, when we want a perfectly uniform rate of rotation between two orientations, we'll prefer the more expensive Quaternion.Slerp, which uses more sophisticated math to blend along the arc directly. Ratchet Freak's answer is a correct formula to use if you want to work with Slerp instead.
Quaternions have identical twins.
For any given orientation, there are two quaternions that describe it: one with a rotation angle less than or equal to 180 degrees (w >= 0), and one with a rotation angle greater than or equal to 180 degrees in the opposite direction (w <= 0).
To get the closest intermediate between two given orientations, we'll sometimes need to exchange one of the inputs for its twin, which we can form by negating all four components x, y, z, and w.

With all that out of the way, here's a method to extract the Lerp parameter t from an initial orientation a, a final orientation b, and an intermediate between them c:
float EstimateLerpFactor(Quaternion a, Quaternion b, Quaternion c) {

    float aa = Quaternion.Dot(a, a);
    float ab = Quaternion.Dot(a, b);
    float ac = Quaternion.Dot(a, c);

    // If the two rotations on opposite sides of the hypersphere,
    // replace b with -b. This is an equivalent orientation:
    // if b = (angle, axis) then -b = (360 - angle, -axis).
    if(ab < 0f) {
        ab *= -1f;
        b = new Quaternion(-b.x, -b.y, -b.z, -b.w);
    }

    float bb = Quaternion.Dot(b,b);
    float bc = Quaternion.Dot(b,c);

    float cc = Quaternion.Dot(c,c);

    float denom = (bb - 2 * ab + aa) * cc - (bc - ac) * (bc - ac);

    if (Mathf.Approximately(denom, 0f))
        return 0f;

    float t = (ac * (bc - ac) - cc * (ab - aa)) / denom;

    return Mathf.Clamp01(t);
}

Assuming all quaternions are unit length, you can get the angle between 2 quaternions by taking the acos of the dot product between them. Then the result is
acos(dot(A, C)) / acos(dot(A, B))

But this is only valid when C is an actual interpolation between them. To verify this you can add one more test:
if(abs(acos(dot(A, C)) + acos(dot(B, C)) - acos(dot(A, B))) > epsilon) return 0;

return acos(dot(A, C)) / acos(dot(A, B));

Basically the sum of the angle between A and C and the angle between B and C must be the angle between A and B (within error margin).

This will be correct for Quaternion.Slerp, since it ensures uniform parametrization of the arc. Quaternion.Lerp does not guarantee this, so its interpolation weights will be slightly different for choices of C close to A or B, particularly when A and B are far apart. (The distortion is least when the start & end are close, and vanishes at the 50% blend mark)

@DMGregory I added the unit length caveat.

That doesn't address the issue I described. Take two unit vectors on the unit circle and draw a line segment (chord) between them. Divide that chord into equal increments, then project each subdivision point back onto the circle, gnomonically. The resulting unit vectors bunch up close to your endpoints, even though the subdivisions were uniform and all inputs & outputs are unit length. The same thing happens 4-dimensionally with Quaternion.Lerp. It's not bad for most situations, but it does impact the exactness of the answer in this case.

This is based on a theory, since I don't really know how the subtracion of Quaternions work. But, I will base it on the basic interpolation formula, and the method I'll provide has worked for me on Vectors, since subtraction is a matter of a difference between each component.
The first is the linear interpolation formula, the second a way to get the time t, which is in your case, the unknown value.

You just need the output, which is C and the initial and final values (A and B respectively). Since the interpolation is linear, it does not matter which components you pass, as long as they are the same axes (in this case I pass all the X's, but you could pass all the Y's, Z's or W's).
Again, this has been proved to work for me with Vectors and numbers, but I don't really know how Quaternion subtraction works, I may investigate it and update the answer. In the meantime, I hope it helps.
Edit:
After some corrections from @DMGregory, I realized I haven't fully tested the function, so I solved for t and found the correct formula:

It is the same formula I found in a book used for getting the Membership Degree on a Fuzzy Logic's System given an input (in your case Quaternion C).
Code corrected:
float GetInterpolationTime(float output, float initialValue, float finalValue)
{
    return ((output - initialValue) / (initialValue - finalValue));
}

void Update()
{
    float t = GetInterpolationTime(C.x, A.x, B.x);
    // Here I use LerpUnclamped in case t is out of range [0, 1]
    if(Quaternion.LerpUnclamped(A, B, t) == C) /// Good to go...
}

Sorry for the misinformation, and hope it helps.

There are several problems here. 1) your "then" line redefines the function f, and is not the correct formula for isolating t. You might mean t = (f(t) - x_0)/(x_f - x_0)?. 2) This style of isolation works for scalars, but since division-to-scalar isn't defined for 2-vectors you might need to include a step taking their magnitudes. 3) Quaternion Lerp includes a normalization step, which means it's a little more complicated to invert than the pure affine case considered here.  Also, we now support MathJax, so you can write your equation directly instead of embedding an image.

You can verify the formula given is incorrect for scalars by checking a case like this:  lerp(1, 2, 1) = 2 but GetInterpolationTime(2, 1, 2) = 2/(1+2) = 0.6666... != 1

You are absolutely right @DMGregory, I corrected the answer already. I'll check about MathJax, appreciate the commentary.

Still not correct. Try the same test case I mentioned before: Lerp(1, 2, 1) = 2 but GetInterpolationTime(2, 1, 2) = (2 + 1) / (1 - 2) = -3. In general, when answering math questions, I recommend rigorously testing the formulas to make sure they're correct, so you don't leave landmines for unwary copy-and-paste coders to discover the hard way. I have a draft answer for this question I haven't submitted yet because there's still a quirk for some inputs I haven't quite solved yet. ;)

Oh, another issue: I notice you've tried to extend your scalar method to work on vectors by only considering the x component of the three inputs. Imagine how that behaves if the x components are all zero (or all the same value, generally) while the y/z/w components are distinct - considering just the x doesn't tell you enough about the whole multidimensional problem to correctly solve all cases.


text:
Visually updating the position of a game object controlled by an animator controller
I have a game object that is controlled by an animator controller. In order to activate the next animator state, the user is supposed to grab this game object, and then move it from Point A to Point B.
As a test, in said game object's Update() method, I added the following line:
this.transform.localPosition += Vector3.up;

When running the game, I can see that the y-coordinate of the game object's position increases every single frame, just as intended. However, visually, the game object's position is not changing at all -- it remains in the same place all the time.
What should I do to ensure that game object's position is also visually updated?
EDIT:
Here are the properties of the animator I am using:

EDIT:
If relevant, here is the skinned mesh renderer for said game object:

if the animator handles the position, then you won't be able to change it in the code

Although I don’t think it would appear to be changing in the inspector if that were the problem.


text:
How can I improve my touch slide mechanic to be more smooth and fluid?
I have the following C# code, but it leaves me with two problems:
void FixedUpdate()
{
    if (Input.touchCount == 1)
    {
        this.transform.Translate(Input.touches[0].deltaPosition.x * 0.009f, 0, 0);
    }
}

Firstly, the gameobject (which is a sphere in my case), has a tendency to leave the ground and fly into the air. Additionally, it is not as smooth and snappy but fluid as I would like it to be.
If you look at some of the following gameplay videos, you will see the kind of movement I am looking for.

"Splashy!" Gameplay
"Sky Ball" Gameplay
"Balls Race" Gameplay

More specifically, from actually playing each of the above games, there is a certain "ratio" that seems to be operating in regards to each swipe gesture and the actual movement of the ball. That is, the ball does not go exactly where the finger goes, for it is slightly ahead, if that makes sense. What I mean is, the device is only so wide, yet for that width, the ball can always reach it's required destination on either end of the horizontal axis. This must mean that for every pixel the finger moves, the ball moves a little bit more to fit that pixel density of the screen. In other words, in the case of "Splashy!", it's clear that even if the finger moves the entire distance across the screen, the ball moves more than double that distance.
By "smooth", "fluid", and "snappy", I mean that the swiping gesture is very responsive. It moves where you want it to and does not over or undershoot. Additionally, the "snappy" effect is present when you stop swiping. The ball seems to "snap" into it's end position.
My question, then, is what is the best way to improve my script as to achieve the polished mechanic I am looking for, as is depicted in the above videos? Also, how can I keep the sphere on the ground without constraining any axes on the rigidbody? I am using Unity3D with C#.
I would appreciate any help you could provide. Thank you.

The trouble with "How did X achieve Y" questions is that unless the developer who worked on X's implementation of feature Y sees your question, and isn't bound from answering by an NDA, AND has the wherewithal and time to post an answer, nobody else can answer it for you. Instead, you'll often find you get better answers by rephrasing your question like this: "How can I improve my feature Y? Here's how I've implemented feature Y so far ...[details] and I'm unhappy with [specific symptom 1] and [specific symptom 2] — how can I improve it?" That way anyone who knows a relevant solution can help.

@DMGregory Thank you. What you say makes sense. The problem is, I can build a simple movement script, such as this one: https://forum.unity.com/threads/simple-swipe-and-tap-mobile-input.376160/ But it does not provide me with the movement I desire.
I included the gameplay videos so others could better understand the mechanic I am going for, and possibly provide advice about how to implement it.

@DMGregory I changed my question. Is that any better?

Improving! "Smooth" "snappy" "fluid" are words that get thrown around very imprecisely though. This question could be even better if you can explain in words the exact behaviour you want. Try walking through the videos frame-by-frame to identify what makes them tick, so you can describe precisely what you need help creating. This also helps make evaluating the answers more objective: for any given answer, we can check it against the criteria you described and ask "does this proposed solution meet this specific requirement?" rather than fuzzy/subjective evaluations like "is it 'fluid' enough?"


text:
Why does my gameobject fly of into the air when the screen is touched?
I am encountering a peculiar problem when updating a piece of code that translates my gameobject left and right based on mobile touch input.
To provide context, the platform upon which the gameobject, which is a sphere in my case, translates, is this:

The platform is 10 units wide, with the sphere in the center.
In its original form, the code looks like this:
void FixedUpdate () {
    if(Input.touchCount == 1) {
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate(Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f);
    }
}

It provides the desired left and right movement, but it has a tendency to allow the ball to leave the platform, and then start moving up and down in the air with each further touch.
To combat that, I tried editing the code as follows:
void FixedUpdate(){
    if (Input.touchCount == 1){
        float touchXComponent = Input.GetTouch(0).deltaPosition.x;
        transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z);
    }
}

This, however, causes the ball to fly of the screen the second it is touched, leaving me with this error in the console:
Assertion failed: Invalid worldAABB. Object is too large or too far away from the origin.

I would have thought that the update I made to the code would keep the ball stationary on the y and z-axes, while allowing it to translate freely on the x-axis. Why is that not the case?
Thank you.

Does the sphere have a Rigidbody? In many cases, mixing rigid body physics simulation and direct transform manipulation can cause hiccups and unexpected behaviours. So if you're using physics you generally want to do all your work physically and stay hands-off with the transform component.

@DMGregory Thank you. I'll try using something like AddForce instead. On another note, were the updates to my other question (about getting smooth movement like current popular games) any good?

If other users are upvoting or answering your question, that's a sign they find it clear and high-quality. If it's downvoted or idling without activity, that's usually a sign it could benefit from clarifying edits. You don't need me to give a personalized rating — the reception of the site's community is what matters.

As this doc says :

If relativeTo is left out or set to Space.Self the movement is applied relative to the transform's local axes.

Which means you're actually translating your object by it's own position every update. To avoid that just change your call to :
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, 0, 0);

Thank you. After making the changes, if you drag the screen, the ball still sometimes lifts into the air.

For this problem, you should freeze Y position of your object. Either by using rigidbody.constraints, or by setting the Y position to a constant every update.

I wanted to do that, but there are other game elements where the ball will be falling, in which case I do want its Y value to change. I need to figure a way to translate the object independent of it y-axis transform. Also, I can't upvote your answer because I only have 14 rep.

I'd add a collider to your object so that it will collide with the plane, let gravity make it fall when there is a hole and add a constraint to freeze X axis. If the X axis matters, you may may clamp it's position for every update between two constant values.

Thank you. That makes sense. Can I ask you one last question? Is the method I'm using the best way to get smooth movement from touch input? I was thinking something involving Vector3.Lerp() or some other easing function would be better, but I'm unsure how to go about that.

The best method to get smooth movement is the one that feels best for the user. If it's Vector3.Lerp(), then go for it. But if your method feels fine, you don't have to change. If you want to use lerp, use the doc (https://docs.unity3d.com/ScriptReference/Vector3.Lerp.html). It really is just a function whose goal is to reach a destination smoothly depending on the time.

Thank you. The problem is, I don't know how to get the Vector3 of the destination. Converting screen space to world space does not seem to help.

From what I understand, you want the ball to move on the X axis only, relative to world coordinates. The current method you're using will do it in the local coordinates (relative to the object).
Since Transform.Translate method already gives you this functionality, you can just change your line from
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z);

to
transform.Translate((Vector3.right * Time.smoothDeltaTime * touchXComponent * 0.5f).x, transform.position.y, transform.position.z, Space.World);

and it should work in theory (I don't have access to Unity right now).


text:
Get internal and external IP addresses in Unity 2018.2.0?
Unity 2018.2.0 makes the Network class obsolete.  I have used "Network.player.ipAddress" in my code to get the local LAN IP address.
    internalIP = Network.player.ipAddress;
    externalIP = new WebClient().DownloadString("http://icanhazip.com");

What code should replace this?  What would be best practice for getting internal and external IP addresses for manual LAN and internet direct connections between server and client?
Internal/external IP addresses are needed so players can load the game, then tell their friends what their IP is to direct connect.

When you tell us why exactly you need the internal and external IP address, then we might suggest you a better solution for your problem.

@Philipp So players can load the game and tell their friends what their IP is for direct connecting.

Have you considered setting up a matchmaking server? It would be a very lightweight task, so a small and cheap cloud VM would do.

@Philipp That might be a good idea in future, but I really need an answer to this specific implementation now.

This will output the IP for every interface on the machine.
foreach(NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
   if(ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
   {
       foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
       {
           if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
           {
               //do what you want with the IP here... add it to a list, just get the first and break out. Whatever.
               Debug.Log(ip.Address.ToString());
           }
       }
   }
}

You'll need to have access to System.Net.NetworkInformation in your project.

Thanks!  This works to bring up a list of IP addresses.  The problem is the first one it returns is 192.168.0.10.  That is pulled on both editor and standalone client.  Previously using Network.player.ipAddress, whenever I'd load a standalone and the editor, and try and direct connect them, they'd have a different 192.168.xxx.  So I'm wondering, is there something I can do manually to fix this, or is it something coded deeper into Unity which is now removed and I can't replicate?


text:
Unexpected positioning when programmatically instantiating objects in Unity?
I'm creating a simple match three game in Unity. I've opted to use Unity's UI system as it takes care of resolution scaling for me. The project is quite simple, at runtime I am programmatically creating an 8x8 grid of tiles via the script below. This script is attached to an empty Game Object residing within a canvas.
public class GameBoard : MonoBehaviour
{

    public int BoardSize = 8;
    public List<GameObject> TileSet;

    void Start ()
    {
        for (float y = 0; y < BoardSize; y++)
        {
            for (float x = 0; x < BoardSize; x++)
            {
                int tileIndex = Random.Range(0, TileSet.Count - 1);
                Vector3 position = new Vector3(x, y, 0.0f);
                GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);

            }
        }
    }

}

As you can see, the first tile is being positioned at a Vector3 of  0, 0, 0. The second at 0, 1, 0, and so on. At runtime this translates to Rect Transforms of 0, 0, -9720, and 108, 0, -9720 respectively.
Where is 108 coming from, and why is the Z an arbitrary -9720 when it should be a constant zero?
I suspect this must be due to canvas scaling, so I have attached an image of the canvas's settings.

I'm not really sure how canvas scale things. But, if you're using RectTransform, you should use AnchoredPosition for positioning objects.

Interesting that 9720 = 9 * 1080.

What's the value of this.transform.translation when your script executes the GameObject newTile = Instantiate(...) line?

I tried every different way of instantiating a game object and the value of pos z would only be correct for the first one instantiated. The only thing that would work for me is Instantiating the Game Object and then setting the localPosition.
It would look something like this.
int tileIndex = Random.Range(0, TileSet.Count - 1);
Vector3 position = new Vector3(x, y, 0.0f);
GameObject newTile = Instantiate(TileSet[tileIndex], position, this.transform.rotation, this.transform);
newTile.transform.localPosition = position; // Don't set position, set localPosition

This results in what I would expect... very strange. I'd be curious to find out why this functions so strangely.


text:
Performant Fog-of-War With Sight Blocking in Unity
In games like Command & Conquer or Age of Empires, players can't see all of the map.  Terrain and enemies are revealed only when the player has soldiers nearby.
As I understand it, the most performant way of doing this is by representing map visibility as a grid of cells.  When a unit moves into a new cell it updates all cells within a circle shape around the unit.
However, I would like to know how to integrate sight blocking.  What I mean by this, is that if a cell is occupied by something which a unit can't see past (like a wall) all cells behind the wall are covered by fog-of-war.
Here's a YouTube video of what it should look like.  The author doesn't go into how they did it, aside from mentioning "brute force shadow casting".

The author of that video gives a step-by-step breakdown in this Tumblr post, which might be useful to you.

@DMGregory I think that may have answered my question.

Sweet! If you get it working, it would be great to add an answer here yourself, so it's easier for future users working on similar issues to search for.

I am working on a performant implementation of a Fog of War, checkout my twitter https://twitter.com/arielsan, my idea is to make a blog post about the it at some point but if you see something that could help you could ask me directly. I will try to answer the question too.

Basically what I do is, for each pixel in vision range, I go pixel by pixel and check a line to the center (using the Bresenham's line algorithm), if there is no obstacle, then the pixel is visible, otherwise, it is blocked.
It works pretty well, ~100 units at 60fps, check out this tweet to see it working. I plan to write a blog post to explain in detail the implementation.
Don't know if that works for you as an answer.

I completed the second blog post about what I am using, not sure if it would be of much help but here it is: https://twitter.com/arielsan/status/1065029151508320256


text:
Networking User Interface Buttons (build queue items)
I am creating a RTS with Unity/C#, and have noticed a problem synchronising build queues.  Is there an ideal solution to handle button prediction?
I think I may have overengineered the solution... Presently when the client clicks a button, it sends a request to the server.  The server validates the request (cost if applicable) and then returns the order to create the build queue item.  Consequently, when the client clicks a button there's a noticeable lag.
Is server validation for button presses, like build queues, in a client-server model overkill?  What would be the ideal solution?

Can you give an example of a case when a queue operation should fail, based on information the client doesn't yet know?

@DMGregory I would assume if someone tried to cheat on a client.  Are you saying practically speaking there really shouldn't be any fail cases?

If the player has modified the client to cheat, they can modify it to show whatever the heck they want on their screen — including showing the item in queue even if the server says no. So your validation isn't there for the cheaters' benefit. It's for the benefit of the ones who are playing by the rules, ensuring they see a consistent game state and that other players' cheating attempts can't impact their game. So, for client-side features, your main concern is that your data may be out of date (eg. if another player recently stole resources from me so I can't afford the item I'm queuing)

@DMGregory It seems like what you're saying could be an answer?

It's meant to be a question. What situations do you have in your game where a non-cheating client might fail to queue an item? Knowing that, we can help you design a system that correctly handles those failure cases.

@DMGregory Sorry, I was getting confused.  Presently when a player presses a button that results in a build queue order, it checks if they have the resources to buy it.  If they do, the order goes through and resources are subtracted.  If they cancel they get resources back.  There's nothing more complicated than that.  I can only think in certain cases the production facility might be disabled temporarily so the queue is paused, but in such an event server is going to send a specific command to clients which will include such context anyway.


text:
Execute function every X points
In my game, the score can go up quite rapidly and by varying amounts, depending on the action taken.
For instance, at the start of the game, one could climb from 1 - 50 one by one, or they could rocket past 50 by getting a score of 10, 25, and 40.
My question is: How do I call a function every time they pass a factor of 50 (50, 100, 150, 200, etc.)?

Here is code that works by polling the current score. This allows you to separate score-keeping code from the code meant to react to score. You can have multiple score-reactors.
You don't actually need polling. You could make it an event-based system. Add objects with a CheckScore function to a list in your score-keeping class. Then treat that list as a list of callbacks. Or just do it every FixedUpdate.
private long step = 50;
private long nextReward = CurrentScore() + step;

public void CheckScore()
{
    while (CurrentScore() >= nextReward)
    {
        nextReward += step;
        // Give reward here
    }
}

It's also easy replace the while loop with an if then implement a kind of cooldown effect so you don't spawn every reward during the same frame.
private long step = 50;
private long nextReward = CurrentScore() + step;
private int countDown = 0;
private int coolDownFrames = ...;

public void FixedUpdate()
{
    if (CurrentScore() >= nextReward)
    {
        if (countDown == 0)
        {
            countDown = coolDownFrames;
            nextReward += step;
            // Give reward here
        }
        else
        {
            countDown -= 1;
        }
    }
}

Testing this right now. :)

I would use a property, so that you can modify the score and compute when a step has been passed;
[SerializeField]
private int step = 50;

private int score ;

public int Score
{
    get { return score ; }
    set
    {
        int delta = value - score ;
        if( value > score && value % step < score % step ) // Handle cases such as score = 45 and newScore = 55
        {
            OnStepPassed() ;
        }
        score = value < 0 ? 0 : value ; // Make sure the score is positive
        while( delta >= step )
        {
            delta -= step ;
            OnStepPassed() ;
        }
    }
}

You can make this much simpler as for(int delta = newScore/step - oldScore/step; delta > 0; delta--) OnStepPassed(); The integer division is already present in the modulo, but this way you handle both jumps of one step and jumps of several steps in the same loop.

Much cleaner solution indeed! You should definitively post it as an answer!

This is cool, but I'd rather not modify the method of gaining score as I'm already almost done with the game. Thank you though!


text:
Would it be worth designing games in which the fighting is suspended so your enemies can get some sleep?
I think one way to motivate kids to get more sleep at night would be to design a series of video games in which the monsters/creatures/aliens, etc., will automatically stop attacking your character between the hours of say 11:00pm - 7:00am.
At 11:00pm, they will cease fighting, will lay down and fall asleep. At 7:00am, they will wake up and resume attacking your character. If you attack them while they are sleeping, you will lose major points or you will instantly die.
Also, you will need to instruct your character to go to sleep during this same period, or your character will be very sleepy when the game resumes and will not perform well.
This particular time period would need to be hard coded into the game so it cannot be changed. So, at 11:00pm in New York City the enemies in the game will go to sleep, and the same thing happens in the game at 11:00pm in Los Angeles, and so forth in all the time zones around the world.
Would it be worth adding this feature to video games or would most kids just refuse to play them?

World of Warcraft's Rest XP is an interesting case study here. They found much it was much more palatable when presented to the players as a positive (you get faster XP earning when you sign in after a break) than as a negative (you get slower XP earning if you play too long).

What would keep the kids from playing another game instead of going to sleep when yours stops working? Or browsing 9gag or whatever instead of sleeping? Also, can you be sure that your players even are kids? What if they're old enough to stay up past 11pm? Or if they're up at 6am so they can some game time in before school? I think you're trying to reinvent parental controls here, which only really make sense for platforms, and not individual games. If anything, you can do some more subtle things like DMGregory suggests.

@Christian, those are good points that you make. I think kIds in general (K-12) are too addicted to video games if they feel compelled to fill all their free time playing video games.

@FanofComets If you want to campaign against video game addiction, then keep in mind that you are talking to members of the drug cartel here.

I can appreciate the thought behind this idea, but in all honesty, you're trying to treat the symptom, not the cause. Your intentions are good, but this is sadly not a case where one person's efforts are really going to make much difference.

I understand where you are coming from. There are some games around with some questionable design decision which encourage the player to focus their whole life around the game. Among these are PvP mechanics which allow players to take advantage of players who don't log in that frequently, timed events which fall into times where players are usually asleep, challenges with a real-time time limit of several days which can only be completed when the player plays many hours each day or other mechanics and design decisions which discourage the player from quitting the game any time they want. Such game mechanics have some serious ethical problems. Especially if paired with pay-to-win microtransactions. But if these are a problem in your game, then you should first consider some solutions which address these mechanics directly.
I think that it is obvious that adding a "crippled mode" to your game which is solely designed to make the player quit playing is not making your game any more enjoyable. If you just want to prevent the player from playing, you could achieve that goal in a far more straight-forward manner which requires far less development resources on your behalf: Just kick them out of your game and prevent the game from starting until 7am. This is a feature you could develop within minutes of development time.
Now the question is whether you as a game designer have the moral responsibility (or in fact the moral right) to tell your players when to go do bed. You are not their parent. Some of your players might not even be children anymore. And besides, your game alone won't convince the players to do this. When they don't feel like going to bed, they will just play a different game. There are more than enough games available on the market, after all.

You bring up a good point about whether or not people will stop playing other games after the game kicks them out, and it's my understanding that this is indicative of a much bigger societal issue that needs to be addressed outside of the designing world.

@Pleiades When you have the problem that your children play video games instead of sleeping, then you might want to ask for advise on https://parenting.stackexchange.com


text:
How much time would it take to make a sprite-based isometric game with customizable characters?
I've never been good with 3-d models, but I can do sprites. I was hoping I could perhaps make a 2-d isometric game that acts like 3-d. Something like Don't Starve is what I have in mind.
Here's the kind of features I would like to include in games:

Rotatable camera. Don't Starve is obviously sprite-based, but you can rotate the camera. The effect may not look that great, but it allows the game to work like it has 3-d graphics when it doesn't.
Customizable character. You choose what your character looks like, such as their clothing, hair style, skin color, maybe their face. The issue is, I also want my characters to be animated. I know the number of sprites I'd have to make for that would be huge, but I figured I could shorten the process with things like palette swapping and reversing sprites. Could I have the game procedurally generate a sprite from multiple parts that are all animated? Or would I have to have every single possible combination pre-rendered? Yeah, I'd still have to make a huge number either way, but I can still cut corners where I can.

And yes, I know having both of these things would require me to create an insane number of sprites, but I'd still like to attempt it, if its possible. Also, I'd like to avoid a pixelated look, if that's doable. And yes, I know that would make creating sprites even more laborious, but gimp makes drawing clean lines rather easy, so I'm not too worried about it.
How long would it take me to create each sprite? With that, I could figure out how long it would take me to craft all of them, if I calculate how many sprites I would need per character.
And yes, thinking about the logistics of it all is immense. Animated, customizable characters in game with a rotating camera, meaning that even static objects would need multiple sprites. And no, I don't intend to include camera pitch. Obviously, I'm pushing the boundaries of what I can do as-is.

Unfortunately we can't answer that, only you can. A very experienced artist can make multiple high-quality sprites in a day. A new artist can make a handful of low-quality sprites in the same time. The same can be said about the programming side. It also has to do with the scope of the game, professional games were made with a group of professionals working on the game for months.

The types of questions we can help you with here are "how do I solve this specific problem?" Judgement calls like "is this game design or art style a good idea?" are things you'll need to decide for yourself, based on your own goals, priorities, research, prototypes/tests/experiments, and estimates. In particular: we can't estimate the speed or quality of work of a person whose work we've never observed. So you're in a much better position to answer this question than us internet strangers are.

Yes, you can create a character from multiple animated parts and layer them over each other at runtime. This is a very common technique. Changing the color tint at runtime is usually not that difficulty either with most graphic frameworks. If you have any issues with this, feel free to post a new question where you tell us what technology stack you are using, how you load and draw your sprites and how exactly you want your recoloring algorithm to work.
But how long it will take to crete all these character parts and animate them is impossible to say. It depends on:

How skilled you are at pixel art
What level of quality you want to achieve
How many different animations you want to create
How many phases you want these animations to have
How many character parts you want

These five factors are multiplied with each other, so it is impossible to give you an estimation without knowing anything about them.
I would recommend you to make a list of objects and animations you need, create your first sprite animation and extrapolate.


text:
Unexpectedly fast rotation after refactoring OpenGL code to add more abstraction
I've been working on an OpenGL program that simply renders a square that rotates in 3D space. The square also has a texture applied to both sides. Here you can see an example screenshot of the program running:

I used very little abstraction in that project and most of the code was in main.cpp (apart from the shader loading and usage).
After finishing this project, I wanted to improve it as much as I could with my current knowledge. I started abstracting away functionality. The final result was a very clean main.cpp file with multiple classes (Mesh, Shader, Resource Manager and Window classes).
Apart from the texture, everything should functionally be the same, but I experienced the following after using the rotate function; left is the abstracted version of the first project, right is the first project:

The square in the new project rotates at a much higher speed than in the previous project. The implementation is the same, as in, the degrees that the square should rotate around the y-axis are the same in both projects - the time the program has been running, which is gotten through GLFW's glfwGetTime().
I checked nearly everything. The .lib files are linked the same way between the projects. There are no differences between the vertex data. Both projects are running in DEBUG mode.
The only difference I could think of is the texture not being applied in the second project, but I recall that the textureless version of the first project was still running with the same speed as it is currently. But rendering a 64x64 texture on a square shouldn't be that expensive to run.
NOTE: I'm using GLM for the matrices and for the rotation transformation.
Does abstracting away all of OpenGL's initializing and buffer code improve performance by that much?
I'm using GLFW for window and context creation, and thus using (float)glfwGetTime() for the angle of rotation along the y-axis.
The second project basically moves over all functionality into categorized classes. So everything to do with meshes was moved to a Mesh class, loading of GLSL shaders and textures was moved over to a ResourceManager class etc. So all functionality should be the same.

Could you elaborate on "abstraction" ? I mean, I know what it means, but if you do it properly, the result should be the same, since in your case it is not, obviously there's something wrong with the code or the idea behind it. Without more information I doubt anyone can answer this accurately.

@TomTsagk I will elaborate as soon as I can, but basically all functionality should be the same. Even cleaning up buffers, window, context etc. is the same. I'll provide much more detail and if I can, source code on GitHub.

sounds like a bug on your end created during refactor. Most likely not resetting a transformation matrix to identity.

As @ratchetfreak commented, I hadn't reset the model matrix to the identity matrix in the render loop. This was indeed omitted from the remade project.
The matrix needs to be reset each frame to the identity matrix because each frame it stores a new transformation (in this situation a rotation) in the matrix, so when the next frame a new rotation transformation is applied, it's applied to all the previous frames' rotations. So for example, on frame #5 the matrix is in a form that stores the rotations of frames 1-4 and the 5th rotation is applied on top of all those.
The resulting effect is a sort of 'exponential' increase in the speed of the rotation, before slowing down for a second and speeding back up again.
Again, thank you @ratchetfreak :)
(I'll accept this as the answer when the site allows me.)

I notice a down-vote on this answer, but I'm not sure why. While it's short, it clearly identifies the source of the issue with enough specificity that a user experiencing a similar problem could find the analogous error in their own implementation. The answer could be even better if it described why failing to reset the model matrix to identity causes the excessively fast rotation observed, but I don't think it's "not useful" in its current form.

@DMGregory I've explained what I think is happening in the solution now. Hopefully it helps others understand how the problem occurred.


text:
Render Stutter - OpenGL or loop timing?

For some time now i have no been able to pinpoint the nature of the rendering stutter shown above(by not clearing the screen, not using SwapBuffers and drawing only to the front buffer). See the big spaces between some balls?

UPDATE 2
By putting the FixedUpdate on another thread(which seems like a good idea on it's own) and using Sleep(1) the loop no longer have the random stutters(which means it not longer stutters when using vsync for the loop timing). Now only the batch of stutters that come on a timing are present. They come in roughly 9 second periods and last for something between 2 and 3 seconds.
So the last culprit must be the sleep timing portion of the code. Right now it looks like this:
    if(!isVSyncEnabled)
    {
        QueryPerformanceCounter(&sleepStart);

        sleepAccumulator += (updateStep - ((sleepStart.QuadPart - loopNewTime.QuadPart) * 1000.0f
                           / counterFrequency.QuadPart));

        while(sleepAccumulator > 0)
        {
            QueryPerformanceCounter(&sleepStart);

            Sleep(1);

            QueryPerformanceCounter(&sleepEnd);

            sleepAccumulator -= ((sleepEnd.QuadPart - sleepStart.QuadPart) * 1000.0f
                                            / counterFrequency.QuadPart);
        }
    }

I tried removing the Sleep, but then instead of 60 the game would lock on 22 fps. Due to the fact that startTime - endTime will give 0 as result since there is no padding in between those. What else can i use as padding for a busy loop?

UPDATE
After some more tests including free movement with a joystick with varying speeds. I managed to gather a more appropriate description of the problem:
SOLVED > This is a monitor thing - It seems like i can see the "ghost" of the last frame in the current frame. This becomes more prominent the faster the object moves. Also it does not get captured in screenshots.
So this makes me suspect that the problem must be related to the way i'm using (or not using)double buffers/swapping/something of the sort. Maybe even a monitor problem?
Some big stutters still happen, but i believe that part is related to the game loop.

Here is the game loop:
u32 loopOldTime = timeGetTime() * 1000;
u32 loopNewTime = loopOldTime;

u32 loopDuration;

// fixedUpdateFrequency and displayDevices[currentDisplayDevice].frequency are 60 in my tests
u32 loopFixedUpdateStep = (u32)((1000.0f / fixedUpdateFrequency) * 1000);
u32 renderStep = (u32)((1000.0f / displayDevices[currentDisplayDevice].frequency) * 1000);

u32 loopAccumulator = 0;

s32 sleepAccumulator = 0;
u32 sleepStart = 0;

u32 framerateTimeThreshhold = 0;
u8  framerateCount = 0;

deltaTimeFixed = loopFixedUpdateStep  / 1000000.0f;

while(isRunning)
{
    loopOldTime = loopNewTime;
    loopNewTime = timeGetTime() * 1000;

    loopDuration = Min(loopNewTime - loopOldTime, 250000);
    deltaTime = loopDuration / 1000000.0f;

    loopAccumulator += loopDuration;

    if((acceptInputWithoutFocus && canRunWithoutFocus) || isFocused)
    {
        -- Input Stuff --
    }

    while(loopAccumulator >= loopFixedUpdateStep)
    {
        if(canRunWithoutFocus || isFocused)
        {
            -- FixedUpdate Stuff --
        }

        loopAccumulator -= loopFixedUpdateStep;
    }

    timeInterpolation = (r32)loopAccumulator / (r32)loopFixedUpdateStep;

    if(canRunWithoutFocus || isFocused)
    {
        -- Update Stuff --

        -- Render Stuff(calculating vertexes and putting those in place) --

        glClear(OPENGL_CLEAR_BITS);

        glBufferSubData(GL_ARRAY_BUFFER, 0, spriteFactory.verticesSize, spriteFactory.vertices);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, spriteFactory.indicesSize, spriteFactory.indices);

        glDrawElements(GL_TRIANGLES, spriteFactory.spriteLimit * 6, GL_UNSIGNED_SHORT, (void*)0);

        SwapBuffers(deviceContext);

        framerateTimeThreshhold += loopDuration;
        ++framerateCount;

        if(framerateTimeThreshhold >= 1000000)
        {
            framerate = framerateCount;
            framerateCount = 0;
            framerateTimeThreshhold -= 1000000;
        }
    }

    sleepStart = timeGetTime() * 1000;

    sleepAccumulator += (s32)(renderStep - (u32)(sleepStart - loopNewTime));

    if(sleepAccumulator > 0)
    {
        Sleep((u32)(sleepAccumulator / 1000));

        sleepAccumulator -= (timeGetTime() * 1000) - sleepStart;
    }
}

Here is the movement code:
r32 speed = 500 * deltaTime;

player->sprite->position.x += speed * input->gamepads[0].axisMap[GAMEPAD_LEFT_STICK_X]->normalized;
player->sprite->position.y -= speed * input->gamepads[0].axisMap[GAMEPAD_LEFT_STICK_Y]->normalized;

player->sprite->position.x = Clamp(0, player->sprite->position.x, screenWidth - player->sprite->width);
player->sprite->position.y = Clamp(0, player->sprite->position.y, screenHeight - player->sprite->height);

Here is the code for the spinlock test that will be mentioned bellow:
while(isRunning)
{
    loopOldTime = loopNewTime;

    if((acceptInputWithoutFocus && canRunWithoutFocus) || isFocused)
    {
        -- Input Stuff --
    }

    if(canRunWithoutFocus || isFocused)
    {
        -- Update Stuff --

        -- Render Stuff(calculating vertexes and putting those in place) --

        glClear(OPENGL_CLEAR_BITS);

        glBufferSubData(GL_ARRAY_BUFFER, 0, spriteFactory.verticesSize, spriteFactory.vertices);
        glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, spriteFactory.indicesSize, spriteFactory.indices);

        glDrawElements(GL_TRIANGLES, spriteFactory.spriteLimit * 6, GL_UNSIGNED_SHORT, (void*)0);

        SwapBuffers(deviceContext);

        framerateTimeThreshhold += loopDuration;
        ++framerateCount;

        if(framerateTimeThreshhold >= 1000000)
        {
            framerate = framerateCount;
            framerateCount = 0;
            framerateTimeThreshhold -= 1000000;
        }
    }

    sleep = true;

    while(sleep)
    {
        loopNewTime = timeGetTime();

        if(loopNewTime - loopOldTime > 15)
        {
            sleep = false;
        }
    }
}

Some notes:

timeBeginPeriod(1) has been invoked beforehand to make the precision
of timeGetTime and Sleep(need confirmation) 1ms.
I'm handling timings in milliseconds.
Variables types:

u > unsigned int || s > signed int || r > float/doable
number > size

I made the following tests:

Put the code that is moving the blocks on Update and scaled with deltaTime.
Put the code that is moving the blocks on FixedUpdate and use timeInterpolation to the vertexes.
Remove the game loop structure and use a simple spinlock as seen above. The fps is of course not locked at 60(63 in the example above).
Switched from timeGetTime to QueryPerformanceFrequency/Counter.
Switched between glBufferSubData and glMapBufferRange.
Tried explicit OpenGL synch with glFinish.
Tried no timing at all.
Tried VSync on and off along all the previous tests.

Here if what i managed to notice:

Vsync makes the way stutter less common. But it still happens in all
cases except the one that uses no timing at all.
The stutters are more
frequent when running movement code on FixedUpdate with
interpolation.
The stutters happen in periods. After some time of them happening constantly, there will be some that they will not happen at all.
The stutters seem to coincide with peaks in timeInterpolation. Some of the time, when interpolation reaches 0.9 >, a stutter happens. And when a period of frequent stutters happen, timeInporlation also peaks frequently.
While using the spinlock, the stutters happens at a fixed frequency.
While recording it i noticed that the stutters happen less in the recording(after, not during) but still do happen.

And this is what i have. At every step i find something new that bounces me between the problem being in my OpenGL code or in my loop code, but never conclusive or clear enough for me to figure out what really is the problem. Frustrating, to say the least.
Thanks in advance for any tips or ways of finally finding out the problem.

How do you use "timeInterpolation"? Do you interpolate between the last two states you computed in the fixed-update loop?

current * interpolation + last * (1 - interpolation)

I've seen in your post that you have uploaded some image, why is not in the question? This would seem very useful. Also, think about future visitors: the link to your project will most likely rot, so you should remove it and not rely on it.

Haven't watched the video but why doesn't SwapBuffers already wait for the next frame?

Only with vSync enable, is my understanding.

RE: "It seems like i can see the "ghost" of the last frame in the current frame", that will be your monitor overshooting as it tries to modify pixel colors as quickly as possible. It's a common problem, particularly for high-end non-gamer-focused monitors.

@JoséCarlosCandido we may benefit from a reformulation of your solution as a new answer to your question.

Calls to timeBeginPeriod/timeEndPeriod won’t result in a Sleep() of 1ms.  You will get anything but 1ms and possible values as high as 10-15ms.  Also, no need to adjust scheduler timeslice for timeGetTime either, the default will give you accurate enough timing.
Your monitor is fine, the ghosting you are seeing is known as temporal aliasing.  If you clear the buffer between moves and correctly implement interpolation, this effect can be mitigated.


text:
Is Quadtree Terrain Decimation applicable today?
It all started from that page.
https://www.gamasutra.com/view/feature/131841/continuous_lod_terrain_meshing_.php?print=1
I didn't quite got what it was all about, so I've looked at this.
https://www.researchgate.net/publication/3410916_Terrain_decimation_through_Quadtree_Morphing
Then I've got some understanding. It was about decimating the more distant patches of the terrain.
And then I've just wondered about one thing. At every frame, the mesh is re-generated and re-uploaded. Wouldn't it be kinda of slow?
Ran the demo provided in the first link and got just 3 fps. What's the big idea of this "optimization"?
My current code has 1048576 vertices for 1024x1024 heightmap, undecimated, and it runs way faster. His code makes my laptop hot.
Another link.
Quadtree vs multiple resolution grids for terrain rendering
That is more useful. It turns out that there might be some mipmapped meshes on the GPU, and the quadtree decides which of them are turned on.
The first question. Is my last guess correct?
Second - am I right the first link isn't useful anymore?
Third - how this applies to modern Android development (I mean at least GLESv2).

It sounds like you already have an even better answer than we could give you: you profiled the code to see how it actually runs. Now you yourself have everything you need to choose the technique that gives you the performance you need. What more are you wondering? We're not going to tell you to use something slower than your current method if it works fine for you.  ;)

I've thought some more on it and found a better way. Imagine that I have a fixed mesh that always follows LookAt function center except for z coord. It is log space in +x and -x, exp space in +y and -y(forward to camera) and 0 z. It is flat nonlinear terrain. Then I displace it in vertex shader with a texture. The texture is mapped to world space, the mesh in view space. So when the camera moves the vertices would have different values while the mesh would not move.

And because it's a terrain, the world space is also the tangent space. So the normals for such a dynamic terrain might be calculated with just 3x3 Sobel kernel over the heightmap.


text:
Split the camera into sections?
I have a layout for my game similar to this:

Where the light gray area is reserved for HUD elements and the dark gray area is reserved for the actual game. One function I want to offer in the dark gray area is the ability to zoom and move around, which works independently from the light gray area, meaning that no matter how far I zoom in/out or how far I move, the light gray area remains unaffected.
How can I do this without always taking the offset center into account? How can I completely separate the game play part and the HUD?

You can set your UI Canvas to render in ScreenSpace - Overlay, so it's mapped to the screen/window, layered on top of everything at the end of the rendering passes, independent of any camera.
You can configure your camera to render to only the bottom-right section of the screen/window by configuring its viewport rect in the inspector or via script.
For example, to render the camera's view to only the bottom-right 80% of the screen/windows's width & height, you'd configure the viewport rect to:
x: 0.2   width: 0.8
y: 0.0   height: 0.8


text:
How to make sure an object NEVER passes through an edge collider (2D)?
In my top down perspective game, I have a ball that bounces off of walls. The ball should behave in a way where it will always bounce off in a 90 degree angle. The ball can only move up, down, left and right and the walls are slanted so that they should always (theoretically) bounce a ball up, down, left or right.
On the ball object, I have a small circle collider 2D and a Rigidbody 2D attached, the walls have a single edge collider 2D attached. Approximately one time out of twelve times, the ball will simply pass through the edge collider, so it's not consistent.
How can I make sure that the ball always registers the collision?
Here's my setup:

The script I use to move the ball:
void Update () {
    switch (direction)
    {
        case 'u':
            transform.Translate(0f, ballSpeed * Time.deltaTime, 0f);
            break;
        case 'd':
            transform.Translate(0f, ballSpeed * -1 * Time.deltaTime, 0f);
            break;
        case 'l':
            transform.Translate(ballSpeed * -1 * Time.deltaTime, 0f, 0f);
            break;
        case 'r':
            transform.Translate(ballSpeed * Time.deltaTime, 0f, 0f);
            break;
    }
}

Additional info:
 - every wall is it's own object with it's own edge collider.
 - the ball always hits the center of the wall because I center the ball object using the center of the wall it touches. Note: I had issues with the ball passing through walls even before I implemented the centering.

Looks like you're making the common error of moving the transform instead of the rigidbody when you want physics behaviour. See this answer for more details on why that causes problems.

Can you post a screen of your scene?

It also looks like your circle has a very small radius, which could cause precision errors. What happens if you significantly increase the radius?

@EdMarty I think I already tried that, and it didn't really help. The ball would still sometimes just pass through the wall.

This is happening because collisions happen in fixed update and you are moving the ball by its transform in the update. You should instead use Rigidbody.MovePosition, or apply a force to it instead or make it kinematic and move the transform but in Fixed update. Take a look at the rigidbody manual and this.

This is true for sure.  However, I have a similar situation that I haven't solved in a year now.  I've tried both RigidBody and non-RB physics and found that in some cases even slow moving objects don't always collide "as expected".

@JesseWilliams I suggest you supply sample code of that specific scenario, then, as there is otherwise no way for people to guess at the issue you are experiencing.

Guys, remember that this is a comment section of an answer. Not another question thread. Please keep any comment specific to the resolution of the original question.

@Alakanu Solved my issue, now the ball always registers the collision. However, now it also behaves strangely when it collides with a slanted wall (/) from the right. Instead of bouncing off from the middle, it "slides" down the wall before continuing straight down. Any idea why that might be? I have a script that centers the ball whenever it hits a wall using the center of the wall, but it somehow works for all interactions except for the ball hitting a / wall from the right side.

I wasn't asking a question, I was giving feedback on the response - that there are still some instanced using kinematics or not, where the engine doesn't describe the motion or collision properly.

@noClue hard to say withouth knowing what is supposed to change the direction the ball travels to

@noClue That sounds like a new problem.  If this answer solved your initial problem, please mark it as the answer.  THEN ask a new question. =)

@Immersive I would love to, but I don't want to give up rep every time just to get some attention to my questions... I hoped I might get some more help here before I pick an answer, but whatever.

@noClue we are fellow developers helping each other, don't think of this website as a place where you are being provided a service. If you want more help, either make your question broader or ask another question.

@Alakanu Who said it was a service?

The fact that you feel like you should receive more.

@Alakanu That's not a fact, that's what you assume. Thanks for leaving out the @ btw, very sneaky.

???? "I don't want to give up rep every time just to get some attention to my questions" this is not a fact I assume. This is you thinking you are "paying" us with rep. It's not how it works.

@Alakanu Again you're just assuming stuff, and why are you leaving out the mentions, do you just want to have the last word or what? I'll let you have it if you want it this badly. Don't put words in people's mouths as if you know what their intention was. Me saying I don't like giving up rep is me commenting on how Stackoverflow doesn't show certain questions enough, so as a result I have to give up rep to make the website show my question more often. Nothing about me expecting service here, more me fighting against the algorithm with a limited amount of rep.

@noClue sir, you are overreacting. I consider this conversation over.

@Alakanu "Sir", I'm just giving you some of your own medicine.


text:
Are most cross-platform C++ libraries really not cross-platform for game developing?
Sorry for my poor English.
Some cross-platform C++ libraries are useful for game developing, e.g., Eigen, Skia, OpenCV, Tensor Flow.  I am not sure whether they are really limited to officially stated supported platforms (desktop and mobile only) without supports on game console and web platforms.  Thank you.
 I just want to conform it.  Let me know whether those libraries are indeed very limited in terms of cross-platform portability for game developing.

Is there a particular task you need to do that you don't find supported out of the box in Unity? If so, asking "How can I achieve Feature X in a cross platform way?" might help focus answers on more constructive solutions that actually move you towards your goal. With your question currently as broad as it is, I think the only answer that covers all the cases you've described is "it depends on the library" — something you probably already know from your research so far. What can we help you solve that will help you move closer to completing your game?

You seem very focused on C++ libraries. While you can write native C++ plug-ins for Unity, typically C# is what you code/script your game with.

This still falls under the "what technology to use", as "does library X support feature Y" is used just for that (without mentioning that these are not "time agnostic", and can be answered by yes or no).

Thanks.  I don't know how to properly rephrase my original question.  I try to simplify my question as this question


text:
How do 3d game engines draw this pattern?
I am doing a small project, where there is a 3d engine, however I do not know how to draw something if it is like the image below. Usually I would draw from farthest back to closest. But here there is no order? How would modern 3d Engines draw this?

Just to make sure, you want to know how you could draw something like that in the 3d engine that you're writing, is that right?

Yes, or at least how it is down in other engines.

The keyword you are looking for is z-buffering.
When a polygon-based rendering engine calculates the pixels covered by a triangle, it doesn't just calculate its x- and y-coordinates on the screen for each pixel, but also it's z-coordinate. The z-coordinate is its distance from the screen.
The engine also creates a z-buffer for each frame it renders. The z-buffer remembers if the engine already drew something to each x/y coordinate, and if it did, what z-coordinate that pixel had. Before the engine calculates the color of a new pixel, it checks if there is already a value in the z-buffer for these coordinates with a lower value than that of the current pixel. When there is, the pixel gets skipped. When there is not, both z-buffer and the image on the screen get overwritten by the current pixel.

Yes, this looks like what I want, it seems a bit expensive though as you have to find the co-ordinate of each pixel and compare it.

@teclnol Not really. The z-buffer is basically a two-dimensional array of floats with the size of the screen and the z-coordinate of a pixel is usually a by-product of the perspective calculations you have anyway. It in fact works so well that 3d engines usually try to render scenes from front to back to avoid unnecessary overdraw.

Yeah that part isn't, I was just unsure of how to find the z value of each polygon. Before, for each triangle I would find each of the three vertices of that triangle on the the 2d screen, then draw a triangle screen, which means I wouldn't know the z-values of the center of the triangle, just the vertexes. It seems a bit expensive to find the z-value of each pixel in the triangle, I am actually a bit unsure how to in fact.

@teclnol Have you heard about projection matrices? The standard method to convert 3d vertices to 2d screen positions is by multiplying it with a matrix, and the z-coordinate is a natural by-product of it.


text:
Temporarily ignore collision?
Same premise as this question. When the ball bounces off of a wall, I want the ball to temporarily ignore all further collision events of the wall it just collided with, for three seconds for example. What's the best way to accomplish this?

There are several ways to do this, using a coroutine:
Disabling the collider
GetComponent<Collider>().enabled = false ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    GetComponent<Collider>().enabled = true ;
}

Turning the collider into a trigger
GetComponent<Collider>().isTrigger = true ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    GetComponent<Collider>().isTrigger = false;
}

Changing the layer
As indicated by Battle, you can use three layers and the collision  matrix. Supposing your wall is in the Wall layer, you can have another layer Ball and PhantomBall. Ball / Wall will allow collision while PhantomBall / Wall won't.
gameObject.layer = LayerMask.NameToLayer("PhantomBall") ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    gameObject.layer = LayerMask.NameToLayer("Ball") ;
}

Using Physics class
Supposing you have a reference to the wall collider
Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, true ) ;
StartCoroutine( EnableCollision( 3 ) ) ;

// ...

private IEnumerator EnableCollision( float delay )
{
    yield return new WaitForSeconds( delay ) ;
    Physics.IgnoreCollision( GetComponent<Collider>(), wallCollider, false ) ;
}

You can use different layers which do not collide with each other. When bouncing one time, wait 0.5 seconds (maybe not necessary), then switch from layer A to B. After 3 seconds, set it back from B to A.
See also:
Unity Editor > Edit > Project Settings > Physics. You will find a table in which you can set it up as you need. Consider using your own custom layers for your game specific objects.
And some documentation.
And how to set layer via script.


text:
Use a different language for engine and game
Just a quick question that I haven't been able to find an answer to, I am creating an engine for a game, I have begin making the engine in C++ but I want to make the game in java. My question is, is there a way to maker my game in a different language on a separate "layer"?

https://stackoverflow.com/questions/4664899/wrapping-c-c-inside-java

Yes, this kind of inter-operation between languages is doable and in fact fairly common. For games, it's typically done as part of implementing a scripting system, which may give some hints as to where to look for further research.
The specific process depending on which languages you'd like to pair together. Almost all languages you're likely to use have some kind of inter-operability mechanism, most of them based on the standardized ABI of C.
For Java in particular, you'd want to look at the JNI (or possibly other community projects like JNA). The JNI will allow you to call functions implemented in C from your Java code, so could implement your "engine functionality" in native code but have your game logic written in Java.
One way to go about this is to declare the existence of the native methods in Java using the native keyword, generate a boilerplate header using the -h flag of the Java compiler, implement the native functions in that header in C++, compile the result into a shared library, load that library from Java and call the functions.


text:
Instantly snap into specific directions?
In my 2d setup, I want the player to constantly move in a specific direction at a set speed. It's similar to "Snake" in that you can only move in four directions and you can't stop your movement.
Right now, the way I do this is by having a char variable "direction", which can either be u, d, l, r (take a guess what those stand for). Based on those letters, I use GetComponent().MovePosition and increase/decrease the position on the x or y axis.
Is there a better way to do this? I would prefer if I could just enter the degree (0, 90, 180, 270) to make the player move in the right direction. I tried AddForce but I couldn't get it to work.
Side note: it's important for me that I can set the direction without player input, as there are some objects that force the player into a different direction.
Edit: As the tag would suggest, I'm looking for a Unity specific answer, as I'm not sure which function would best suit my needs.

Possible duplicate of How do I make an entity move in a direction?

@Bálint I fail to see how that's relevant to my Unity specific question. Maybe to explain the concept, but I'd like to know how it's done in Unity.

Here's a solution I found thanks to help from @cmprogram.
Rotating the object:
rb.eulerAngles = new Vector3(0, 0, angle);

Making the object move in the new direction inside FixedUpdate:
rb.velocity = rb.right * speed * Time.fixedDeltaTime;

Very simple.


text:
Designing client-server to mitigate hosting advantage?
My game will be client-server, and I'd like to prevent the hosting player from enjoying the usual benefits you'd associate with playing on a server.  For example, the advantage of the server running ahead of time compared to clients.
Are there simple ways of mitigating host advantage?  Or do I have to make something complicated?  My naive solution would be having the host run a "ghost" state, and a client state, on the same map.
The ghost state is an authoritative server simulation, it doesn't render the simulation which remains invisible, but does run ahead of time making calculations and decisions as usual.  The host also plays a client on the same map, in which their input is regarded as any other client across the network, and like any other client is required to wait for the server simulation to make and transmit outputs.  And so the host doesn't enjoy an advantage because they aren't playing the simulation which is making executive decisions on the game state ahead of client time.
Has this solution been done by any other games, or is there a better way of handling the problem?

The best way to minimize host advantage is to have good lag compensation which makes sure that the outcomes match what the players see on their screens.
For example, When you are developing a first person shooter and want to know if a shot hits an opponent, take the latency of the shooter into account. If the shooter has a 40ms ping (round-trip time server->client->server), then check all hit collisions from the positions where the shooter was 20ms ago and against where the opponents were 40ms ago. That way you are detecting hits against what they saw on their screen when they pressed the fire button. When the victim's HP get reduced to zero that way, declare them dead but give them a grace period equal to their latency in which their shots are still counted (they made these shots before they saw their character die).
Yes, this might occasionally lead to implausible outcomes, like two high-pingers killing each other simultaneously with Hitscan weapons. But that's what you get with online gaming.
Lag compensation is a very wide topic, and the best practices and applicable techniques vary depending on the genre of your game. If you have any questions about how to mitigate lag advantage in a specific situation, feel free to post another question.


text:
What to use if you want a looping list?
No, I'm not talking about foreach. I have the following list:
public List<float> angles = new List<float>(new float[] { 0, 90, 180, 270 });

This list can vary depending on the object I use, having only 0 and 90 or all except 270 for example.
What I want to do is have a rotClockwise and rotCounterClockwise function that grabs the value before or after a given value. Here's some pseudo code:
function float rotClockwise(angle) {
    return angles.grabNextAngle(angle);
}

function float rotCounterClockwise(angle) {
    return angles.grabPrevAngle(angle);
}

So calling rotClockwise(90) would return 180, rotCounterClockwise(90) would return 0, rotClockwise(270) would return 0, etc.
How can I accomplish this? Is there a list type that allows me to loop back to the beginning when I reached the end?

AFAIK there is no class in the C# standard which works like a circular list. However, it is quite easy to build such a class yourself:
public class RotatingFloatList {

    private int current = 0;
    private float[] values = new float[] { 0, 90, 180, 270 };

    public float GetCurrent() {
        return values[current];
    }

    public float GetNext() {
        current++;
        if (current >= values.Length) current = 0;
        return GetCurrent();
    }

    public float GetPrevious() {
        current--;
        if (current < 0) current = values.Length - 1;
        return GetCurrent();
    }
}

Try it online!
Exercises for the reader to make this class more reusable:

Have it take the values from a constructor.
Turn this into a generic class so it can be used for other things than floats.

Add extra values so it seems to wrap and use IndexOf in the correct range to avoid overflow.
public List<float> angles =new List<float>(new float[] { 0, 90, 180, 270, 0 });

float nextAngle(angle){
    return angles[angles.indexOf(angles, 0) + 1]; //looks from the start and
    //will never pick the last element because it's a duplicate of an earlier one
}

float previousAngle(angle){
    return angles[angles.indexOf(angles, 1) - 1]; // looks from index 1 and will never pick 0
}

However using floats like that isn't ideal because if you ever get a rounding error then indexOf will return -1.
Using an enum NORTH, EAST, SOUTH, WEST for this is a better idea with a conversion to the actual angle or orientation when needed.

A circular buffer is simple to implement, you can do it as Philipp suggest or you may - for example - use index % array.Length to query (unless the index is negative).
Remember that accesing a negative index of the array is an IndexOutOfRangeException.
However, what you want is something slighly different, since you want to find the previous and next items given a value.
Assuming we start with a sorted array, we can do this with Array.BinarySearch. We will not use IndexOf for reasons that will become clear later.
First, our array:
var array = new float[] { 0, 90, 180, 270 };

And what we are going to be looking for:
var query = 10;

I will add rotClockwise and rotCounterClockwise to store the adjacent values...
float rotClockwise;
float rotCounterClockwise;

Then, we execute the Array.BinarySearch...
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);

Ah, but it would return negative if it is not found, we need to check that...
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    // ...
}
else
{
    // ...
}

If the result is positive, it is easy, just add or substract 1 to searchResult:
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    // ...
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

Now, when it is negative...
Remember that accesing a negative index of the array is an IndexOutOfRangeException.
Array.BinarySearch is actually telling us where we would, in theory, insert the new value... (This is why we do not use IndexOf) we have to start by getting the bitwise complement of the result:
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    searchResult = ~searchResult;
    // ...
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

Now, since that is the index where it would be inserted, it is also the index of the first item that is larger than the query... unless the query is larger than all, in which case we want to get the first item. In either case index % array.Length will do.
Ah, and for the last item larger than the query, we just substract 1.
float rotClockwise;
float rotCounterClockwise;
var searchResult = Array.BinarySearch(array, query);
if (searchResult < 0)
{
    searchResult = ~searchResult;
    rotClockwise = array[searchResult % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}
else
{
    rotClockwise = array[(searchResult + 1) % array.Length];
    rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
}

And there you go. Well, almost, the code is not aware that these are angles...
You can transform the input like this (not optimized):
if (query < 0)
{
    query += (1 -(int)(query / 360)) * 360;
}
if (query >= 360)
{
    query -= (int)(query / 360) * 360;
}

... and optimize, error check, encapsulate as needed.

I have adapted the code like this:
public static void Main()
{
    var array = new float[] { 0, 90, 180, 270 };
    var queries = new float[] {-1000, -15, 0, 1, 10, 90, 95, 300, 270, 780};
    foreach (var item in queries)
    {
        var query = item;
        if (query < 0)
        {
            query += (1 -(int)(query / 360)) * 360;
        }
        if (query >= 360)
        {
            query -= (int)(query / 360) * 360;
        }
        var tuple = Rot(array, query);
        Console.WriteLine(item + " = " + query + " Clockwise: " + tuple.Item1 + " CounterClockwise: " + tuple.Item2);
    }
}

public static Tuple<float, float> Rot(float[] array, float query)
{
    float rotClockwise;
    float rotCounterClockwise;
    int searchResult = Array.BinarySearch<float>(array, query);;
    if (searchResult < 0)
    {
        searchResult = ~searchResult;
        rotClockwise = array[searchResult % array.Length];
        rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
    }
    else
    {
        rotClockwise = array[(searchResult + 1) % array.Length];
        rotCounterClockwise = array[searchResult == 0 ? array.Length - 1 : searchResult - 1];
    }
    return new Tuple<float, float>(rotClockwise, rotCounterClockwise);
}

Output:
-1000 = 80 Clockwise: 90 CounterClockwise: 0
-15 = 345 Clockwise: 0 CounterClockwise: 270
0 = 0 Clockwise: 90 CounterClockwise: 270
1 = 1 Clockwise: 90 CounterClockwise: 0
10 = 10 Clockwise: 90 CounterClockwise: 0
90 = 90 Clockwise: 180 CounterClockwise: 0
95 = 95 Clockwise: 180 CounterClockwise: 90
270 = 270 Clockwise: 0 CounterClockwise: 180
300 = 300 Clockwise: 0 CounterClockwise: 270
360 = 0 Clockwise: 90 CounterClockwise: 270
365 = 5 Clockwise: 90 CounterClockwise: 0
780 = 60 Clockwise: 90 CounterClockwise: 0

Try it online!
Addendum:
Of course, this code can be made generic. You may not want to deal with float. You may also be interested in supporting an IComparer<T> interface, there you can check with your prefered method of comparing floating point numbers.


text:
Do old games still generate revenue for their developer companies?
For the purpose of this question, let's say an "old" game is one released over 20 years ago, or for which the platform it runs on has become unavailable.
Do the developers still earn revenue off of titles this old?
If the answer is no, why aren't more of these titles made available for free (officially)?

What do you think the current surge of companies releasing retro consoles and their titles is about. Or nintendo's virtual console.

Tibia makes more money than ever, and it's almost 22 years old.

Yes, they do. You never know if an IP you considered worthless might become valuable again.
For example, 10 years ago nobody thought Sega and Nintendo would ever make another cent from their 8 bit and 16 bit games. But then came the pixel art retro boom. Sega released a bunch of their Mega Drive catalog on Steam and Nintendo created the Virtual Console to re-release their old classics on their new systems. I don't think any of these old games really sell that many copies, but it's nevertheless revenue on investments which were already written off ages ago.
There are also specialized stores like Good Old Games which try to re-monetize older PC titles (although they recently re-specialized and also sell new releases).
But often releasing an old classic can be more trouble than it's worth. Possible barriers are:

Unresolved copyright questions. Game companies get formed, sold, merged, split, renamed, closed, liquidated, bought etc. all the time. Often multiple companies work together and share the copyright to a game. Sometimes you have things like music tracks, brands or technology which are licensed from 3rd parties and the contracts do not explicitly allow a re-release. Trademarks might have expired and other game companies might have registered similar trademarks in the meantime. The resulting chaos can often lead to a situation where nobody is really sure who has the necessary rights to re-release an old game. If the game would have a large economic value, it might be worth it to pay some lawyers for a few dozen hours to find out, but often just that alone might be more than the economic value of the game. A good example was the drama surrounding No One Lives Forever. tl;dr: multiple game companies said "Maybe we have the rights to the game according to some contract buried in some file cabinet, but we don't care enough to find out. But if you try to release it, we will find out and if we do we will sue you!"
Waiting for the right moment. They want to see if the IP might become more valuable. Maybe the company got some plans in the shelf to revive an old review in form of an HD re-release? Maybe they are waiting for the retro gaming boom of that particular era of gaming history? If they release it now, they might lose out on larger profits in the future.
It might cannibalize your actual market. People don't need to buy any of your new games while they are busy playing all your old games. While you might not really lose a large number of sales that way, you might lose at least a few sales if the timing is bad.
The PR effect for your company might actually be negative. One could argue that releasing your old games for free could be a great advertisement for your new games. But keep in mind that the perception of old games through nostalgia goggles is often far better than it is when you actually play those games. So the halo-effect* your old game has on the perception of your new game might in fact be negative. This is a risk which is hard to estimate, but it is there and might cause management to hesitate.
There is no reason to do it. Even if you release an old game for free in an "as is" state, you need to write a press release, add a download page to your website, pay for server capacity for the download, might have legal liabilities, might have to offer support, etc.. All of these are peanuts compared to the costs associated with a "real" release, but the benefit minus cost calculation of $0 minus peanuts is still negative.

*has nothing to do with the game Halo

At least some do although perhaps not in the way you are thinking. Old, but still new enough to be digitally distributed games could still bring in the occasional revenue. But games with physical aspects (cartridges) are eventually no longer manufactured and eventually their first-party sales revenue will dry up.
However, it may still be possible to make money on the licensing of the IP or sale of related property, and a company may account that as revenue from from products.
As for why “old” games aren’t always released for free, well, it tends tends to come down to the fact that the owner wants to maybe make money re-releasing the game in the future or that making it available for free would actually cost them (in manufacturing, hosting or support for example) and thus not be an attractive business proposition.


text:
How can I create a 2D sprite shadow like in "Alto's Odyssey"?
I've seen that the game "Alto's Odyssey" has a very nice way of projecting shadows on the ground the player is sliding on:

How could i replicate that?
Would I use some shader magic, or by projecting a 3D mesh/image on the ground plane?

I don't know how the game looks while you are playing (how the shadow moves) but from the screenshot it looks like you just take the player's sprite, mirror it and scale it down on Y and place it on the ground. There is no point over complicating stuff with shaders and 3D meshes for a 2D shadow.

@TomTsagk the shadow squashes down when the player gets close to the ground, and gets stretched when he goes up

@TomTsagk that way though it wouldn't look believable...

drop shadows aren't realistic anyway, they are mostly so players can know where the player it relative to the ground.

@GabrieleVierti Exactly what you describes is what you can do on a 2D game. Squash down the shadow sprite when the player gets close to the ground, and stretch it when he goes up. Wouldn't look believable? I made a game once with a simple black circle for a shadow, that shrinks as the object gets away from the ground. Realism is not the only answer to make something believable in a fantasy world.

@TomTsagk I'd upvote an answer about the technique you describe with a little more detail.

Wow, I had never noticed the shadow before...

My approach would be similar as mentioned in the comments.
I would take a grey copy of the sprite and would have it mirrored.
I would set an offset for the shadow which depends on how far the player is away from the floor. You can use Rays to check that.
I also would apply the rotation of the player object to shadow object inversed (just the negative value).
The shadow depends on how you set your imaginary light source. so you can use other values. But I would say.
float shadowOffset = playerheight / 2; //so shadow is always halfway-> for realistic light effects
position = currentFloorPosition - new Vector2(0, shadowOffset);
rotation = -playerRotation; //not sure about this line that it works
shadowScale *= (shadowOffset * adjustValue) //maybe you need a adjust value which makes sure that the shadows size is good
//code to find the actual postion of the floor

so in this code example, you get a rough idea. You need to find the current position of the floor because it´s not constant as it´s curvy. You could also use the player position as a reference point for your shadow offset but I would be scared that the shadow jumps off the floor.
To find the current position of the floor you could use a ray or a line cast and use the hit point as the current position.
If you have any questions feel free to comment or message me.
I hope I could help you. BTW these lines are more pseudo code than the real working code you might tweak some values etc.

I hope I thought right that shadows get bigger as you get farer away from your floor :P


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

What specific part of a specific tutorial did you find unclear or unsuited to your needs?

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