text:
Listview With Custom Adapter, Checkbox Items And Select All option
I have an application that populate data from sqlite and put in a listview
1 of the holder in listview layout is a checkbox.
I also have 1 checkbox in the forupload activity which named select all, that if all the items in the listview are checked, the select all checkbox will be set as checked. And if I check the select all checkbox, all the items in the listview will be checked
ForUploadActivity.xml
<CheckBox
            android:id="@+id/chckbox_selectall_forUpload"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SELECT ALL"
            android:textStyle="bold"
            android:textAlignment="center"
            android:textSize="20sp"
            android:button="@null"
            android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
            android:drawableEnd="?android:attr/listChoiceIndicatorMultiple"
            tools:ignore="HardcodedText" />

        <ListView
            android:id="@+id/listview_forUpload"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center" />

**ListviewLayout.xml**

<TextView
    android:id="@+id/holder_name_forUpload"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:textStyle="bold" />

<TextView
    android:id="@+id/holder_address_forUpload"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@android:color/black"
    android:textStyle="bold" />

**ForUploadActivity**

ListView New_forUpload_List;
private Button Upload_Selected_Items, Delete_All;
com.vicjames.irca.ListAdapters.ForUploadListAdapter forUploadListAdapter;
private ArrayList list_forUpload_id = new ArrayList<>();
private ArrayList list_forUpload_name = new ArrayList<>();
private ArrayList list_forUpload_address = new ArrayList<>();
CheckBox select_All;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_for_upload);

    New_forUpload_List= findViewById(R.id.listview_forUpload);
    select_All = findViewById(R.id.chckbox_selectall_forUpload);
    viewData_forUpload();
    New_forUpload_List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        }
    });
    select_All.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

        }
    });

}

public void viewData_forUpload() {
    db = new DatabaseHelper(getApplicationContext());
    sqLiteDatabase = db.getReadableDatabase();
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT ID, (Last_Name || ' ' || First_Name || ' ' || Middle_Name) as Name, (Barangay || ' ' || Town) as Address FROM FOR_UPLOAD", null);
    list_forUpload_id.clear();
    list_forUpload_name.clear();
    list_forUpload_address.clear();

    if (cursor.moveToFirst()) {
        do {
            list_forUpload_id.add(cursor.getString(cursor.getColumnIndex("ID")));
            list_forUpload_name.add(cursor.getString(cursor.getColumnIndex("Name")));
            list_forUpload_address.add(cursor.getString(cursor.getColumnIndex("Address")));
        }
        while (cursor.moveToNext());
    }
    forUploadListAdapter = new com.vicjames.irca.ListAdapters.ForUploadListAdapter(getApplicationContext(),
            this.list_forUpload_asc_rec,
            this.list_forUpload_name,
            this.list_forUpload_address);

    New_forUpload_List.setAdapter(forUploadListAdapter);
    cursor.close();
}

**ForUploadListAdapter**

public class ForUploadListAdapter extends BaseAdapter
{
private Context context;
private ArrayList list_upload_id;
private ArrayList list_upload_name;
private ArrayList list_upload_address;
public ForUploadListAdapter(Context context, ArrayList<String> list_upload_id, ArrayList<String> list_upload_name, ArrayList<String> list_upload_address) {
    this.context = context;
    this.list_upload_id = list_upload_id;
    this.list_upload_name = list_upload_name;
    this.list_upload_address = list_upload_address;
}

@Override
public int getCount() {
    return list_upload_id.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return 0;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    ForUploadListAdapter.Holder holder;
    if (view == null)
    {
        @SuppressLint("WrongConstant") LayoutInflater layoutInflater =(LayoutInflater) this.context.getSystemService("layout_inflater");
        view = layoutInflater.inflate(R.layout.layout_for_upload_list, null, true);
        holder = new ForUploadListAdapter.Holder();
        holder.holder_fordownload_id = view.findViewById(R.id.holder_id_forUpload);
        holder.holder_fordownload_name = view.findViewById(R.id.holder_name_forUpload);
        holder.holder_fordownload_address = view.findViewById(R.id.holder_address_forUpload);
        view.setTag(holder);
    }
    else
    {
        holder = (ForUploadListAdapter.Holder)view.getTag();
    }
    holder.holder_fordownload_id.setText(list_upload_id.get(i));
    holder.holder_fordownload_name.setText(list_upload_name.get(i));
    holder.holder_fordownload_address.setText(list_upload_address.get(i));

    if (i % 2 == 1)
    {
        view.setBackgroundColor(Color.parseColor("#708090"));
    }
    else
    {
        view.setBackgroundColor(Color.parseColor("#00574B"));
    }

    return view;
}

public class Holder
{
    CheckBox holder_fordownload_id;
    TextView holder_fordownload_name, holder_fordownload_address;

    private Holder()
    {

    }
}

}

I tried [this][1] but I can't make it work..

can anyone give me idea how to implement this function in my project..

Thank you in advance..

  [1]: https://www.tutorialspoint.com/how-to-get-all-checked-items-in-a-listview-in-android

This looks like a general programming question to ask on StackOverflow. It does not appear to require game development specific expertise.

yah..but they deleted that question. Now I can't post or ask anything there.. When I open the site.. it says "You have a history of asking low quality questions."

You might want to work on that then, before you face a similar restriction here. For example, I notice you didn't even format your code above consistently. This sends a message to other users "your experience of reading my question is not worth my time" so they may very well feel that answering the question is not worth their time in return. Your question should also explain what you tried (not just link to a tutorial), and detail exactly where it went wrong / what specific problem you ran into trying to make it work.


text:
What are some of the tricks engine can use to render object that have extremely high polygons efficiently?
What are some of the tricks engine can use to render object that have extremely high polygons efficiently? I know one thing we do is render only the parts that the camera points at, but I am wondering if there are many more techniques used other than that one.

Batch, Batch, Batch. There is also a chance that you are seeing less polygons than you think. There is a lot that can be done with textures, levels of detail, and clever shaders to add detail to something with less polygons. But, if we are only talking about high polygon count, no tricks… Batch, Batch, Batch.

Questions asking for open-ended lists of tips are generally considered too broad for this site. Are you currently experiencing an inefficiency problem when rendering high-poly models? If so, editing your question to describe how your rendering process works now, and where your profiling is showing a bottleneck, would help focus this question on one specific problem that we can help you solve. You might already be using some tips, and others might not apply to your situation, so including detail about your problem helps answers zero-in on what new info would be most helpful.

There are three basic approaches to this problem.
Render Less
This includes techniques that allow you to skip rendering polygons that are not visible, while maintaining a high polygon count for those that are visible. It might include backface culling, frustum culling, visibility culling; LOD techniques might also fit here.
Render More Efficiently
Batching is the classic technique here, but it might also include scene traversal optimizations, shader optimizations, and other techniques that let you get more work out of available compute resources.
Fake It!
This includes techniques that let you take a low polygon representation and make it look like high polygon; normal mapping is one classic such technique, but it may also include tessellation or dynamic geometry creation.
On the whole you won't use one of these techniques in isolation, although batching is the one that is most likely to give you best results across the widest variety of use cases.

source: Stack Exchange

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

sort: votes


text:
Why can't I create a D3D12 Device with the highest performance adpater retrieved by EnumAdapterByGpuPreference?
    IDXGIAdapter* higher_performance_adapter;
    dx_result = dxgi_factory->EnumAdapterByGpuPreference(0, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE,
                                                         __uuidof(IDXGIAdapter),
                                                         (void**)&higher_performance_adapter);
    if(SUCCEEDED(dx_result))
    {
      UINT output_index = 0;
      IDXGIOutput* output;
      while(higher_performance_adapter->EnumOutputs(output_index, &output) != DXGI_ERROR_NOT_FOUND)
      {
        DXGI_OUTPUT_DESC output_description = {0};
        output->GetDesc(&output_description);

        ++output_index;
      }

      ID3D12Device* device;
      dx_result = D3D12CreateDevice(higher_performance_adapter,
                                    D3D_FEATURE_LEVEL_12_1,
                                    __uuidof(ID3D12Device),
                                    (void**)&device);
      if(SUCCEEDED(dx_result))
      {

          ...

I'm trying to create a D3D12 device selecting the GPU with the higher performance because passing null to the adapter parameter at D3D12CreateDevice gets the first adapater from EnumAdapters, which is the Intel integrated GPU. But, when I got a IDXGIAdapter object of my dedicated GPU, the EnumOutputs function failed, as well as the D3D12CreateDevice. Why is that? Why these functions fails when using the dedicated GPU, which in my case is a NVIDIA, ?
The returned dx_result is "0x887a0004 : The specified device interface or feature level is not supported on this system. "
That don't makes sense, since my system supports DirectX12.

Ok, I found the issue. I just opened my task manager to see information about my NVIDIA GPU. On DirectX verison it saids 12 (FL 11.0) which I realized that FL stands for Feature Level, which is exactly the seconds parameter for D3D12CreateDevice. I Just changed D3D_FEATURE_LEVEL_12_1 to D3D_FEATURE_LEVEL_11_0 and it works.
Now, I don't get it why the EnumOutputs failed. I mean, no outputs were found, event with the index 0.

See Anatomy of Direct3D 12 Create Device for some general advice on Direct3D 12 device creation. Keep in mind that you can in fact have a system where only some of the drivers/devices supports DX12 while others only support DX11. D3D_FEATURE_LEVEL_11_0 is also the best choice for broad hardware support for DX12.

In "hybrid graphics" systems (see AMD / NVIDIA versions), the output is not 'owned' by all devices. The integrated part usually owns the physical output to the device, while the discrete part does not. Similarly if a WARP device is created, it has no 'outputs'. You should also look at this thread.

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


text:
Unity C# Invoke Function Freezes Program
if(Input.GetKeyDown(KeyCode.G) && ammo <= 9)
        {
            ableS = false;
            while(ammo <= 9)
            {
                Invoke("bulletplus", 0.5f);
            }
            ableS = true;
        }

This is the main part I am having trouble with.
Down there is ALL my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class gun : MonoBehaviour
{
    Vector2 rotation = new Vector2 (0, 0);
    public float rot = 3;
    public Vector3 pos;
    public Rigidbody Orb;
    public Text ammoT;
    public int ammo = 10;
    bool ableS = true;

    void Update () {
        // Ammo
        if(ammo >= 7)
        {
            ammoT.GetComponent<Text>().color = Color.green;
        } else if(ammo >= 4)
        {
            ammoT.GetComponent<Text>().color = Color.yellow;
        } else {
            ammoT.GetComponent<Text>().color = Color.red;
        }

        // Rotation
        rotation.x += -Input.GetAxis ("Mouse Y");
        rotation.x = Mathf.Clamp(rotation.x, -70, 70);
        rotation.y += Input.GetAxis("Mouse X");
        transform.eulerAngles = (Vector2)rotation * rot;
        pos = new Vector3(transform.position.x, transform.position.y, transform.position.z);

        // Shoot Choklats
        if(Input.GetMouseButtonDown(0) && ammo >= 1 && ableS)
        {
            ammoT.text = "Ammo: " + ammo.ToString();
            ammo -= 1;
            Rigidbody projectile = Instantiate(Orb, pos, transform.rotation);
            projectile.velocity = transform.forward * 50f;
        }

        // Reload
        if(Input.GetKeyDown(KeyCode.G) && ammo <= 9)
        {
            ableS = false;
            while(ammo <= 9)
            {
                Invoke("bulletplus", 0.5f);
            }
            ableS = true;
        }
    }

    void bulletplus()
    {
        ammo += 1;
        ammoT.text = "Ammo: " + ammo.ToString();
    }
}

You pointed out the exact part of the code that is making your program freeze. You have a loop with a condition (ammo <= 9), yet the body of the loop won't make the condition to be false. Invoke calls the named function at a later time, but the process that calls the named function won't run until the Update function has finished. Therefore, you are calling Invoke infinite times.

Another way to look at what Panda Pajama explained: Unity does not advance game time until Update() method is finished. So that half a second your Invoke waits for never comes.

You seem to be under the impression that this line of code asks to do multiple things:
Invoke("bulletplus", 0.5f);

Schedule the method named "bulletplus" to be called 0.5 seconds from now.
Pause the execution of the current method we called it from, and let the rest of the engine continue running its updates and rendering for the frame.
Don't resume this method until "bulletplus" has run to completion. After that, resume the calling method with its prior state on the next line after the Invoke.

In actual fact, it only does the first line, in bold. Pausing and resuming the calling method are not features it offers according to the documentation. You can verify this yourself with a simple test:
void Start()
{
    Debug.LogFormat("{0}: Start starts at {1}", ++callOrder, Time.time);
    Invoke("InvokeReporter", 0.5f);
    Debug.LogFormat("{0}: Start finishes at {1}", ++callOrder, Time.time);
}

void InvokeReporter() {
    Debug.LogFormat("{0}: Invoked method runs at {1}", ++callOrder, Time.time);
}

You can see Invoke does not add any delay between the first and second halves of Start - they run back-to-back in the same frame.
So, as was pointed out to you in the comments, this is an infinite loop:
while(ammo <= 9)
{
     Invoke("bulletplus", 0.5f);
}

Scheduling an invocation of "bulletplus" to happen later does not increase the value of the ammo variable now. So if ammo was less than 10 when we entered the loop, it will still be less than 10 no matter how many times we repeat the loop, and we can never escape.
Apart from a coroutine hitting a yield statement, Unity executes each MonoBehaviour message method completely, from top to bottom or the first return statement, before moving on to the next object/message or proceeding with any of the other work of the frame.
So if your Update method gets stuck in this infinite loop and never returns, then Unity is stuck executing it endlessly, unable to move onto the next script that needs updating, or draw a new frame, or process new input. Your game hangs because the engine can't get to updating the window.
It looks like what you want is a coroutine something like this:
Vector2 rotation = new Vector2 (0, 0);
public float rotationSpeed = 3;
public Rigidbody projectilePrefab;

public Text ammoText;
public int ammo = 10;
bool reloadInProgress = false;

void Update () {
    // Rotation
    rotation.x += -Input.GetAxis ("Mouse Y") * rotationSpeed;
    rotation.x = Mathf.Clamp(rotation.x, -70, 70);
    rotation.y += Input.GetAxis("Mouse X") * rototationSpeed;
    rotation.y %= 360.0f;
    transform.eulerAngles = rotation;

    // Can't shoot or start another reload while already reloading.
    if(reloadInProgress)
        return;

    if(Input.GetMouseButtonDown(0) && ammo >= 1)
    {
        UpdateAmmo(-1);
        Rigidbody projectile = Instantiate(
                                 projectilePrefab,
                                 transform.position,
                                 transform.rotation);
        projectile.velocity = transform.forward * 50f;
    }

    // Reload
    if(Input.GetKeyDown(KeyCode.G) && ammo <= 9)
    {
        // Start a method that can take turns with the engine,
        // pausing for multiple frames then resuming when needed.
        StartCoroutine(Reload());
    }
}

IEnumerator Reload() {
    reloadInProgress = true;

    while(ammo <= 9) {
        // Put this coroutine on hold for a period of time,
        // while letting the rest of the game run.
        yield return new WaitForSeconds(0.5f);
        // Then resume our execution on the next line:
        UpdateAmmo(+1);
    }

    reloadInProgress = false;
}

// Let's do this update work only when the ammo changes, not every frame.
void UpdateAmmo(int ammoChange) {
    ammo += ammoChange;
    ammoText.text = "Ammo: " + ammo.ToString();

    if(ammo >= 7) {
        ammoText.color = Color.green;
    } else if(ammo >= 4) {
        ammoText.color = Color.yellow;
    } else {
        ammoText.color = Color.red;
    }
}

Thank you very much!!! This is the first time I have ever asked someone and responded like this... well appreciated!!


text:
Please spot something wrong in my code (Instantiation)
So, when this code runs, it will just spawn like 1000 copies of pipe(two rectangles) even with the Invoke.Here is my code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class generator : MonoBehaviour
{
    public GameObject pipe;
    GameObject piper;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Invoke("MakePipe", 1.0f);
    }

    void MakePipe()
    {
        piper = Instantiate(pipe, new Vector3(transform.position.x, Random.Range(-9f, 9f), transform.position.z), transform.rotation);
        piper.AddComponent<Pipe>();
    }
}
```

Why wouldn't it? What do you want to happen instead?

After 1 second it will begin to spawn pipes every frame - even the comment above Update() says that. Every frame you call a code that waits for 1 sec to do its thing.

I want to spawn pipes in 1 second intervals

@TroyD then you need to only call it once per second instead

How will I do it?

Oh nvm I have found InvokeRepeat or something... I sort of forgot, but its in the code

The simpliest solution is, you can count elapsed time in Update method by Time.deltaTime, when it reaches the desired cooldown, you call MakePipe, and reset timer.

If you fire a new Invoke every frame, you'll get a new pipe every frame after the delay finishes.
It looks like you want something much simpler:
IEnumerator Start() {
    while (true) {
        yield return new WaitForSeconds(1f);
        MakePipe();
    }
}

This starts when the script is loaded/enabled, waits one second, makes a pipe, then waits another second, in a loop forever, with no messy looking up of method name strings.


text:
Is collision detection with static environment necessary for npcs
I can't find any information on this topic. I'm wondering about the differences between the collision detection approach for player as opposed to npcs.
Basically NPCs will move strictly along the navigation mesh (constructed for static environment) with a pathfinding algorithm. And should in theory not collide with any static obstacles. In that case do we really need to check for collision against the static environment?
As opposed to NPCs, players are not bounded by navigation mesh. So we would definitely have to handle collision with static environment.
I'm wondering what the general consensus is around this in game development?

It sounds like you've reasoned this out for yourself. If in your game NPCs move only by their own navigation and can never leave the navmesh (eg. they can't be hurled by an explosion), then in your game navmesh alone would suffice, would it not? Don't rely on "general consensus" — it's a pretty worthless concept in game development where we're all working on vastly different games with unrelated needs. If this works for your game, use it — you do not need the blessing of strangers to do what works for you.

@DMGregory I don't completely agree. I don't want to reinvent the wheel if there's a generally accepted way to do something. I may go with an idea that seems promising at first, but turn out to have many shortcoming I didn't see right away. That's why I would rather listen to people who have had experience in doing something similar.

I haven't thought at all that the npcs may get pushed out of navigation mesh by explosion or other forces. Thanks for the suggestion! So I guess in that case I would definitely need collision check with static environment for npcs. And otherwise could go without it.

Summarizing my comment above:
You can forego collision-checking/handling between NPCs and static geometry if and only if NPCs can never leave the navmesh.
If an external force can throw NPCs off the navmesh, then they could potentially get into a situation where they'd collide with static geometry outside the navmesh area.
In some games this can cause a glitch where an NPC knocked back by a dynamic collision or explosion becomes stranded and can't find their way back to the navmesh, or just passes straight through the static objects entirely and falls out of the level.
If this can happen in your game, you may want to enable collision-checking anytime something pushes or ragdolls an NPC, and then disable it again once the NPC is safely back in control of their motion on the navmesh.
If you have no outside forces or other influences that can push NPCs off the mesh, or you enforce the navmesh bounds in such a way that they override these other influences, then you may be safe skipping static collision checks with them entirely.

In many games, the player is in fact following the navmesh. The player says the direction they would like to go and the character agent determines whether or not it is possible. This is much less computationally heavy than calculating collisions with the static environment. By following the navmesh, the NPCs are also able to move where the player can.


text:
How to calculate best move in Match-3 game?
I am having a hard time identifying how to approach this problem.
If you have a match 3 game and the objects can only be swapped horizontally and vertically, and only swapped if it will result in a match of 3 or more jewels, which will be removed, with each removed jewel adding +1 to the score.
How would I find the best possible move? I'm confused at where to start and been searching for a while now and getting nowhere.

Board  6x6 or 8x8
Matches  = 3 or more of same kind
write function to find best swap for maximum score.

Any help would be greatly appreciated !
EDIT: So I could iterate through the entire board with a nested for loop for the rows and columns, but im not sure what approach to take from here.
For example, say I start with top left which is "red" and I want to test if swapping this will result in a match. How would I go about searching and identifying all possibilities that would result in swapping this left equaling a match and score of 5.
**If I am being really unclear I apologies and will remove my question and possible reword.

Do you want the best move right now, or are you looking moves in advance?
If it's just the best move right now for the most points on this move, try every legal move and then pick the one with the highest value. Assume incoming gems during a chain reaction don't match with anything so you get the best you can calculate with no concern for what random gems might fall in to replace them.
If you want to look moves in advance, then you use the minimax algorithm on the above tactic. As you go more moves in advance, the unknown non-matching gems will take up more and more space, which mimics the inability to plan very far in advance in these games.

Thanks for your response!
Its for the move right now, so which jewel if moved up,down,left or right, will return the greatest amount of points.
Just confused how to implement the proper search.

Can you edit your question james, to show where you ran into trouble implementing the search?

Sure, apologies if im not being clear

Another approach is to brute force it. (Basically what Almo wrote, I will just explain the steps a bit more if you want only the best single move)

Make a copy of your game board. You always only work with the copy, not the original board.
You start at the top left tile. We are iterating now over the board, always checking to the right and bottom. You don't need to compare it to the left/ top since it would be a duplicated check.
If your current tile is a valid move, check how many points you got for it. If it was your first valid move, save the tile and direction of your move and the score. If it is a second valid move, compare the score. If it is higher, replace your old saved tile/ direction/ score.
After each valid made move, you grab another copy from the board and continue from the tile you checked last.
You can also check multiple moves, like what is the max score you can make in 3 moves. All you need to to is change the copy you take in 1. from the result board you get after you made the move.

One thing you need to pay attention is, how are you generating new tiles. If you have some CreateRandomTile(), you should replace it by a list that gets prefilled by a few dozen tiles from your CreateRandomTile(). That way you guaranty that you always have the same board. (And it is easier compared to clone the random function). You won't be able to evaluate the absolut best for 10 moves ahead, but 3 moves ahead is all you need. When you find the best 3 next moves, just make the first of the three and reevaluate again the next 3.

Would you want to count future random tile drops in your prediction function? A human player wouldn't be able to predict that the next 2 tiles to drop will be blue, completing a combo that makes this low-scoring move actually high-scoring, so it might be "cheating" if the AI can see the future or peek into the dealer's deck that way. One small optimization you can make is to pre-scan your board and record with each tile the number of tiles of the same colour it's connected to. Then you can test if an initial move is valid and get its score in constant time, without repeated adjacency searches.

It depends on for what he needs the function. If it is a power up bonus, it would make sense that it could display the most powerful move including dropping tiles

I'm pretty sure this problem doesn't have a neat algorithm to it, so brute force is the way to go:
var optimalMove = {points: -1, x: null, y: null, direction: null}
for each (x) {
    for each (y) {
        for each (direction in [up, down, left, right]) {
            // Create identical copy of the board so we don't mess up the actual board
            var copy = realBoard.copy()
            copy.moveTile(x, y, direction)
            var points = copy.removeConnectedTiles()
            if (points > optimalMove.points)
                optimalMove = {points, x, y, direction}
        }
    }
}
realBoard.moveTile(optimalMove.x, optimalMove.y, optimalMove.direction)

Can be slightly optimized by not doing a move if the board would look identical, e.g:
if(tileAt(x, y).color == neighbor(x, y, direction).color)
    continue

If you're having trouble finding which tiles are connected to which other tiles (so, finding the actual score) I would (off the top of my head...) look for the biggest Flood Fill. The algorithm is quite simple:
function floodFill(x, y, color = null, checked = []) {
    var tile = tileAt(x, y)
    if(color is null)
        color = tile.color
    else if (tile.color is not color)
        return 0;

    var sum = 0
    if(checked does not contain {x + 1, y})
        sum += floodFill(x + 1, y, color, checked + {x + 1, y})
    if(checked does not contain {x - 1, y})
        sum += floodFill(x - 1, y, color, checked + {x - 1, y})
    if(checked does not contain {x, y + 1})
        sum += floodFill(x, y + 1, color, checked + {x, y + 1})
    if(checked does not contain {x, y - 1})
        sum += floodFill(x, y - 1, color, checked + {x, y - 1})
    return sum
}

var highest = {score: -1, x: null, y: null}
for each (x, y) {
    if (floodFill(x, y) > highest.score)
        highest = {score: floodFill(x, y), x, y}
}

My implementation might have some issues, check the linked wikipedia page. Can definitely be improved in performance (if a tile has already been checked, no need to check it again).


text:
Smooth out movement of the snake in a 2d Snake game
I am working on a 2-D snake game in C++ with the SFML library. I would like to smooth out the movement of my snake as it looks extremely choppy currently.
How the Snake moves
The snake is made up of a list of parts. If I want to move the snake, I simply remove one part from the back (.pop_back()) and then add a new part in the front accrding to the velocity. This works perfectly. The speed of the snake must be the same as the distance between the parts.  So if the distance is 15, the will be 15. But a speed of 15 is extremely high, so I need to only update the snake every few frames or use sf::Sleep(). Since the snake moves such a high distance every frame, the movement doesn't look smooth at all. And since the speed must be equal to the distance between the parts, reducing the speed doesn't work too. How can I come about tackling this?

What's different with this question and the one you posted before? What's the issue with what has been discussed in the chat following the question? Please avoid deleting a question and reposting it, use the edit feature instead.

@Vaillancourt I posted a new question because i felt my previous one wasn't clear. The movement is still choppy :(

Okay, well when there are no answers, it's generally better to edit the question instead of deleting and reposting.

In particular, deleting and reposting instead of editing can look like an attempt to spam and circumvent moderation from the perspective of the algorithms the site uses, and cause automated restrictions to apply to your account. Editing avoids any false alarms like this.

I was writing an answer and then the question was deleted, I assumed it was solved, and let the black hole take what I had written. I'm busy now, probably I'll answer later.

@Vaillancourt tbh, this question is a little different from the previous one, I abandoned my previous idea.

Yes, as long as there are no answers, it's okay to change the scope a bit when editing a question :)

This solution is for grid based games. The idea is to have "turns". A turn will happen regardless of whatever or not there is input or not. At the end of the turn the avatar will be aligned to the grid, and a turn always takes the same time.
Pseudo-code:
var current_time = get_current_time();
var elapsed_time = current_time - start_time;
update_input(ref input);
if (elapsed_time > turn_duration)
{
    elapsed_time -= turn_duration;
    start_time += turn_duration;
    for (var part_index = 0; part_index < tail.length - 1; part_index++)
    {
        var part = tail[part_index];
        var next_part = tail[part_index + 1];
        part.start_position = part.end_position;
        part.end_position = next_part.start_position;
    }

    var final_part = tail[tail.length - 1];
    final_part.start_position = final_part.end_position;
    final_part.end_position = head.start_position;
    head.start_position = head.end_position;
    head.end_position = compute_next_position(head.start_position, input);
}

head.current_position = interpolate(head.start_position, head.end_position, elapsed_time);
for (var part_index = 0; part_index < tail.length; part_index++)
{
    var part = tail[part_index];
    part.current_position = interpolate(part.start_position, part.end_position, elapsed_time);
}

Thus, for every part, and for the head, we are storing where it was at the start of the "turn", and where it will be at the end of the turn. We use the elapsed time since the start of the turn to compute the current position via interpolation.
When, the turn ends, we use the input and the last position of the head to compute the next position of the head.
You can buffer input if you like. You can treat no input as going in the same direction if you like.
The code above can be modded to interrupt the motion. That would require to have an end_time and check against that, instead of turn_duration. Then you can update the motion as soon as input comes, and still have the turn end at the same instant. However, I do not think that is appropriate for snake.

(I can copy this over to your original question if you'd like to undelete that one and delete/close this one instead)
I'd solve this by storing an array of the grid points the snake head has run through, and the next point it's on its way toward.
Then we'll store a progress variable between 0 and 1, that represents how far the snake has progressed from its old position to its new position.
We'll number our snake parts from 0 for the head up to snakeSize - 1 for the last tail segment. In our positionHistory array, 0 will be the point the head is moving toward now, 1 will be the point the head just left, and snakeSize will be the point the last tail segment just vacated.
We can update the state like so:
progress += deltaTime / secondsToCrossOneTile;

if (progress >= 1.0f) {
     // TODO: Handle activating a new tail segment here
     //       when finishing the previous growth phase.

     // TODO: Handle eating a pellet here and beginning a new growth phase.

     for (int i = snakeSize; i > 0; --i) {
         positionHistory[i] = positionHistory[i - 1];
     }

     positionHistory[0] = PickNextPoint();

     progress -= 1.0f;
}

(You could also store your history as a circular buffer, and just shift the starting offset instead of copying all the data over one notch)
Now every frame we can run through each piece in the list, using this progress value as an interpolation weight between its old position and the new position.
for(int i = 0; i < snakeSize; i++) {
    snakePart[i].position = lerp(positionHistory[i+1], positionHistory[i], progress);
}

When you want to add a segment to the snake, you place it at the position of the last tail segment, and leave it stationary there until the next time we hit our progress >= 1.0f condition. Then you append it to the snakePart collection and extend the position history an extra notch.


text:
Synchronizing clients
I have a server-client setup where each client has a number of screens attached, and the screens together form the display. As such, the visuals displayed by each client needs to be roughly in sync. Luckily the domain is not high speed, so I don't have to have them all perfectly in sync, but obviously more in sync is better.
The physical network: About 10 clients need to be synced together. All clients that need to be synced are on the same gigabit LAN, latency is sub 1ms.
The network protocol: Clients are running 100ms behind real time (so there is a 100ms buffer for the server to send out updates).
The digital environment: Realistic environments moving at generally a slow speed (think rate of turn in the order of 10 degrees/minute generally, however it's possible to increase up to maybe 720 in extreme circumstances).
Requirements: There should be as little visible lag between clients as possible.
Requirements for answers: A concept is enough, pointing out the limitations or advantages to different methods would be appreciated. It would be great if it's something you've tried and had failures or successes with in the past, but spit-balling is ok too.
What a good answer would look like: "Using NTP is fine up to X ms or syncing Y clients, but if you need more accuracy than that you should look into doing Z". It doesn't need to be crazy in depth!

When you implement the simple solution (1) of each client synchronizing with a time server, do you get results that are adequate for your needs?

Comments are not for extended discussion; this conversation has been moved to chat.

Consulting the links in this answer, the system time in Windows for example can be synchronized to within 50 or even 1ms depending on your network setup — but this again is a detail of your specific installation that is in your hands to test but we can only guess about. This is why these quick tests are so important to understand the details of the problem space you're working within.

@DMGregory The expected de-sync artifacts would be tearing (lines across the screen not lining up). The visuals are realistic landscapes. The domain is not high speed such as an FPS. How do I translate that into a ms timing that could be assessed as acceptable? In my opinion that is an impossible step, which is why I am struggling to find this line of inquiry useful. I feel like a more useful approach would be to suggest solutions and give their expected performance. Eg "NTP is fine to 500ms" or whatever.

@DMGregory If you tell me what kind of solutions you are thinking about and how they perform then I can try to assess them. I strongly feel that would be a more productive avenue than trying to figure out how many MS would be acceptable through guesswork, and THEN discussing solutions and their performance in the end anyway.

Perfect. That's the kind of detail we need in your question, so edit it to be sure it states that clearly up-front. You can play to find the amount of desync you can tolerate by just getting a 60 fps video file of similar content as your app and playing it on two side-by-side devices. As for figures for NTP timing, you can find that through a web search — you can see I already provided you with three such values in the link above, but as I keep reminding you, this depends on your network configuration, which is why a test will tell us so much more about what will/won't work in your context.

@DMGregory It's hard to write a question without knowing what to include, I will edit in the details. Unfortunately there's a bit more nuance but a video might be an ok test. If you let me know what details would help you arrive and an answer then I can try to give you information. If you have 5 potential solutions then just a few lines would be plenty to help me research. Just let me know!

If you want to create a video wall (a large display from many smaller ones), then you should know that many graphic cards can do that out-of-the-box. They are usually limited to 3-6 displays, but there is some specialized hardware which can do many more. Could it be a better solution to have just one client and connect multiple monitors to it?

@Philipp That would eliminate a lot of headaches, however we require 30+ monitors and they are driven by quite beefy hardware so one machine is unfortunately not an option.  Definitely a good suggestion though if less monitors were needed, this question could well be an XY problem :)


text:
How to hide a sprite on trigger when the player enters the trigger zone?
I am making a roof for my 2D top down survival game, and I want to make it so that the roof disappears when the player enters the building, and re-appears when they leave.
Here is the code I've written so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Roof : MonoBehaviour {
    public GameObject roofGameObject;

    void OnTriggerEnter2D(Collider2D collision) {
        roofGameObject.SetActive(false);
    }

    void OnTriggerExit2D(Collider2D collision) {
        roofGameObject.SetActive(true);
    }
}

I got it to work so that, when I go in, the roof it disappears. But when I leave it stays disappeared. How can I fix that?

Is this script attached to the roofGameObject or one of its children, by any chance?

the roof game object

This script should not be part of the roof. Can you attach it and its trigger collider to the building instead? That way you won't get "trigger exit" messages when the roof is switched off.

Thanks so much its working now!

If you've solved your problem, please post your solution as an Answer below.

The problem is that an inactive GameObject no longer checks for trigger events. So when the collider which triggers the reactivation of the roof is on the roof itself, then it won't be able to reactivate itself.
One solution is to separate the trigger area for activating and deactivating the roof and the roof itself into two separate GameObjects.
Another solution is to not deactivate the whole roof gameObject, but only its Renderer component. That way the roof will disappear visually, but anything else the roof does will still work:
void OnTriggerEnter2D(Collider2D collision) {
    roofGameObject.GetComponent<Renderer>().enabled = false;
}

void OnTriggerExit2D(Collider2D collision) {
    roofGameObject.GetComponent<Renderer>().enabled = true;
}

By the way: Instead of making it disappear completely, you can also make it render slightly transparent. Assuming you are using a SpriteRenderer (as implied by 2d), you can do that by changing its color property to something with a low alpha-value:
Color translucentWhite = new Color(1.0f, 1.0f, 1.0f, 0.2f);

roofGameObject.GetComponent<SpriteRenderer>().color = translucentWhite;

However, in a 3d game, you likely want to use a MaterialPropertyBlock instead of the color-property.

the performance is better (on the build-in render pipeline) because it doesn't create new materials at runtime each time you change the color .
When you have shaders which have more than one color property, then you can control which color(s) to change.

Interestingly, the performance advantage of material property block goes away on the new scriptable render pipelines, which just shove all their material properties into one big buffer and draw in a batches by shader anyway. Now I need to get in the habit of figuring out which rendering pipeline folks are using to know which performance advice is relevant to them. Transition periods are messy!

@DMGregory That's good to know.


text:
Heat bar that always goes down but when near fire it goes up
For the fire I have this script on it.
public class HeatingZone : MonoBehaviour
{
    public float heatPerSecond = 1.0f;

    void OnTriggerStay2D(Collider2D other)
    {
        PlayerHeat heat = other.GetComponent<PlayerHeat>();
        if (heat != null)
        {
            heat.Heat(heatPerSecond * Time.fixedDeltaTime);
        }
    }
}

On the player I have this script.
public class PlayerHeat : MonoBehaviour
{
    public int maxHeat = 100;
    public float currentHeat;

    public HeatBar heatBar;

    void Start()
    {
        // all objects should spawn with full health
        currentHeat = maxHeat;
        heatBar.SetMaxHeat(maxHeat);
    }

    // method for getting healed
    public void Heat(float amount)
    {
        currentHeat += amount;
        // make sure we can't heal further than max health
        if (currentHeat > maxHeat)
        {
            currentHeat = maxHeat;
        }
    }
}

And for the heat bar I have this script.
public class HeatBar : MonoBehaviour
{
    public float UpdatedHeat;
    public Image Heat;
    public float HeatDecreasePerSecond;
    public int maxHeat = 100;
    public Slider slider;
    public Gradient gradient;
    public Image fill;

    // Start is called before the first frame update
    void Start()
    {
        HeatDecreasePerSecond = -0.5f;
    }

    // Update is called once per frame
    void Update()
    {
        UpdatedHeat += HeatDecreasePerSecond * Time.deltaTime;
        Heat.fillAmount = UpdatedHeat / maxHeat;

        if(UpdatedHeat >= maxHeat)
        {
            UpdatedHeat = maxHeat;
        }
    }

    public void SetMaxHeat(int heat)
    {
        slider.maxValue = heat;
        slider.value = heat;

        fill.color = gradient.Evaluate(1f);
    }

    public void SetHeat(int heat)
    {
        slider.value = heat;

        fill.color = gradient.Evaluate(slider.normalizedValue);
    }
}

There are no errors but it is not working. Please help.

"not working" is just about never enough information to diagnose a problem. There are many millions of ways for something to not work, including having no apparent effect, having the wrong apparent effect, runtime or compiler errors, setting your PC on fire, etc. The more you can tell us about the specific symptoms of the problem, the better we can narrow down the cause.

At a glance, it looks like you're tracking two different heat values. Your bar has a heat variable that goes down, and your player heat script has a heat variable that goes up. Did you mean to keep this state information in one place, so both the increase and decrease effects take place on the same stored quantity?

Oh maybe I mixed up heat variables. And I meant to only have one. Thanks and by not working I mean the heat bar is still going down in the fire trigger.

The problem appears to be that your PlayerHeat component does not tell the HeatBar component when its currentHeat value changes. There appears to be a method HeatBar.SetHeat which is supposed to be used for that purpose, but that method never gets called.
I would recommend to add a call to that method in the PlayerHeat.Update method. You could put it into PlayerHeat.Heat so the bar only gets updated when the heat actually changes. But you declared PlayerHeat.currentHeat as public, which means that it might get changed in other ways. So you need to keep that possibility in mind and continuously update the health bar in Update... or make that variable private and properly encapsulate access to it. (By the way: it is generally a good idea to declare everything private by default and only make things public when you have a good reason to.)
Further, it appears that you tried to implement the logic for continuously reducing heat in HeatBar.Update. Your implementation does not actually do anything, because all it does is change a variable UpdatedHeat which then does not get used for anything.  But I would not put that code there anyway, because the heat loss mechanic is not a part of the heat bar on the UI. It's a part of the player heat mechanic. So it should be part of the PlayerHeat behavior (if not a separate behavior). You might also notice that the currentHeat now changes every update, so one more reason to put the call to heatBar.SetHeat into PlayerHeat.Update.
public class PlayerHeat : MonoBehaviour
{
    public int maxHeat = 100;
    public float currentHeat;
    public float heatLossPerSecond;

    public HeatBar heatBar;

    void Start()
    {
        currentHeat = maxHeat;
        heatBar.SetMaxHeat(maxHeat);
    }

    void Update(){
        currentHeat -= heatLossPerSecond * Time.deltaTime;
        if (currentHeat <= 0) {
            currentHeat = 0;
            Debug.Log("You froze to death :(");
        }
        heatBar.SetHeat(currentHeat);
    }

    public void Heat(float amount)
    {
        currentHeat += amount;
        if (currentHeat > maxHeat) {
            currentHeat = maxHeat;
        }
    }
}

Thanks so much for the code cleanup and fix. But I am still having a problem. In the console it says this.
Assets\Scripts\PlayerHeat.cs(27,25): error CS1503: Argument 1: cannot convert from 'float' to 'int'
This is what is on line 27 heatBar.SetHeat(currentHeat);

@jiasjfo You should decide if you want to handle heat as type int or type float and then use the same type everywhere. (I would recommend float, so you don't get any problems with small changes getting rounded to 0 and thus not doing anything). But if you do want to convert (which I would not recommend), you could do this: heatBar.SetHeat((int)currentHeat);

Thanks so much it works!

So if i wanted to make it so when the players heat is under 40 it changes the players speed to slower. Would i say an if statement and say set player speed or something idk.

@jiasjfo Sounds like a good approach. If you have any problems with that, please open a new question.


text:
For my Heat I want to change the players speed but its not working
I have a heat bar for my player and I want it so if the player is at 40 heat or under the players speed slows. This is my script. The problem is when the player gets to under 40 heat the speed is not changing. Is this because I have a player speed on my movement script?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerHeat : MonoBehaviour
{
    public float maxHeat = 100;
    public float currentHeat;
    public float heatLossPerSecond;
    public float moveSpeed = 4f;

    public HeatBar heatBar;

    void Start()
    {
        currentHeat = maxHeat;
        heatBar.SetMaxHeat(maxHeat);
    }

    void Update()
    {
        if (currentHeat <= 40)
        {
            moveSpeed = 2;
        }

        currentHeat -= heatLossPerSecond * Time.deltaTime;
        if (currentHeat <= 0)
        {
            currentHeat = 0;
        }
        heatBar.SetHeat(currentHeat);
    }

    public void Heat(float amount)
    {
        currentHeat += amount;
        if (currentHeat > maxHeat)
        {
            currentHeat = maxHeat;
        }
    }
}

This is my movement script
public class PlayerMovement : MonoBehaviour
{
    public float moveSpeed = 5f;

    public Rigidbody2D rb;
    public Camera cam;

    Vector2 movement;
    Vector2 mousePos;

    // Update is called once per frame
    void Update()
    {
        movement.x = Input.GetAxisRaw("Horizontal");
        movement.y = Input.GetAxisRaw("Vertical");

        mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    void FixedUpdate()
    {
        rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);

        Vector2 lookDir = mousePos - rb.position;
        float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
        rb.rotation = angle;
    }
}

It does not look like you are setting the new speed value on your movement script. Can you include the movement script too, seems like an easy fix! You are setting the local variable moveSpeed  (local to PlayerHeat) to 2 when the current is equal to or less than 40, but you need to access the movement script and set the speed to this new value, you should also handle what happens when you are above 40 heat, resetting to default or some such.

I included the movement script now

I don't see where moveSpeed is declared in your movement script. It doesn't look like it's reading it from the heat script. How were you intending for these two scripts to communicate with one another?

You need to make sure you either drag the PlayerMovementScript into the slot on the PlayerHeat script or use GetComponent<ScriptName>() if it is on the same object!
What is worth bearing in mind is, all "MonoBehaviour" Scripts are Components that live on Game Objects so if you had a MonoBehaviour Script called "PlayerHealth" you could use this.GetComponent<PlayerHealth>(); to retrieve it.
Then do something like playerHealth.TakeDamage(damageAmount); to call public functions on it or, as you see below public fields(variables)
You would do something like
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHeat : MonoBehaviour
{
    public float maxHeat = 100;
    public float currentHeat;
    public float heatLossPerSecond;
    public float moveSpeed = 4f;
    //either drag your player movement script into this slot in the inspector
    public PlayerMovement playerMovementScript;

    public HeatBar heatBar;

    void Start()
    {
        currentHeat = maxHeat;
        //or if the script is on the same object you can just do
        //GetComponent<ScriptName>();
        playerMovementScript = GetComponent<PlayerMovement>();
        heatBar.SetMaxHeat(maxHeat);
    }

    void Update()
    {
        if (currentHeat <= 40)
        {
            //here we set the moveSpeed variable of playerMovementScript to the new
            //speed!
            playerMovementScript.moveSpeed =  2;
        }
       else
       {
           //You can reset the value here if you go above 40 heat, or not, upto you!
            playerMovementScript.moveSpeed =  2;
       }

        currentHeat -= heatLossPerSecond * Time.deltaTime;
        if (currentHeat <= 0)
        {
            currentHeat = 0;
        }
        heatBar.SetHeat(currentHeat);
    }

    public void Heat(float amount)
    {
        currentHeat += amount;
        if (currentHeat > maxHeat)
        {
            currentHeat = maxHeat;
        }
        }
   }

Thanks so much!


text:
OnTriggerEnter error: The message parameter has to be of type: Collider
I have a crate and I want to make it so if you are in the trigger of the crate a UI appears and says "Click E to loot".
I have the UI setup but the script is not working. Here is my script and after it are the errors.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class UI_Appear : MonoBehaviour
{
    [SerializeField] private Image image;

    void OnTriggerEnter(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            image.enabled = true;
        }
    }

    void OnTriggerExit(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            image.enabled = false;
        }
    }
}

The errors say:

Script Error: OnTriggerEnter
The message parameter has to be of type: Collider
Script Error: OnTriggerExit
The message parameter has to be of type: Collider

Your error message tells you exactly what's wrong: when you implement the OnTriggerEnter message, Unity expects the parameter to be of type Collider.
But the way you wrote your OnTriggerEnter(Collider2D other), its parameter is of type Collider2D.
These are completely unrelated types - one is from the 3D physics system using PhysX, the other is from the 2D physics system using Box2D.
If you want 2D physics, you need to use the 2D versions of these message functions, as shown in recent answers to your questions:
void OnTriggerEnter2D(Collider2D other)
{
    // ...
}

Thanks I also added a on start the image is false because it was showing itself on start. Do you know how to make is so when I click E in the trigger the crate destroys itself? I just dont know how to only let it work when in trigger.

Did you consider storing a boolean variable when something enters the trigger, and clearing it when it leaves?


text:
Crate destroy when in trigger and button E pressed
There are no errors in the console but I feel like im doing something wrong. The crate is not destroying when I click E.
public class CrateDestroy : MonoBehaviour
{
    public GameObject crate;

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                Destroy(crate);
            }
        }
    }
}

Does the crate have a Collider attached to it with "is Trigger" checked?
"Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody. If both GameObjects have Collider.isTrigger enabled, no collision happens. The same applies when both GameObjects do not have a Rigidbody component." - https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html

Okay I added a trigger collider( I had it in the wrong spot) But when I click E it deletes sometimes. I spam E and it eventually deletes.

Seems like that is another question, perhaps with this question, you should answer your own question, and explain why the events weren't triggering for others in the future, then start a new one,  I can help you with that one too.

Do not edit the solution into your question, instead you can post an answer yourself and mark it as accepted.

"If both GameObjects have Collider.isTrigger enabled, no collision happens" This is somewhat misleading. As shown in the matrix at the bottom of this page, trigger messages are still sent between two colliders with isTrigger checked, so long as at least one of them is non-static.

Solved Make sure to have the trigger collider in same game object as the script.

Although your code already works and your problem is solved, the script can be cut down a little bit and become a bit more efficient. Instead of using an if statement wrapped in another if statement, you can simply combine the two together, as seen below:
void OnTriggerStay2D(Collider2D other)
{
    if (other.CompareTag("Player") && (Input.GetKeyDown(Keycode.E)))
    {
            Destroy(crate);
    }
}


text:
What in the BOTW game engine makes physics behave wildly when certain actions are triggered during bullet-time?
What in the BOTW game engine makes physics behave wildly when certain actions are triggered during bullet-time?
https://www.youtube.com/watch?v=dXKsTrwZ6XY
Also, what can you do to prevent it? Is this problem unavoidable when you include bullet-time?

Probably it is better to word this question in terms of imitating that behavior. Yes, it can be avoided. It seems to be something with time scaling. I'm not sure if forces, velocities, or what.

I’m voting to close this question because we can't know exactly what's going wrong. There are a few possibilities, but absent a dev coming here and telling us, this question can't be answered.

Is this a problem you've encountered in your own game? Showing us how you've run into it in your own development can make it easier to find fixes/preventative measures that will work for your context.


text:
Rotation matrix to look at point p
Assume a left-handed coordinate system where x is right, y is up, and z is into the screen. You have a unit vector pointing up along the y-axis. What's the rotation matrix for pointing the unit vector along the y-axis to an arbitrary point p?
I was asked this question during a phone screen. The interviewer implied there's an easy way to get this rotation matrix by "dropping in" a few values. I'm reading a 3D math book hoping to find this easy way but no luck yet. The ways to get this matrix in the book all seem too long to recite over the phone during an interview.
I think I can see part of the solution. The rows of the matrix are the post-transformation basis vectors. So the middle row of the matrix is just the point p possibly normalized (since that's where the y-axis will be post-rotation).
Any help with this easy "drop in" way of getting the rotation matrix is much appreciated!
Edit: If it seems like the problem statement is missing information please call it out. I feel like I remember the interview clearly but I could have left something out (or the interviewer could have).

First let's get the direction we want our y vector to point:
yDirection = Normalize(p - viewPoint);

(Here viewPoint can be the origin, since it doesn't look like you were given a specific location for the observer)
If this works out to be the zero vector then we need to fall back on some sensible default, which I'll elide here.
There's an infinite number of rotation matrices that will map the local y+ axis to point along yDirection (take any matrix that does this, and apply an extra rotation around the axis yDirection: now you have a new distinct matrix that still does what we asked), so we'll need to make some arbitrary choices here.
Let's decree that our rotation will take the local x+ axis and map it into the world xz plane. We always have at least one way to do this while staying perpendicular to yDirection. If we have a whole plane of choices, then we'll just map it to the world x+ axis by fiat.
xDirection = Cross((0, 1, 0), yDirection);

if (xDirection == (0, 0, 0)) {
     xDirection = (1, 0, 0);
} else {
     xDirection = Normalize(xDirection);
}

Now we have two perpendicular unit vectors to map x and y to. We can cross them to get the remaining z:
 zDirection = Cross(xDirection, yDirection);

And finally we can combine the three into a rotation matrix, whose first column is xDirection, second column is yDirection, and third column is zDirection. (Assuming you multiply Matrix * vector. If you go vector * Matrix, then use these direction vectors as the matrix's rows instead)
I work through this relationship in more detail in this answer.


text:
Help with inventory!
Ok so i made this inventory script but the items are not picking up and not appearing in the inventory. Im new to c# so that is why im asking this question also ive never done an inventory before. I want the medkit to go in the medkit slot. And bandage in the bandage slot and so on. Here are my scipts.
Here is my inventory script attached to the player.
public class MedInventory : MonoBehaviour
{
    public bool[] isFull;
    public GameObject[] MedkitSlot;
    public GameObject[] BandageSlot;
    public GameObject[] CoffeeSlot;
    public GameObject[] SyringeSlot;
}

Here is the medical pickup script attached to the item pickup.
public class MedPickup : MonoBehaviour
{
    private MedInventory medInv;
    public GameObject itemButton;

    private void Start()
    {
        medInv = GameObject.FindGameObjectWithTag("Player").GetComponent<MedInventory>();
    }

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            if (other.CompareTag("medkit"))
            {
                for (int i = 0; i < medInv.MedkitSlot.Length; i++)
                {
                    if (medInv.isFull[i] == false)
                    {
                        medInv.isFull[i] = true;
                        Instantiate(itemButton, medInv.MedkitSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }

            if (other.CompareTag("bandage"))
            {
                for (int i = 0; i < medInv.BandageSlot.Length; i++)
                {
                    if (medInv.isFull[i] == false)
                    {
                        medInv.isFull[i] = true;
                        Instantiate(itemButton, medInv.BandageSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }

            if (other.CompareTag("coffee"))
            {
                for (int i = 0; i < medInv.CoffeeSlot.Length; i++)
                {
                    if (medInv.isFull[i] == false)
                    {
                        medInv.isFull[i] = true;
                        Instantiate(itemButton, medInv.CoffeeSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }

            if (other.CompareTag("syringe"))
            {
                for (int i = 0; i < medInv.SyringeSlot.Length; i++)
                {
                    if (medInv.isFull[i] == false)
                    {
                        medInv.isFull[i] = true;
                        Instantiate(itemButton, medInv.SyringeSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }
        }
    }
}

Please help and thanks!

Are there any errors?
Is the casing on your tags right? I notice some are capitalized and some aren't.
You are repeating yourself a lot in this code. See about splitting it into more methods so you can avoid that? 4. Is it actually the player that is supposed to have ALL these tags?

There are no errors. 2. Yes I just checked again all the casing and spelling is right. 3. I will look at that. 4. The player should only have the Player tag I think.

"if (other.CompareTag("medkit"))"
I do believe you are checking the player for that tag, are you not? "other" being what you collided with?

Oh how would i call that tag function for an item pickup?

It looks like you are checking the same "other" GameObject in your OnCollisionStay function for two different tags. This should successfully identify your player (assuming they are tagged as "Player") but will skip all code adding items to their inventory (since the player is not tagged "medkit", "bandage", etc.). You should be able to fix this by checking your pickup gameobjects tag.
I apologize if the code sample below is confusing (I figured since you are new to coding cleaning up the script a little might be helpful as an example), the key take away is that instead of calling gameObject.tag to check the current pickup item type instead of other.ComapreTag. You may also want to look into using interfaces/subclasses for your items since they should probably fit and it would let you avoid having a separate array for each item type.
public class MedPickup : MonoBehaviour
{
    private MedInventory medInv;
    public GameObject itemButton;

    private void Start()
    {
        medInv = GameObject.FindGameObjectWithTag("Player").GetComponent<MedInventory>();
    }

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            GameObject[] targetSlot = new GameObject[0]; // need to initialize this to something to avoid compiler error.
            bool validItem = true;

            switch (gameObject.tag)
            {
                case "medkit":     targetSlot = medInv.MedkitSlot;     break;
                case "bandage":    targetSlot = medInv.BandageSlot;    break;
                case "coffee":     targetSlot = medInv.CoffeeSlot;     break;
                case "syringe":    targetSlot = medInv.SyringeSlot;    break;
                default:           validItem = false;                  break;
            }

            if (validItem)
            {
                for (int i = 0; i < targetSlot.Length; ++i)
                {
                    if (!medInv.isFull[i])
                    {
                        medInv.isFull[i] = true;
                        Instantiate(itemButton, targetSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }
        }
    }
}

Thanks! This works but only the first item you touch is picking up. Also the Item buttons are appearing over the character at all times. I need those buttons to appear only when its in the players inventory.

No worries glad it helps a little even if buggy. Since I copied and reorganized your original code a little I don't think I introduced any new issues. Did you have similar problems with your old code or is this definitely something I introduced? As far as I can tell this should simply add a button each time an object is picked up and parent the button to the targetSlot transform. You may need to move the localPosition or localRotation to match your UI. As for this only working once, you may want to look into using break points to see if other pickups are firing the script when collided.


text:
Inserting into the first available inventory slot
Hello my inventory system picks up one item but does not pickup any more to fill the other two slots. It is saying the whole inventory is full when it should be one slot is full.
Here is my code for the inventory and this is attached to the player.
public class MedInventory : MonoBehaviour
{
    public bool[] isFull;
    public GameObject[] MedkitSlot;
    public GameObject[] BandageSlot;
    public GameObject[] CoffeeSlot;
}

This next script is attached to the items you pickup.
    public class MedPickup : MonoBehaviour
{
    private MedInventory medInv;
    public GameObject itemButton;
    private void Start()
    {
        medInv = GameObject.FindGameObjectWithTag("Player").GetComponent<MedInventory>();
        itemButton.SetActive(false);
    }

    void OnTriggerStay2D(Collider2D other)
    {
        if (other.CompareTag("Player"))
        {
            GameObject[] targetSlot = new GameObject[0];
            bool validItem = true;

            switch (gameObject.tag)
            {
                case "medkit": targetSlot = medInv.MedkitSlot; break;
                case "bandage": targetSlot = medInv.BandageSlot; break;
                case "coffee": targetSlot = medInv.CoffeeSlot; break;
                default: validItem = false; break;
            }

            if (validItem)
            {
                for (int i = 0; i < targetSlot.Length; ++i)
                {
                    if (!medInv.isFull[i])
                    {
                        medInv.isFull[i] = true;
                        itemButton.SetActive(true);
                        Instantiate(itemButton, targetSlot[i].transform, false);
                        Destroy(gameObject);
                        break;
                    }
                }
            }
        }
    }
}

Well, you are only checking if your medInv is full but you should check if the target slot is full. Your isFull code is missing as well.

How would you do that?

There is so much wrong with the code on many places, you should first read up a bit about arrays and what they are or for what they are used. Second - how many items can you stack into each slot? Are you setting it in the inspector or can you hold only one item of each? (medkit, bandage, coffee)

Why is this code on your pickup object at all? When you pick up a coffee cup, is it because you decided you wanted some coffee? Or did the coffee cup decide that for you and insert itself into your hand?

Thanks sorry if its messy and wrong im just a begginer

@jiasjfo - don't apologize for being a beginner, we all have to start somewhere. It's just that, for us to be able to help you, you need to explain to us clearly what you're trying to do, as we can't understand all the relevant aspects of it by just looking at the code. Maybe I'm wrong, but it looks like you found some code online, and modified it without really understanding what exactly it does. That's OK, but now some bits of the code don't entirely make sense to us, so it would help if you clarified things further.

E.g, it's not clear why you have 3 arrays for your inventory slots - is that on purpose (e.g., you can stack up several medkits into the same slot), or is it a fluke, and you meant to have a single slot for a medkit? You need to tell us a bit more about what you're trying to do. Also, it would help if you read up a bit on how to use arrays and loops (or went through this tutorial).

Okay I will be more clearer and @FilipMilovanović I do want to be able to stack multiple items.

First, let's simplify your pickup. We'll use an enumeration to denote our various inventory item types, so we're not constrained by the tag system and don't need to do messy string marshalling and comparisons.
public enum InventoryItemType : int {
    Medkit,
    Bandage,
    Coffee
}

Now your pickup class can be a "Plain Old Data Structure" - a coffee cup takes no actions on its own, so it needs no methods.
public class Pickup : MonoBehaviour {
    public InventoryItemType type;
    public RectTransform inventoryButtonPrefab;
}

Notice how now, we don't need every pickup in the game to hold a reference to the inventory UI - that's not the coffee cup's job!
The inventory can be managed in one place, by a script on the player character. (Or on each player character, allowing you to support multiplayer. Or you could allow NPCs to pick up items, etc. - much more flexibility this way)
public class PlayerInventory : MonoBehaviour {
    // For convenience, let's make a type that bundles together
    // the UI slot for our inventory item, and the item that's in it.
    [System.Serializable]
    public struct InventorySlot {
        public RectTransform container;
        public RectTransform contents;
    }

    public InventorySlot[] MedkitSlots;
    public InventorySlot[] BandageSlots;
    public InventorySlot[] CoffeeSlots;

    void OnTriggerEnter2D(Collider2D other) {
        // We test whether this object has the component we care about,
        // so it's free to use tags for other purposes.
        if(!other.TryGetComponent(out Pickup pickup))
            return;

        // No need to initialize this with a value we're about to overwrite anyway.
        InventorySlot[] inventory;
        switch(pickup.type) {
            case InventoryItemType.Medkit:  inventory = MedkitSlots;  break;
            case InventoryItemType.Bandage: inventory = BandageSlots; break;
            case InventoryItemType.Coffee:  inventory = CoffeeSlots;  break;
            default:
                Debug.LogErrorFormat("Unknown pickup type {0}", pickup.type);
                return;
        }

        for(int i = 0; i < inventory.Length; i++) {
            var slot = inventory[i];
            if(slot.contents != null)
                continue;

            slot.contents = Instantiate(pickup.inventoryButtonPrefab, slot.container, false);
            inventory[i] = slot; // Save our modifications to this slot.
            Destroy(other.gameObject);
            return;
        }

        Debug.LogFormat("Can't pick up {0}, inventory slots all full.", pickup.name);
    }
}

Okay so where should the Button prefabs go? In the center of the UI? at 0,0? These buttons look like the items you pick up.

Also only the medkit is working when i put it at 0,0 in the UI or the middle of the screen it goes to the slot. But the bandage and coffee just go to a random place on the screen. Also when I click play the when i put the button prefabs in the middle of the UI they appear in the game too

The button prefabs are not part of your scene. They're assets in your project folder, as prefabs normally are. Note that this isn't anything new in this version, I just took the itemButton you were already using and renamed it.

Okay so now all the items go to there slots except the bandage. Do you know why?

Okay nevermind it works now the bandage prefab was not at 0,0


text:
Texas hold'em game logic loop
Ok, so I was thinking of making a Texas Hold'em game, and I wanted to write down the game logic loop before starting. Here's what I have. Tell me if I missed anything or if anything is wrong.

Game sets or determines the number of players.
Game hands out 2 cards to each players.
Game takes a minimum amount of tokens from each player
Game lets players fold, play, or raise
If someone raise, the game let's other players fold or play, and then loop through the players who decided to play, but haven't put in the amount of required tokens.

If someone goes all in and one other person accepts, then the cards
of both players are shown.

Game draws 3 random cards and show it to the players.
Steps 4 to 5 are repeated to the player who didn't fold.
Game draws 1 more card and show it to the players
Steps 4 to 5 are repeated to the players who didn't fold.
Game draws 1 more card and show it to the players.
One player wins the lot
Repeat until one player is left.

Is this the correct loop? Is there anything to add or modify? Can you make this clearer?

There are some split pot rules you are missing. Point 11,there can be more than one winner. As well when for example two player go all in (one with 5 and one with 10 chips). A third person calls. The person with 5 chips has the highest cards, but he won't win the full pot. You would need to determine if the second all in or the third person gets the rest.

More than 1 winner? I have never heard of it. Does it only apply when there are 3 players? What are the exact rules?

It's called split pot for more than one winner and the other scenario is called side pot. You should be able to find more information with those search terms


text:
The gameloop is stucking the window
I tried to display a player image in a 800x600 window using PyGame but when I try it, the window just gets stuck (immovable with mouse drag, minimize,maximize and close button is stuck and not clickable).
I have no Idea for the reason.
Here's the code:
from pygame.locals import *
pygame.init()

fps = pygame.time.Clock()

WINDOW_SIZE = (800, 600)
pygame.display.set_caption("Game")
screen = pygame.display.set_mode(WINDOW_SIZE, 0, 0)

player_image = pygame.image.load("Witch.png")
location = [0,0]

while True:

    screen.blit(player_image, location)

    pygame.display.update()
    fps.tick(60)

pygame.quit()

Please help me where I have made a mistake or what I should do. Thanks in advance.

You need to handle events regularly. Usually that is calling pygame.event.get(). For example:
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

If you are doing nothing with the events, you can call pygame.event.pump() instead.


text:
text rendering artifact when rendering in 3D opengl GLfW
Main.cpp
//Variables
const unsigned int width = 896, height = 504;

//Initiating GLFW Window
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

//Creating a GLFW window
window = glfwCreateWindow(width, height, "Jaguar", NULL, NULL);

//Checking if Window was initiated
if (window == NULL) {
    std::cout << "GLFW FAILED TO INITIATE WINDOW!\n";
    glfwTerminate();
}

glfwMakeContextCurrent(window);

//Centering Window
int windowWidth, windowHeight;
glfwGetWindowSize(window, &windowWidth, &windowHeight);
const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor());
glfwSetWindowPos(window, mode->width / 2 - windowWidth / 2, mode->height / 2 - windowHeight / 2);

//Setting-Up window's icon
GLFWimage icon[1];
icon[0].pixels = stbi_load("resources/images/gui/icon/icon.png", &icon[0].width, &icon[0].height, 0, 4);
glfwSetWindowIcon(window, 1, icon);
stbi_image_free(icon[0].pixels);

//Checking if Glad was initiated
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
    std::cout << "GLAD FAILED TO BE INITIATED\n";
}

glEnable(GL_CULL_FACE);
glEnable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

stbi_set_flip_vertically_on_load(true);

//Setting-Up Viewport
glViewport(0, 0, width, height);

//Intitiating MainMenu
states.push(new MainMenuState(*window, &states));

font.cpp
FT_Library ft;

if (FT_Init_FreeType(&ft)) {
    std::cout << "FREETYPE::Failed to initialize library\n";
}
FT_Face face;
if (FT_New_Face(ft, filePath, 0, &face)) {
    std::cout << "FREETYPE::Failed to load to font: " << filePath << "\n";
}

// set size to load glyphs as
FT_Set_Pixel_Sizes(face, 0, px);

glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

for (unsigned char c = 0; c < 128; c++) {

    if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
        std::cout << "FREETYPE::Failed to load glpyh\n";
    }
    unsigned int texture;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, face->glyph->bitmap.width,
        face->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE,
        face->glyph->bitmap.buffer);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    Character character = {
    texture,
    glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
    glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top)
    ,face->glyph->advance.x };

    Characters.insert(std::pair<char, Character>(c, character));
}
FT_Done_Face(face);
FT_Done_FreeType(ft);

text.cpp
// activate corresponding render state
shader.use();
glUniform3f(glGetUniformLocation(shader.id, "textColor"), color.x, color.y,
color.z);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(VAO);

// iterate through all characters
std::string::const_iterator c;
for (c = string.begin(); c != string.end(); c++)
{

    Character ch = font.Characters[*c];

    float xpos = position.x + ch.bearing.x * scale;
    float ypos = position.y - (ch.size.y - ch.bearing.y) * scale;

    float w = ch.size.x * scale;
    float h = ch.size.y * scale;
    // update VBO for each character
    float vertices[6][4] = {
        { xpos,     ypos + h,   0.0f, 0.0f },
        { xpos,     ypos,       0.0f, 1.0f },
        { xpos + w, ypos,       1.0f, 1.0f },

        { xpos,     ypos + h,   0.0f, 0.0f },
        { xpos + w, ypos,       1.0f, 1.0f },
        { xpos + w, ypos + h,   1.0f, 0.0f }
    };
    // render glyph texture over quad
    glBindTexture(GL_TEXTURE_2D, ch.textureId);
    // update content of VBO memory
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    // render quad
    glDrawArrays(GL_TRIANGLES, 0, 6);
    // now advance cursors for next glyph (note that advance is number of
1/64 pixels)
    position.x += (ch.advance >> 6) * scale; // bitshift by 6 to get value in
pixels (2^6 = 64)
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);

There is a box because you're rendering the text over the scene.

@a_donda Is there a way to just render the text and have the box transparent?

Are you correct use alpha blending? Are you draw text last? And are you have alpha in texture?

Yes. But the freetype pages and numerous examples explain that exhaustively. Also, you don't want to have blending enabled all the time. Here's how text rendering can go: extract glyphs, assemble font texture/s, assemble static buffer/s for fixed text. Enter loop: assemble dynamic buffer/s for per frane text, render scene, enable alpha blending, render text, diable alpha blending, next frame.

@a_donda I understand the article im just not sure if im over seeing something like if i forgot to enable something at the current moment performance is not a concern right now

Show the code of your shader.

@d3m4nz3 Im using the shader provided by the learn opengl: https://learnopengl.com/code_viewer_gh.php?code=includes/learnopengl/shader.h

That's the C++ code used to load the shaders, not the source code of the shaders. The shaders are the files written in GLSL language. Since you obviously didn't write them yourself, there's little chance that there is a problem in there, though.

@d3m4nz3: Shaders are in there. The example does work, Imo, OP has problems with OpenGL state. I suggest to first run the learnopengl code (which it does right away), then combine it with a scene. If problems occur then, they can ask again naming the changes they did. The snippets shown are just learnopengl code, the errors are elsewhere (probably in the sequence of draw calls and state changes). And, btw., as stated in the there, this is not a sustainable way of text rendering in the long run.

To remove box around text(ASSUMING YOU HAVE GL_DEPTH_TEST ENABLED):
Disable GL_DEPTH_TEST
before drawing your text
Enable GL_DEPTH_TEST after rendering text

That's a guess. It may suppress the symptom in your case, but if done right depth remains untouched. After the scene has been rendered the text is rendered with alpha blending enabled.

@a_donda I have enable alpha blending im still getting a box  around my text

Its not a depth test problem. Depth test can complete hide glyph, but cant create rect.

@НикитаСамоуков  As you can see from the image i get this box around my text when i don't disable and reenable depth test..... I want to use the text as a UI like life left ect.....  That doesn't interact with the world cords but just the window cords

Its not a depth test problem. Warch your draw order, you should draw text last.

@НикитаСамоуков I try drawing  my text last....My triangle draws over my text and now i cant see it

Now when you draw text last you see triangle over your text, and now its a depth test problem. For correct draw text(and other gui stuff) you should: 1)Draw gui last. 2) Disable depth test. 3) Enable blending.

authors: Никита Самоуков


text:
XNA configuration on legacy code
Background:
Our biomechanics and Advanced Surgical Technologies Lab wrote a surgery navigation system desktop application in C# around ten years ago.  One of its major functions uses XNA Game Studio 4.0 to aid in the interactive interface for rendering in 2D and 3D cloud data originating from CT (medical scan data in DICOM format), and then segmenting that data and reconstructing it to generate surface models (stl format).
Summary of problem:
The whole application worked fine and still does on the old hardware, but, while compilation succeeds, execution fails in one aspect related to XNA processes destined for the GPU processor rather than the main PC CPU.
The import of data from DICOM and various filtering and scaling all works, and basic rendering also works on previously compiled source code and executable code on Windows 7 machine (details later below).  Also, compilation and execution work fully on an old Win PC with the Visual Studio 2013 environment.
Our attempts to compile the same source code and execute on newer hardware and environment with Win 10 and Visual Studio 2019 have partly failed.  The compilation works, and most of the execution works, except for some rendering of XNA processes destined for the GPU processor.
More details:
The user interface successfully renders bitmaps through the Texture2D class (Microsoft.Xna.Framework.Graphics) initialized with the grayscale data from previous number crunching operations in our code.
In another part of the interface, where we think and say above may rely on the (onboard GPU) processing, using the same Texture2D object, but when the code involves setting parameters of  Effect (Microsoft.Xna.Framework.Graphics.Effect) using Texture2D, drawings which use the  spriteBatch.draw function is not rendering on the modern PC platform we set up.
We guess the relevant code which fails to do the job is the following.  Pls note that it simply fails to render parts of the image which require image processing (filters, thresholding, boundary detection, etc.), AND without any errors/exceptions reported.
            GraphicsDevice device = SosGraphicsDeviceService.Instance;
            SpriteBatch spriteBatch = SosGraphicsDeviceService.ServiceInstance.SpriteBatch;

            string technique = SosRenderModeName.GetTechniqueName(renderMode_, false);

            BlendState blend = device.BlendState;
            DepthStencilState depth = device.DepthStencilState;
            RasterizerState raster = device.RasterizerState;

            Effect.CurrentTechnique = Effect.Techniques[technique];

            Effect.Parameters[“useModelBuilderTextureInclude”].SetValue(includeTexture != null);
            Effect.Parameters[“modelBuilderTextureInclude”].SetValue(includeTexture);
            Effect.Parameters[“modelBuilderTextureExclude”].SetValue(excludeTexture);
            Effect.Parameters[“modelBuilderTextureCorrection”].SetValue(correctionTexture);

            Effect.Parameters[“minThreshold”].SetValue(minThreshold);
            Effect.Parameters[“maxThreshold”].SetValue(maxThreshold);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive, SamplerState.PointWrap,DepthStencilState.Default, RasterizerState.CullNone, effect_);

            foreach (EffectPass pass in Effect.CurrentTechnique.Passes)
            {
                pass.Apply();

                spriteBatch.Draw(texture, new Rectangle(0, 0, 512, 512), Color.White);
            }

            spriteBatch.End();

The following are some of the functions we use in our effect file if that helps to identify the Shader Model Version.
•   float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{

       return float4(1, 0, 0, 1);
}
•   technique Technique1
{
       pass Pass1
       {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader  = compile ps_2_0 PixelShaderFunction();
       }
}

To try to see which settings or aspects of the environment are causing the problem, we tried to recompile the same code in a variety of configurations and execute on both the old and new machines which having different hardware, drivers, libraries, and different installation configurations.
For example, we tried:
•   Changed Compatibility mode to match Win7
•   Reduced color mode to 8bit
•   Changed Screen Resolution
•   Ran in administrator mode
•   Changed Game profile to Reach
The modern PC platform just would not render with the interface that utilizes Effect.
To recap, below is a summary comparison of the two setups, the one that works on the left, and the one that does not on the right, in terms of hardware, system, and environment setup. We tabulate here the hardware and system environment of each case.  If needed, I can upload the whole System information file.

Desktop_Old  (Works)
Desktop_New (does not work)

System OS
Microsoft Windows 7 Enterprise
Microsoft Windows 7 Professional

OS version
6.1.7601 Service Pack 1 Build 7601
6.1.7601 Service Pack 1 Build 7601

System Type
X64-based PC
X64-based PC

Total Physical Memory
7.88GB
15.9GB

Display
NVIDIA Quadro 1000M
Intel HD graphics 4600

Resolution
1920 X 1200 X 59 hertz
1280 X 1024 X 60 hertz

I/O port
Just one
three

Driver
nvlddmkm.sys
Igdkmd64.sys

Installed DirectX
DirectX11
DirectX11

IDE
Visual Studio 2013
Visual Studio 2019

Game Profile
HiDef
HiDef

Unsafe Code
Allowed
Allowed

Also, this is the previous post for the same problem and thanks for responding.

XNA is very very outdated, have you tried using Monogame? It is actively supported and should not require a lot of code changes - even the namespaces stay as Microsoft.Xna.Framework. Is there a specific reason you must stick to Microsoft's XNA specifically?

Have you tried the latest Intel graphics driver from Intel?

While I have spent years working with XNA across Xbox 360, Windows Phone 7 and PC, this kind of a problem is typical and requires lots of tedious configuration of the target system.
While I was once successful in past, it took more effort than to simply update graphics API (say, DX8 to DX11).
Every new version of VS links against different libraries. Given how long ago was XNA abandoned, you have no business in attempting to compile it there.
For my personal projects in XNA, I still use VS2010 even though I have three other newer versions of VS on PC (different languages and APIs). It's just not worth the effort.
I would, however, very strongly recommend mirroring the Dev HW as you are one unexpected catastrophe away from being unable to deploy critical bug fixes to the production HW.
Oh, and I didn't see anything about trying the Quadro inside the Intel HD box. Seems like a very simple and quick exercise (just to rule out the Intel drivers).