text:
How to format bespoke struct, so that it appears like Vector3 in Unity Editor inspector?
I have a bespoke struct, which has XYZ variables just like Vector3, but unlike Vector3, the inspector does not display them neatly and horizontally. I have tried to read documentation and copy Vector3 to no avail. Please tell me how to make my custom struct display XYZ in the inspector exactly like Vector3. Below is a screenshot from the Unity editor to show the difference ("Test" is a Vector3, Position is my own class).

The search term is CustomPropertyDrawer, google gives https://forum.unity.com/threads/making-a-proper-drawer-similar-to-vector3-how.385532/

As Zibelas noted, you can use a custom property drawer. However, let's analyze why you are making a custom struct with the same fields as a Vector3 (or why you probably shouldn't).
If your struct functions exactly the same as a Vector3 (or Vector3Int), there's no point in using it over Vector3, since Unity's APIs make extensive use of Vector3.
If your struct behaves like a Vector3 but adds new functionality, you should strongly consider using extension methods or helper functions instead. For example, let's imagine you want a way to swap the X and Y values for some reason. One way to do this is with extension methods:
public static class ExtensionMethods {
    public static void SwapXY(ref this Vector3 v3) {
        float temp = v3.x;
        v3.x = v3.y;
        v3.y = temp;
    }
}

This adds a new function to Vector3 which we can use like any other function! Note that I used the ref keyword because Vector3 is a value type and in this example we're modifying the original value.
Vector3 test = new Vector3(1, 2, 3);
test.SwapXY();
Debug.Log(test); //(2.0, 1.0, 3.0)

Alternatively, we can use static helper functions:
public static class Vector3Helpers {
    public Vector3 SwapXY(Vector3 value) {
        return new Vector3(value.y, value.x, value.z);
    }
}

So when should you consider creating your own struct?

To make the struct immutable. Vector3 is mutable (its fields can be changed after it is created). Mutable structs are generally discouraged in C#, but Unity makes extensive use of mutable structs for debatable reasons I won't get into here.
For type safety. For example, if a function argument expects a position and you want to be sure you don't accidentally pass in a Vector3 representing euler angles, you could make a Position struct that's otherwise identical to Vector3.
If you want to change how Vector3's existing functions work (I can't think of any reason you'd want to do this)
If you want to add new fields, or implement other new functionality that can't be accomplished with extension methods.
To make the struct serializable. That doesn't directly apply here because Vector3 is already serializable, but standard structs built into C# like TimeSpan are not compatible with Unity's serialization system.
To change the precision (e.g. use doubles instead of floats)

I think this post has some useful resources, but to be an answer to the question that was asked, it should also at least briefly show how to use the CustomPropertyDrawer.


text:
Copyright/trademark protections of character classes
I want to create a game that uses character classes from World of Warcraft. Are the classes protected by copyright/trademark law? For instance WoW has a Warlock class that is essentially a spell-caster focused in dark magic and summoning demons.

You may be interested in How closely can one game legally resemble another?

No, that question is different. The only thing that will be used is a single class.

That's a degree of similarity, and the question above answers "what degree of similarity is a problem?" - you will learn faster if you don't shut out potential insights for not being in the exact form you expected them to be in advance.

During the planing and design of your game, I suggest you do a bit of research.
For instance, a simple search for "Warlock" in my favourite search engine leads to Wikipedia which shows that the concept of warlocks dates back to long before WoW was created. Even Heroes of Might and Magic had Warlocks in 1995, long before WoW.
Often, game designers will not try to invent new terms, they'll use something that exists before that players recognize easily.
IANAL, but it's safe to say that these terms are not copyrighted, nor trademarked. Just keep in mind that you should come up with original skills and features; you may get on a more slippery slope if you also intend to "borrow" the skills and features offered in another game.

Related reading from RGP Stack Exchange: Are classes from a tabletop RPG copyrightable?

source: Stack Exchange

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

sort: votes


text:
Unity Input Buffers
I’m working on the framework for my 2.5D fighting game in Unity (it’s gonna be similar to Street Fighter IV) and I’ve got movement down so I want to start adding attacks. Since there’s going to be special attacks I want to add an input buffer as well (the input system I currently have is incredibly basic so I want to apply the input buffer to it as well). This is how it looks like so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    public CharacterController controller;
    private Vector3 direction;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float hInput = Input.GetAxis("Horizontal");
        direction.x = hInput * speed;

        controller.Move(direction * Time.deltaTime);
    }
}

I’ve seen some tutorials on it but they either aren’t explained that well or not that easy to translate into different kinds of projects. What would be the most efficient way to implement an input buffer? I've found this code on a Unity forum, but I'm not sure how I can apply this to multiple chained inputs like quarter circle forward motions:
private List<ActionItem> inputBuffer = new List<ActionItem>();  //The input buffer
private bool actionAllowed;  //set to true whenever we want to process actions from the input buffer, set to false when an action has to wait in the buffer
//Notice I don't have any code here which sets actionAllowed to true, because that probably depends on states like in the middle of throwing a punch animation, or checking if a jump has finished, or whatever

void Update()
{
    checkInput();
    if (actionAllowed)
    {
        tryBufferedAction();
    }
}

//Check inputs here, and add them to the input buffer
private void checkInput()
{
    if (Input.GetKeyDown(Keycode.W))
    {
        inputBuffer.Add(new ActionItem(ActionItem.InputAction.Jump, Time.time));
    }
    //Add checks for all other inputs here
}

//Call when we want to process the inputBuffer
private void tryBufferedAction()
{
    if (inputBuffer.count > 0)
    {
        foreach (ActionItem ai in inputBuffer.ToArray())  //Using ToArray so we iterate a copy of the list rather than the actual list, since we will be modifying the list in the loop
        {
            inputBuffer.Remove(ai);  //Remove it from the buffer
            if (ai.CheckIfValid())
            {
                //Means the action is still within the allowed time, so we do the action and then break from processing more of the buffer
                doAction(ai);
                break;  //We probably only want to do 1 action at a time, so we just break here and don't process the rest of the inputBuffer
            }
        }
    }
}

private void doAction(ActionItem ai)
{
    //code to jump, punch, kick, etc

    actionAllowed = false;  //Every action probably has some kind of wait period until the next action is allowed, so we set this to false here.
    //Some code somewhere else needs to be written to set it back to true
}

I also plan on adding graphic to show the player’s inputs similar to DBFZ or SFV but I’ll climb that mountain once I reach it

Have you searched for past Q&A on this topic and the related topic of detecting analog stick flick gestures? How have you tried applying what you've found so far, and where specifically did you run into trouble?

It looks like you want to achieve a Hadouken or something like that. Input buffers are not for this. It is used to store inputs that can't have immediate effect, and will be automatically released when idle. You need to cache all instructions (released or not) for a period of time and extract combos from them according to the rules. Maybe use an algorithm like string matching.

@Mangata Ur right. I did some more digging and I managed to come up with a pretty good solution where I name an attack in a list then I can add and remove inputs in that list. If you press all the inputs withtin a certain time frame of each other the special move comes out. Here's the code: https://www.toptal.com/developers/hastebin/mazaleqomu.csharp

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


text:
Calculate the coordinates of an offset in 3D space knowing the initial rotation and final rotation of the object
Working on a game mod in FiveM in which I am representing bullet impacts with drawn lines in the game world along their flight path. I am getting a normalized vector and then calculating the offset from the entity, and this works well for rigid-body entities like cars but for peds with skeletons not so much. I am trying to shift and attach the impact to the damaged entity bone, but am struggling to calculate the offset given the initial rotation/position, and then the current rotation/position. I looked at quaternions, and angle of rotation, but am not sure how to translate that into a function to calculate the final coord using the originally calculated offset.
Anyone able to point me in the direction of the math I need to solve this? Essentially I am just looking for the final 3D coords, and know I need some sort of advanced math (trig, quats, etc) to find it but am struggling to understand which solution I need.
I know I basically have the following:
initial rotation of entity bone, initial position of entity bone, initial offset from entity bone, initial coordinates of offset
and
final rotation of entity bone, final position of entity bone, and the offset I need to find the coords
and need to calculate
final coords of the offset

How do "initial offset from entity bone" and "initial coordinates of offset" differ from one another? What coordinate space are they measured in?

The gist of it is that you need a matrix transformation for the bone. Well, two:

The one at the moment you want at the time of impact, let us call it A.
And the current one, let us call it B.

Now, let us say you have a point p_a in a reference coordinates system (whatever space you have the point defined it) at the time of impact. We convert it to the space of the bone (also at time of impact):
p = inverse(A) * p_a

Then we convert that back to the reference coordinate system, but using the other matrix, so we have the current position in the reference coordinate system:
p_b = B * p

It appears from what you say that each transformation is described as a combination of translations and rotations. So you could create the transformation matrix by making a translation matrix and a rotation matrix and multiplying them together.

I don't know how exactly it is setup in what you are working with (I do not understand what you say about offset), but I expect it to be something similar to a scene tree or scene graph.
If that is the case, each object has a transformation relative to its parent. For example, the bone has a transformation relative to its parent bone, and so on, until the parent is a game object or similar, which has a transformation relative to the root of the scene, which we call global or world coordinates.
Then, if you know the path from your reference coordinate system to the bone, you can make translation matrices and rotation matrices for the transformations, multiply them together in order, and that should give you the matrix you need.

Do not lose track of what is positioned relative to what. I also remind you that matrix multiplication is not commutative. That means that the order matters. Fortunately it is either one order or the reverse order, so if it is not working, try flipping the multiplication order.

Sorry, I am still learning game dev, in FiveM you are able to get offsets from entities which are basically the local coords for the entity, and then can use that to calculate world coordinates. So say the bullet impacts at the very front of the vehicle, my offset would be say vector3(0.0, 1.0, 0.0) or 1 unit forward of the entity's position.
Now that I explain it I realize I actually can't get that offset from the entity bone, and instead only have it for the ped. So basically i'm trying to rotate a coord around another coord knowing the previous and current rotation.

@user2828652 If you have all the information about the bone relative to the "ped", you should be able to create a matrix that describes the bone space relative to the "ped". Then, if you have the the position you want also relative to the "ped", you should be able to convert that position to a position in bone space. And to find out where it is when the bone moved, you do the operation backwards but swapping the old matrix with the new one.

I'm trying to find the end position of the 'flight path' of the bullet relative to the bone specifically, but it sounds like I need to create a transformation matrix then and use that to find the coordinates new position relative to the entity bone?
https://i.imgur.com/teKFmfH.jpeg for context, basically I am using the coords of the impact and the coords of a normalized vector to recreate the flight path of the bullet, for rigid objects this is easy, but still doesn't take into account things like doors opening or closing on the vehicle.

@user2828652 I'm guessing the offset are vectors in space. How is the rotation described? I believe FiveM is this: https://fivem.net correct? I tried looking up the documentation, but I can't find something about bones. Edit: I found https://docs.fivem.net/natives/?_0x17C07FC640E86B4E

The function I am using is GetOffsetFromEntityGivenWorldCoords() found here, it basically just returns the local coords when given a set of world coords, it gives it in a vector format, but I am not sure if it is actually a vector (like I said I am new to all this and am still trying to understand all the math behind stuff).
https://docs.fivem.net/natives/?_0xCE6294A232D03786 is one of the functions related to entity bones (which are the bones set up in the 3D model). So peds have hand, spine, foot bones etc, vehices often have door/seat bones.

Sorry, found here for the first function: https://docs.fivem.net/natives/?_0x2274BC1C4885E333

@user2828652 I'm guessing that GET_OFFSET_FROM_ENTITY_GIVEN_WORLD_COORDS and GET_OFFSET_FROM_ENTITY_IN_WORLD_COORDS are opposite. I don't know how you could decide what boneIndex to use, but given a boneIndex, you could use _GET_ENTITY_BONE_ROTATION to get the rotation in Euler angles, I guess. But rotation around what? Perhaps _GET_ENTITY_BONE_POSITION_2 is the position. Then you could make a matrix with that. It would take experimentation. Yet, which bone to use seems a stop gap for me. If a bullet impacts a "Ped", how do you know which bone you should use to track where it hit?

https://i.imgur.com/RKQ64gh.png
I get it from a separate eventhandler that listens for a base game event that is triggered by a network entity being damaged. I then can get the bone, and its rotation at the time of impact, a seperate function normalizes the vector which is created between the bullet impact and the weapon that generated it to draw the angle of impact. Like I said, I have the initial rotation of the bone, and am able to later get the position/rotation, I just wasn't sure of how to do the math to calculate the new position after rotation.


text:
Unreal Engine 5 foliage paint not working
I just learned unreal engine 5 and right now is trying the foliage paint.
So I'm having difficulty of making the foliage paint to work, here is the video:
https://youtu.be/oWrE8-JBdOo
as you can see, i believe i have done everything right but the tree's aren't showing up.
anyone know why ?
thankyou !


text:
Can a game have characters named after video game franchises?
The video game Battlerite, a free to play team brawler, includes a hero called "Destiny", essentially named after the Destiny video game franchise. Is this legal, and why it is not a trademark infringement?

Voting to close as duplicate as it essentially the same as Is it legal to use car manufacturers' names in a game?

In general, does X infringe on Y is determined by context & when needed, the court system. Legal where? Things that may be legal in on place might not hold in another. Do they know? Sometimes it's up to the IP holder must discover violations & enforce their rights. What's the intent? Some applications might be legal (Destiny is a common enough name) & others not (if Battlerite appears to be leveraging the Destiny franchise popularity for its gain). These are just some of the issues potentially at play; complex legal questions are best directed to legal professionals.

What is the difference between this question and your previous question?

This does not look like a question about how to develop a game, but a question about law you should ask a lawyer. This site draws experts in the making-a-game parts of game development. If you want an expert in trademark law, you're much less likely to find them here than on dedicated legal sites. Trademark law does not take on a separate "game version" that only game developers know about if the supposed violation happens to occur in a game, so I don't see any reason to bring this question to a gamedev site rather than to a trademark lawyer.

I'll start by saying that I'm by no means a legal expert and that your question will be much better answered in the Law Stack Exchange.
That being said, from my understanding of the U.S. copyright and trademarks laws, it depends on the specifics of the use of the name. As you seem to know, names aren't under copyright, but under trademarks. In order to keep your trademark, you need to defend it, otherwise you'll loose it. This is why the Elder Scrolls sued Mojang for the use of Scrolls in the name of one of their games. They needed to do so to keep their trademark, but they lost because Scrolls is too common of a word to be kept by one person. Also, remember that the trademark law is meant to benefit the consumers, not the companies, to make the products differentiable. So if the two products, or the use of the name in both cases, is easily differentiable, it should not be a trademark infringement. In your case, unless Destiny clearly refers to the game or one of its characters, I don't think it would be a trademark infringement. Imagine if all books using the word destiny could to be sued for that, it wouldn't make any sense.
But remember that I might be completely off, especially if you're not talking about the U.S., in which case I refer you to Law Stack Exchange (linked earlier) or to your relevant jurisdiction's website to read the actual laws, such as:

US Federal Code
Consolidated Laws of New York
Consolidated Acts and Regulations of Canada


text:
Simple deform modifier (bend) preserve UVs
What is the best way to minimise stretch when bending a plane? I'm making a road kitbash to use in Unity and would like the road markings to remain a consistent size when the road bends (I'm using more complex markings than just lines). Here I've added a texture to a straight and curved section to illustrate the problem:

I've tried adding and sliding edge loops lengthwise but they have no effect. I've tried skewing the UVs (scaling the longer edge smaller and vice versa) which does correct the scale problem, but then the shapes rotate and don't line up with a straight section if placed next to it.
Here's an example of what I'm trying to achieve - the markings are correctly oriented perpendicular to the road and are all of the same size:

I achieved this using a bunch of planes in an array, but as there will be thousands of markers in the scene, I'd prefer to use larger meshes for long sections of road to keep the draw count down. Also, the road has an asphalt texture and any stretching would be noticeable close up; again, this could be solved with separate meshes for the roads, but I'd then need transparent textures for the markings, which would add tons of overdraw. I could use UV islands, but again, extra draw calls.

What's your desired outcome here? Can you sketch it? If you want exact alignment at the ends, ie. the same number of texture repeats over the length, then there has to be stretching because the same amount of texture has to cover a longer distance at the outside edge. If you want no stretching, then the same amount of texture cannot cover both the shorter and longer edges, leading to a mismatch at one end or both. If you show us the road markings you're using, we may be able to suggest a more bending-friendly way to draw them than relying on conventional texture mapping over the road itself.

@DMGregory Thanks, updated the post with desired result.

Looks to me like you want three separate strips, each with a different number of texture repeats according to their length.

@DMGregory Sure, I was thinking that too and will probably go with it. The bulk of the texure is asphault though and the stretching is apparent on that too when the camera is close enough and there would be a visible seam by each marking. I updated the post again (last paragraph) to explain.

Sounds like what you really want to ask is "how to texture a bending road in Unity" and the bend modifier/blender tags are a red herring. You may be able to apply the asphalt texture in worldspace and then layer on the markings as decals, for just two draw calls once static batching combines the meshes.

@DMGregory So I profiled performance each method (transparent marking strips over opaque aspault, opaque strips, transparent planes, opaque planes, decals) in a rough demo scene with a few thousand markings and transparent marking strips over opaque aspault using the standard shader in Cutoff render mode was pretty performant, in fact using one set pass call less than opaque. So, strips it is. thanks for the input.

If you've solved your problem, be sure to write up your solution as an Answer below.

After much torturing of UV maps I conclude it's usually not going to be possible to get a neat result - mapping a 2D image on a non-linear plane (or 3D shape) will always yield stretching somewhere.
One solution is to hide the stretching in your scene, either rotated away from the camera or obscured by other objects.
In this case I solved the issue by using separate meshes for the markings that sit on top of the asphalt mesh with a transparent shader. That way I could planar map the asphalt, and as the markings are in thin strips, stretching could be minimised even around corners, as manipulating the UV map is much easier when you have less UVs to work with.


text:
How do I do damage with spawned particles with MCreator?
I would like to create a sword that summons particles that do damage (like the katanas of the demon slayer mod) could someone help me? I've been trying for days.

IIRC particles are entirely cosmetic by definition. So you either have some entities that are not particles and do damage, or you do damage and make particles (which don't do damage but you already did the damage)

then I have two questions:

is it possible to create an invisible entity?
can I make the attack zone bigger than 1x1?

yes for both, probably


text:
Find bone-system given a mesh
Animation newbie here. Usually, how do people call the process of finding the bone-based system corresponding to given mesh? I'm looking for machine-learning-based solutions that could improve the process.

"Finding" a bone-based system implies that one already exists in the first place. Perhaps you are talking about the process of creating a bone rig and linking it to the mesh?

Thanks for the reply and for your clarification! Yes, creating a bone rig and linking it to the mesh is a great description of what I'm looking into. Does this set of actions have a specific name?

The process of creating bones for a 3d model and linking vertices of the mesh to those bones so they can be animated is usually called "rigging".


text:
What class should access my database?
I would like to code a turn-based RPG, and I decided to use a database to store all skills in the game. Now I have to decide as well which class can see this database, and how classes pass around these data.
(Edit: the main reason I would like to use a DB is to avoid editing skills as scriptable objects in the editor. I guess they require too many clicks to edit in games of this type.)
My intuition says that almost every class should be able to see the database, and an attribute of skills can be used as signals.
For example, suppose a skill has attributes skill_name and dialog. When a player character uses a skill Strike, the character class spits a signal skill_used("Strike"). Any class received this signal will search for Strike in the database and does its task. For instance, the dialogue_manager shows dialog of Strike. I don't know how complex the actual coding is, but conceptually it may work.
However, this is like making a massive singleton class DATABASE. Any class cannot be tested without the database.
Question: Is it fine to allow many classes to access the database? If not, what type of classes should access the database, and how?

Myself, I would not use a database in this way. It sounds like a single skill use could trigger dozens of redundant look-ups, as each system searches the DB for the skill key to find out what it's supposed to do, instead of just referencing a skill object that has the relevant data/behaviour on hand, without an extra query step.

Ah-ha, so it seems better to use skills themselves as signals?
The main reason I would like to use a DB is to avoid editing skills as scriptable objects in the editor.

Yep, you can store your data in the database, but once the game is started, it builds objects based on the database content so it is stored in memory.

Thank you both, I would consider going that way!

When making a Pokemon-like monster battler with my students, I built an Excel import pipeline, so we could edit the collection of monsters and skills in a spreadsheet, then have a one-button import routine that would build/update all the ScriptableObjects for us, using the latest spreadsheet contents. If you'd like to ask "How to bulk edit many skills without manually modifying a ScriptableObject for each one" I could walk through that solution.

Also, my comment was generic and not specific to Unity. When asking a question, it's often better to add more details so that you could get better answer.

Actually, I wrote this question in a generic way intentionally since I was thinking about code architecture. But implementation may be the most important thing! I am also interested in the bulk edit technology, though it is a bit far from the original question to edit. Could I add it anyway?

You can always post it as a separate question if you like.


text:
Close door after player has entered a room
I can't figure out how to make the triggered door open and then close again. I managed to open the door, but can't figure how to close it again once the player is inside the room. Here's my code so far:
public GameObject upDoor;
public GameObject downDoor;
public bool openDoor;

void Update()
{
    if(openDoor) //(openDoor == true)
    {
        upDoor.transform.Translate(Vector3.up * Time.deltaTime);
        downDoor.transform.Translate(Vector3.down * Time.deltaTime);
    }

}

void OnTriggerEnter(Collider other)
{
    Debug.Log("Trigger Entered");
    openDoor = true;
}

void OnTriggerStay(Collider other)
{

}

void OnTriggerExit(Collider other)
{
    openDoor = false;
}

This is how I edited the code, but I'm having a compile error.. I don't know what else I could do?
I tried else->return false; but that would cause an error as well.
void Update()
{
    if(openDoor) //(openDoor == true)
    {
        upDoor.transform.Translate(Vector3.up * Time.deltaTime);
        downDoor.transform.Translate(Vector3.down * Time.deltaTime);
    }
    else
    {
        upDoor.transform.Translate(Vector3.down) * Time.deltaTime);
        downDoor.transform.Translate(Vector3.up * Time.deltaTime);
    }

}

"I'm having an error" should always be followed with the full description of the error. Don't make us guess. Here you have a mismatched parenthesis in this line: upDoor.transform.Translate(Vector3.down) * Time.deltaTime); - see how you have one ( but two )s? Always make sure your parentheses occur in matched pairs.

Your last code seems okay, except, that you wrote an extra ) by accident, and you have to stop closing the door once it's fully closed. One way to do that is to count how many frames open it is, ++ when opening and -- when closing, don't close any more once it's 0.


text:
How to rotate a child game object everytime when parent rotates?
I have a GameObject called Gun, and a GameObject called Hand which is a child of other GameObject named Player.
When I pick up the gun, it becomes a child of the hand.
The problem is, when the player rotates (and so, Hand rotates too), the gun's not rotating, it stays at the same rotation.
Here's the Gun script:
using System.Collections.Generic;
using UnityEngine;

public class LaserGun : MonoBehaviour
{
    public GameObject Hand;
    public Transform LaserSpawnPoint;
    public Movement movement;
    public Rigidbody2D rb2D;
    public GameObject Laser;
    public bool IsInHand;

    public void Start()
    {
        Hand = GameObject.Find("Hand");

        movement = GameObject.Find("Player").GetComponent<Movement>();

        rb2D = this.GetComponent<Rigidbody2D>();
    }

    public void OnMouseDown()
    {
        this.transform.parent = GameObject.Find("Hand").transform;
        this.transform.position = Hand.transform.position;
        GetComponent<BoxCollider2D>().isTrigger = true;
        GetComponent<Rigidbody2D>().isKinematic = true;
        IsInHand = true;
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && IsInHand == true)
        {
            Instantiate(Laser, LaserSpawnPoint.position, transform.rotation);
        }

        if (Input.GetKeyDown(KeyCode.Q) && IsInHand == true)
        {
            this.transform.parent = null;
            GetComponent<BoxCollider2D>().isTrigger = false;
            GetComponent<Rigidbody2D>().isKinematic = false;
            IsInHand = false;
        }
    }
}

And here's the Player's movement script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    public float speed;
    public float jumpForce;
    public float moveInput;

    public GameObject Hand;
    public GameObject HeldObj;

    private Rigidbody2D rb;

    public bool facingRight = true;

    private bool isGrounded;
    public Transform groundCheck;
    public float checkRadius;
    public LayerMask whatIsGround;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();

        Hand.transform.rotation = this.transform.rotation;
    }

    void FixedUpdate()
    {
        isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);

        moveInput = Input.GetAxis("Horizontal");
        rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

        if (facingRight == false && moveInput > 0)
        {
            Flip();
            Hand.transform.Rotate(new Vector3(0, -180, 0));
        }
        else if (facingRight == true && moveInput < 0)
        {
            Flip();
            Hand.transform.Rotate(new Vector3(0, 180, 0));
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
        {
            rb.velocity = Vector2.up * jumpForce;
        }
    }

    void Flip()
    {
        facingRight = !facingRight;
        Vector3 Scaler = transform.localScale;
        Scaler.x *= -1;
        transform.localScale = Scaler;
    }
}

Some info (might be useful)

The game is 2D
The "Hand" object is an empty game object
There is no animator on player and the gun objects

I tried to upload the image of this but for some reason Stack does not let me do this.
Any help will be appreciated!

I think you can create a property you will use to rotate parent objects via only. And inside this property you can have Action that will rotate the child object. Or create custom subscribtion for parent rotation.

It is a little difficult to determine from just your code what is the issue, because a lot of things can be causing the issue.

Is your Gun parented to the Player when picked up? I know your code says it does, but you may want to check in your Inspector when playing to see if it actually is, because other Components or snippets of code may be unparenting it.
An Animator may be affecting the positioning and rotation of your Gun or Player, and this may in turn be affecting your Gun and making it not rotate properly.
Is the Player a skinned mesh? If it has a skeleton, and your "Hand" object is a mesh, it may move weirdly. For skinned meshes, you will want to parent objects to the bones instead of the meshes when you want them to move with the body part.

I'm sorry my answer isn't more specific, but Unity has a lot of different moving parts, and I need more information to be able to pinpoint the issue more specifically for you.

I will try to edit the question and add the screenshot to it so it might get more clear than it is now, I hope it will get better to understand


text:
How would I go about fixing my variable rate SDL timestep?
I my gameloop is going around 10x faster than what it should be and I have no idea how to fix it.
I tried multiple different other variable rate timesteps but none seem to be as effective as this one.
int main(int argc, char* args[])
{
    Uint32 t = 0;
    Uint32 dt = 10000 / 60.0;

    Uint32 currentTime = SDL_GetTicks();

    game = new Renderer();

    game->init("window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, false);

    while(game->running()){

        Uint32 newTime = SDL_GetTicks();
        Uint32 frameTime = newTime - currentTime;
        currentTime = newTime;

        while(frameTime > 0.0)
        {
            float deltaTime = std::min(frameTime, dt);
            game->handleEvents();
            game->update(deltaTime/1000);
            frameTime -= deltaTime;
            t += deltaTime;

            t += dt;
        }
        game->render();
    }

    game->clean();

    return 0;
}

Whenever I call
g.transform.position.x+=1/60.0;

in the render function, I expect it to move 1 pixel every 1 second but it moves way to fast.
Does anyone know how I can slow this down or what I'm doing wrong?

Uint32 dt = 10000 / 60.0;
This should mean 1000 / 60.0, right if this is original source, your item moves 10times faster than 60 fps

I tried that and it just makes it faster. The original from gaffer on games is in seconds while this one is in milliseconds.

yeah but milliseconds are 1000 / 60.0 = 16.666 ms per frame, not 166.66 ms per frame.
There is another error but twisting numbers until it works is not the right strategy :)

The other problem is that you always call the update as long as frameTime >0.0 so if frameTime is always 1 ms, you will still run the while loop 1000 times per second. As you call game->update(...) it seems you are not taking this time argument into account in your update function (at least in your sniplet)

If there were 3.5/60 of a second since the last render, your game loop runs 1/60 and then 1/60 and then 1/60 and then another 0.5/60 so 4 steps in 3.5/60 of a second. If there was 0.001/60 of a second your game loop runs 1 step with 0.001/60 of a second. This is not a fixed timestep loop.


text:
Is there a generic formula to determine the angle of deflection off of a rectangle?
I have a perfect 2D system, with no friction, elasticity, etc. A ball is colliding with a rectangle. I know the angle of the motion of the ball in degrees. I want to figure out how said angle will change upon collision. I determine the angle of collision by averaging angles of a bunch of points in the intersection. What do I do with these two angles? Maybe I also have to determine if the corner is in the intersection as well and handle it differently? Also, the angles con be larger than 360. It doesn't matter for movement, since it's in polar coordinates, but it may hinder calculations?

The edges of your rectangle are just straight lines, so the angle of reflection is equal to the angle of incidence:

Now, if this surface has its own angle, we can factor that in. Call the angle of incidence/reflection θ and the angle of the surface Φ:

So our new angle is θ + Φ. But how do these relate to the angle of the original vector? Let's call that α:

Then we have, from the sum of the interior angles and the supplementary angle of Φ:
α + θ + (π - Φ) = π
α + θ = Φ
and the angle we want is
θ + Φ = 2 Φ - α
where, to reiterate, α is the angle of our incoming object and Φ is the angle of the reflecting surface.
For inside corners, you can consider that as two reflections off of surfaces that are at an angle of π/2 to each other, resulting in a turn of π (back in the direction it came from).
For outside corners, you can consider the plane of reflection as perpendicular to the vector to the point of contact:

This time μ is the angle of the vector drawn from the ball's center to the point of collision. So now
Φ = μ + π/2
and the resulting angle is
2 Φ - α = 2 μ + π - α
where, again, α is the direction of motion and μ is the angle from the center of the ball to the point of contact.


text:
Why does this voxel engine crash after a few seconds?
I'm trying this voxel engine in Python. It runs ok, but it crashes after a few seconds. Does anyone know what is happening?
import glfw
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import pyrr
from TextureLoader import load_texture
from random import random as rnd
import numpy as np

from camera import Camera

cam = Camera()
WIDTH, HEIGHT = 1280, 720
lastX, lastY = WIDTH / 2, HEIGHT / 2
first_mouse = True
left, right, forward, backward = False, False, False, False

# the keyboard input callback
def key_input_clb(window, key, scancode, action, mode):
    global left, right, forward, backward
    if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
        glfw.set_window_should_close(window, True)

    if key == glfw.KEY_W and action == glfw.PRESS:
        forward = True
    elif key == glfw.KEY_W and action == glfw.RELEASE:
        forward = False
    if key == glfw.KEY_S and action == glfw.PRESS:
        backward = True
    elif key == glfw.KEY_S and action == glfw.RELEASE:
        backward = False
    if key == glfw.KEY_A and action == glfw.PRESS:
        left = True
    elif key == glfw.KEY_A and action == glfw.RELEASE:
        left = False
    if key == glfw.KEY_D and action == glfw.PRESS:
        right = True
    elif key == glfw.KEY_D and action == glfw.RELEASE:
        right = False

# do the movement, call this function in the main loop
def do_movement():
    if left:
        cam.process_keyboard("LEFT", 0.05)
    if right:
        cam.process_keyboard("RIGHT", 0.05)
    if forward:
        cam.process_keyboard("FORWARD", 0.05)
    if backward:
        cam.process_keyboard("BACKWARD", 0.05)

# the mouse position callback function
def mouse_look_clb(window, xpos, ypos):
    global first_mouse, lastX, lastY

    if first_mouse:
        lastX = xpos
        lastY = ypos
        first_mouse = False

    xoffset = xpos - lastX
    yoffset = lastY - ypos

    lastX = xpos
    lastY = ypos

    cam.process_mouse_movement(xoffset, yoffset)

vertex_src = """
# version 330
layout(location = 0) in vec3 a_position;
layout(location = 1) in vec2 a_texture;
layout(location = 2) in vec3 a_offset;
layout(location = 3) in vec3 a_offset_texture;//In order for every cube to have it's own texture
uniform mat4 projection;
uniform mat4 view;
uniform mat4 move;
out vec2 v_texture;
void main()
{
    vec3 final_pos=vec3(0.,0.,0.);//= a_position + a_offset;
    final_pos.x = a_position.x + a_offset.x;
    final_pos.y = a_position.y + a_offset.y;
    final_pos.z = a_position.z + a_offset.z;
    gl_Position =  projection * view * move * vec4(final_pos,1.);
    v_texture.xy = a_texture.xy + a_offset_texture.xy;
    //v_texture = a_texture + a_offset_texture; code here
}
"""

fragment_src = """
# version 330
in vec2 v_texture;
out vec4 out_color;
uniform sampler2D s_texture;

float map(float value, float min1, float max1, float min2, float max2) {
  return min2 + (value - min1) * (max2 - min2) / (max1 - min1);
}

float roundValues(float fvalue,float ivalue) {
    return 0.f;
}

void main()
{
    vec3 sky_col = vec3(172./256.,32./256.,32./256.);

    vec4 in_col = texture(s_texture, v_texture);

    float coe = 1.-gl_FragCoord.z/(100.*gl_FragCoord.w);

    in_col.x = map(coe,0.,1.,sky_col.x,in_col.x);
    in_col.y = map(coe,0.,1.,sky_col.y,in_col.y);
    in_col.z = map(coe,0.,1.,sky_col.z,in_col.z);

    out_color = in_col;
}
"""

# the window resize callback function
def window_resize_clb(window, width, height):
    glViewport(0, 0, width, height)
    projection = pyrr.matrix44.create_perspective_projection_matrix(45, width / height, 0.1, 100)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

# initializing glfw library
if not glfw.init():
    raise Exception("glfw can not be initialized!")

# creating the window
window = glfw.create_window(WIDTH, HEIGHT, "My OpenGL window", None, None)

# check if window was created
if not window:
    glfw.terminate()
    raise Exception("glfw window can not be created!")

# set window's position
glfw.set_window_pos(window, 400, 200)

# set the callback function for window resize
glfw.set_window_size_callback(window, window_resize_clb)
# set the mouse position callback
glfw.set_cursor_pos_callback(window, mouse_look_clb)
# set the keyboard input callback
glfw.set_key_callback(window, key_input_clb)
# capture the mouse cursor
glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

# make the context current
glfw.make_context_current(window)

multiplier=float(2.)
batch_coe=float(1./multiplier)

#              positions        texture_coords
cube_buffer = [-0.5, -0.5,  0.5, 0.0, 0.0,#where it used to be 1.as image uperbounds, now it hase been replaced with batch_coe
             0.5, -0.5,  0.5, batch_coe, 0.0,
             0.5,  0.5,  0.5, batch_coe, batch_coe,
            -0.5,  0.5,  0.5, 0.0, batch_coe,

            -0.5, -0.5, -0.5, 0.0, 0.0,
             0.5, -0.5, -0.5, batch_coe, 0.0,
             0.5,  0.5, -0.5, batch_coe, batch_coe,
            -0.5,  0.5, -0.5, 0.0, batch_coe,

             0.5, -0.5, -0.5, 0.0, 0.0,
             0.5,  0.5, -0.5, batch_coe, 0.0,
             0.5,  0.5,  0.5, batch_coe, batch_coe,
             0.5, -0.5,  0.5, 0.0, batch_coe,

            -0.5,  0.5, -0.5, 0.0, 0.0,
            -0.5, -0.5, -0.5, batch_coe, 0.0,
            -0.5, -0.5,  0.5, batch_coe, batch_coe,
            -0.5,  0.5,  0.5, 0.0, batch_coe,

            -0.5, -0.5, -0.5, 0.0, 0.0,
             0.5, -0.5, -0.5, batch_coe, 0.0,
             0.5, -0.5,  0.5, batch_coe, batch_coe,
            -0.5, -0.5,  0.5, 0.0, batch_coe,

             0.5,  0.5, -0.5, 0.0, 0.0,
            -0.5,  0.5, -0.5, batch_coe, 0.0,
            -0.5,  0.5,  0.5, batch_coe, batch_coe,
             0.5,  0.5,  0.5, 0.0, batch_coe]

cube_buffer = np.array(cube_buffer, dtype=np.float32)

cube_indices = [ 0,  1,  2,  2,  3,  0,
                 6,  5,  4,  4,  7,  6,#it needs fixing in indexing and invericies
                 8,  9, 10, 10, 11,  8,
                12, 13, 14, 14, 15, 12,
                16, 17, 18, 18, 19, 16,
                20, 21, 22, 22, 23, 20]
                #4,  5,  6,  6,  7,  4

cube_indices = np.array(cube_indices, dtype=np.uint32)

shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))

# VAO, VBO and EBO
VAO = glGenVertexArrays(1)
VBO = glGenBuffers(1)
EBO = glGenBuffers(1)

# cube VAO
glBindVertexArray(VAO)
# cube Vertex Buffer Object
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)
# cube Element Buffer Object
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices, GL_STATIC_DRAW)

# cube vertices
glEnableVertexAttribArray(0)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 5, ctypes.c_void_p(0))
# cube textures
glEnableVertexAttribArray(1)
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 5, ctypes.c_void_p(12))

textures = glGenTextures(1)
load_texture("basilikh_kakava.jpg", textures)

#### instance VBO
instance_array = []
offset = 1

for z in range(0, 50, 2):
    for y in range(0, 50, 2):
        for x in range(0, 50, 2):
            translation = pyrr.Vector3([0.0, 0.0, 0.0])
            translation.x = x + offset
            translation.y = y + offset
            translation.z = z + offset
            instance_array.append(translation)

len_of_instance_array = len(instance_array) # do this before you flatten the array
instance_array = np.array(instance_array, np.float32).flatten()
####
#### instance VBO texture
instance_array_text = []

for z in range(0, 50, 2):
    for y in range(0, 50, 2):
        for x in range(0, 50, 2):
            translation = pyrr.Vector3([0.0, 0.0,0.0])
            instance_array_text.append(translation)

len_of_instance_array_text = len(instance_array_text) # do this before you flatten the array
instance_array_text = np.array(instance_array, np.float32).flatten()
####

instanceVBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
glBufferData(GL_ARRAY_BUFFER, instance_array.nbytes, instanceVBO, GL_STATIC_DRAW)
#glBufferData(GL_ARRAY_BUFFER, instance_array.nbytes, instance_array, GL_STATIC_DRAW)

glEnableVertexAttribArray(2)
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
glVertexAttribDivisor(2, 1) # 1 means, every instance will have it's own translate

####new code for textures

#instanceVBO_text = glGenBuffers(1)
#glBindBuffer(GL_ARRAY_BUFFER, instanceVBO_text)
#glBufferData(GL_ARRAY_BUFFER, instance_array_text.nbytes, None, GL_DYNAMIC_DRAW)

#glEnableVertexAttribArray(3)
#glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
#glVertexAttribDivisor(3, 1) # 1 means, every instance will have it's own texture

####

glUseProgram(shader)
glClearColor(172./256.,32./256.,32./256.,1.)
glEnable(GL_DEPTH_TEST)
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

projection = pyrr.matrix44.create_perspective_projection_matrix(45, WIDTH / HEIGHT, 0.1, 100)
cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0., 0., 0.]))

#model_loc = glGetUniformLocation(shader, "model")
proj_loc = glGetUniformLocation(shader, "projection")
view_loc = glGetUniformLocation(shader, "view")
move_loc = glGetUniformLocation(shader, "move")

glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
#glUniformMatrix4fv(model_loc, 1, GL_FALSE, cube_pos)

glEnable(GL_CULL_FACE);
glCullFace(GL_FRONT);
glFrontFace(GL_CW);

# the main application loop
while not glfw.window_should_close(window):

    #index=int(rnd()*(len_of_instance_array_text-1)*3)

    #instance_array[index]=rnd()*100

    #instance_array_text[index]=batch_coe*int(rnd()*multiplier)
    print("0")
    #glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
    #glBufferSubData(GL_ARRAY_BUFFER,0, instance_array.nbytes, instance_array)

    print("1")
    #glBindBuffer(GL_ARRAY_BUFFER, instanceVBO_text)
    #glBufferSubData(GL_ARRAY_BUFFER,0, instance_array_text.nbytes, instance_array_text)
    print("2")
    glfw.poll_events()
    do_movement()
    print("3")
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    print("4")
    move = pyrr.matrix44.create_from_translation(pyrr.Vector3([0., 0., 0.]))
    print("5")
    glUniformMatrix4fv(move_loc, 1, GL_FALSE, move)
    print("6")
    view = cam.get_view_matrix()
    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
    print("7")
    glDrawElementsInstanced(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None, len_of_instance_array)
    print("8")
    glfw.swap_buffers(window)
    print("9")
# terminate glfw, free up allocated resources
glfw.terminate()

What troubleshooting steps have you taken? Do you get any particular error message on crash? Have you run this with a debugger that can give you information about where the crash originated? Have you tried instrumenting the code with logs so you can determine the last section executed or the last game state prior to the crash? Most volunteers won't do those steps on your behalf, so it helps to do as much legwork as you can to narrow down the cause of the issue. Ideally, you'd shrink this question from a complete dump of all the code to just a Minimal Complete Verifiable Example.

what does the message say when it crashes?


text:
Why do my game objects become invisible as soon as I attach the material to which this shader script is applied?
I wrote a shader script that is an extension of the Sprite-Lit shader in previous Unity versions' standard assets in an attempt to feather the edges of a sprite using additive blending. Here is the script:
Shader "Unlit/Sprite-Lit-Add-Feathering"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
        [PerRendererData] _AlphaTex("External Alpha", 2D) = "white" {}
        [PerRendererData] _AlphaTexST("External Alpha ST", 2D) = "white" {}

        // Gradient property for the feathering effect
        [PerRendererData] _Feathering("Feathering", 2D) = "white" {}
    }

    SubShader
    {
        Tags
        {
            "Queue"="Transparent"
            "IgnoreProjector"="True"
            "RenderType"="Transparent"
            "PreviewType"="Plane"
            "CanUseSpriteAtlas"="True"
        }

        // Set the blend mode to "Blend One One" to enable additive blending
        Blend One One

        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #pragma target 3.0

            #include "UnityCG.cginc"

            struct appdata_t
            {
                float4 vertex   : POSITION;
                float4 color    : COLOR;
                float2 texcoord : TEXCOORD0;
            };

            struct v2f
            {
                float4 vertex   : SV_POSITION;
                fixed4 color    : COLOR;
                half2 texcoord  : TEXCOORD0;
            };

            v2f vert(appdata_t IN, uniform fixed4 _Color)
            {
                v2f OUT;
                OUT.vertex = UnityObjectToClipPos(IN.vertex);
                OUT.texcoord = IN.texcoord;
                OUT.color = IN.color * _Color;
                #ifdef PIXELSNAP_ON
                OUT.vertex = UnityPixelSnap (OUT.vertex);
                #endif

                return OUT;
            }

            fixed4 frag(v2f IN, uniform sampler2D _MainTex, uniform sampler2D _Feathering) : SV_Target
            {
                // Sample the texture and multiply it by the vertex color
                fixed4 c = tex2D(_MainTex, IN.texcoord) * IN.color;

                // Sample the feathering gradient to get the feathering factor
                float featheringFactor = tex2D(_Feathering, IN.texcoord).r;

                // Multiply the color by the feathering factor to achieve the feathering effect
                c *= featheringFactor;

                // Return the resulting color
                return c;
            }

            ENDCG
        }
    }
}

However, as soon as I attach the material to which this script is applied to to any 2d sprite game object, the game object simply becomes invisible in both scene view and game view. Why is this the case, and what should I modify in order to fix this problem?

Can you show us the textures/colours you're using for each property, and what the background behind the sprite looks like in your scene?

my guess is your vertex colors are all zero - try changing COLOR in your vertex structs to COLOR0
If that doesn't work, maybe try working off this example for basic vertex lighting visualization

Thank you so much! However, I changed all the vertex structs to COLOR0 and the sprites still turn invisible when the material with the shader script is applied:( I really can't figure out what the issue is:(

hmm what happens if you comment out where you apply the vertex color?


text:
How do I resize an OpenGL texture created using new DSA?
My texture class uses new function glTextureStorage2d() (which OpenGL recommends), but the problem here is that this function makes the texture size immutable, unlike the old glTexImage2d(). I'm making a photo-viewer app, so how do I reset the texture data to another image with different dimensions?

You create a new texture.

... which is the same thing your graphics driver was doing before, by the way. Every time you changed the size, it was making a new texture and deleting the old one.


text:
Is FFXV's LOD system similar to Unreal Nanite's LOD system?
I was reading this article and it seems the LOD system in FFXV is similar in that the texture is not swapped, but the number of polygons changes depending on the distance. Is Nanite the same, or is it way more advanced than the FFXV LOD system? If so, in what ways?

This just describes what all level of detail systems do. I don't see anything in the article that suggests this is particularly similar to Nanite's virtualized geometry approach — can you clarify what's making you associate this with Nanite specifically? There are existing articles and videos explaining Nanite's technique in more detail than we could easily go into in an answer here, so I think you'd find your curiosity better-satisfied elsewhere.

Well, it seems like it doesn't require a new model and new texture to be loaded in like Nanite, that's why I asked the question. I am wondering if what are the differences between the two approaches.

What in the article suggests that the model is not loaded in? Re-using the same texture between LoDs is not unique to Nanite.


text:
What is the process of making a chracter creator like black desert in godot/unity?
example
I get the point of switching heads or other body part models as long as they are all attached to the same bones then the animations will work, but what about changing the color of lips, eyelashes, skin, armor? those games don't have 100 different UV per model, they only have the body UV, the head one, the eye UV so 3 at most since the armor UV replaces the body UV
Plus those types of games also give access to momentary bones that change the shape of the mesh giving almost complete control over shaping a character, it not something new, Tera and Aion did it back in 2006-2007.
it's actually very common in Eastern games but almost no one does it for western games, I can't even find any tutorial that goes in depth into this or someone working on it at least showcasing the workflow

but what about changing the color of lips, eyelashes, skin, armor? those games don't have 100 different UV per model, they only have the body UV, the head one, the eye UV so 3 at most since the armor UV replaces the body UV

You can change the colors with shaders, controlled by shader parameters (I mean: uniforms).
For example, have the shader add a color only in areas defined by a texture (you can have additional textures and query them with the same UVs).
Since you only need one channel as mask to decide where to apply a color, you can define multiple areas in the same texture by using the different color channels. Furthermore the value of the channel can control intensity of the color.
You might want to have the base color be gray-scale, and apply the color by multiplication. So you change the hue and saturation, but keep the brightness of the base color gray-scale.
You might also be interested in doing hue rotation in shader.
It is also common that different cloth pieces reuse are the same mesh and same UV but with different texture (taking advantage of alpha transparency and scissors).
Also be aware that you can have bone attachments. I mean, other meshes that follow the transformation of the bones but are not part of the character mesh. Which you can use for armor, weapons and accessories.

Plus those types of games also give access to momentary bones that change the shape of the mesh giving almost complete control over shaping a character, it not something new, Tera and Aion did it back in 2006-2007.

No momentary bones. Don't change the skeleton structure in runtime. However you can have extra bones in the skeleton that are not used by the animation. Yet you can allow these extra bones to deform the mesh, and you can allow the player to pose them.
Be aware that your animations won't work (well or at all) if you have a different skeleton. So even allowing the player to stretch the bones is problematic. If you need to support something like that you will need a proper animation retargeting solution.
However, I suspect what you are referring to is something else: have multiple base meshes (all with the same vertex count and topology), and  combine interpolate them linearly by weights controlled by the player (with sliders). This modifies the mesh (moves the vertex around), not the skeleton. See also blend shapes.


text:
In C#, is there any performance reason to implement ECS?
The formal ECS specification was developed to address gaming in a JavaScript environment.
In any C# translation, this implies all of the classes' members must be public.
My concern is that too many JavaScript developers are transitioning to C# without a full understanding of classes, interfaces, interfaces and inheritance(and capitalization), and the speed drawbacks to that approach, when compared to execution times of properly written classes and interfaces.
So my question is: could the ECS be implemented in a way that fully utilizes C# without sacrificing speed and FPS?

You need 300 rep to create new tags, but the [tag:c#] tag already exists so you can just use it.

Also, "formal ECS specification"; which specifcation?

"all of the classes' members must be public" — here you're talking about the component data, specifically, right? (Although for performance in C# the components would usually be structs, not classes) We have some past Q&A about implementing ECS style solutions in C# that might be of interest to you as well.

"The formal ECS specification was developed to address gaming in a Javascript environment." - I wonder where you read that. ECS comes primarily from the C / C++ community, which benefits the most from it performance-wise because the programmer has a lot of direct control over memory management.

By the way: Unity has an experimental ECS system that uses C#. However, idiomatic ECS code in Unity is limited to a subset of the C# language that doesn't allow classes (only structures).

I highly recommend learning ECS and creating a mini-game with it.  It is fun to make, and will let you learn an entirely new paradigm.

@Philipp no, it doesn't "come primarily from C/C++ community" - the two seminal articles are entirely language-agnostic. The benefits are memory layout and complexity management, which are useful even in such horrible languages as Python and JavaScript.

@Evorlor, I am familiar with the basic concept, better now, same structure inverted data.  Turns out,  I have been using these concepts all along for my projects.

Performance will always depend on implementation. It's definitely possible to make well-performing non-ECS games, or poorly-performing ECS games, but there are certain performance tricks that ECS lends itself well to: particularly data-oriented design (DOD).
To have something to contrast against, let's imagine another component-based game written in a more idiomatic Object-Oriented Programming style (arguably naïve, but it helps for the sake of example):

Class GameObject contains a list of component instances attached to it.

Component is an abstract class (or an IComponent interface) with a virtual Update() method.
We implement different derived classes descending from Component (or implementing IComponent) for each different behaviour we want.

A scene contains a list of active GameObject instances.

Each frame, we iterate over each object in the scene, and each component on that object, calling Component.Update() which has been overridden for each behaviour we need.

In contrast to this, we'll implement our DOD-focused ECS version so that components are struct types, and we'll store them in contiguous arrays of the same type. Game objects with particular mixes of components will be just an index within a set of parallel component arrays commonly called an archetype. Systems will implement update functions that iterate over all archetypes with a specific component signature.
So we've added quite a bit of complexity and given up some flexibility. Now adding/removing a component from a game object isn't just a matter of calling List.Add()/RemoveAt(), instead we need to extract it from one archetype's buffers and append it to another, possibly creating a new bespoke archetype for this combination of components - certainly messy!
But here's what we can gain from this:

Good data locality: each cache line you pull in contains not just the component you want to act on now, but also the next component in the buffer, so it's already waiting for us when we want it. The linear access pattern allows the CPU to predict and pre-fetch the next cache line we'll want, letting us make full use of the available CPU and minimizing waiting on the slow memory bus.
This also works if a single system needs to access/modify multiple component types - using a Structure of Arrays layout, we can race down multiple of these packed buffers in parallel.
In contrast, our OOP example has strewn the GameObject and Component instances more or less randomly around the heap - taking whatever slot was available each time we called new Foo(). When we want to know what component to access next, we have to look up a pointer from the list, check that it's valid, then try to read the memory at that location. That memory is very likely not already in cache, so we incur a cache miss - burning hundreds of CPU cycles just waiting for the component data to be fetched from main memory - that's time when our CPU could have been doing useful work!

Good code locality: because we have one system executing again and again on  a big batch of data, the code we need to run is also continually in cache. We might even be able to write our update functions so they update batches of components at the same time - or the processor might be able to rearrange our code on the fly to interleave multiple loop iterations, so the fast parts get done while we're still waiting on the slow parts (it's scary what these chips can do these days!)
But for our naïve OOP example, we don't know which component class's Update() we want to call until we call it. That means chasing a pointer to the component instance, chasing a pointer to its VTable, and chasing a pointer to the function code to run it just once. Then for the next component we come to, we have to do it all again, since it's very likely a different component type than the previous one. Since we haven't used this new component's code lately, it's been evicted from the instruction cache and we need to burn hundreds of cycles again waiting to read it back in.

In practice, this data-oriented approach can yield large performance wins. I routinely hear from Unity developers who have observed 10x speedups when migrating code from conventional MonoBehaviour scripts (which act similar to the naïve OOP example) into Unity's Job System (which acts similar to the DOD ECS example).
Granted, that's not entirely a fair comparison because Unity's Burst compiler and multithreading give extra advantages to the Job version. But it's also true that it's the clear structure and dependency relationships of the ECS model that allow them to implement those optimizations.
What about public and private?
It's true that a system needs some means to change the internal state of the components, and the simplest way to do that is to make components Plain Old Data Structures with all members public. ECS purists may say this is the only way and that you should never have any code in a component.
But you don't get points for how "pure" your ECS is - what matters is how much you like working with it.
So you could implement private members in a component type, and setter or mutating methods on it that help it maintain some invariants without that responsibility leaking into the corresponding systems (or worse, needing to be shared or duplicated across multiple systems). If these methods are small, they might well get inlined into the system update methods anyway.
The "no code" guideline is mainly to help you step out of the "one update at a time" mentality that member methods encourage, and start to see opportunities for "batch update" approaches when you think of components as a stream of data. But we can bend that rule when it helps us develop more flexibly, avoid bugs, etc.

So... does all this mean we should always implement ECS, and never use convenient OOP features like inheritance, interfaces, etc?
Heck no!

The advantages described above assume you have big lists of components - enough to outweigh any overhead you're paying to get them into and manage those lists in the first place. In a game that has just a handful of objects of each type, you're not going to see big wins. Such a game will probably run just fine in the classic OOP style.
Where ECS shines is in games with huge numbers of similar objects. Think physics simulations with hundreds of dynamic bodies, crowd sims with hundreds of agents, endless procedural worlds that need to generate content over the horizon as fast as you can race towards it. If you're not making the kind of game that needs to cram all that in, you can prioritize ease of development instead. Because...

DOD ECS is kind of a pain. There's a lot of up-front complexity to set up, and conceptually simple things like adding/removing/disabling/re-enabling a component suddenly require non-trivial engineering. References between objects are also tricky to manage in this scheme.
All this makes iterating on a game in development much more complicated, and you might need larger refactoring to implement a design change, compared to how easily you can swap out and experiment with new component behaviours in OOP. So if you're not sure if you need ECS speed, or your game concept is still in flux, it may pay to prioritize development speed over processing speed - at least early in the project. Then once you have the core gameplay needs solidified, you can evaluate whether your performance is adequate, and whether a migration to ECS would be worthwhile.

We can take half-steps toward fixing the worst time sinks, without completely abandoning the OOP convenience. Re-using objects from a pool initialized at start-up helps improve data locality. Iterating your components in order by type rather than by what object they're attached to helps improve code locality. Using concrete types when practical saves the overhead of virtual method calls. You can probably think of dozens of other ways the simplistic OOP approach above could be improved, without paying the full engineering cost of the ECS style.

A good tweet I just saw helps put this in perspective:

Juan Linietsky
@reduzio
This is how I see abstraction/optimization balance in sw design:
Code executed less often is the large majority of the codebase and can benefit from more abstraction. Code executed more often needs better algorithms, and critical code (small minority) needs to be data oriented.

The abstraction we get from C# class inheritance, interfaces, virtual function calls, references, etc. helps a lot with stuff in the middle and left of that chart. And for many games, that's all you need. But some games have features at the right side of the graph, that demand the kind of high data throughput where these indirections are too costly, and the limitations/complexity of data-oriented approaches are a worthwhile trade for the speed we can get.

Thank you for you answer to the question as asked.  From your description of the DOD ECS model, this sounds like my tile system that uses one (or more, parallel) array(s) of integral types(saves an offset multiply and add compared to a struct). Works great for non-sparse data(memory usually wins, for arbitrary non-random values).  --  I use 95% concrete classes with interfaces, more for contract than their rare use. So  the answer for my case is probably not; beyond what I am already doing. I do not use Unity 3D.


text:
Dealing with block corners in a grid-based raycaster
I'm trying to build a simple grid-based raycaster, but I'm having trouble with rendering block corners.
First of all, I want to change the color of all the y-axis walls. But a block's corner belongs to both the y and x axis, so it's never clear whether it should be recolored or not. Because of this, when I place several blocks in a row, I end up with a wall with a bunch of vertical stripes on it.

The second issue is that when two blocks are placed in such a way that only their corners "touch", a ray can pass between them and hit something behind them, allowing the camera to see things it should not be able to.

Here is my current implementation of a raycaster that showcases these issues, written in Rust with Raylib:
use raylib::prelude::*;

struct Map {
    scale: i32,
    data: Vec<Vec<i32>>,
}

impl Map {
    fn get_tile(&self, mut x: i32, mut y: i32) -> i32 {
        (x, y) = (x / self.scale, y / self.scale);
        let (max_y, max_x) = (self.data.len(), self.data[0].len());
        if y >= 0 && x >= 0 && y < max_y as i32 && x < max_x as i32 {
            return self.data[y as usize][x as usize];
        }

        return 0;
    }
}

struct Camera {
    fov: i32,
    range: i32,
    h: i32,
    w: i32,
}

impl Camera {
    fn draw(&self, player: &Player, map: &Map, display: &mut RaylibDrawHandle) {
        display.draw_rectangle(0, 0, self.w, self.h / 2, Color::BLACK);
        display.draw_rectangle(0, self.h / 2, self.w, self.h / 2, Color::GRAY);

        for i in (-self.fov / 2)..(self.fov / 2) {
            let (mut rx, mut ry);
            let ra = player.direction + (i as f32).to_radians();

            // slow but simple
            for step in 1..self.range {
                rx = (player.x.round() + step as f32 * ra.cos()).round() as i32;
                ry = (player.y.round() + step as f32 * ra.sin()).round() as i32;

                // only recolors one side, but showcases issue well
                let mut color = Color::WHITE;
                if rx % map.scale == 0 {
                    color = Color::LIGHTGRAY;
                }

                if map.get_tile(rx, ry) > 0 {
                    let dist = (
                        step as f32 * (player.direction - ra).cos()
                    ).round() as i32;
                    let line_height = (map.scale * self.h / dist).clamp(0, self.h);
                    let line_width = self.w / self.fov;
                    display.draw_rectangle(
                        self.w / 2 + i * line_width,
                        self.h / 2 - line_height / 2,
                        line_width,
                        line_height,
                        color
                    );
                    break;
                }
            }
        }
    }
}

struct Player {
    speed: f32,
    rotation_speed: f32,
    direction: f32,
    x: f32,
    y: f32,
}

impl Player {
    fn move_relative(&mut self, side: f32, fwd: f32, delta: f32, map: &Map) {
        let normalized = Vector2::new(side, fwd).normalized();

        let speed = self.speed * delta;
        let mut nx = self.x + speed * normalized.y * self.direction.cos();
        let mut ny = self.y + speed * normalized.y * self.direction.sin();

        let side_direction = self.direction + 90_f32.to_radians();
        nx = nx + speed * normalized.x * side_direction.cos();
        ny = ny + speed * normalized.x * side_direction.sin();

        if map.get_tile(nx.round() as i32, ny.round() as i32) == 0 {
            (self.x, self.y) = (nx, ny);
        } else if map.get_tile(nx.round() as i32, self.y.round() as i32) == 0 {
            self.x = nx;
        } else if map.get_tile(self.x.round() as i32, ny.round() as i32) == 0 {
            self.y = ny;
        }
    }

    fn rotate(&mut self, r: f32, d: f32) {
        self.direction += r * self.rotation_speed * d;
    }
}

fn main() {
    let (mut rl, thread) = raylib::init()
        .size(800, 450)
        .resizable()
        .title("rustcast")
        .build();

    rl.set_window_min_size(64, 64);
    //rl.set_target_fps(60);

    let map = Map {
        scale: 40,
        data: vec![
            vec![1,1,1,1,1,1,1,1,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,0,0,0,1,0,0,0,1],
            vec![1,0,0,0,0,1,0,0,1],
            vec![1,0,0,0,0,0,0,0,1],
            vec![1,1,1,1,1,1,1,1,1],
        ]
    };
    let camera = Camera {
        fov: 80,
        range: 600,
        w: 800,
        h: 450
    };
    let mut player = Player {
        speed: 50.0,
        rotation_speed: 10.0,
        direction: 0.0,
        x: 100.0,
        y: 100.0,
    };

    while !rl.window_should_close() {
        let delta_time = rl.get_frame_time();

        let (mut move_h, mut move_v, mut rotate) = (0, 0, 0);
        if rl.is_key_down(KeyboardKey::KEY_A) { move_h -= 1 };
        if rl.is_key_down(KeyboardKey::KEY_D) { move_h += 1 };
        if rl.is_key_down(KeyboardKey::KEY_W) { move_v += 1 };
        if rl.is_key_down(KeyboardKey::KEY_S) { move_v -= 1 };
        if rl.is_key_down(KeyboardKey::KEY_Q) { rotate -= 1 };
        if rl.is_key_down(KeyboardKey::KEY_E) { rotate += 1 };
        player.rotate(rotate as f32, delta_time);
        player.move_relative(move_h as f32, move_v as f32, delta_time, &map);

        let mut dis = rl.begin_drawing(&thread);

        dis.clear_background(Color::BLACK);
        camera.draw(&player, &map, &mut dis);
        dis.draw_fps(0, 0);
    }
}

What can I do to fix these issues? And is it possible to do that without adding a lot of complexity?

Since you have a grid, you know something important: the ray is passing through a series of adjacent grid cells. You can fix both of your problem cases by making your code obey this rule.
Right now you're sampling along a fixed step size, which can skip over corners. A way to patch this algorithm to succeed would be to notice whenever the previous grid cell and the current grid cell are diagonally adjacent, and pretend the ray hit the one of the two diagonal cells in the mean time, thus making each individual step cross a specific, single face of a grid cell.
bad       patched
\ ##      \ ##
 \##  ->   `\#
##\       ##|
## \      ## \

Then, while you're doing this adjacency analysis, you can also determine which face of a grid cell is being entered (= which coordinate is changing and whether it is incrementing or decrementing). Then, you can choose colors according to that face and the cell coordinates, rather than only using the cell coordinates. If you do this, you will never see vertical stripes.

However, there is a better algorithm which not only inherently doesn't have this problem, but is also more efficient and precise because it takes exactly one step per grid cell examined (rather than taking steps smaller than cells). It is the algorithm presented in "A Fast Voxel Traversal Algorithm for Ray Tracing" by John Amanatides and Andrew Woo, 1987, and which I wrote up a practical example of in this answer, and later wrote a Rust version (though that is complicated with additional requirements, so it may not be the clearest sample).
While this algorithm as described is for 3D, you can make it 2D by just deleting the “Z” branch from the comparisons.

I took the first, simpler approach of patching my current algorithm. That fixed both my issues.


text:
ScenePointToLocalPointInRectangle no longer works after reloading scene
I have created a GUI that floats over an object. However, when I reload the scene, the ScreenPointToLocalPointInRectangle() function does not work and acts as if I used WorldToScreenPoint() instead. Here is a video showing the problem I'm facing.
This is my current code:
using UnityEngine;
using UnityEngine.UI;
using System;

public class GUI : MonoBehaviour
{
  public GameObject pressgui;
  public Image image;
  public float Radius;
  float x1,x2,y1,y2,ex,ey,vx,vy,cx,cy,tx,ty;
  float offset;
  int reverse;
  Vector3 reverseR;

  void Awake() {
      offset = 20f;
      x1 = Screen.width/2*-1+offset;
      x2 = Screen.width/2-offset;
      y1 = Screen.height/2*-1+offset;
      y2 = Screen.height/2-offset;
  }

  void Update() {
    pressgui.active = false;
    image.enabled = true;
    Vector3 loc = transform.position;
    var screenPosition = Camera.main.WorldToScreenPoint(transform.position + new Vector3(0.5f,2,0));

    Collider[] colliders = Physics.OverlapSphere(loc,Radius);
    RectTransformUtility.ScreenPointToLocalPointInRectangle(
        (RectTransform)pressgui.transform.parent, // pressgui's container
        screenPosition ,          // position measured in pixels
        null,                    // use this for Screen Space - Overlay canvas
        out Vector2 uiPosition // local UI space position
    );
    foreach (Collider hit in colliders){
        if(hit.gameObject.tag == "Player"){
            image.enabled = false;
            pressgui.active = true;
            pressgui.transform.localPosition = uiPosition;
        }
    }

    reverse = 180;
    reverseR = -Vector3.forward;
    vx = uiPosition.x;
    vy = uiPosition.y;
    if (vx > 0 )ex = x2; else ex = x1;
    if (vy > 0 ){ey = y2;} else {ey = y1;}
    if (vx == 0 )cx = 0;cy = ey;
    if (vy == 0 )cx = ex;cy = 0;
    tx = (ex - 0) / vx;
    ty = (ey - 0) / vy;
    if (tx <= ty ){ cx = ex; cy = 0 + tx * vy; }else{ cx = 0 + ty * vx;  cy = ey;}
    image.transform.localPosition = new Vector2(cx,cy);

    if(screenPosition.z<0){
        image.transform.localPosition = new Vector2(image.transform.localPosition.x*-1, image.transform.localPosition.y*-1);
        reverse = 0;
        gyakuu = Vector3.forward;
    }
    var dir = new Vector2(0,0) - new Vector2(image.transform.localPosition.x,image.transform.localPosition.y);
    var angle = Mathf.Atan2(dir.x,dir.y) * Mathf.Rad2Deg - reverse;
    image.transform.rotation = Quaternion.AngleAxis(angle,reverseR);
  }
}

Here's my Image setup:

Canvas setup:

And the object to which the script is attached:

Usually this is a symptom of one of the objects you were referencing getting unloaded. Check whether pressgui is null here. (In general: always check for null when something mysteriously stops working - it rarely has anything to do with the code attempting to use the null, and everything to do with the code that made the reference null, or failed to repopulate it)

@DMGregory: I debugged it, both before and after reloading. guican (UnityEngine.RectTransform) Debug:Log (object) was displayed.

I notice you no longer have an if check skipping this unless the player is close. Is it possible that multiple objects are running this script after a reload and fighting over where tp place pressgui? We'll need you to update the question to include a Minimal Complete Verifiable Example of the problem: every line of code and every step of scene setup needed to reproduce the problem in a new, empty project. Strip out anything not required, to keep this as lean as possible. Once we can reproduce the problem, we can test solutions to be sure they'll work for your situation.

@DMGregory: I used "Find Reference In Scene" to find conflicts, but it only attaches to one object.

When I say every line of code and every step of scene setup, the every is very important. The code above will not compile because we don't have the declaration of checkpoint, image, loc, radius, etc. To ensure you are sharing a Minimal Complete Verifiable Example, create a new, empty project. Add to the project only the content that is explicitly described in your question. If that project does not compile, run, and demonstrate the problem, you have not finished making your MCVE yet.

We're still lacking the instructions to set up a scene with this script, image, and pressgui set up in such a way as to reproduce the issue.

@DMGregory: Excuse me, what exactly do I have to do?

I've explained to you multiple times now. A reader needs to be able to use ONLY the information in your question to create a new project that demonstrates this problem. If you have not told them where to attach this script, or what to assign to its inspector fields, then they cannot succeed at that task.

@DMGregory: Changing the screen size was also found to cause the UI to move incorrectly.


text:
Possible to have Rule Tiles work with Rule Tiles in other Tilemaps in Unity?
I am using Rule Tiles to draw walls for my top down 2D Unity game. I have already been able to implement custom Rule Tiles that will work with each other (ie two different Rule Tile setups that still auto-tile together) but now I want to do the same but with Tiles that are in different Tilemaps.
The reason I have different tile maps is so that I can specify different behavior for certain sections of my walls when the player hits it. My idea is that I can paint my walls using either the "default" tilemap that just has basic colliders, OR I can paint parts of the wall with a different tilemap so that section of the wall has a certain behavior. All while all of the tiles still auto-tile and auto-update to look correct.
Is this possible? It seems that Rule Tiles simply are not aware of Tiles in other Tilemaps at all. If this isn't possible, is there a better way to do this? Thanks!

You may need CustomRulesForRuleTile. And access other tilemap data in your custom rules.


text:
Can a game use mythology-related names?
For instance can a game for collecting pets (such as cats, dogs, dragons, etc.)include a list of mythological names and then name the pets using these names?

What are you concerned might stop you from doing this? Are you worried that the Greek god Zeus himself might take you to court for violation of his personality rights, or misrepresentation of his brand? Or skip the legal process and just smite you with a lightning bolt?  More seriously, this seems like a question you could answer with the most cursory research of recently released games, including God of War Ragnarok, Hades, or Immortals Fenyx Rising, all of which feature characters with mythological names, with no evidence of adverse divine intervention.

You seem to be asking a lot of questions about legal topics. You should probably hire a lawyer.

Yes it can.
But you can't dress the pet, or draw it in a similar fashion that has been done before. You can't name your cat pet Zeus and dress it like Zeus the Mighty, for instance.
IANAL.

When it comes to legal questions, then don't rely on opinions from anonymous strangers from the Internet like me. Before you publish such a project, get a consultation with a real lawyer who specializes in intellectual property law. But the way I as a legal layman understand copyright and trademark law is this:
Regarding copyright: Ancient mythology is free for the taking, because the authors are already dead for much longer than 70 years. Just be careful that what you take is really from ancient mythology and not from another much more recent pop culture adaptation of that mythology. For example, when you have the Norse god Thor in your game, that's OK. But if that Thor has lots of aspects that aren't from Norse mythology but actually adapted from the Marvel character of the same name, then you might get into trouble with the almighty legal department of The Mouse.
But then you still need to be wary of trademarks. Because with trademarks, the question is not "who invented it", but "who uses it in commerce".
The purpose of trademarks is to avoid consumer confusion. The legal argument that is made in court to get someone liable for trademark infringement is "Consumer who want to buy our product could get confused by the similar name of this competing product and buy that instead".
For example, if you would name a game "Hades", then you could probably get into trouble with Supergiant Games because consumers could mistake your game for theirs and thus cost them sales. The excuse "But the term Hades is a concept from Greek mythology that is thousands of years old" would probably not save you. However, if you have just a location named "Hades" in your game while the game itself is named something completely different, that's probably not a trademark violation, because with an entirely different title it's unlikely to lead to consumer confusion.

For more information on copyright and trademarks for game developers, I recommend this video presentation from GDC 2018: Practical IP Law for Indie Developers 301: Plain Scary Edition.