text:
User magic creation system that isn't programming
I would love to create an RPG with a magic system in it that gives the player a LOT of freedom.
To the extent they can make their own spells, systems of magic etc., bind spells to items, and so on.
Spells and magic would obviously have constraints, but doing lots of research into magic, and spending time creating spells etc. should allow players to create more and more powerful spells.
I'm really struggling how to come up with an interface through which they can create spells that isn't directly similar to programming. I don't want it to be so simple/boring as typing a sequence of commands that get triggered by clicking on a wand and calling that a spell.
I would love it if it were less human-intuitive, linearity combinations etc. weren't obvious or easy to figure out, and it was possible to explore the magic system deeply to discover more complex ways to piece together magics.
Are there any precedents? Does anyone have any ideas on how such a system could be implemented?

The Elder Scrolls: Oblivion had some spell creation mechanics in game: https://en.uesp.net/wiki/Oblivion:Spell_Making

@disc_code22 that looks too boring/simple. Just setting parameters on existing spells, and running a few at once.

Do you know Path of Exile? The abilities there are considering one main spell and up to 6 modifiers that the player can add as they like. They can choose from hundreds and it ranges from multi case, more projectiles, element converting to totems casting it.

Maybe an interface similar to Unity shader graphs could be considered? Please ignore the specifics in that image, and imagine its properties and images were all about magic effects.

The spell system in Magicka is also an interesting read when delving into a topic like this.

@disc_code22 The system in Oblivion isn't very well designed, IMO. It allows the player to create ridiculously overpowered spells without even trying to find any obscure exploits in the system. If anything, it serves as a good example of what not to do. It's quite a while ago that I played Oblivion, but I remember very well that the moment I had unlocked that system, the difficulty curve took a nosedive.

Approaching it from a different angle, something I was really touched by was Zelda BotW's elements. You can use all the old standard magic, but when that magic interacts with the environment, it's beautiful. Fire on grass creates an updraft. Lightning in water makes the attack AoE. Water puts out fire. Now you don't just have enemies that are weak to a certain element for "reasons," you have situational gameplay where your magic is more useful

Noita did a decent job at this.

A system of base spell types with a robust selection of modifiers may suit your needs.
For example, a fire ball spell might normally lob a ball of fire in an arc in front of you, that explodes upon hitting a surface or enemy.
At this point, modifiers can be linked to the spell. Depending on the style of the game, these can be explicit modifiers that state exactly what they do, or more esoteric runes that only hint at what effect they may have.
Some examples of possible modifiers:

A modifier that makes a spell bouncy would make the fireball bounce
off surfaces until it hits an enemy or times out and explodes anyway.

Several mods could affect spell trajectory, making spells fly in a
more predictable manner, or giving them a wild unpredictable snaking
or zigzagging pattern.

A mod could cause the spell repel itself from nearby surfaces

Spells could leave a puddle of water when hitting a surface. Consider now that this might create a synergy with a fireball base and a bouncy modifier, where every time the fireball bounces it creates a puddle of water which is then turned into a cloud of hot steam on every collision with a surface.

To add some depth, modifiers that make a spell easier to use may decrease the overall power, while adding more chaos into the mix rewards the player with a higher damage but harder to use spell.
If a large variety of base spells and modifiers are created, the player can then explore and theory craft how different combinations will work for (and against!) them. A fire ball thrown like a boomerang, may not be ideal for the players well being, for example.
An example of a game that utilizes a system similar to this is Noita. It goes even a little bit further by having wands that effect the spells and modifiers slotted in them.
Here is a wiki link to a list of the spells / modifiers in Noita as a reference.

huh, never heard of this game before, that system is surprisingly complex. I do think that the "back end" of it is what OP wants, but the interface seems to be more programming - like which is what they want to avoid.

A fire ball thrown like a boomerang, may not be ideal for the players well being That's a fun way of saying players can blow themselves up, right?

@Mars Right. I think some inherent risk is important in a system like this to help avoid reduction into a numbers game where spell crafting is over-optimized to be as effective as possible. If there is risk involved with a more powerful / useful spell, the player has to play a balancing game with utility versus their own safety.

Check out the magic system in Stonekeep, where runes are combined to add modifiers. It is one of the best magic systems I have seen.

What you want is something that is unpredictable yet consistent but lets the player make an educated guess, with power progression.
Unpredictable
The more "input" your spell system can take, the more chaotic the results can appear. Have your spells take both a mix of components as well as an incantation (arrange runes, take some text input, draw a constrained pattern with the mouse/touchpad/joystick).
Consistent
A couple of behind-the-scenes formulas take the inputs, convert them to numbers and spit out more numbers that result in some basic values for your spell (its range, energy cost, power, effect strength). You can use the input or a part of it as a seed for a PRNG, which gives random numbers, but always the same ones if given a specific seed and state. The point is that if the player makes the spell exactly the same way twice, it should come out exactly the same way.
Educated guessing
Add some rules to your calculations that let certain components vaguely relate to the final results. Perhaps a certain herb always makes the spells made with it affect the undead more. Maybe one of the runes (nearly) guarantees a longer range or wider spread.
Power progression
Make more components available as the player progresses and have the player's own statistics play into the spells. The Fireball cast by a novice mage barely singes a monster's hair; the one a Grandmaster Wizard can muster will only leave a blackened spot and a foul smell in place.
Multiple ways of casting
Make the magic effects different depending on who or how they're cast upon. An ice spell can make the ground slippery, freeze an enemy in place or extinguish the spellcaster who's been set on fire.
Randomize the rules
If you want each playthrough to be unique and the spell creation, testing and learning aspect to be an important game mechanic, make the rules random every playthrough - so that people don't memorize/write down in a wiki all the strictly best combinations. Alternatively, don't, and now you have a nice emergent magic system going.

Not sure what "unpredictable" means, but that sounds like the opposite of what I'd want. It sounds like OP also wants something systemic, like programming, without the tedium of programming.

@Mars second to last paragraph, OP wants something that isn't easy to figure out. Unpredictability means there's no telling what the result will be of any particular combination, but the outcome is always the same so once the player learns a good combination they can reuse it.

Ah, when you put it that way, I see what you mean. I didn't know you were responding to that particular point there. Sounds god-awful though. "Hey, we have 2^10 spell combinations, with no particular patterns! Good luck spending every waking second for the rest of your life finding something good!"

I also suggest to have some vague direction to it so that it is possible to "hint" towards specific effects. Perhaps a few pre-existing spells to ease the player into the system could be a good idea.

I think less human-intuitive probably wasn't what OP wanted to say. You can have complex results where you might not realize side effects at first, but if it's not easy to understand, it's just not going to be fun

This will definitely require a lot of tweaking and playtesting. It may also be a game mechanic without mass appeal. There hasn't been any obvious feedback from OP yet, perhaps I missed the mark entirely, or was right on point, or right in between.

First of all you need to make it clear to yourself what kind of magic system you really want. As far as i know there is no common definiton for it, but i would call it scientific magic vs blackbox magic. You want scientific magic.
Blackbox Magic is somewhat unapproachable, unintuitiv and not explainable. Most games like Skyrim and most other games do it like that. There might be a source for the magic, but magic effects are just THERE. And either they are usable and recreatable (by casting spells or binding them to items) or they are part of the world (like magical creatures, portals and other magical effects).
Scientific Magic is what i like to call magic that is approachable, repeatable and able to get almost infinitly complex. Instead of the caster saying 'Fire ball' and a flaming ball of exploding fire flies in the enemies face, the caster understands, that his spell first weaves a ball of in a magic matrix, fill that ball with mana, adjust this infused mana with the aspect of fire and propel it with a fling of another magic matrix. If this sounds like an engineer process... well, it is. And as this all seems constructed, maybe there is a way around it.
So to design this engineering approach, i also want to adress some of htmlcoderexe's examples, as i find some of them quite fitting, while others not so much.
Approachable
As i said, this kind of magic has to be approachable. What i mean is, that in its basics, it should seem logical. Fire is hot and the opposite of cold. If something is moving, a force has been applied, etc.
Your magic system needs to have basic elements, that do something, but not a lot.
In addition to that, if you combine two of those basic elements, something different might happen.
Repeatable
Lets combine two elements and try the spell -> Something happens.
Combine the elements in the same way -> Same thing happens.
Combine the elements in another way -> The same thing or something different happens.
Anything else and the player might be discouraged to try something new because... something new could happened if he does the same thing again... so why change?
Infinitly complex
Now instead of two basic elements, build some more complex elements from several basic elements, combine those to a greater effect (and more mana required) and to create more complexe elements or to archive different effects.
I dont want to trick you. To archive this kind of depth, you certainly will to implement some kind of 'Programming', but the trick is to not let the player have the feeling that it is. So lets design it.
The idea
Imagine this. In your world is a language, that conveys magic effects into the real world. Something like the dragon language from Skyrim.
Lets asume you have some basic words (our basic elements) your player starts with. Deep down in a ruin, he finds the word for Iref, but does not know, what it does. He speaks the word and something in his hands begins to burn, maybe even some of his clothes. From this he knows, that Iref is Fire. Not very useful yet, but somewhere else he finds the word Llab and casts it, and he sees a 'ball of magic' infront of him.
As a natural explorer, he tries 'Iref Llab' and a magic ball filled with fire appeares. It does not move and if touched, it just bursts like a bubble, not like an explosion. And so he tries to find new words and combines them.
To implement it, let the player have some kind of writing board, where he writes those runes (maybe more like drag and drop) or something and arrange them like he thinks it is right. Technical this IS programming, but the fun behind is to figure out the way you are able to programm more complex stuff.
Now you can think of other ways to modify the interactions. E.g. instead of fire the player gets Temperature. Now it makes a difference how he combines that with the ball. 'Temperature Ball would be a ball filled with fire, while Ball Temperature would be an ice ball. ** Temperatur Ball Velocity ** would push that Fireball away from the caster, while Velocity Temperatur Ball would push the ball against the caster etc.
Later on an experienced caster would get more complexe elements like **temperature ball* or ** ball temperature* as an own Word to implement in the spell, and even this could be combined to more complex spells.

A fire ball that really explodes
A Healing Aura with different targets
Creating intelligent creatures from differen basic elements
A ball filled with multiple fireballs (something like a cluster grenade)

Evolution instead of programming
Simply put: the player chooses spells and then obtains mutations and combinations of these spells. Repeating this step will eventually refine spells to a player's liking, without requiring any programming.
In the context of evolutionary algorithms, the player would determine the fitness of spells by experimentation.
But be warned, that writing good mutation and crossover functions, for things with the same level of sophistication as programming, can be very challenging.

Have each spell consists of a power level, a projection method, an element, and a series of optional modifiers controlled with slider bars.
The power level determines a spell's base mana cost, required user level, etc and will scale up the potency of the spell as it is increased.
The projection component says if it is a touch spell, a line of sight spell, an aura, an AOE etc.  Each projection also has fixed co-effecants that apply to it such as base potency, range, radius, rate of fire, etc. These values are balanced against each other such that each projection's baseline efficiencies are make since against their weaknesses.
The element determines what a spell's power actually means.  A fire element would turn a spell's potency into fire damage, but a heal element would turn it into a health recovery, and a root element would use the potency to determine how strong of a monster it can hold, etc.
Lastly you have your modifiers.  These are sliders that are dynamically added to the UI based on the projection and element type.  For example, an AOE might have sliders for More Damage <-> More Radius, More Damage <-> More Range, and More Mana <-> Longer Cool Down, etc.  and a Fire element might have additional sliders for things like Quick Weak Burn <-> Strong Long Burn, and Burn Chance <-> Initial Damage, etc.
While this sort of system opens up countless spell combinations, the UI is can be entirely managed through a simple series of drop downs and sliders that anyone should be able to easily grasp.
As for the research thing, this could be approached 2 ways:
One is player knowledge based research (IE: Meta Gaming).  If the system is complex enough, "un-intended" metas and exploits will crop up.  You can leverage knowledge of these metas through intentionally lacking and vague in game descriptions of things. So don't tell players this effect has 50% armor penetration and 25% less damage, just tell them there is a trade off and force them to experiment to see when those trade offs yield the best results.  You can further this by adding Easter Egg side effects to abilities that you just do not mention at all like making Light based AOEs and Auras break stealth or making casting ice spells break burn effects.   As a result you will see more experienced players and factions naturally rise to the top by knowing how to exploit these esoteric knowledges.
Example of Meta gaming based research: Lightning attacks get a massive to-hit bonus against enemies in heavy armor; so a player cranks the accuracy <-> damage slider all the way to damage letting the lightning easter egg effect compensate for the inaccuracy, then push the range <-> cool down slider all the way to cool down because heavy armored opponents are slower meaning you get to dictate the engagement range. Then put armor penetration <-> damage slider all the way to armor penetration since this spell is specialized at killing tanks.  By exploiting the natural weaknesses of heavy armor, a less armored faster opponent can run in close and bear into him with massive armor penetrating DPS killing an opponent who may theoretically be much stronger.
The other more common way to do it is that you could make all of the above unlockable content; so, you might just start off with 1-2 projection types, 1-4 elements, and no modifiers.  Then as you achieve things whether it be through finding reagents or crafting tools, leveling up, or whatever, you unlock new types and elements as you progress. I personally find this approach more boring, but it tends to appeal better to mainstream audiences because newer players often mistake that which they do not understand with bugs, "bad game design", and hax.  If you start them off limited to few enough options that they can understand it, and expose them slowly to emergent metas, then it's less of a shock to the player.

How does this solve the research and mystique aspects of it? I would like a magic system that players have to delve into and discover for themselves. Can't just present them a slider UI.

@theonlygusti I've expanded on that.  You actually can just give them sliders because no system is perfectly balanced.  The more you give people choices and the less you explain the repercussions of these choices, the more experience will factor into effective spell crafting and and casting.


text:
OpenGL viewport is stretched
For this project I am using GLFW, glad and glm.
My window looks like this:

The dimensions of the window are correct, but the viewport is stretched, making my square into a rectangle.
How do I use a 16:9 resolution (1280x720) without my viewport stretching?
This is what the window should look like:

I have a projection matrix set up in my code, and sent to my shader:
projection = glm::perspective(glm::radians(camera.fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 1000.0f);
glUniformMatrix4fv(glGetUniformLocation(basicShader.ID, "projectionMatrix"), 1, GL_FALSE, glm::value_ptr(projection));

EDIT:
So I update the viewport everytime the window is resized, to it's correct dimensions. But now, even with a 1:1 (600x600) aspect, the square remains a rectangle. So I guess it isn't the viewport's fault? So something else is causing the stretch, as far I know the vertices aren't at fault, seeing as they're correct:
std::vector<GLfloat> vert {
         1,  0,  0,   1.0, 0.0,
        -1,  0,  0,   0.0, 0.0,
        -1,  1,  0,   0.0, 1.0,
         1,  1,  0,   1.0, 1.0,
        -1,  1,  0,   0.0, 1.0,
         1,  0,  0,   1.0, 0.0
};

And the modelMatrix is set up correctly, without any changes being made to it.
My vertex shader:
#version 330 core
layout (location = 0) in vec3 Pos;
layout (location = 1) in vec2 TexCoord;

out vec2 texCoord;

uniform mat4 modelMatrix;
uniform mat4 projectionMatrix;
uniform mat4 viewMatrix;

void main() {

    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(Pos.x, Pos.y, Pos.z, 1.0f);
    texCoord = TexCoord;
}

Do you make sure to update the viewport and projection matrix whenever your window is resized?

Yes, I have a method which gets the window's width and height and adjusts the projection matrix appropriately. Though my problem isn't that the viewport is being stretched, when the window is resized. My problem is that the viewport is already stretched at the start.

Can you post your vertex shader as well, please?

@MaximusMinimus added it

You're drawing a rectangle because your vertices define a rectangle, not a square.

source: Stack Exchange

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

sort: votes


text:
Player sometimes doesn't jump up while moving and jumping at the same time
My issue is that the player sometimes (occasionally) doesn't jump up while moving. It sometimes works, sometimes don't. It's weird, and I am not sure whether it's the code problem, or the tile collider's problem, here's the code:
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    [SerializeField] private LayerMask platformsLayerMask;

    public Rigidbody2D rb;

    public float MovementSpeed = 100f;

    public float JumpingHeight = 100f;

    public BoxCollider2D bc;

    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    void Awake()
    {
        rb = transform.GetComponent<Rigidbody2D>();
        bc = transform.GetComponent<BoxCollider2D>();
    }

    void FixedUpdate()
    {
        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, JumpingHeight * Time.deltaTime);
            Debug.Log("Jumping");
        }
        HandleMovement();

    }

    private bool IsGrounded()
    {
        RaycastHit2D raycastHit2d = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask);
        Debug.Log(raycastHit2d.collider);
        return raycastHit2d.collider != null;
    }

    void HandleMovement()
    {
        if (Input.GetKey(KeyCode.A))
        {
            rb.velocity = new Vector2(-MovementSpeed * Time.deltaTime, rb.velocity.y);
            Debug.Log("Going Left");
        }
        else
        {
            if (Input.GetKey(KeyCode.D))
            {
                rb.velocity = new Vector2(+MovementSpeed * Time.deltaTime, rb.velocity.y);
                Debug.Log("Going Right");
            }
            else
            {
                //no keys pressed
                rb.velocity = new Vector2(0, rb.velocity.y);
                Debug.Log("No key pressed");
            }
        }
        if (rb.velocity.y < 0) //reponsive jumping and falling
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        else if (rb.velocity.y > 0 && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
        }

    }

}

This happens because FixedUpdate() is not meant for input handling, as it runs every a certain amount of time (specified in settings) and not in every frame so it's not guaranteed to run every frame. You should add it to the Update() method instead, which is guaranteed to run every frame.

Thanks, now it works everytime. The issue is everytime I hit play, and then if the first key I hit is a space, then it will bounce super high. But if I don't hit space the first time and instead press d or a to move left to right, the jump is normal.

@SkullCutter You should mark this question as answered, create a new question for your new issue, and post a link to that question in these comments

Why would they accept the answer if it creates a new bug?

@Vaillancourt Because the problem asked is solved. Other people in the future might have the same problem as the one that later occured here and they most probably won't expect to find a solution in the comments. Each question should solve only one specific problem.

No, their problem is not solved, they can't jump the way they want and they have to post a near-duplicate question to get it fixed.

The title question states clearly that the problem is that sometimes the player doesn't jump at all, not that the player doesn't jump the way they want. These are 2 completely different questions.

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


text:
How should shader be structured? (GLSL)
I've been writing, deleting and rewriting OpenGL programs in C++ but usage of shaders confuse me. I don't know how it should be structured.
Scenario A:
(In a world we have a sun, the sun should shine upon everything in the world and on a lake or there would be fog which should only be visible from outside the building but not inside)
So far, I am thinking that I would write a global sun structure in C++ then pass its value to all shaders, then in all used shaders I would write the same lighting functions over and over again.
So I would be repeating codes...
How would you construct your shader program in such scenario?
And Should I write a shader for each model?

I would write the same lighting functions over and over again
...Why?
A shader pipeline is a series of actions:

Inputs from CPU (or GPU, in some cases; optional)
Vertex Shader
Geometry Shader (optional)
Fragment Shader
Retrieve buffers to CPU (optional)

^ At no stage is there any repetition in this sequence.
If you're saying that you need to do the same thing from different places... well, let's say you have two higher level lighting functions called "outdoor lighting" vs. "indoor lighting"; if there are parts of their code that are the same, then you factor these out into separate sub-functions, that you call from different places in your higher-level lighting functions. Most of these smaller functions will be very small, < 10 lines, performing some elementary action.
It's basic Refactoring 101.

I really don'y known why, based on the information i've got right now, I would do as I described but let me clarify my question a bit more, "Should I write a shader for each model"?


text:
Are there functions in GML?
I am trying to learn how to use GML to solve one of my previous prolems, as well as everything I have heard has said it is better to just learn it over DnD. As I have only ever programmed in python I am really fond of my functions, and it is at this point just how I think of code.
Is there any kind of functions similar to pythons in GameMaker?

I've down-voted this question because it does not demonstrate research effort. Please remember to read the documentation for the tools you're using and do your own search with your favourite search engine to see if you can find your own answers. Don't underestimate your ability to solve problems yourself! :)

A basic web search for 'functions in gml' answers your question.

Yes.
Open your favourite search engine and type in "GameMaker function" or "GML function" - your very first result will be this page from the official documentation:

The general definition of a function is something like this: A function has an input and an output, and the output is related somehow to the input. In GameMaker: Studio you use functions as part of the program to make things happen in your game and there are a great number of GML (GameMaker Language) functions available to you, all of which are explained in the Reference section of the manual.
In GML a function has the form of a function name, followed by the input arguments between brackets and separated by commas (if the function has no input arguments then just brackets are used). Here is an outline of the structure of a function:
<function>(<arg0>, <arg1> ,... <arg15>);
Generally there are two types of functions - First of all, there is the huge collection of built-in functions which are used to control all aspects of your game, and, secondly, any scripts you define in your game can also be used as a function (but not always).

You'll also find this other page from the documentation:

Scripts
Scripts are the way in which GameMaker: Studio permits you to design your own functions.
...
The Script Editor
When you open the script editor, you should first give your new script a name. This should be something sensible and easy to remember and recognise, and must not start with a number or have any symbols (except the under-bar "_" symbol). The name you give the script is the one you will use later as a function in code. It is also a good idea to write some comments at the start of the script (see the above image) to outline the script arguments and how it should be used, especially if you are going to work as part of a team, or plan on using many scripts in your game.

Please remember to put in your best research effort before posting on this site. This is a question that's answerable in five seconds with a search engine or a quick look at the documentation for the tool you're using.

If you are looking for something similar to def myFunction (): in Python, you can use scripts.
In game maker studio, there are many built in functions you can use to design your games. If you want to create your own  custom functions, you can use the a script tool in game maker studio. Once written, script can be called as a function in any game object of your game project.


text:
The jumping height changes randomly, and it is not due to the fact that I press the space bar longer. It is just random
Sometimes, the jump height will be so high, and sometimes it jumps normally. How do I solve this? Code:
using UnityEngine;

public class PlayerController : MonoBehaviour
{

    [SerializeField] private LayerMask platformsLayerMask;

    public Rigidbody2D rb;

    public float MovementSpeed = 100f;

    public float JumpingHeight = 100f;

    public BoxCollider2D bc;

    public float fallMultiplier = 2.5f;
    public float lowJumpMultiplier = 2f;

    public Animator anim;

    void Awake()
    {
        rb = transform.GetComponent<Rigidbody2D>();
        bc = transform.GetComponent<BoxCollider2D>();
    }

    void Update()
    {
        if (IsGrounded() && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity = new Vector2(rb.velocity.x, JumpingHeight * Time.deltaTime);
            Debug.Log("Jumping");
        }
        HandleMovement();

    }

    private bool IsGrounded()
    {
        RaycastHit2D raycastHit2d = Physics2D.BoxCast(bc.bounds.center, bc.bounds.size, 0f, Vector2.down, 1f, platformsLayerMask);
        Debug.Log(raycastHit2d.collider);
        return raycastHit2d.collider != null;
    }

    void HandleMovement()
    {
        if (Input.GetKey(KeyCode.A))
        {
            rb.velocity = new Vector2(-MovementSpeed * Time.deltaTime, rb.velocity.y);
            Debug.Log("Going Left");
            transform.localScale = new Vector2(-1, 1);
        }
        else
        {
            if (Input.GetKey(KeyCode.D))
            {
                rb.velocity = new Vector2(+MovementSpeed * Time.deltaTime, rb.velocity.y);
                Debug.Log("Going Right");
                transform.localScale = new Vector2(1, 1);
            }
            else
            {
                //no keys pressed
                rb.velocity = new Vector2(0, rb.velocity.y);
                Debug.Log("No key pressed");
            }
        }
        if (rb.velocity.y < 0) //reponsive jumping and falling
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
        }
        else if (rb.velocity.y > 0 && Input.GetKeyDown(KeyCode.Space))
        {
            rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
        }

    }

}

What if you put your code in fixedupdate instead of update?

No, if you do fixedupdate, then sometimes jumping while running won't work

That sounds like an underlying bug that desperately needs fixing

@htmlcoderexe No, it's very much by design that FixedUpdate does not necessarily run exactly once per frame. It's up to the developer to put anything that needs to tick exactly once per frame into the Update loop, and put anything that needs to tick at a consistent rate in game time in FixedUpdate — the entire reason for these two methods is so developers can choose the tick rate that's right for the functionality they need.

Oh, I did not see the distinction. In fact had to reread your text a few times, I think I get it now. Is this Unity-specific?

Don't scale your jump velocity by Time.deltaTime
What that says is "If I running at a low framerate, jump higher" which is not what you want. You want a consistent change in velocity no matter whether the button was pressed on a short frame or a long frame.
For consistency, you'll want to put your falling acceleration in FixedUpdate, so you get the same falling arc at any framerate.

That's what they had at first https://gamedev.stackexchange.com/questions/179696/2d-player-sometimes-doesnt-jump-up-while-moving-and-jumping-at-the-same-time

Note that I said put the falling acceleration there, not the input check. Moving the input check to Update was correct. Moving all movement physics was incorrect.

So you suggest to add a constant velocity for the jump impulse? Also, please enlighten me: why is putting all the movement physics in FixedUpdate incorrect?

@vaillancourt I believe DMGregory was saying that putting all the movement physics in Update was incorrect. The input checking should be in Update, but then the physics effects should take place in FixedUpdate, as you say.

Maybe you should insert your comment from the question here. It's a valuable advise in general and the issue is a common culprit. And a good explanation for this question as well.


text:
After the player collides with the enemy, it keeps moving backwards until it falls down a cliff
My player will basically be pushed back forever after colliding with an enemy. I have tried changing the mass of the player to like 100, but it still does the same thing. The force that pushes the player is already 1f, so there must be something wrong with the code. Code:
[SerializeField] private LayerMask platformsLayerMask;

[SerializeField] private Rigidbody2D rb;

public float MovementSpeed = 100f;

public float JumpingHeight = 100f;

[SerializeField] private BoxCollider2D bc;

public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;

[SerializeField] private Animator anim;

private enum State {idle, running, jumping, falling, hurt}
private State state = State.idle;

private Collider2D coll;

[SerializeField] private int cherries = 0;
[SerializeField] private Text cherryText;

[SerializeField] private float hurtForce = 10f;

void Awake()
{
    rb = transform.GetComponent<Rigidbody2D>();
    bc = transform.GetComponent<BoxCollider2D>();
    coll = transform.GetComponent<Collider2D>();
    anim = transform.GetComponent<Animator>();
}

void Update()
{
    if(state != State.hurt)
    {
        Movement();
    }
    VelocityState(); //referencing the void VelocityState
    anim.SetInteger("state", (int)state);
}

void Movement()
{
    float vDirection = Input.GetAxis("Vertical");
    if (coll.IsTouchingLayers(platformsLayerMask) &&  vDirection > 0)//the player is only able to jump if it is on the ground
    {
        rb.velocity = new Vector2(rb.velocity.x, JumpingHeight);
        Debug.Log("Jumping");
        state = State.jumping;
    }

    float hDirection = Input.GetAxis("Horizontal");

    if (hDirection < 0)
    {
        rb.velocity = new Vector2(-MovementSpeed, rb.velocity.y);
        Debug.Log("Going Left");
        transform.localScale = new Vector2(-1, 1); //flips sprite
    }
    else
    {
        if (hDirection > 0)
        {
            rb.velocity = new Vector2(+MovementSpeed, rb.velocity.y);
            Debug.Log("Going Right");
            transform.localScale = new Vector2(1, 1); //flips sprite
        }
        else
        {
            //no keys pressed
            rb.velocity = new Vector2(0, rb.velocity.y);
            Debug.Log("No key pressed");
        }
    }
    if (rb.velocity.y < 0) //reponsive jumping and falling
    {
        rb.velocity += Vector2.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
    }
    else if (rb.velocity.y > 0 && vDirection > 0)
    {
        rb.velocity += Vector2.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime;
    }

}

private void VelocityState() //for switching states for animations
{
    if(state == State.jumping) //when jumping, if the player starts falling, switch to falling animation.
    {
        if(rb.velocity.y < 0.1f)
        {
            state = State.falling;
        }
    }
    else if(state == State.falling) //when falling, if the player touches the platform, switch to idle.
    {
        if (coll.IsTouchingLayers(platformsLayerMask))
        {
            state = State.idle;
        }
    }
    else if (state == State.hurt)
    {
        if (Mathf.Abs(rb.velocity.x) < .1f)
        {
            state = State.idle;
        }
    }
    else if (Mathf.Abs(rb.velocity.x) > Mathf.Epsilon) //if running, switch to running animation.
    {
        //moving
        state = State.running;
    }
    else //if it is not everything above, idle
    {
        state = State.idle;
    }
}

private void OnTriggerEnter2D(Collider2D collision) //cherries
{
    if (collision.tag == "Collectible")
    {
        Destroy(collision.gameObject);
        cherries += 1;
        cherryText.text = cherries.ToString();
    }
}

private void OnCollisionEnter2D(Collision2D other) //enemies
{
    if (other.gameObject.tag == "Enemy")
    {
        if (state == State.falling)
        {
            Destroy(other.gameObject);
        }
        else
        {
            state = State.hurt;
            if(other.gameObject.transform.position.x > transform.position.x)
            {
                //enemy is on my right therefore I should be damaged and moved left
                rb.velocity = new Vector2(-hurtForce, rb.velocity.y);
            }
            else
            {
                //enemy is on my left therefore I should be damaged and moved right
                rb.velocity = new Vector2(+hurtForce, rb.velocity.y);
            }
        }
    }
}

When you're in your hurt state, you're skipping the movement method that sets your horizontal velocity. Did you mean to replace this behaviour with something that would slow you to a stop when hurt?

You should not change the velocity of the RigidBody directly.
Try using AddForce instead.
if(other.gameObject.transform.position.x > transform.position.x)
{
    rb.AddForce(-hurtForce,rb.velocity.y,0,ForceMode.Acceleration);
}

This is definitely the first thing you should change and observe the effects of @SkullCutter

Your problem is here:
if(state != State.hurt)
{
    Movement();
}

Movement is the only code that modifies your object's velocity. Without that, your object will coast up to the whims of physics.
For a knockback, we want a bit of sliding, but not an unlimited amount. So let's add some drag.
if(state != State.hurt)
{
    Movement();
} else {  // You could also add a time condition here to put the brakes on after a delay.
    var velocity = rb.velocity;
    velocity.x *= 0.9f; // Quick and dirty deceleration.
    rb.velocity = velocity;
}

Remember to put this in FixedUpdate to ensure you get consistent behaviour regardless of the framerate.


text:
Is there a way to make the enemy start its pathfinding once the player is in a certain distance than the enemy
I am currently using A stars' pathfinding code here: https://arongranberg.com/astar/. So I didn't create any scripts, and used the scripts provided by astar. But the problem here is that even though my player is very far away from my enemy, the enemy will still move towards the player, which is something I don't want. I want the enemy to only move towards the player once the player is a certain distance from the enemy. Also, I am working in unity 2d. Can anyone help me make a code for this?
Edit: I have made a script that makes the enemy pathfind using Brackeys tutorial, and then I manually added a code that checks the distance between the player and the enemy, and if the distance is something like 20f, then force will be added to the enemy. But somehow it still doesn't work, so here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;

public class EnemyAI : Enemy
{
    public Transform target;
    public Transform eagle;

    public float PlayerToEnemyDistance;

    public float speed = 200f; //speed of eagle
    public float nextWaypointDistance = 3f; //the distance of the next waypoint

    Path path; //the current path we are following
    int currentWaypoint = 0; //the current waypoint along that path we are targetting
    bool reachedEndOfPath = false; //checks whether the eagle has reached the end of path or not

    Seeker seeker; //references our seeker script
    private Rigidbody2D rb;

    void Start()
    {
        seeker = GetComponent<Seeker>(); //referencing seeker script
        rb = transform.GetComponent<Rigidbody2D>(); //referencing rigidbody
        InvokeRepeating("UpdatePath", 0f, .5f); //allows the eagle to keep generating path
        rb.gravityScale = 0.000001f;
        speed = 0f;
    }

    void UpdatePath()
    {
        if(seeker.IsDone()) //so what multiple paths won't be generating at once
            seeker.StartPath(rb.position, target.position, OnPathComplete);
        //generates a path
        //first word in bracket is starting position
        //second word in bracket is ending position
        //third word in bracket is a function we call after we finish calculating the path
    }

    void OnPathComplete(Path p) //generate a path called p
    {
        if (!p.error) //if we didn't get an error for the path
        {
            path = p; //set current path to newly generate path called p
            currentWaypoint = 0; //resets progress along the path
        }
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        PlayerToEnemyDistance = (target.position.x - eagle.position.x);
        //cheks the distance between the player and eagle

        if (path == null) //if there is no path, return
            return;

        if (currentWaypoint >= path.vectorPath.Count) //checks whether eagle has reached the end waypoint
        {
            reachedEndOfPath = true; //reaches end of path
            return;
        }
        else
        {
            reachedEndOfPath = false; //doesn't reach end of path
        }
        //get the direction of the next waypoint along our path
        Vector2 direction = ((Vector2)path.vectorPath[currentWaypoint] - rb.position).normalized;
        Vector2 force = direction * speed * Time.deltaTime;

        if(PlayerToEnemyDistance <= 30)
        {
            rb.gravityScale = 0f;
            speed = 300f;
            rb.AddForce(force); //adds force
        }

        //the below line checks the distance of the next waypoint
        float distance = Vector2.Distance(rb.position, path.vectorPath[currentWaypoint]);

        if(distance < nextWaypointDistance)
        {
            currentWaypoint++;
            //we have reached our current waypoint and ready to move on to the next one
        }

        if (rb.velocity.x >= 0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(-1f, 1f, 1f);
        }
        else if (rb.velocity.x <= -0.01f) //flip sprites
        {
            eagle.localScale = new Vector3(1f, 1f, 1f);
        }
    }
}

How do you currently tell the enemy to move toward the player? Assume users here have never seen the particular A* implementation you're using, and show us enough detail of your scripts and Inspector set-up for us to advise on what you need to change.

So you're telling us that the AStar pathfinding is 'always active'
In this AStar module you mention, there will undoubtedly be some way to turn it on and off for individual entities (enemies) it is attached to.
What you need to do is twofold.

Create a 'trigger' for activating the pathfinding for an individual enemy
Activate the pathfinding.

For 1. I recommend that you either do a simple distance check for now, in that the enemy checks his distance from the player, then if the player is within a certain distance, trigger the pathfinding to begin, and stop the distance checking.

you could improve this at a later date by using collision overlap events, which are usually a feature of many physics simulations in common engines.

For 2. it will be up to you to look through the code of the module, ask for support or look at documentation to find out how to enable and disable the pathfinding.

Just did what you said, made my own line of code that pathfinds, and then only add force to the enemy when player and enemy's distance is less than 30, but it somehow still doesn't work. I edited the original text and added the code there so you can see it.

Ok. I don't know the module code, and I can't very well tell where I should be looking in your code. I think you very likely have a logical error somewhere, so you should be debugging this yourself.

A cheap way of solving this would be to limit the max path length the algorithm can find. No idea how to do that for an unknown asset with no source code...


text:
Animation for some reason doesn't trigger after death
So I am trying to trigger this explosion animation after this enemy dies, but for some reason the animation doesn't trigger. I've made sure that the explosion animation is linked to "Any State", and that the transition from any state to the explosion animation has the trigger "Death". Here is my script (only the important parts):
using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour
{

    [System.Serializable]
    public class EnemyStats
    {
        public int maxHealth = 100;

        private int _curHealth;
        public int curHealth
        {
            get { return _curHealth; }
            set { _curHealth = Mathf.Clamp(value, 0, maxHealth); }
        }

        public void Init()
        {
            curHealth = maxHealth;
        }
        public int damage = 40;
    }

    public EnemyStats stats = new EnemyStats();

    private Animator anim;

    [Header("Optional: ")]
    [SerializeField]
    private StatusIndicator statusIndicator;

    void Awake()
    {
        anim = transform.GetComponent<Animator>();
    }

    public void DamageEnemy(int damage)
    {
        stats.curHealth -= damage;
        if (stats.curHealth <= 0)
        {
            GameMaster.KillEnemy(this);
            anim.SetTrigger("Death");
        }

        if (statusIndicator != null)
        {
            statusIndicator.SetHealth(stats.curHealth, stats.maxHealth);
        }
    }

    public void OnCollisionEnter2D(Collision2D _colInfo)
    {
        Player _player = _colInfo.collider.GetComponent<Player>();
        if (_player != null)
        {
            _player.DamagePlayer(stats.damage);
            DamageEnemy(999999999);
        }
    }
}

Will the script looks fine to me and I am not sure about the solution to the problem but I am just guessing that have you checked the "time scale" if the scale is 0 then animator won't work. also, make sure that the trigger is assigned to transition.

Sorry but where is time scale? I just got started in Unity 2 weeks ago, so I am still kinda noob. Also, the trigger is assigned to the transition, so I am not sure why it isn't working.

Sorry for the delay... I hope you found a solution to your problem. But from time scale I mean "The scale at which time passes. This can be used for slow-motion effects or pausing games etc.". For more information, please visit the link. https://docs.unity3d.com/ScriptReference/Time-timeScale.html

pretty sure I didn't mess with the time scale. I didn't have the word: Time.timeScale in any of my scripts so...

Humm... seems strange... Then try to debug inside "if (stats.curHealth <= 0) { Debug.Log("Dead") } and check if compiler reaches there or not if not then its means that condition is not getting true so there is a problem with damage and if you see debug message then its means that there is a problem with the animator so then I guess we have to investigate animator further.

just spent like 20 minutes writing an answer just to find out his account doesnt exist.

Here is a quick set up guide on 2D animations, perhaps you can run through these and see if you've missed any.

Step 1
Add an animator component to your gameobject you want to animate.

Right Click in the project window and create a new Animator Controller

Step 2
Click on the object your animating, and open the Animation window. (Window/Animation/Animation).

Click new clip in the animation window, and give it a name + somewhere to save to.

Step 3
Animate it, you can do whatever you like for this step, add particles, disable/enable stuff. It's up to you.
Step 4
Open the Animator window (Window/Animation/Animator). You should see your animation as a node in the animator, if you don't, find the Animation Clip you saved, and drag it into the Animator window. If you don't see the animator in the animator window, make sure you have your object selected.

Step 5
Go to the 'parameters' section in the Animator window, create a new 'trigger' parameter, you can call it whatever you like. By default you will have 3 nodes, an Entry node, an Exit node, and an Any State node. The entry node is similar to the Start() function in scripting. It allows you to set an 'idle' animation that will play on start. The exit node and any state node aren't really important for this example although if you're using death you may want to connect any state -> death node instead of idle -> death. That way you can die whenever.
Step 6
Go back to your object and head back to the animation window.

In the dropdown, click new. (I'm using a random animator from my game so I have more)

Name the animation idle or something similar, and then create your idle animation. It doesn't even have to be animated it could just have 1 keyframe with your idle stuff in it. Now go back to the animator and select the idle node you just made, Right Click it and select 'set as layer default state'.
Step 7
Now Right Click on the idle animation and Click 'make transition' this will make an arrow, selected your death animation or whatever you made earlier.

Click the arrow, there are a few options, first disable exit time, because we want the death animation to happen instantly without waiting for the previous animation to finish.
You can set a transition duration if you want the animations to smoothly transition from one another but you can mess around until it suits you. I have it off in this one.
Make sure you have a condition too and select your trigger as the condition.

Now in code you can get the animator like this:
animator = GetComponent<Animator>();

note there is no need for this transform.GetComponent<>()
Set the trigger like this:
animator.SetTrigger("triggername");

I think the main problem the OP faces (even if this is a really old question), is the combination of destroying the game object and playing an animation on top.

He uses GameMaster.KillEnemy(), whether that destroys or not I'm not sure.

From the title, that little snippet of code and that normal animations usually don't cause this problem, it is almost save to assume that killEnemy will destroy the object and the animation does not play for that reason. A 3 year old question most likely won't give us clarification


text:
How do I initialise levels sequentially?
I have been learning opengl and I have made good progress over past few months.  However I still struggle to understand game logic in C++, I am new to C++ too.
Say I have this program.
#include <headers>

int main()
{
    #Step 1
    VAO_VBO_EBO_inits();

    while(!glfwWindowShouldClose(window))
    {
        glClearColor(.2f, .2f, .3f, 1.f);
        glClear(GL_COLOR_BUFFER_BIT);

        #Step 2
        DrawCalss();

        glfwPollEvents();
        glfwSwapBuffers(window);
    };
    return 0;
};

For OpenGL programmers this should be clear.
With this structure, I have to load all levels and then draw part of them like so.
Step 1 feeds the gpu the vertex data and its attributes.
Step 2 binds shader programs and draws the vertices
Say I have A, B, C, D levels, within  VAO_VBO_EBO_inits(); function I have to load all A, B, C, D levels then within DrawCalss(); function will draw only related levels.
DrawCalss(); function is dynamic but  VAO_VBO_EBO_inits(); invoked only once.
What I want to do is create separate game loops for each levels and be able to switch between levels, and as I switch levels preceding level should be unloaded and next level reloaded.
Since I am new to C++ I don't know what way would be the most efficient, that's why I have not tried anything.
How do I achieve it? what is the best practice for such scenarios?

I'm most familiar with seeing this done in a data-driven way. Rather than having a different game loop for each level, you have one game loop, that updates and draws objects that have been loaded into a data structure like a scene graph. Loading a level just means emptying the contents of that data structure and replacing it with a new batch of content.

@DMGregory but what about memory allocation, what if Level B is heavier than Level A? as far as I know we don't have a way of resizing pre-allocated memory in C++?

Often games pre-allocate for the worst case, then fill as much as they need and tolerate some "wasted" empty space much of the time, because it's faster than allocating and de-allocating the exact right size all the time, and saves fragmentation. You can ask a question about this specifically and someone with deeper knowledge of game engine memory management in C++ can answer in more detail.

What I would probably do is using the inheritance mechanism of C++ and have a level superclass which level subclasses inherits from. The superclass contains virtual functions for creating, destroying, updating and rendering a level.
You can then have a pointer to the current level so that only a single level is updated and rendered at a time.
If each level should be created and handled differently, the inheritance mechanism will work good but if they work exactly the same and every level is created/handled the same, you might not need to use inheritance and instead just have a level class that is instantiated multiple times, one for each level in your game.
Below I've added a simple code example showing how such classes can be constructed/structured and a simple state machine to switch between game states (menu, game, end credits etc).
First we have the level superclass:
class ILevel
{
public:

             ILevel                     (void)                  {}
    virtual ~ILevel                     (void)                  {}

    virtual void    Create              (void)                  = 0;
    virtual void    Destroy             (void)                  = 0;
    virtual void    Update              (const float DeltaTime) = 0;
    virtual void    Render              (void)                  = 0;

public:

    ILevel*         GetPreviousLevel    (void)  const               {return m_pPreviousLevel;}
    void            SetPreviousLevel    (ILevel* pPreviousLevel)    {m_pPreviousLevel = pPreviousLevel;}

    ILevel*         GetNextLevel        (void)  const               {return m_pNextLevel;}
    void            SetNextLevel        (ILevel* pNextLevel)        {m_pNextLevel = pNextLevel;}

    unsigned int    GetID               (void)  const               {return m_ID;}
    void            SetID               (const unsigned int ID)     {m_ID = ID;}

    std::string&    GetName             (void)  const               {return (std::string&)m_Name;}
    void            SetName             (const std::string& rName)  {m_Name = rName;}

    bool            GetIsFinished       (void)  const               {return m_IsFinished;}

protected:

    // A pointer to the previous level - might wanna be able to return to the previous level etc
    ILevel*         m_pPreviousLevel;

    // A pointer to the next level for easy transition between the current level and the next
    ILevel*         m_pNextLevel;

    unsigned int    m_VBO;
    unsigned int    m_IBO;
    unsigned int    m_VAO;

    // A numerical ID of the level (1 for level 1, 2 for level 2 etc) might be needed
    unsigned int    m_ID;

    // A string for naming the level might also be needed
    std::string     m_Name;

    bool            m_IsFinished;

};

Then we have the class(es) that inherits from this superclass:
class CLevel1 : public ILevel
{
public:

             CLevel1        (void);
    virtual ~CLevel1        (void);

    virtual void Create     (void) override;
    virtual void Destroy    (void) override;
    virtual void Update     (const float DeltaTime) override;
    virtual void Render     (void) override;

};

class CLevel2 : public ILevel
{
public:

             CLevel2        (void);
    virtual ~CLevel2        (void);

    virtual void Create     (void) override;
    virtual void Destroy    (void) override;
    virtual void Update     (const float DeltaTime) override;
    virtual void Render     (void) override;

};

As you can see above, they looks identical, but you might wanna handle them in different ways and have unique data in each.
Then we have the actual entry point and its mainloop:
enum EGameState
{
    MENU = 0,
    GAME,
    END_CREDITS,
};

ILevel* pCurrentLevel = nullptr;

EGameState GameState;

void Update(void)
{
    if(GameState == EGameState::MENU)
    {
        UpdateMenu();
    }

    else if(GameState == EGameState::GAME)
    {
        pCurrentLevel->Update(Time.DeltaTime);

        if(pCurrentLevel->GetIsFinished())
        {
            ILevel* pNextLevel = pCurrentLevel->GetNextLevel();

            // Destroy the current level
            pCurrentLevel->Destroy();

            if(pNextLevel)
            {
                // Set the new current level (i.e, the next level)
                pCurrentLevel = pNextLevel;

                // And create it
                pCurrentLevel->Create();
            }

            // If pNextLevel is not valid (i.e it's a nullptr), the current level is the last level
            else
                GameState = EGameState::END_CREDITS;
        }
    }

    else if(GameState == EGameState::END_CREDITS)
    {
        UpdateEndCredits();
    }

    glfwPollEvents();
}

void Render(void)
{
    glClearColor(0.2f, 0.2f, 0.3f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);

    if(GameState == EGameState::MENU)
    {
        RenderMenu();
    }

    else if(GameState == EGameState::GAME)
    {
        pCurrentLevel->Render();
    }

    else if(GameState == EGameState::END_CREDITS)
    {
        RenderEndCredits();
    }

    glfwSwapBuffers(window);
}

int main(int argc, char* argv[])
{
    InitializeGLFW();

    GameState = EGameState::GAME;

    ILevel* pLevel1 = new ILevel;
    ILevel* pLevel2 = new ILevel;

    // Create the actual level, create the VBO, IBO, VAO etc
    pLevel1->Create();
    pLevel1->SetPreviousLevel(nullptr);
    pLevel1->SetNextLevel(pLevel2);
    pLevel1->SetID(1);
    pLevel1->SetName("Level 1");

    pLevel2->SetPreviousLevel(pLevel1);
    pLevel2->SetNextLevel(nullptr);
    pLevel2->SetID(2);
    pLevel2->SetName("Level 2");

    // Set the current level
    pCurrentLevel = pLevel1;

    while(!glfwWindowShouldClose(window))
    {
        Update();
        Render();
    };

    return 0;
}

This is just an example on how the game can be constructed/structured and you might need to adapt it to work for you and what's working for your specific game.
One think you can also ask yourself is whether you want to have all the levels loaded in memory or if you only want to have the current level in memory. In the end, it depends on your game and if it's a small one, with only a few levels, it might be okay to have them all in memory.


text:
How do open world game engines allocate memory?
My troubles
I've been trying to create a game engine but since I am not well experienced in C++ I am having trouble deciding on how to load new scenes efficiently level by level or just an open world.
Example
Recent games are heavy, Most populat games are about 40 to 100 gigabytes but neither RAM nor GPU have that much memory at least Normal PC or Consoles.
So obviously most game engines pre-allocate enough memory to fit the scene and sometimes just tolerate some wasted memory but how would you decide how much is enough?
Possible solution
I was planning to create separate game loops, before entering the game loop I would load each level, then start the loop, thus I would be able to deallocate preceding level and then reallocate new memory for a next level.
Since I am new to the world of games and memory management my solution may sound rather stupid, But I need to know how to handle such situations efficiently.

Your multiple game loops solution doesn't sound like it would work for an open world game, since it assumes each level is played in isolation, sequentially — where you can never see the edge of the next level while you're still in the previous one. Is that a problem for the game you're making? If not, then "open world games" might not be the right target to learn from, as they've solving for a different set of constraints than you are.

Sure, multiple game loop solution obviously is not suitable for open world games but I wanted to include open world option in my question for detailed answer)))

If you want to get deep into the weeds, there was a good GDC talk on memory allocation systems for games a few years ago. :)

Creating a seamless open world without loading bars is not an easy task. There are lots of small and large problems which need to be solved. This is not a beginners project!
The basic approach is usually to divide the world into sections and only load those sections which are around the player. When the player moves around the world, new sections and their assets get loaded from hard drive into memory and further away sections get deleted.
When you want a high view distance which would require you to load lots and lots of sections, then you usually load the further away sections in a lower level of detail. Simplified geometry, lower resolution textures and no simulation of any moving objects. When the player comes closer, those low-detail sections get replaced with high-detail sections. This requires that you have multiple levels of detail for every section.
The radius in which you load full-detail, mid-detail and low-detail sections is a question of memory budgetting. You should nail down early how much RAM you expect the end-user devices to have at least and how much of that RAM you can budget for the environment. Do a back-of-the-envelope calculation how much RAM a section will take in each detail level. After you implemented the first sections, confirm those assumptions through profiling. This should tell you how many sections you can afford to load at once.
When you target the PC or Phone market, then the capabilities of end-users devices can differ by a lot. So you might choose to make the quality level ranges configurable for the end-user. You could also try to detect how much RAM the users device has and adjust view ranges dynamically.
It can be a good idea to move this constant loading, replacing and unloading of sections to a separate thread, so it doesn't slow down the main game. But now you need to deal with what happens if the player moves very quickly and manages to enter a section which isn't fully loaded yet. You could put the player in the low-detail environment, but this is going to result in a very poor game experience and game-breaking bugs. Showing a loading bar after all might be the better solution for this situation.

In my experience, we'll often attack the budgeting problem from the opposite angle: assuming a fixed number of loaded chunks/LoDs based on our view distances, we calculate how much memory each chunk is allowed to use. Then our authoring and testing tools flag when any chunk exceeds that budget, so our level designers and technical artists can target them for optimization.

@DMGregory Would you have time to go into further detail and write an own answer? I would be really interested in reading how you at Ubisoft handle that stuff in your open world games.

I'm afraid as a game designer myself, I don't have first-hand knowledge of the guts of most of these systems, particularly down at the level of memory allocation. I know the high-level theory, and some of the day-to-day outcomes like budget warnings in test builds, but I don't think I can provide a better answer than yours on this topic.

@DMGregory I think your contribution to Philipp's answer would be great,  I would be very glad to accept both of your answers and solution.


text:
How do you refer to the objects covering the ground?
Newbye here. In the industry lingo, what is the best way to indicate the objects covering the ground (trees, rocks, ...)? Is props OK?

Can you tell us a bit more about the context? Many games these days will procedurally cover the ground in lightweight GPU grass or debris to disguise the bare terrain mesh. Since these are usually generated in the fly rather than specifically placed, they probably wouldn't be called "props," but other objects that your level designers place on the ground might be. Got an example of the kind of conversation you want to have with the word you're searching for?

@DMGregory thanks for the comment! As you suggested, the objects (both small such as leaves and small rocks, and big such as large stones and trees) are generated on the fly. Someone in my studio suggested game assets. What do you think?

I'm writing some technical documentation, trying to be both precise and reader friendly ;-)

If I'm understanding correctly, StarCraft calls such objects doodads. Link

I would say game assets is definitely not specific enough. Everything in your game is an asset — the terrain itself, the shaders and textures it uses, every JSON or XML data file.
Similarly, I'd argue props is also too broad. A chair or a sword could reasonably be called "props" too, but they're not scattered terrain items like you're describing.
(Though to be fair, maybe your game has no chairs or swords or any other variety of prop, and so in this case it's OK to use a broad term)
If your game has different biomes that need to scatter a different mix of grass and trees and rocks, I'd be tempted to call these "biome objects" — but that might be needlessly complex if you don't have multiple biomes.
Some other options: (none of these are particularly standard, just looking for phrases that describe your use case)

Terrain Dressing
Scatterables
Debris
Ground Cover


text:
Java clicking on tiles detection
I am making small isometric game, where I want to do something when user clicks a tile. I can simple do it by mouse location, but I want to be able for zooming and moving camera. It will be 2D game using Java awt. I will be printing grid with the diamond style. Can I make that I will make object of the tile map and locate the mouse whatever the camera is?
Thanks for any help, Maratonec.

"Can I" yes you can. "HOW" will depend on the rest of your code. Please show us an example of the code you're using to lay out and draw your map from the current camera perspective now, and we can use those details to help you write a picking function that corresponds with the conventions you've chosen.

For this you have to wait, because I don’t have currently avaible computer and I am only planning and asking for thinks I don’t know


text:
Game free publishing website?
I am making game that will be completely free and I want to publish it. The publishing platform have to be free and it can be done without any contract or specific license. I simply upload my files make my game page and that’s all. Thanks for help, Maratonec.

I think itch.io is what you are looking for.

No listing fee.
No approval process.
You don't sign away any of your IP rights.
You don't have to promise exclusivity.
You can choose if people can play/download your game for free, for a fixed price or for a pay-what-you-want optional donation.
If you choose to monetize your game, you can set a commission percentage to whatever you think itch.io deserves for their services.

Can I upload there Java games?

@Maratonec If the game comes in form of a file people can download and run, then you can.

Thanks you! I am looking on the site


text:
How can I tell if a Gameobject is currently touching another Gameobject with a specific tag?
I've seen similar questions to this here on Stack Exchange — Game Development, but none of the answers to them have helped my problem. I am working in Unity 2019.2.18f1 with Visual Studios 2019 Community.
What I want to know how to tell when one Gameobject (the player) is currently touching another game object with a tag name of "Block". When the player collides with a "block" I want it to set: jumpPossible = true; But when it leaves the block (by jumping or falling off) jumpPossible = false;
What I currently have in my PlayerController script (the important stuff anyways):
private void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        jumpPossible = true;
    }
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        jumpPossible = false;
    }
}

The problem I am having is when the player is currently on a block and then touches another block. When it leaves the one of the blocks, it will set: jumpPossible = false; and so you can't jump.
What I want for this script to do is whenever the player is touching any Gameobject with a tag of "Block" it should allow it to jump.

We call this type of code a "ground check" and we have lots of existing Q&A about it. Usually it's solved not with tags and contact events, but with physics layers and ray/shape casts.

Rigidbody2D has that handy method GetContacts, but unfortunately the 3d Rigidbody seems to miss that feature.

@Philipp you can get the contacts in the collision parameter of the OnCollision*() methods

@MaxPlay But that won't get you all the contacts the rigidbody is colliding with right now. Only those which relate to the collision between the two colliders which triggered the method call. If the rigidbody also touches some other colliders right now, you won't find those there.

To solve this particular problem, I would store a reference to the objects in a list, instead of setting a variable. In this case, I am using a HashSet, because it is faster than using a list, can only contain each entry once and we do not want to access the objects inside.
private HashSet<GameObject> touchingObjects = new HashSet<GameObject>();

public bool CanJump => touchingObjects.Count > 0;

private void OnCollisionEnter(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        touchingObjects.Add(collision.gameObject);
    }
}

private void OnCollisionExit(Collision collision) {
    if (collision.gameObject.CompareTag("Block")) {
        touchingObjects.Remove(collision.gameObject);
    }
}

Aside from that: Look into the link DMGregory provided. It could have better approaches to the problem that you are facing.


text:
How efficiently use SDL_RenderFillRects?
For the sake of learning C++, I would like to optimize a "Game of life" project I made.
In my first attempt, I used a bunch of SDL_RenderFillRect to draw the board squares.
In my second attempt, I used a single SDL_RenderFillRects to avoid the cost of calling the GPU a lot of times.
However, I am probably wrong in my second implementation because it is not faster than the first one (or barely 5%). Moreover, my implementation is all but elegant.
In the two cases, I only draw the living cells.
The SDL_RenderFillRect solution:
SDL_Rect fillRect;
for (int column=0; column<array_width; ++column)
{
    for (int row=0; row<array_height; ++row)
    {
        if (board[column][row]) // // Checks if the cell is alive
        {
            fillRect = {column*CELL_SPACE,row*CELL_SPACE,CELL_SIZE,CELL_SIZE};
            SDL_RenderFillRect(gRenderer, &fillRect);
        }
    }
}

The SDL_RenderFillRects solution:
SDL_Rect fillRect;
static SDL_Rect rect_list[120000]; // The list of squares to be drawn
int array_index_count = 0;
for (int column=0; column<array_width; ++column)
{
    for (int row=0; row<array_height; ++row)
    {
        if (board[column][row]) // Checks if the cell is alive
        {
            fillRect = {column*CELL_SPACE,row*CELL_SPACE,CELL_SIZE,CELL_SIZE};
            rect_list[array_index_count] = fillRect; // Adds the cell to the array
            ++array_index_count;
        }
    }
}
SDL_RenderFillRects(gRenderer, rect_list, array_index_count);

I am not happy with the way I use SDL_RenderFillRects.
First, I don't know in advance how many living cells there will be, forcing me to declare an oversized array.
Second, I indeed avoided a lot of SDL_RenderFillRect calls, but at the price of long iteratings over the rect_list array.
How to use the SDL_RenderFillRects function properly?

Have you specifically identified a performance bottleneck with this part of the code? Also, what version of SDL are you on, one of the more recent releases added batching I think?

I installed SDL2 a week ago so I have the last version! I didn't identified performance bottlenecks, just measured their overall execution time. The only difference is that in the first version, I call SDL_RenderFillRect for each cell, and in the second version, I add each SDL_RenderFillRect to an array which I then pass to SDL_RenderFillRects. Maybe the added iteration time doesn't compensate for the GPU call gains, but it would negate the whole point of having a SDL_RenderFillRects function I suppose :/


text:
Java - set resolution of game
Hi everybody I am making small game using  pure Java 8 and rednering it by Java AWT Graphics2D method . My question  is how to make that user can change the quality of game. For example: 720p, 1080p, 1440p. Something similar that is when playing YouTube video.
The steps I will make?

Make 3 pictures of each, each with different quality.
Then load them.

Is this the right way?
But Java is default only 72dpi so each of them will be the same quality. So how to render it in different resolution?
Thanks in advance,
Maratonec
Edit:
I will be using LibGDX for rendering. So I will be using OpenGL.
But still don’t know how to make in LibGDX.
Edit:
So I now understand that using LibGDX mipmap I will make my scaling nicer. So I will have 1440p image and scale it up down? Or I will have to have each image for each resolution (720p, 1080p,1440p) and they will change to user selected resolution and only scaling to the window size?
The second method I have in mind how to do, but for second I need code example.
Thanks one more time for spending time with beginner!

This reddit thread offers some third-party libraries you might be interested in. https://www.reddit.com/r/gamedev/comments/19ubgo/scaling_and_resolution_in_my_java_game/ I would personally recommend something like LibGDX.

Yes thanks! Any idea doing it from scratch?

Here's a pure Java AWT solution that I found: https://stackoverflow.com/questions/11225113/change-screen-resolution-in-java

Thanks I read that before. But that is for whole monitor. I won’t only change quality of my textures

This can be done via scaling, see here.
However...
Q: Why do render quality levels like you are proposing to implement, exist in games & video? That is, lowering texture quality while keeping the window / viewport size the same?
A: To improve performance on lower spec machines.
But... windowed Java AWT can't (?) be assumed to work that way. Instead, it uses the native resolution of the desktop and the size of the window within that desktop, to define the number of pixels / texels to be rendered, in x & y. AWT is not really designed for games or videos, but for simple desktop UI, graphing and diagrams. (Whether AWT's scaling and rendering mentioned above is GPU-accelerated, is up for debate.)
So if you keep things at the same size, but lower the quality, then you are possibly not changing the number of pixels that must be rendered - but rather just having to double or quadruple those texels into the final render's pixels. This makes the game look worse, potentially with no performance improvement.
So if you want a quality setting that will definitely decrease the rendering load (and thus isn't a complete waste of time!), you need to use a render technology like OpenGL for Java, in the form of e.g. LibGDX renderer, LWJGL, or JOGL. This is because GPU-based rendering actually will do less work when you render fewer texels, so that lowering quality actually does something useful.
So to have any assured benefits to what you're doing, I would suggest switching to a renderer that is intended for games. Else you may be wasting your time. EDIT: Google "libgdx mipmap" for more.

This is exactly the right answer - you can't conceivably do this from scratch and get a solid efficient solution, you need external render technology.

Thanks a lot! It open my mind! I am using LWJGL for simple 3D objects, but don’t know how to make 2D. Probably go for LibGDX. I will wait some time and then mark this as the final answer!

Any idea how ti make it in LibGDX?

@Engineer What? There is some filters

google "libgdx mipmap" - and learn what you need to know.

Can I do that by setting the World size?

@Maratonec I work with OpenGL directly (which LibGDX encapsulates), so I can tell you the principles but not the specifics of how LibGDX exposes mipmapping. Perhaps mark this answer as accepted, and ask a new one about level of detail using LibGDX?  Or search this site for "libgdx mipmap".

Still confused, but ok! I now know how the pixel filters work, but how to tell gpu that the original image resolution is 1440p and I want to scale it down to 720p, to have better performance. Then I will apply the texture filters to be the textures nicer.


text:
What is the rule with number of levels?
I have been making my first game, I have a number of levels I was thinking of making, around 20-30 but I'm not sure if this is too many. Is there a hard and fast rule for number of levels to include in a game?

As I'm sure you've found from your own research, games have wildly varying numbers of levels - from a handful to hundreds. So there's no simple rule to spit out the right number for any game. Instead, think about your goals: how much play time do you want to offer players? How much play time does each level give you? How much variety do you have in your content and mechanics to make each level interesting? etc...

I wouldn't think there is a hard and fast rule. Maybe think about what your levels are trying to get the player to do. If you're just adding variety then I would keep the number low, but maybe create groups of levels e.g. level 1 has 5 stages and teaches the player all of the basic skills they'll need, level 2 has five stages that introduce a new mechanic/enemy/graphical theme etc. I think the aim of that style would be keep stepping up the skill required for each level, while adding something new/tweaking something every few levels to keep the player learning.


text:
SDL2. Why I'm getting a Segmentation Fault in the free() function? Also, am I doing the rendering stuff right?
So, I'm new at C programming and SDL2 and I'm trying to get something working here to write some games. First, I would like to know if I'm doing the rendering stuff the right way.
I'm kind of confused about the software and hardware rendering. Here I'm using a SDL_Texture and SDL_LockTexture to write raw pixels into it. I would like to know if I should use SDL_Surface instead, and, how can I get the best performance out of the hardware.
I allocate the memory for the pixels in the SDL_WINDOWEVENT_EXPOSED, which is called the first time a window appears, and everytime the window is resized, so then I can reallocate a new memory for the new window size.
For that to work, I need to SDL_DestroyTexture and free(pixels) to allocate newer ones in a new resized SDL_Texture, at least I think I need. The problem is... I'm getting a Segmentation Fault right in the free() call, according to GDB (GNU Debugger), and I don't know why, it's probably some stupid beginner error.
It is important to mention that, in the first while(running) iteration, the function free() is not called, so, the SegFault only happens the first time I resize the window. Here is the code:
#include <stdio.h> // fprintf, printf

#include <SDL2/SDL.h>

typedef struct
{
  SDL_Texture* texture;
  void* pixels;
  int width;
  int height;
  int pitch;
  int bytes_per_pixel;

} Render_Buffer;

void rendering_testing(Render_Buffer* render_buffer)
{
  if(SDL_LockTexture(render_buffer->texture,
                     NULL,
                     &render_buffer->pixels,
                     &render_buffer->pitch) != 0)
  {
    fprintf(stderr, "Failed to lock SDL texture: %s\n", SDL_GetError());
  }
  else
  {
    uint8* row_first_byte = (uint8*)render_buffer->pixels;

    for(uint16 y = 0; y < render_buffer->height; ++y)
    {
      uint32* pixel = (uint32*)row_first_byte;

      for(uint16 x = 0; x < render_buffer->width; ++x)
      {
        *pixel++ = 0x00ff00ff;
      }

      row_first_byte += render_buffer->pitch;
    }

    SDL_UnlockTexture(render_buffer->texture);
  }
}

int main(int argc, char* argv[])
{
  if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  {
    fprintf(stderr, "Failed to initialize SDL: %s\n", SDL_GetError());
    return -1;
  }

  int window_width = 640;
  int window_height = 480;

  SDL_Window* window = SDL_CreateWindow("Breakout",
                                        SDL_WINDOWPOS_CENTERED,
                                        SDL_WINDOWPOS_CENTERED,
                                        window_width,
                                        window_height,
                                        SDL_WINDOW_RESIZABLE
#ifndef DEBUG
                                        |SDL_WINDOW_FULLSCREEN_DESKTOP
#endif
                                        );
  if(window == NULL)
  {
    fprintf(stderr, "Failed to create SDL window: %s\n", SDL_GetError());
    SDL_Quit();
    return -1;
  }

  SDL_Renderer* renderer = SDL_CreateRenderer(window, -1,
                                              SDL_RENDERER_ACCELERATED|
                                              SDL_RENDERER_PRESENTVSYNC);
  if(renderer == NULL)
  {
    fprintf(stderr, "Failed to create SDL renderer: %s\n", SDL_GetError());
    SDL_DestroyWindow(window);
    SDL_Quit();
    return -1;
  }

  Render_Buffer render_buffer = {0};
  render_buffer.bytes_per_pixel = 4;

  bool8 running = true;
  while(running)
  {
    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
      switch(event.type)
      {
        case SDL_QUIT:
        {
          running = false;
        } break;

        case SDL_WINDOWEVENT:
        {
          switch(event.window.event)
          {
            case SDL_WINDOWEVENT_EXPOSED:
            {
              if(render_buffer.texture)
              {
                SDL_DestroyTexture(render_buffer.texture);
              }

              SDL_GetWindowSize(window, &window_width, &window_height);
#ifdef DEBUG
              printf("window width: %d\nwindow height: %d\n", window_width, window_height);
#endif
              render_buffer.width = window_width;
              render_buffer.height = window_height;

              render_buffer.texture = SDL_CreateTexture(renderer,
                                                        SDL_PIXELFORMAT_RGBA8888,
                                                        SDL_TEXTUREACCESS_STREAMING,
                                                        render_buffer.width,
                                                        render_buffer.height);

              if(render_buffer.texture == NULL)
              {
                fprintf(stderr, "Failed to create SDL texture: %s\n", SDL_GetError());
                SDL_DestroyRenderer(renderer);
                SDL_DestroyWindow(window);
                SDL_Quit();
                running = false;
                return -1;
              }

              if(render_buffer.pixels)
              {
                free(render_buffer.pixels); // SEGFAULT HAPPENS HERE!!!
              }

              render_buffer.pixels = malloc(render_buffer.width *
                                            render_buffer.height *
                                            render_buffer.bytes_per_pixel);

              render_buffer.pitch = render_buffer.width * render_buffer.bytes_per_pixel;

            } break;

            default:
            {
              // TODO
            }
          }
        } break;

        default:
        {
          // TODO
        }
      }
    }

    rendering_testing(&render_buffer);

    SDL_RenderCopy(renderer, render_buffer.texture, NULL, NULL);
    SDL_RenderPresent(renderer);
  }

  SDL_DestroyTexture(render_buffer.texture);
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}

Should I use malloc() and free() or something else instead?
What can I do to solve this SegFault error? What can I do the get the best performance out of the renderer while writing pixels manually into the memory, and what is the right way to do that? What can I do better that I'm not doing here?
For now, thanks so much for the attention!

Your segfault is happening because you're calling free on already freed memory. SDL_DestroyTexture frees the memory managed by the SDL_Texture that you 'Destroy'.

Also you shouldn't be destroying your renderer, window and quitting SDL until you're out of that loop, you're currently doing each twice, under certain scenarios, you should be fine to just leave the calls to those functions at the end of your main() for now, where you have another set of them. In general you shouldn't need more than one call to SDL_Init(). Also one call to SDL_Quit(), and only after you're completely done destroying/freeing up everything else related to SDL.

@JoshuaHedges you are dam right! Thank you very much!

Oh, but, if I manage to write only one SDL_Quit() at the end of the main() function, I will need to write a bunch of if's and else's. Do you think it's a better programming practice to not write a bunch of return in the middle of the code and instead use a return_value int variable to use at the end of the program? I dont think it's such a big deal to do that. Actually, the SDL wiki always call return when checking for a feature initialization in the middle of the code.

Hey @JoshuaHedges, the SDL_DestroyTexture is not freeing my pixels memory. When I resize the window and look to the memory usage in the task manager, it only gets bigger. If pixels were freed, the memory usage should increase and decrease when resizing the window.

It's better practice to put your setup and shutdown in separate functions like AppSetup and AppShutdown or something, and that's also where you'd include things like script language and rendering or audio engine startup and shutdown, then use those functions in main. It's also better practice to keep one return value that is, if it's state and purpose is clear, like "setup_error" could be a simple int/boolean (boolean is int but behaves different due to macros when you pull in stdbool.h). It's not a problem where your returns are located, but functions would help organize it all.

The task window won't show stable memory usage because a lot of the resources are managed by the operating system, though it shouldn't deviate by too much. should be reusing the texture, and even using it's internal pixel surface, rather than maintaining your own pixel buffer. SDL_Texture has a pixel buffer, You should use SDL_CreateTexture. If you could update your code to show your most recent work then I can help better and write an answer that should help you resolve your issue, and be started in a good direction.

After the SDL_UnlockTexture the pointer to the pixels gets invalidated. From SDL
documentation

As an optimization, the pixels made available for editing don't
necessarily contain the old texture data. This is a write-only
operation, and if you need to keep a copy of the texture data you
should do that at the application level.

Also is explained in LazyFoo's documentation.

After the texture is unlocked the pixel pointer is invalid so we set it to NULL.


text:
Why is Metal is rendering textures SLIGHTLY darker than they should be?
I already checked this question. Using [MTKTextureLoader.Option.SRGB : false] in texture loader options doesn't work. All that happens is when I do [MTKTextureLoader.Option.SRGB : true], it's a lot darker instead of slightly darker. There must be something else. Here is an example of this unwanted behavior.

As you can see I am using the mouse to hold the original packed ice texture over the rendered one. It's considerably lighter, even with [MTKTextureLoader.Option.SRGB : false].
Here is my fragment function:
fragment half4 TextureFragment(VertexOut VertexIn [[stage_in]], texture2d<float> Texture [[texture(0)]]) {
    constexpr sampler ColorSampler(mip_filter::nearest, mag_filter::nearest, min_filter::nearest);
    float4 Color = Texture.sample(ColorSampler, VertexIn.TexCoord.xy / VertexIn.TexCoord.z);
    return half4(Color.r, Color.g, Color.b, 1);
}

How can I fix the problem? How can I render the actual texture instead of a darker version?
Note: I must fix the problem, not work around it. A workaround would be like return half4(Color.r, Color.g, Color.b, 1); from the fragment shader. I must fix the problem from the root.

If you draw the background white instead of black, do the colors look lighter?

@PandaPajama I tried a white background, and the texture is still darker


text:
SAT Collisions: Resolving rotations
Currently I have a working 2D SAT collision system with only boxes, but works with static rotations as well, leaving room for triangles. One of the issues I've been able to resolve was tunnelling, thanks to this thread's psuedocode that I got working for myself.
Problem is, this doesn't support moving rotations like a system using a minimum-translation-vector. If I rotate alongside the side of an object, the system will fail even if I'm not moving.
My first thought in solving this was to use the longest line you can draw in a square (that being the points on either side of a square) and comparing the length of that to whatever side on any axis, but even squares have different sizes on any given rotation projected onto an axis.
The system also doesn't work with multiple objects, because - while you can use the algorithm on a group of objects and find the shortest distance out of all of them - if I conserve my velocity relative to the colliding axis, diving into the crest of 2 objects means I will phase through one of them not beyond a 45 degree angle.
Is there an effective way to resolve collisions on rotations and groups of objects, while using this anti-tunnelling algorithm? I don't care if it's expensive, I'll take whatever you can think of.

I am not sure how you can use SAT to resolve continuous rotations but I know of two other algorithms that may do the trick, however they are made for convex shapes.
The first one is conservative advancement(you can check out Erin Catto's presentation on youtube) this will give you the time of impact using translation and rotation and of course does take up some resources.
An other algorithm is GJK Raycast, it is less precise but takes up less resources. It can give you a lower time bound where you are sure that the objects will not be intersecting at that time bound. This algorithm is exact for translation, but for rotation you must "swipe" a sphere on your collider to encapsulate the rotation. Even though it's not precise it's still pretty decent. You can read more about this on Gino Van Bergen's papers(http://www.dtecta.com/papers/unpublished04raycast.pdf) or on his website (dtecta.com).
However I once heard that it is impossible to resolve exactly continuous collision detection in real time, so yes it is possible but not in real time. I personally do static checks (GJK & EPA) for "slow objects" and I do a GJK raycast test for "fast" moving objects vs "slow" moving objects. It's not exact but it still gives decent results, the player/projectiles cannot go though walls anymore.
In the end I didn't really answer your question though, I haven't seen any papers on SAT continuous collision detection it probably is possible, although it might be just as complicated or maybe even more than the algorithms described above. Hope this helped at least a bit.


text:
Where can I find the Roblox Material/Terrain textures?
The textures shown in this image: Where can I find them? I am making a Roblox game, it's a terrain based mining game, and I want to add an inventory. Where can I find the textures for the terrain to use as icons? I am not allowed to use screenshots. I am looking for the terrain textures that get rendered, not the icons in the terrain editor. Where in Roblox studio are they located?

You can find them inside of the game files. If you're on windows 10, use cortana to search up "Roblox" inside of your apps, right click it, and then press "show file location". Then you can look into the game files and find the textures. Also, if you want to use these as a icon, you will have to first copy and crop these images into squares and then upload it to roblox as a decal. Then you may insert a decal into your gui and insert the ID of the image.


text:
How come non creatable/destroyable Roblox instances have :Destroy() :Clone() etc?
Roblox has many types of instances. But services and other NonCreatable Instances (ReplicatedStorage, Workspace, etc.) still have methods for creating or destroying. Why? Why do they have :Destroy() and :Clone() methods if they cannot be destroyed or created? What's the point of inheriting these from the Instance class?
What's the point of inheriting a property that can't be used?

Very likely it is a workaround to some technical limitation. I don't really know what, I don't know enough of roblox internals to tell. And very likely most people on the site don't know either.

By the way, let us assume some user in this site knows, and that person logs in every day… In that scenario, just by time zone and scheduling differences, it might take 24h to get an answer (it has only been 5 hours so far), perhaps it can take a few days if that person skips holidays and weekends… Worse if that person only has time to log in a day per week… All that assuming that person exist, and is willing to answer. By doing useless edits as you said you will get attention, alright, but not necessarily the attention you expect.

I’m voting to close this question because questions about "why" a game does X is not a good fit for this site since only the developers of the game themselves can answer it correctly and accurately.

I can't speak to whether this applies to Roblox specifically (hopefully someone with in-depth knowledge of that tool can share a more detailed answer), but most programming languages don't give you a choice of which parts of a parent type to inherit or which ones to skip.
Once you inherit from a particular type, you get everything that type defines, even if you don't plan to use half of it.
So you often end up leaving the items you don't need with their default implementation, or overriding them with an implementation that throws an error in case someone uses these unsupported methods by mistake.
Even if this inheritance restriction does not apply to Lua scripting directly, it may apply to the underlying back-end code that the script interfaces with.
The actual inherited methods cost practically nothing (just one extra entry in a VTable somewhere, not even an entry per instance), so it's often not worth the grief of refactoring the inheritance hierarchy into a more complex form to avoid this unnecessary inheritances.
That said, this kind of inheritance complication is one reason why game developers often favour composition over inheritance, as a way to glue-together only the functionality a particular entity needs, without hauling in a pile of unnecessary inheritance, or locking the types into a rigid contract with one another that's difficult to modify later.

But that's dumb, inheriting values you don't use. Inheritance is dumb. Why even inherit properties at all? Why don't they just define every class individually?

Every Roblox instance has these methods, they could "remove" them for these particular instances but there's no need as you are not expected to use them anyways.